diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..929ca5e4f4d668d1207e6f6936c5c3805add2c0d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,24 @@
+# Local environments and caches
+.venv/
+**/__pycache__/
+.pytest_cache/
+.runtime/
+.cache/
+# OS metadata
+.DS_Store
+**/.DS_Store
+__MACOSX/
+**/._*
+# Private site settings and runtime recordings
+.env
+.env.*
+*.env
+cell.env
+/data/
+/recordings/
+/logs/
+# External model assets
+*.safetensors
+*.ckpt
+*.pt
+*.pth
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/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/LICENSES.md b/LICENSES.md
new file mode 100644
index 0000000000000000000000000000000000000000..cdf3c763000ad807637d7036986a2946a055fb72
--- /dev/null
+++ b/LICENSES.md
@@ -0,0 +1,12 @@
+# 许可证 / Licenses
+
+| 组件 / Component | 源码许可 / Source license | 文件 / File |
+| --- | --- | --- |
+| Flexiv UMI inference | Apache-2.0 | [LICENSE](flexiv-umi-infer/LICENSE) |
+| FLUX UMI | Apache-2.0 | [LICENSE](flux-umi/LICENSE), [NOTICE](flux-umi/NOTICE) |
+| OpenPI UMI | Apache-2.0 | [LICENSE](openpi-umi/LICENSE) |
+| Gemma terms | Gemma Terms of Use | [LICENSE_GEMMA.txt](openpi-umi/LICENSE_GEMMA.txt) |
+
+模型权重、编码器和厂商SDK需另行准备,并遵循各自许可。
+
+Model weights, encoders and vendor SDKs are configured separately and retain their respective licenses.
diff --git a/README.md b/README.md
index 154df8298fab5ecf322016157858e08cd1bccbe1..1389d54ff452cba41f936d3afab48908df227778 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,79 @@
---
license: apache-2.0
+language:
+ - en
+ - zh
+tags:
+ - robotics
+ - umi
+ - bimanual
+ - openpi
+ - flux
+ - inference
---
+
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+# iUMI Inference · 双臂UMI推理与部署
+
+Crobotia iUMI的模型推理与机器人部署代码,支持OpenPI(π0.5)和FLUX后端,包含配置模板、启动脚本及双臂名义URDF。
+
+## 获取代码
+
+```bash
+git clone https://huggingface.co/Crobotia/iUMI_Inference
+cd iUMI_Inference
+```
+
+| 目录 | 内容 |
+| --- | --- |
+| flexiv-umi-infer/ | 策略服务、机器人/相机/夹爪接口及数据记录 |
+| flux-umi/ | FLUX模型与UMI数据表示 |
+| openpi-umi/ | OpenPI模型、数据变换与客户端 |
+| scripts/ | 模型服务和机器人端启动脚本 |
+| configs/ | 推理配置模板 |
+
+OpenPI使用Linux(glibc ≥2.31);按`openpi-umi/.python-version`配置Python3.12,在该目录运行`uv sync --frozen --python 3.12`。
+
+FLUX使用`scripts/run_flux_server.sh`,OpenPI使用`scripts/run_pi05_server.sh`,机器人端使用`scripts/run_robot.sh`。两类模型使用独立环境,按各子项目说明安装依赖。启动前配置模型资源路径及设备标定;机器人脚本默认为dry run。
+
+运行前准备模型权重、所需编码器、厂商SDK及设备标定。输入输出约定见`docs/INFERENCE_CONTRACT.md`,安装与设备配置见各子项目README。
+
+---
+
+
+
+# iUMI Inference · Bimanual UMI Inference and Deployment
+
+Model inference and robot deployment code for Crobotia iUMI, with OpenPI (π0.5) and FLUX backends, configuration templates, launch scripts and a nominal dual-arm URDF.
+
+## Get the code
+
+```bash
+git clone https://huggingface.co/Crobotia/iUMI_Inference
+cd iUMI_Inference
+```
+
+| Directory | Purpose |
+| --- | --- |
+| flexiv-umi-infer/ | Policy service, robot/camera/gripper interfaces and recording |
+| flux-umi/ | FLUX models and UMI representation |
+| openpi-umi/ | OpenPI models, data transforms and client |
+| scripts/ | Policy-server and robot-agent launchers |
+| configs/ | Inference configuration templates |
+
+For OpenPI, use Linux (glibc ≥2.31) and Python 3.12 as pinned in `openpi-umi/.python-version` and run `uv sync --frozen --python 3.12` from that directory.
+
+Launch FLUX with `scripts/run_flux_server.sh`, OpenPI with `scripts/run_pi05_server.sh`, and the robot agent with `scripts/run_robot.sh`. Use separate environments for the model backends and follow each project's dependency instructions. Configure model resource paths and cell calibration before launch. The robot script defaults to dry run.
+
+Before running, prepare model weights, required encoders, vendor SDKs and cell calibration. See `docs/INFERENCE_CONTRACT.md` for input/output conventions and the subproject READMEs for installation and device configuration.
+
+## 许可证 / License
+
+源码采用Apache-2.0许可,各子项目保留原有声明;Gemma、模型资源及厂商SDK遵循各自条款。详见[LICENSES.md](LICENSES.md)。
+
+Source code is licensed under Apache-2.0, with upstream notices retained in each component. Gemma, model resources and vendor SDKs retain their respective terms. See [LICENSES.md](LICENSES.md).
diff --git a/checksums.sha256 b/checksums.sha256
new file mode 100644
index 0000000000000000000000000000000000000000..d45e3372531d5d8de5c739111f3de359e615afc6
--- /dev/null
+++ b/checksums.sha256
@@ -0,0 +1,307 @@
+6b9d5bb0a11b8f11de5274ae0168adcb26bb4a9a92ce2785cb9d9fb81eb62742 .gitignore
+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 LICENSE
+14239d1e7b350d922e247861520079c99b2f3bf572154af74890b85bc25ea65c LICENSES.md
+b8074f763f8e1d8b20ec809d315e67123a53bfd458e89f973f8993880f246bdb README.md
+60e7b1fa5876ac5074cda70fd52fa03814352f8be4fbc0b49eabe8f549325f32 configs/inference.env.example
+7fe74fe0ec4ece29718a69ab686be6693157b9b4b7356bff9c5c1498fb8f742b docs/CHECKPOINTS_FLUX.md
+ecaf5b17769bc593d53b5170d857902ba39db840baff1ccfb358f056cd2a5b6f docs/CHECKPOINTS_PI05.md
+8aedc1e1c6cb6531b5fdc825a9e89421457542b6bb951f6ebf35cbd4a5fa2266 docs/INFERENCE_CONTRACT.md
+118ba0b007d38dbca6b458de432977b8ddfd8ac80689056b59aaba0ede857457 docs/VALIDATION.md
+9526e276e76a8991c508eb44303eb2c70a32820d05ab1edd158c03c70e77d89b docs/validation.json
+42eee4254f5c858d4b8394e089c755c5593fa245004a3f3bc3790adcb2b64d3e flexiv-umi-infer/.gitignore
+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 flexiv-umi-infer/LICENSE
+b10b1431edc043376db249fe9670d8add3dce5accd4cc417a2ab596a5b655a8b flexiv-umi-infer/README.md
+80183544c5e1e0989543cd8890c718744ac2ef80372638768c08747a4c53ed44 flexiv-umi-infer/configs/anchor.example.json
+c660c0c97fc00fd18826fb476752f66c4b9f0ed28a1e837c58c4101f28887ee4 flexiv-umi-infer/configs/cell.env.example
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/data/.gitkeep
+841aac6628213fd95738357123dc35d0ec284f5b019c13b753d4569b990699e8 flexiv-umi-infer/pyproject.toml
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/tests/__init__.py
+16fa68ba18ded9fc02ce0ea4683d59b304bce8f3a306da9b7646c9cc624ea2ab flexiv-umi-infer/tests/conftest.py
+8f4ada186a728752e46b1c685213c8abe2a0631f0e87f57cfd9c20b297be301d flexiv-umi-infer/tests/test_cloth_defaults.py
+2afd295bbed79e36b59cc9affbb9c77ba6793916adfc8b21b6363c07c10aef4b flexiv-umi-infer/tests/test_flexiv_trace.py
+3e682defbaa40a0476ed5d1919cd96b0538e2a89584091bad984bca94329c642 flexiv-umi-infer/tests/test_flux_action_dual.py
+03b742081d40c132b11bb838b56d3cd12d37aa1440954d290ac0ed5c5a5b3798 flexiv-umi-infer/tests/test_rollout_rec.py
+af575d5a0a1473936a4f886fa1466465bb1b694b51bf009182295d03f9bf4b71 flexiv-umi-infer/tools/README.md
+92a07fbe0962ac7d93d54576968e8f7baf4d249597aba2d5f8634b822651d061 flexiv-umi-infer/tools/insta360_cli_dual.cc
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/__init__.py
+58423863c5a932691a10c32a2047462777e87882c42771d87d7001b3582d0cde flexiv-umi-infer/umi_infer/check_cam.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/codec/__init__.py
+3c483daaabc2688f6c81616ca9bf6cdcf5a5f425429b348a5f83e30530fa5642 flexiv-umi-infer/umi_infer/codec/umi_decode.py
+82ef7d599f403d6104c77bdcd5f015ed7a7cee215d9ed204d0c9fb1983354b49 flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py
+0897f80a731cdcc71914eef3bfe806a9bfbabe18f6bf60d587bef6fcd04a23c9 flexiv-umi-infer/umi_infer/codec/umi_spline.py
+3be9b7e5a74f2c1de805a0574710967cecebdd55aa0850fb8a31933dd0673b97 flexiv-umi-infer/umi_infer/config.py
+82e5485459cac03989d7799676df5fafa9f06b19ed99d3c13142784721e2e2f6 flexiv-umi-infer/umi_infer/export_E.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/policies/__init__.py
+0c3c35af3126ea2716484ce6e0a5852d49021dd7fe32d04e7960e5e23eb14eb4 flexiv-umi-infer/umi_infer/policies/base.py
+1688a89dd2d291c9350ae700e88ab28d97f0623c0de1dec205693f88f8c4200d flexiv-umi-infer/umi_infer/policies/flux_action_dual.py
+06b2f047a719623dc9b83fac3b690c006e6fa89e3afcea9b619635353dfd0263 flexiv-umi-infer/umi_infer/policies/mock.py
+e0cdbb82653cc0fe7d5a9cbdce99422dd665b307e84eb9c3d406608f1c654a7d flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py
+da2e71e8410be9bb734716eaf8b55a24a4ae86229359e6c941f22228e157ad2f flexiv-umi-infer/umi_infer/policy_server.py
+79eff4d235eb5fe03f2bcf1e731a0b79614dec76d9faf02e8dfd159267d6168e flexiv-umi-infer/umi_infer/protocol.py
+0517326eae9d98e77fd37741b9b69c8298af257042ee433806a260ed99a6c090 flexiv-umi-infer/umi_infer/robot_agent.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 flexiv-umi-infer/umi_infer/robot_io/__init__.py
+c2a3a19b09a7d507e79142748c45979c41a8e07d49219ce6b05ebb1fcc6a49b1 flexiv-umi-infer/umi_infer/robot_io/base.py
+5bc074b735e533d16f9a301b8019dfd2ed09143a2eeeb5af4e493c64cf2fea3d flexiv-umi-infer/umi_infer/robot_io/cam_ids.py
+effc2e2a3740f74b982408ab4a578fa5c08dd00019d2a2dea6572344c2231baf flexiv-umi-infer/umi_infer/robot_io/flexiv.py
+70f9f69e495e978cd010518b43cffe838e05c8b9768dbbc3323f45aeabf1cd4a flexiv-umi-infer/umi_infer/robot_io/gripper_can.py
+c6fdd15f60481270c6208a9b7e428f85315a6273865308a84cd829303cb5ad88 flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py
+7438aa26f6ae5ad5e866d741abc0b1cbe588092e499d4ae081bb4482fb57d9ba flexiv-umi-infer/umi_infer/robot_io/insta_live.py
+1b48a111a668ac06ca641b0462b1568130906555d9823b353931dc46f01da598 flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py
+4cb45a18fde7e181223bfb91d4afc44a5279c2bcd577ef703fb3c7a1c975d9e2 flexiv-umi-infer/umi_infer/robot_io/mock.py
+d995f56cb8b535a82ffc5a7df7f31e62782e24c55c8db02139ee3409b08d2c18 flexiv-umi-infer/umi_infer/robot_io/pose_math.py
+5cd362467442c368baad7412166b51d1ac57dc714dc5535e1aca8484c39df551 flexiv-umi-infer/umi_infer/robot_io/rollout_rec.py
+6d05cf21d13cf85ad7fcede2fb4eb615052d616341f1065b59caf41f9a749398 flexiv-umi-infer/urdf/flexiv_rizon4_dual_umi.urdf
+94795a39dbf0403579cb3b520eb32b17da77cf7a18f96a70897a4bd7269eca3a flux-umi/.github/workflows/cpu.yml
+d63b857a6ffdd4a439699799d055011cb326dd6a8153cbfca7d9f08e3dea963f flux-umi/.gitignore
+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 flux-umi/LICENSE
+583bba0e76b647a973d86854f8af7b983c4bbc29dae239e22da1e0288efb9b61 flux-umi/NOTICE
+7f0e9239598e3c48b42f276f2dc7945fd0fb309eb2585ddda5c94b7b6ece8ef7 flux-umi/README.md
+c39d803c7a1485b12f4e14f535858d5c5c27e4e757484b140e7858ba93587cd9 flux-umi/configs/droid/public_sample.lock.json
+3f98670de9e60f8b19f0a712e24be69b04f5161e569ae08f6adac66fe3ecd4bc flux-umi/configs/droid/train.json
+a77bd3fbf83c99fc0739d0541006080809ea62af65f125f672860bcf56a60e91 flux-umi/configs/games/train.json
+9ce066fa24a42a24407de232892e948b3c307a239ef2ba2b9ce8f0de66221fdf flux-umi/configs/so101/community_corpus.json
+73c1bcdb3b9ecd5448a26d0d1bbd21b9eef4668fcbc0766e09543ff1a48e395b flux-umi/configs/so101/train.json
+20a357bb2c45c64f792a5e089999d67616aaa4009d7303b8226c14d9518fbe0f flux-umi/configs/umi/umi_posttrain_16g.json
+85caaee496298274765d4871cd3a6c910fc0d39fdfa40cd371d4c7225ac54cd9 flux-umi/docs/embodiments.md
+7fe74fe0ec4ece29718a69ab686be6693157b9b4b7356bff9c5c1498fb8f742b flux-umi/docs/folding-checkpoint.md
+04c31dd1d5cddc271f49c2ac58a2df1fcaf45bda6618535d483cae830b0c2b37 flux-umi/docs/setup.md
+c827725c899f6ca3a90f771acd4c77e096b552e8619c9574b08e8ab77f10b86b flux-umi/docs/training-environment.md
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/examples/__init__.py
+475dd51707eef76d456694d6a3ee3f04f93cba894db87e00c2ec98966eea0b53 flux-umi/examples/games/README.md
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/examples/games/__init__.py
+8f03a3b2121a4c858386e2485f7ff7205ee9ca9813ce705864cb5b7bb278880c flux-umi/examples/games/dataset.py
+3790c03edcf680dd24f43bbdb1cd74dd03a2c20ac5ae6c1494f40caee2d1fbb7 flux-umi/examples/games/test_trainer_games.py
+3a1acee06057729348accfdc709c5702a23605f70f74260a7dbdc1ee40f0db07 flux-umi/pyproject.toml
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/__init__.py
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/checkpoints/__init__.py
+db0c3018885375a6edf989a5d31fb5c227a46960a7a35ba1cb69c976cc96fd60 flux-umi/src/flux_action/checkpoints/artifacts.py
+80d3aea6cebc03be04b17893e03bf124318dc42908e5a5f786c859cba4eac8e1 flux-umi/src/flux_action/cli.py
+4a35842b6d27852f3b70920c863c3258c82dc266891c5690d15a2731f75f3353 flux-umi/src/flux_action/config.py
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/data/__init__.py
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/data/droid/__init__.py
+e250e91835e875165db883432ce70bea20383a60be69d1ba5af4f9b7a1722bfe flux-umi/src/flux_action/data/droid/cosmos.py
+2743077fb20902916fdbc1e22114a151d6948506bd410c78373f2cd47e9ae3c1 flux-umi/src/flux_action/data/droid/episodes.py
+9ceea7ae053591580bc54fece2d4be08e3901711994058ec04ad8fe39a3d6fdb flux-umi/src/flux_action/data/droid/index.py
+467d2d45cbabe5b7be3e1ce093a8cdadcebdeca7a58fbfb0fcc4f78528844d68 flux-umi/src/flux_action/data/droid/video.py
+1efbe639cf11f4aa1a645c5d9e04cc50339df45ed9833f9108a3add12181d61e flux-umi/src/flux_action/data/lerobot/__init__.py
+cb23610fd2fa05e0409b1692a116c3b88c91e998a8c2e43c7922ccd69a5a5f31 flux-umi/src/flux_action/data/lerobot/index.py
+73f8f63e827c72ba71bb5c23477d57e261ccd841d365987853c5542447cd80c1 flux-umi/src/flux_action/data/schema.py
+d002e5ce430c1a610d01b499a3736fb07b2d6ebd93ebd5abe804cfc1d88caa65 flux-umi/src/flux_action/data/umi/__init__.py
+58579872786bc383fa45884e8319741d22317095effb7943935e05a47bfc3503 flux-umi/src/flux_action/data/umi/all_windows.py
+036d6af65e697822c4720eb38bb04abf5ba150b7f9d7846968fa04739634badb flux-umi/src/flux_action/data/umi/dataset.py
+f6800fcac7d980846bac532741a6c38522cca5b0dcc284221e6b8cada5dd1dbd flux-umi/src/flux_action/data/umi/representation.py
+2d7a4032a8da9c0944d2e5c0d4a1c077c0953ed4280c34a503f1fbf5cd16332c flux-umi/src/flux_action/data/windows.py
+fd70af80e92ea4d4a32d479a0d6c42916beb0aa0e597665e5fb64e29dc70b04e flux-umi/src/flux_action/hub.py
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/inference/__init__.py
+8dd300f3363f34cd1381cee30d8e64ba967e6a21cbcc98fe23e5438c3dd7bbfb flux-umi/src/flux_action/inference/evaluate.py
+6391d17e89cb01c7e4be41938fc7a5347e2ba74f9dfbe31300b54f5d13888ac5 flux-umi/src/flux_action/inference/offline.py
+cc20073e7c82221047ac7bc29d223b933fab569d211cf615b3d209e040d2de2b flux-umi/src/flux_action/inference/precision.py
+93855fe06f89d55551ec7601342f4c7ee4bca40ff037648f04a1259e7a113613 flux-umi/src/flux_action/inference/sampling.py
+2a4acc16b7840fdb9b842ad9d63657d62c0318cd0456d07ec1a2a91a5e36be67 flux-umi/src/flux_action/inference/so101.py
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/models/__init__.py
+a479eb38ac8b23b889d9ff35597b694aab23a1be84bb64d8e1f38c6bfd551322 flux-umi/src/flux_action/models/cute_qknorm_hybrid.py
+3f953df25e520b0d9c4dfb8c70e1f4a871a0e71a7086c77a5630e10538165b6a flux-umi/src/flux_action/models/cute_rmsnorm_kernel.py
+1e2f93599c864c7200e4764d94a3718eb5ae9cacd6ed57b25abcb3ae7c980f10 flux-umi/src/flux_action/models/cute_rope.py
+759ec807617ff5472cd501d2bd53f043aaa881b38e5e6d0da5bc581c28fcdb17 flux-umi/src/flux_action/models/cute_vae_rope_kernel.py
+3d75a54345d2e600abafcc6df7ed6fc31bb88461b5213edd70306c62b622c88c flux-umi/src/flux_action/models/dit_cute_qknorm.py
+35706af2eaec9fbb698f3dd70d86780a568a817f87455838df059bfce309a037 flux-umi/src/flux_action/models/dit_fanout_linear.py
+5aa3858278a13b0792e6c426e7bcf64ac4ad0b89873e23a6b18c721e3bdba9ff flux-umi/src/flux_action/models/dit_mod_rows.py
+43da24b19a0d91c0bf594cab7121767306ab87d95f3f62e3cd616716f999ab4e flux-umi/src/flux_action/models/dit_norm_mod_gate.py
+67100afc68724051b27bd609aa16a506514239888de17d2b34b35844fbc2dfb0 flux-umi/src/flux_action/models/dit_out_stage.py
+ee5429a56a4fd980984bc7b0b8f6083dbb3167df9986133e3863114c3d576212 flux-umi/src/flux_action/models/dit_qknorm_rope_fused.py
+d934ec932e13f248c3ba4cf32af9918cf0aa49849817041eb92f9cf3aec6aaa4 flux-umi/src/flux_action/models/dit_qknorm_triton.py
+3a9175d739257a8d2daa48e62bbc6abb9eb95bcef6a659803664b9b1ff82f058 flux-umi/src/flux_action/models/dit_rope_triton.py
+57b5e0f507d223b06d098873741b2c7e3d0bf155c2db31d199f9b2011abb235a flux-umi/src/flux_action/models/dit_swiglu_fused.py
+b972c2da876ce30af417ced99eac45e24e5f7a30373fb771e079070ec1f33cb5 flux-umi/src/flux_action/models/dit_time_embed_dedup.py
+c24b02a9d188a3eaafcb1dc89de551433a4d7269e11dae5af4248be246a16fe0 flux-umi/src/flux_action/models/positional.py
+de51616e5a3c22d9852d6ca17440b9b7db8e0dda22c52b79600406b3404bf948 flux-umi/src/flux_action/models/runtime.py
+0b0f736c8b5b92c4354a4733f0d9aef885d871e0057aa7650dcb76b9c4ce6b36 flux-umi/src/flux_action/models/swiglu_native_out.py
+b5643ec523f7fdd591da73a7ff4d82fab96483c4ffc1c0e417a48649450a8dac flux-umi/src/flux_action/models/swiglu_native_out_adapter.py
+fb76e4cbb8654c6007c4c9a8dc43abfb623dc164d85bbc285b79d522cb851063 flux-umi/src/flux_action/models/text_encoder.py
+8c36a9fd8e9f1bead55ed0283238fbe6f206b24967fb5d5c2c6ee7baa3062d3d flux-umi/src/flux_action/models/transformer.py
+a0f737d097901c58fd88162699328ec6b44b0a05ba54f71dc1d971725ca30ecd flux-umi/src/flux_action/models/transformer_inf_bf16.py
+130ddd62b5b5ee4f908a3f84eee035e8f2aad37e85c976e846199986b2043548 flux-umi/src/flux_action/models/transformer_inf_fp8r.py
+393f2d646d52923eabb23559ce9788d4434e177de770fd464786119bb2c2e06e flux-umi/src/flux_action/models/vae_cute_rmsnorm.py
+a2057ea6a88d17dce2a2ca15d068aca3ad5c2f4132ee35623b6ff9489911fd45 flux-umi/src/flux_action/models/vae_cute_rope.py
+7b5835ce3f3f096b9a052bd420e2a3ad0453d46894d619a6531e77ffdc01a0dd flux-umi/src/flux_action/models/vae_fused_gemm.py
+5ce201e1482634fd00b14f5bb05310a08453423cf218cb29dc6b8ef03a48d3de flux-umi/src/flux_action/models/vae_fused_pointwise.py
+2913a95b65f3ce75503c41601aa304ad4610eee95ba95c213b32003678960d61 flux-umi/src/flux_action/models/vae_graphed.py
+02084a113dd0e13e0881d01f69815f6f55352f8bdf28e7989d25ab2a45e7011c flux-umi/src/flux_action/models/vae_ln_exact.py
+4b4b00790103992513addd52950b513f1a1043a0145d11efb139164e4b0fbec8 flux-umi/src/flux_action/models/vae_merge_glue.py
+1fdfaea257f47b13434326900a3b0463d0068e7bba40a25320ff48bf971e176d flux-umi/src/flux_action/models/vae_na3d_triton.py
+f133d9c3ee3b3a01310f177bd16386f4738db79d427b7bdb624115e6e5350ab8 flux-umi/src/flux_action/models/vae_na3d_v2.py
+c8c00d90e1ec6c4fc326c57751070ad1a3845ae4a087494db478bc8062d8da92 flux-umi/src/flux_action/models/vae_natten_no_lse.py
+e6a8caa6f9af2ed8bbe225618d99566627917af27786f490293e3cc5b4de9f4d flux-umi/src/flux_action/models/vae_natten_tokperm.py
+860a8a290b05f3dfa83a5972ddc8ef0c9b3d8d285ee38e23a495f95c4a44e38f flux-umi/src/flux_action/models/vae_qk_fused.py
+ea71196f17d11c05f9b35778c13eea745497369f68f383f76c35b68b6e727d5e flux-umi/src/flux_action/models/video_vae.py
+13aff43233302324336c0aadf73e97f210095adc133bdccf5e2cbbc4308d450f flux-umi/src/flux_action/models/wiring.py
+aa0558daf2743d0c251fd2f433ed7a98cd54689057421ac74f96782f811155bc flux-umi/src/flux_action/policy.py
+96bcc989a090429dd733f1ceb2f844af3e888bd26f43c9c20f9fea1eca18d007 flux-umi/src/flux_action/processing/__init__.py
+74fecbda8f05b453e694ec2457f6a8f35424a393e21aa42f135ba846dbb14362 flux-umi/src/flux_action/processing/batched_preprocess.py
+cb6448d7de6b0fc0050f73237c6a6f864dd2c903881beece45b78f5ba2eea40d flux-umi/src/flux_action/processing/history.py
+73ac9b89b5015c02d1c629fc1494cc4743ed2d1784e9c0d0a3285f85fb06f492 flux-umi/src/flux_action/processing/normalization.py
+dc88b0129304a00e112d1f693695a42aa48eb85de6550d93f4584b80a558b513 flux-umi/src/flux_action/processing/packing.py
+9821634dc48decda1111dbf1ac28ed6cb68aef7630c3c65aa93a4d51e207f827 flux-umi/src/flux_action/serving/__init__.py
+d9c277e50262e000a46c9a131f334eed16a362f625c5b10e727d9a5919ea8896 flux-umi/src/flux_action/serving/protocol.py
+f78eed26f8e292c8aeba5abadecba2327b2862ab6e583fd237483106fc04b2c4 flux-umi/src/flux_action/serving/robolab.py
+0f9286a4ec247764c23cc33cc71bb861e9f0e870e366848966df874bab1e660c flux-umi/src/flux_action/training/__init__.py
+e1d7ae9450ce01034a85b4c5c762f715f71859e3c5f6a4e3592a246b50616e89 flux-umi/src/flux_action/training/activation_offload.py
+b027cf267a763da50263de7ddc584056872ae31d54d2866f9c1c7079f60c1e8a flux-umi/src/flux_action/training/checkpoint.py
+3d11e924c18e5ebe2cb4b37df7ff02acea488f5536f3f0e74545d74e3a7e6b40 flux-umi/src/flux_action/training/data.py
+7780780f7baa04ed5ce02cec7d9f7cec30275933b725a99d19d7b161a92ede6f flux-umi/src/flux_action/training/distributed.py
+e31869e09e9b81d6ddd229f190bdd30efcbc26aa754e6d320c970a85dc2f9199 flux-umi/src/flux_action/training/ema.py
+4fb5dbddcc3cba6faec091bf28532d2b89e7bf6dafb8909c3e562f00a79cff98 flux-umi/src/flux_action/training/schedule.py
+935ed868abfd630aacc9a18a0d625b3a8c872bb81feaef7c61789549b1fdd478 flux-umi/src/flux_action/training/timing.py
+1aed33cccd133ee9ad4b41ad47e1ceefc7b98e710092682c275a439b407f26ff flux-umi/src/flux_action/training/trainer.py
+e1068092ab789c254812642439b35dfcb014ff2dcfe477efb25ce7b1e7f2f3b0 flux-umi/tests/conftest.py
+d745251355b5e9b01b0b7561efef09dd4d969f81f039485bf75fc74cc614c568 flux-umi/tests/fixtures/so101_history/README.md
+6870eaf267ebad5fc3f7dd6fd7147fa61e8126411166e0b0cc93b4bb7f56818c flux-umi/tests/fixtures/so101_history/config.json
+becfefcda2c7116d31d83c8877b015d30dffaedbfce8fa2d854521b738b81d62 flux-umi/tests/fixtures/so101_history/policy_postprocessor.json
+4c6fb125252845fe64258ce4cfac8d6f29297be77d285abf862f0b894b55ae76 flux-umi/tests/fixtures/so101_history/policy_preprocessor.json
+622cf6eff6e33254bcb12d3b265411f16044b0dcfbdf10c7cab1c34014049cd6 flux-umi/tests/synthetic_droid.py
+8bfb1259b8a1b57dfb46367733b3ffb52e464fa928c65f7124b412f53ed8b050 flux-umi/tests/synthetic_lerobot.py
+c91fd843ab8a263734d9cebbffd6b611b18b97c83afb7b603e86765c5e20a76c flux-umi/tests/test_cameras.py
+4e75d642efd6d921289652c99a4343609ff24d8c89e6ae2297d6f6823af24416 flux-umi/tests/test_cosmos.py
+e38c9c061aab7bebe82e5f1bd57ab566c7c51d6ae034e47d6ea1e4b02b0ee1f7 flux-umi/tests/test_data.py
+8ed736acec7e20f72d7fe0801071af21e4c86578c36a0b068086bab4c278d09f flux-umi/tests/test_droid_cli.py
+9af867e8e3ce3a06e337883c75661fa3eb53d261c6d4756e8e37d9829ae1a8f8 flux-umi/tests/test_history_inference.py
+eb70c02c0f6c90ef5a64493c658578ec2e2ce1303d7ec12898032d1c1c7144a4 flux-umi/tests/test_history_training.py
+e4637f2d8076c559201f826cae48c0fedfe6a088a716a6778a348a7815d12a8e flux-umi/tests/test_hub.py
+5b5d1128e4ccc19329dc2808df712f81f79eeef4748a2541033b73201978d8f2 flux-umi/tests/test_lerobot.py
+13dbda4ce5d3bc49d4700926ed978035795abeae83418013e4fadf4f596d34b2 flux-umi/tests/test_offline.py
+342e7397ad71c070ed58d55720ac10187ee6ad5cecb5e45130236feaff55736d flux-umi/tests/test_packed_windows.py
+e55df90dd630985d7474b9bb7233c70e250e47ade9ff01e6484a974b0dc36001 flux-umi/tests/test_policy.py
+64eab8c716530e6e92c486869867814dd9f8601e6e2f2f85f6643c3809b4acf1 flux-umi/tests/test_policy_optional_dependencies.py
+3669e45970485e01acec311c0266086a3b4a029bcf8fcd586ea755c01a959ce4 flux-umi/tests/test_precision.py
+06e6c466d990f444334691100cd89302cd5f4dcd51148c1e2ef2db752cec3210 flux-umi/tests/test_serving.py
+976288b37a5050a030bf5c4ea13de17106e7cc37a9f42c8027d74f3439cd71d4 flux-umi/tests/test_shared_encoder_hub.py
+3af3afbdf0a28c2be3cd859a878044a4319592941821402157a780a35c9531d7 flux-umi/tests/test_so101_config.py
+6689cd91bc6c7bd15cfe1b7aed37de8bb6b1638c2fd2966450b4605eed031ecb flux-umi/tests/test_state_dropout.py
+e438667accd30209006f4e235c6ec2d3af4bf104332dc1e4cf788b843cdddb9d flux-umi/tests/test_umi_epoch_stream.py
+d714339a8c0564a7e17d42185ee5844b4b9b44029bfa3f9f41f1bd8a7f69fa0c flux-umi/tests/test_vae_training_prefix.py
+0bc606326d4f17d96e4cacdcd0368528743cdff786bf49315c741ab11e80a28e flux-umi/tests/test_video.py
+3d8311cea3965fb1764f1605328fa0ce5c0ecc48804bf2660747b59a0f61be6c flux-umi/tests/test_video_vae.py
+396665643eb2a5a7369129e7769d67699e0812855fd695bada7621042c7ba86a flux-umi/tests/training/test_activation_offload.py
+7ad190a394daae6ba8085005933a24e4dae340142c347b14312a2db5d5700c90 flux-umi/tests/training/test_batched_preprocess.py
+87f887d4a09266af0679c111761840c675022bdf1a84b6914fa03aba9ef0622d flux-umi/tests/training/test_checkpoint.py
+8c41a301d77906a3139b4221dbc334c3b722ef6d14a9217d00812537eef99cc0 flux-umi/tests/training/test_dit_fanout_linear.py
+46b820c5b0d6d97c56f3a8a5ace818dab87bfe9039c847ba46106b8672f4c2d2 flux-umi/tests/training/test_dit_last_layer_rows.py
+180c5fb4fd90c1cdd1ebd3a46fd25f5805ba4f39304b086b314610ce5a1cf84b flux-umi/tests/training/test_dit_mod_rows.py
+942c81331915b5c4217b02d49d26b4003c0841d47135afc1b767d0bb11d613ba flux-umi/tests/training/test_dit_out_stage.py
+82aac2ef0d0a3150fdd00722d9defb6cec1492e0c60468cc9adf100ce3549906 flux-umi/tests/training/test_dit_qknorm_rope_fused.py
+b1b9781927c6d7166cbf97eaa4f8d1b49b9eac76ee434a7c23c11e4a92972d1f flux-umi/tests/training/test_dit_rows_fixes.py
+329bc03e022bde95f44618d451d193c87f77695f3483d5ac0595fd883cd7808b flux-umi/tests/training/test_ema.py
+c7e849db640ad0677ecc5dbb1b680f6ce93eb7dd1f647e9b210f20cb19c10a86 flux-umi/tests/training/test_embodiment_plug.py
+71313d3e72bdb697e72a8cdc13e2cb738c37c63ae3b07d95596d9ce1831698e3 flux-umi/tests/training/test_pack_cache.py
+751df4a73effff80bdb58942ccc940185249a54e196ec9a7285d97012a6bc1fc flux-umi/tests/training/test_perf2_options.py
+ebab8e9b34a239be10f8079be095ca03f01790cd172d6c22d739be1a2dad79b9 flux-umi/tests/training/test_perf3_options.py
+73ab34152145688f52c7079a0af1f5f95e51d601e5ac4a07686a6480d6c5e1ec flux-umi/tests/training/test_resume_prefetch_rng.py
+99bd98c1a375fabf01a06481ab45da2616a787584add997826c3e2a46f56d3ae flux-umi/tests/training/test_schedule.py
+079c7919a3debcac9bade3c2caa11585b33e3371e17ae29ee244a786a722f3c9 flux-umi/tests/training/test_trainer.py
+c8ff99f7063c6a3dcc4e04f123386707bd705be776eb60ffb72ee59a6d16ca03 flux-umi/tests/training/test_vae_fused_gemm.py
+2b483d559e5a82e320fd2d114f5ad4f4705a62c3ad070fe4644ad7d02917855d flux-umi/tests/training/test_vae_ln_exact.py
+b19331fdf78702f0e82765cfc1fe046f1ee45a2d1dfac11199a55e96b6148bb7 flux-umi/tests/training/test_vae_merge_glue.py
+de3282f5f097d0a81ba58c8bfc0c999173a8337a5008a41b318ae26c2bde1779 flux-umi/tests/training/test_vae_na3d_v2.py
+3c0256e77d1cd1991b22fdadea124235b4e3d1fa40cdb7707a33bd25607d2500 flux-umi/tests/training/test_window_loader.py
+0049930820d1dd6116108d0c8a5d09c216f87fe4c37db01d5e219da4ea571bce flux-umi/tools/prepare_umi_lerobot_v3.py
+033f224839a39a259ccfd502a47116d0d659f31a5b93e5e581575c4f9fb2ece8 flux-umi/tools/train_umi.sh
+8586969ff00e43b6c85606406ae6014ec79c10459df842967ab464e6a7373a09 flux-umi/uv.lock
+10d44f6bfb4a32403a5cb7a279e7d0ccf39b2e9978214fb04584bded9b8a4945 openpi-umi/.github/workflows/pre-commit.yml
+5ddee83abe84731df1896aad0bb931696b6b0f94ed5fa46251c4a42c6be2bbd5 openpi-umi/.github/workflows/test.yml
+eae6f7ba5c007c6b2bc6848a9aca84475ce842c6692b5558cb8522f9b95dc2ba openpi-umi/.gitignore
+5cb58628e068c3a25facd810095cb0e8f80ae7558d0a67ba197c01d9513baec5 openpi-umi/.pre-commit-config.yaml
+7b55f8e67b5623c4bef3fa691288da9437d79d3aba156de48d481db32ac7d16d openpi-umi/.python-version
+8da333112457fd84815551065bd3a3f80160054bbe89cc5794f57bfba2d50a89 openpi-umi/CONTRIBUTING.md
+43070e2d4e532684de521b885f385d0841030efa2b1a20bafb76133a5e1379c1 openpi-umi/LICENSE
+3e2c24001f9ef57bf7ec959a3658fbb49cdad113cdf394c264da9d16f9bdd132 openpi-umi/LICENSE_GEMMA.txt
+49001b2f146bbe97b5cad11898f44e904a7b2b4e4125c3d681842e3ac1094176 openpi-umi/README.md
+ecaf5b17769bc593d53b5170d857902ba39db840baff1ccfb358f056cd2a5b6f openpi-umi/docs/folding-checkpoint.md
+65ac9a3a555a2d3e78b75c9a4a446ad56e981842f81eaceef09e928e972adeab openpi-umi/docs/norm_stats.md
+2146b043c6f92c618b44b81cf021d0352082211ebe250766918f32cc510f543c openpi-umi/examples/convert_jax_model_to_pytorch.py
+00e8cb0e589d8f473588528f271f780fbe20cb67ba778e3e827d30cc3eb6cc92 openpi-umi/packages/openpi-client/pyproject.toml
+91447944015cec709e8aa7655f7e9d64e1e4508e7023a57fe3746911c0fc6fed openpi-umi/packages/openpi-client/src/openpi_client/__init__.py
+019b9d69cb26cc681331a2f95dbe60a2cc7b02d6d309c5d15b6457ab39798234 openpi-umi/packages/openpi-client/src/openpi_client/action_chunk_broker.py
+88e98e0f06293f3c4767db675061664c4bba12f87242ba1e64377d1b8de8069e openpi-umi/packages/openpi-client/src/openpi_client/base_policy.py
+d48b4bd7f44e79fe6db8a8e07c9161144fa250be686e1245014a8b47e6171977 openpi-umi/packages/openpi-client/src/openpi_client/image_tools.py
+4df4b0ba0b95ba5e47160039c3e837a64d50c802b419a588211dffbaa732589c openpi-umi/packages/openpi-client/src/openpi_client/image_tools_test.py
+c04568948fcee52b691e3be4b6cffb759f7e79ad67530fcd5d23095a0d13c057 openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy.py
+2c6dd236720dae716d7bdf842b7d506a165e9563bf9d4376c95289269adcb973 openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py
+b559885afd9645a91b9b6ee12a28513295474f987d11b16610fc0479dbe6de5b openpi-umi/packages/openpi-client/src/openpi_client/runtime/agent.py
+c4d63952d1954bd4b72a3122223df36794812fea74cf1c7023433b5a90473c1c openpi-umi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py
+1c12e5054b3401dec5f1f8b71eef0f625cb60e2b50784dcf19afa32c77107a7e openpi-umi/packages/openpi-client/src/openpi_client/runtime/environment.py
+3daa242a9ce61ffb210789ef3ba6b1e3cade9de757fcd36af7b174c530345ea8 openpi-umi/packages/openpi-client/src/openpi_client/runtime/runtime.py
+d269a2af8ec4056beb310e5c3c97d4468af01549c7ef80dd905652d8ac64f85b openpi-umi/packages/openpi-client/src/openpi_client/runtime/subscriber.py
+36557cb0b91ccf31cd4fb4b508306850d76ed0feb4028dac5182d0f5a5d88005 openpi-umi/packages/openpi-client/src/openpi_client/websocket_client_policy.py
+b115474a844299a32543792c9676d658ad2e9e4158ffc3d12d9a37e302f6bfc0 openpi-umi/pyproject.toml
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/scripts/__init__.py
+61927c15848032db2d9bf10add57be9bdc4fab6268206dd43a87d05034066f36 openpi-umi/scripts/build_destatic_manifest.py
+6573eb6c30bb645befe3b01771d19c9b7c37f244bbcb8bb4046328f2d5ddb8a6 openpi-umi/scripts/compute_norm_stats.py
+90c2c413e31771b4ea5cb08441f083826974339ced66feb197c01ce041a4e288 openpi-umi/scripts/train_pytorch.py
+b3d290c71400f17bb89edd0f2c82a4b8181868542eed6f3d3018d86ac0e0ba43 openpi-umi/scripts/train_umi_v3.sh
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/__init__.py
+626672e385fb276396c119e2220421065c58f8ec602401e8bf2ae509f9fffaf3 openpi-umi/src/openpi/conftest.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/models/__init__.py
+7e42ada4ae7e9995f0ef3e33a0c224758323c2015e2d9d72ec15726a8a001d2a openpi-umi/src/openpi/models/gemma.py
+563c6e1ffd8afa31c406bcb8894a605e87df88f6c075d398d97a57af6bc3aefa openpi-umi/src/openpi/models/gemma_fast.py
+ced28716950c34d84a1a6d0b03b1d9550000732721df884818080b6e78cb3289 openpi-umi/src/openpi/models/lora.py
+a0f10525de7773310402b3ffa636e88ffff7035f3179b140aacc6809c122f085 openpi-umi/src/openpi/models/lora_test.py
+0d74bc1d8f4623ac3d8e543710b8bf75f9b95e588a3ebf6127c659e001385cff openpi-umi/src/openpi/models/model.py
+f8e71f195045d4e3ef1ddfafb2337fa52e5aa2f89bce1fde62f5cbfb67121f21 openpi-umi/src/openpi/models/model_test.py
+24b32d7c6ed5e409459afa8ca5af96a4dae09c2dcdf48e828907e411f4f12342 openpi-umi/src/openpi/models/pi0.py
+e15d71586f1a561b35c5651227607613fb16d2df411f3708b1c9d36b02544285 openpi-umi/src/openpi/models/pi0_config.py
+627332a555046f2744ef144c45f8bd3361a9820cf68854a4528d0fdbba7e9aa3 openpi-umi/src/openpi/models/pi0_fast.py
+5082873014a7fc45fb8414f517909e1c24cdafea980a1fb612e0aea6058ed0fe openpi-umi/src/openpi/models/pi0_test.py
+14b4df0be280d5769fb0dc31a40cde27525dbb1980cc998c28475d62fa3cad32 openpi-umi/src/openpi/models/siglip.py
+4eb8bd30360ebab22325e72ddad6f9ca192a87065f9ebda1239aaa953fd5acc5 openpi-umi/src/openpi/models/tokenizer.py
+5abd179ce883420e39d4d18b33d0123290af752da243003aa48a3bc06dbb9517 openpi-umi/src/openpi/models/tokenizer_test.py
+88866638ee4775f46a222561a957bd35e20600fe38c5888b587016ad77b1065f openpi-umi/src/openpi/models/utils/fsq_tokenizer.py
+d285d057636c3cba2d1fd3b37693b18075ad4b9c3b47bbde807c34c6c376ac93 openpi-umi/src/openpi/models/vit.py
+08fd8d750519f0fb44fc5173311e50a30f4c8f32c02e51244b4f8e47b32cd52f openpi-umi/src/openpi/models_pytorch/gemma_pytorch.py
+0c7b9f1de02ed886da49035e3fa1b38efea46eb6209489cb4f594f777f97b70c openpi-umi/src/openpi/models_pytorch/pi0_pytorch.py
+6a44e91be2d7a724c6140d2cc98ed0a631b8d38bbb29f63b380a0a19f903bbf6 openpi-umi/src/openpi/models_pytorch/preprocessing_pytorch.py
+26fd0d0f52730ab32b6f337eb73ae9a26cb71ae0915bc49eced1d0e2ed8d0ec6 openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py
+17eeb54e277939e58cd6f8a92719a275e36baf0c9f463b2754227d42f87aedde openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py
+c945d330b829264f927f3ee5339f977238631772de07a28e855e265bb85fd53c openpi-umi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py
+466e8eb7887ac5ccc98118a3169298d6ab65a284d834bae74751e3854dbc4245 openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py
+ef2e99500f263fdd78db9d4d9a255e29d844eb92f53c25ad640f8056700ef84b openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py
+50d7ad972d80142ecb0f03b0780dacfd3af212946f4c9aac31a204b02db4543d openpi-umi/src/openpi/policies/aloha_policy.py
+7d0893555964d485e231f70084125084a99495705ddd74b29461229d524fff26 openpi-umi/src/openpi/policies/droid_policy.py
+ad01e5be74516d9ec9aeb1f76294d5c9f7f7179a60f1f7fbbb35e7646534f81a openpi-umi/src/openpi/policies/libero_policy.py
+a2ac5236e23b11d0f5a840d4a8fef148d89dba921d5452ec5dfcd5a6ffa46f20 openpi-umi/src/openpi/policies/policy.py
+dc4202b420676ca9af61a141b1096dfd1efced635d06d4846e9a0537b8ded288 openpi-umi/src/openpi/policies/policy_config.py
+9dbb20963600367a7e7abfc97d1e326916777c57a87b39b1bc4070ba64676683 openpi-umi/src/openpi/policies/policy_test.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/py.typed
+1370d345e6c3c5b8f15573050e485e60a5b423d1df33e24b237805e6b442b026 openpi-umi/src/openpi/serving/websocket_policy_server.py
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 openpi-umi/src/openpi/shared/__init__.py
+6524945566eab3eb97b75a6280ba4724617b4d028c55f05172b283c3de68a026 openpi-umi/src/openpi/shared/array_typing.py
+8711d466cdaec488633e5509a000af6a7411b2d56f7ce6161f718f2389aa7786 openpi-umi/src/openpi/shared/download.py
+234ee70ab2501a1421f6c44cbd83c1e16747597023319ae1446bed9d44f17072 openpi-umi/src/openpi/shared/download_test.py
+0f8fcb355288119e56acb56d550c1cc1f3a9edddceb0dc5b319f955943ef7767 openpi-umi/src/openpi/shared/image_tools.py
+842374579dc9f4c2907da5e8bb555efe5a3f4902b659720c8e90115863dd59fe openpi-umi/src/openpi/shared/image_tools_test.py
+4da7111ba3011c4d1c381c9ed17257771df6a50ed89182647c3fb6f79208005e openpi-umi/src/openpi/shared/nnx_utils.py
+6c2cea4946fb07e51801530400d2b2fd94730e195cd290d6b6960114eca9739d openpi-umi/src/openpi/shared/normalize.py
+fda27a21cf37f337b12bcab71229407c2a349c5965c33f278bdc468ed03f58af openpi-umi/src/openpi/shared/normalize_test.py
+3cc32682ec3609e9075dabd991488edb9d7f6c045443f58963d733f99c468dbd openpi-umi/src/openpi/training/checkpoints.py
+38c5a1710c4910831bd10fd34324b880b98a63481d92af22ba3b88fdabd2a7f3 openpi-umi/src/openpi/training/config.py
+e0de9e5caa099edb37aa1d682bbf438cc3a3fae1aea50efd37a992571efcda83 openpi-umi/src/openpi/training/data_loader.py
+a0cf1bc293e8b0eb9bc5516bc05d30d9940da06c94fcfa1addca7267f8358815 openpi-umi/src/openpi/training/data_loader_test.py
+1d3a057a040240218234d7dbc6680ee4fe8256f2058531a0f9fefd3f7ee995a4 openpi-umi/src/openpi/training/droid_rlds_dataset.py
+c2ab92efb5e0d675118ad812113fd1c3cb3a62cdab5d79066014266e82df12d8 openpi-umi/src/openpi/training/misc/polaris_config.py
+914acdd74ccf90e6779c13a5093140595c7e4f687e9e0b167439446a81d74c01 openpi-umi/src/openpi/training/misc/roboarena_config.py
+603ee4ce4d5f727872840557004b047b7dccbcf86d86263558952bf617e6fd26 openpi-umi/src/openpi/training/optimizer.py
+c67c4112a126ab097571c8a882fd1ee3f106b15b6e608e7205ac7f29b44ca985 openpi-umi/src/openpi/training/sharding.py
+7b9a4b0b09b040cb88c9e99700f8d3a7cca129db08584edebd3b0f8558bae5d4 openpi-umi/src/openpi/training/umi_data.py
+60bce67368e855fec1d55bde128d32e90cfe07b82f57cdc1d639e3efda0dd1fd openpi-umi/src/openpi/training/umi_data_test.py
+9b67c127451104e37535581c40870e43bd502da4e5f1bfc0da98f36dbf427472 openpi-umi/src/openpi/training/umi_v3_dataset.py
+9893f2a84147b938df4508e6a930c278ce4366c093e37585b1e5e0d1a11f9448 openpi-umi/src/openpi/training/umi_v3_dataset_test.py
+b684e674343f86ef5e976f279a586d3fe2f885e901f396ac899ed136abc7eca6 openpi-umi/src/openpi/training/utils.py
+a54ac3222f81f8c6233241bc16b6f369c9416cdaa83f7058f96f7ddcfde1a3b4 openpi-umi/src/openpi/training/weight_loaders.py
+707425a385306ca6debd01dbaa0323a6214db56d101830114d97c6af9e944c4d openpi-umi/src/openpi/transforms.py
+d76f3ee8c5d7dc1c6fb6cb3b36b45ef30dd1de1ab5bc054bcb03deb79dcc06a8 openpi-umi/src/openpi/transforms_test.py
+5e3a9a0a12d9a6048afea5591f4520c98585499cbd4a8343dcabfe2aaed94e3d openpi-umi/uv.lock
+64eee33af95370863538323cfa58013adb4242ed5e91722e9d2ee1b6c2e19f09 scripts/mock_roundtrip.py
+62ee3cdc906e4c4f6a5f61380ed008122fb578ac3e8881685900548f2daed5de scripts/run_flux_server.sh
+5329fa1de87f2bf0ca6f07ae47dc5ff3de227f285add740271e6de85d26553d5 scripts/run_pi05_server.sh
+4899458d570b0b56eaf029cbe47175a6cede66d820ed09290c010f807159d604 scripts/run_robot.sh
+d5882b05e35e5ef1623c904e1620ec0d37aa1287ef5113cf6cf95abc8e85882f scripts/test_release_assets.py
+f0efd493273087599d3e02d6f4dd59ceef6139bf115cc9a8f54cecc307ebe898 scripts/verify_assets.py
diff --git a/configs/inference.env.example b/configs/inference.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..182e3adc6f6fa6e808a516360b963ac175abe9e1
--- /dev/null
+++ b/configs/inference.env.example
@@ -0,0 +1,24 @@
+# Copy to a PRIVATE file and source it in the matching environment.
+# Never distribute the filled file, credentials, device serials or runtime recordings.
+FLUX_EXPORT_DIR=/path/to/checkpoints/flux_fold_clothes_bf16
+FLUX_RESOURCES=/path/to/flux_resources
+PI05_CHECKPOINT_DIR=/path/to/checkpoints/pi05_fold_clothes/epoch_2
+TOKENIZER_DIR=/path/to/tokenizer_root
+UMI_INFER_DATA=/path/to/cell_data
+TASK_PROMPT="fold the clothes"
+SERVER_URI=ws://127.0.0.1:8765
+SERVER_HOST=127.0.0.1
+SERVER_PORT=8765
+DEVICE=cuda:0
+# Explicit reference settings. They mirror this source's CLI defaults, not a verified video recipe.
+FLUX_SAMPLER=euler
+FLUX_STEPS=4
+FLUX_SHIFT=42
+FLUX_GUIDANCE=1.0
+FLUX_ACTION_GUIDANCE=1.0
+FLUX_SEED=0
+PI05_DENOISE_STEPS=10
+# Optional Python executables for separate environments:
+#FLUX_PYTHON=/path/to/flux_env/bin/python
+#PI05_PYTHON=/path/to/pi05_env/bin/python
+#ROBOT_PYTHON=/path/to/robot_env/bin/python
diff --git a/docs/CHECKPOINTS_FLUX.md b/docs/CHECKPOINTS_FLUX.md
new file mode 100644
index 0000000000000000000000000000000000000000..6133334ae228d9a601d3153c20a9c9414bfbf7a8
--- /dev/null
+++ b/docs/CHECKPOINTS_FLUX.md
@@ -0,0 +1,38 @@
+# Cloth-folding inference checkpoint
+
+The following inventory was provided by the model owner. Weight bytes and the remote manifest/config have not been independently downloaded or validated during this documentation update. Internal job IDs, experiment names, bucket names and training-storage paths are intentionally omitted from this public document.
+
+## Provided export
+
+```text
+checkpoints/flux_fold_clothes_bf16/
+ config.json
+ manifest.json
+ model.safetensors
+```
+
+- Format: already exported inference policy, BF16; **do not export it again merely to run inference**.
+- Selected checkpoint: step 14418, model weights (not asserted to be EMA).
+- Reported weight-file size: 13,894,466,592 bytes.
+- Earlier training checkpoints at steps 4806 and 9612 were reported in training storage; only the final step was reported in the supplied remote export.
+- The 16-GPU training template in this source archive is not evidence of this checkpoint's exact training configuration. The supplied experiment label suggests a different worker/window/epoch setup; obtain the actual train configuration rather than treating that template as the rollout recipe.
+
+## Loading
+
+`flux-action infer` accepts this **export directory**, not a raw training `step-N` directory. `FluxActionPolicy.from_pretrained` reads the policy config and verifies the manifest against config/model bytes. Keep the three files together; if any file is changed, a matching manifest must be generated by the proper export path.
+
+The supplied inventory lists only policy weights/config/manifest. The VAE and text encoder are separate requirements of the policy code. Resolve the locations referenced by `config.json` and verify that they are accessible in the inference environment. A policy-weight export alone does not establish that encoder assets are bundled.
+
+Read sampler, num_inference_steps, guidance_scale, guidance_scale_action and sampler_shift from the actual export config; do not replace them with guessed settings from a training template. The model owner reports this export as ready for inference; the current source still validates those fields at load/inference time.
+
+Once the matching environment, encoder assets and a correctly prepared UMI observation NPZ are available:
+
+```bash
+flux-action infer --checkpoint /path/to/checkpoints/flux_fold_clothes_bf16 --observation /path/to/umi_observation.npz --task "fold the clothes" --output /path/to/new_inference_output --device cuda
+```
+
+The NPZ must use the export's camera keys and 20-D UMI relative state; a raw 16-D pose is not the model state. A UMI robot adapter must restore anchor-relative action chunks and handle robot coordinates/grippers. This command is a documented interface, not a new runtime validation of the remote weights.
+
+## Weight release checks
+
+Before distributing the actual checkpoint, inspect config strings for internal encoder/checkpoint paths. Changing `config.json` to portable locations requires regenerating its manifest hash; silently editing config while retaining the old manifest will fail integrity checks. This documentation update does not modify or redistribute the remote weights.
diff --git a/docs/CHECKPOINTS_PI05.md b/docs/CHECKPOINTS_PI05.md
new file mode 100644
index 0000000000000000000000000000000000000000..4ae7c1ea611886bb0bd77cc0ecd1decf731a40ad
--- /dev/null
+++ b/docs/CHECKPOINTS_PI05.md
@@ -0,0 +1,48 @@
+# π0.5 cloth-folding inference checkpoint
+
+This inventory was supplied by the model owner. Remote model bytes and metadata have not been downloaded or executed during this documentation update. Public paths below are neutral examples; internal job IDs, experiment names and storage addresses are omitted.
+
+## Provided checkpoint
+
+```text
+checkpoints/pi05_fold_clothes/epoch_2/
+ model.safetensors
+ metadata.pt
+ assets/umi_v3/norm_stats.json
+```
+
+- Model/config family: π0.5, `pi05_umi_v3`.
+- Selected checkpoint: epoch 2; epoch 1 was also reported in training storage, but only epoch 2 was reported in the supplied remote location.
+- Reported model-file size: 7,473,091,464 bytes.
+- `optimizer.pt` is not in the reported copy. Its absence does **not** prevent inference; it does prevent an exact optimizer-state training resume from that copy alone.
+- Use `assets/umi_v3/norm_stats.json` from this checkpoint. Do not replace it with statistics recomputed from the one-hour sample.
+- `metadata.pt` is supplied for checkpoint metadata; the generic `create_trained_policy` PyTorch path is driven by the training/model config, safetensors weights and normalization statistics. It does not require loading optimizer state for inference.
+
+## Training information and provenance
+
+The supplied experiment label indicates 16 workers, global batch 1280 (80 per worker), 2 epochs, action horizon 50, peak LR 7.5e-5, zero warmup, a 1.5-epoch hold and linear cooldown. These are label-derived details, not a replacement for the saved run configuration. Confirm them against the run configuration before presenting them as a fully reproduced experiment.
+
+The existing shell launcher is single-node. The README's 8-worker command is a portable example, not the reported 16-worker run. Do not present it as the exact multi-node launch used for the video.
+
+## Policy construction
+
+Prepare the patched transformers environment described in the main README. With a compatible runtime, the generic loading interface is:
+
+```python
+from pathlib import Path
+from openpi.policies import policy_config
+from openpi.training import config as training_config
+
+checkpoint = Path("/path/to/checkpoints/pi05_fold_clothes/epoch_2")
+config = training_config.get_config("pi05_umi_v3")
+data_config = config.data.create(config.assets_dirs, config.model)
+policy = policy_config.create_trained_policy(
+ config,
+ checkpoint,
+ repack_transforms=data_config.repack_transforms,
+ norm_stats_path=checkpoint / "assets/umi_v3/norm_stats.json",
+ pytorch_device="cuda",
+)
+```
+
+This illustrates the existing API and explicit UMI repack/statistics wiring. It has not been run against the remote weights. `policy.infer` still needs both wrist images, previous/current 16-D pose states, and the prompt in the agreed observation schema. It returns a model-space action chunk, not directly executable Flexiv commands. A robot adapter must preserve the per-chunk anchors and restore absolute target poses with the correct calibration and gripper units.
diff --git a/docs/INFERENCE_CONTRACT.md b/docs/INFERENCE_CONTRACT.md
new file mode 100644
index 0000000000000000000000000000000000000000..bd1b9378b5b30fe3e3a880772f23af1a5ed10bff
--- /dev/null
+++ b/docs/INFERENCE_CONTRACT.md
@@ -0,0 +1,16 @@
+# Input/output and frame contract
+
+Robot IO reads both wrists and two proprio frames `[previous,current]`, one native model frame apart in executed progress. Wire poses are `[x,y,z,qx,qy,qz,qw]`; Flexiv native poses are wxyz and the IO handles that boundary. The dataset is a camera optical-frame pose, not automatically a robot flange pose.
+
+For each hand, E = inverse(T_flange_camera):
+
+- Model camera input: `T_world_camera = T_world_flange @ inverse(E)`.
+- Relative training state: `inverse(T_current_camera) @ T_previous_camera`, current gripper.
+- Relative target: `inverse(T_current_camera) @ T_future_camera`.
+- Robot target: `T_current_camera @ T_predicted_relative @ E`.
+
+20 dimensions total: each hand uses translation3 + first-two-rotation-columns6 + gripper1. Raw pose buffers are16 dimensions, wxyz, metres, gripper degrees; they must be encoded. Anchor each chunk using the same current pose captured when its observation was made. No cross-hand common SLAM world frame is assumed by the training input.
+
+FLUX uses32 steps /30Hz and both wrist images. π0.5 uses50 model steps with a32-D model head padded from20-D UMI targets; its adapter returns20-D actions and restores absolute camera poses, then flange poses. Optional upsampling changes sample count/dt; robot-side playback scaling changes wall time without redefining the model's previous/current state contract. Local servo cadence is separate from request cadence.
+
+This sample's Observation/Action msgpack protocol is defined in `flexiv-umi-infer/umi_infer/protocol.py`. Generic OpenPI clients use a different wire envelope. Use the provided robot_agent and policy_server together.
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
new file mode 100644
index 0000000000000000000000000000000000000000..a2c6b3db50af4465f093ebe8c47ed1087c02b311
--- /dev/null
+++ b/docs/VALIDATION.md
@@ -0,0 +1,3 @@
+# 验证范围
+
+源码已完成语法检查、离线接口与记录测试、配置资产检查及mock协议往返验证。实际部署需结合模型资源、设备环境及标定进行集成验证。
diff --git a/docs/validation.json b/docs/validation.json
new file mode 100644
index 0000000000000000000000000000000000000000..0776768139a976154d6843f0d5cd2b68abeb7921
--- /dev/null
+++ b/docs/validation.json
@@ -0,0 +1,18 @@
+{
+ "python_syntax_files": 245,
+ "shell_syntax_files": 5,
+ "forbidden_matches": [],
+ "git_entries": [],
+ "urdf_sha256": "6d05cf21d13cf85ad7fcede2fb4eb615052d616341f1065b59caf41f9a749398",
+ "omitted_display_media": [
+ "flux-umi/docs/assets/flux-3-action-hero.webp",
+ "flux-umi/examples/games/assets/grunt_step3000.gif",
+ "flux-umi/examples/games/assets/vector_step3000.gif"
+ ],
+ "offline_tests_passed": 8,
+ "asset_preflight_tests_passed": 2,
+ "in_process_roundtrips_passed": 3,
+ "real_weights_loaded": false,
+ "hardware_tested": false,
+ "full_flux_model_test_suite_run": false
+}
\ No newline at end of file
diff --git a/flexiv-umi-infer/.gitignore b/flexiv-umi-infer/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..66900674cf74250e095322c6c6e6e6ab44d6918e
--- /dev/null
+++ b/flexiv-umi-infer/.gitignore
@@ -0,0 +1,10 @@
+__pycache__/
+*.pyc
+.pytest_cache/
+*.egg-info/
+cell.env
+data/*
+!data/.gitkeep
+rollouts/
+tools/insta360_cli_dual
+weights/
diff --git a/flexiv-umi-infer/LICENSE b/flexiv-umi-infer/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/flexiv-umi-infer/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/flexiv-umi-infer/README.md b/flexiv-umi-infer/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..462c1e9f28546fbb87d75b3c045535b968b8290b
--- /dev/null
+++ b/flexiv-umi-infer/README.md
@@ -0,0 +1,308 @@
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+# flexiv-umi-infer · 双臂UMI实机推理
+
+用于Flexiv Rizon4双臂平台,配置两台Insta360 X4 Air腕载相机及两只达妙电机夹爪。支持[OpenPI / π0.5](../openpi-umi)、[FLUX](../flux-umi)或mock策略。包含名义双臂URDF,不含权重、数据集、mesh及现场标定;使用入口见[上级说明](../README.md)。
+
+## 工作方式
+
+机器人电脑运行`robot_agent`与Flexiv IO,GPU机器运行`policy_server`。双方通过WebSocket传输msgpack消息(`umi_infer/protocol.py`):Observation包括两路腕相机、前一帧/当前帧TCP位姿及夹爪;Action包括法兰位姿块、夹爪开度及dt。机器人本地伺服线程为100Hz。
+
+- 默认同步推理:执行完一个动作块后,采集新观测并请求下一块。
+- IK由Flexiv控制器执行;IO使用`NRT_CARTESIAN_MOTION_FORCE`下发世界系TCP位姿,`Model.reachable`仅作预检查。
+- 数据位姿属于腕相机光学系。每臂外参`E = inv(T_flange_cam)`;输入`T_cam = T_flange @ E^-1`,输出`T_flange = T_cam @ E`。
+- 观测中的`[prev, cur]`相隔一个原生模型帧(1/30秒);这里指已执行进度,不是墙钟时间。
+- 默认回放时间缩放为2.5倍,以满足控制器加速度限制,不改变模型dt或状态含义。
+
+## 代码结构
+
+| 路径 | 职责 |
+| --- | --- |
+| umi_infer/policy_server.py | 策略创建与WebSocket服务 |
+| umi_infer/robot_agent.py | 机器人控制循环 |
+| umi_infer/protocol.py | Observation / Action消息 |
+| umi_infer/policies/ | π0.5、FLUX和mock策略 |
+| umi_infer/codec/ | π0.5推理、相对动作解码、样条上采样 |
+| umi_infer/robot_io/flexiv.py | 双臂预检查、伺服线程与记录 |
+| umi_infer/robot_io/insta_live.py | CameraSDK CLI → FIFO → ffmpeg相机流 |
+| umi_infer/robot_io/gripper_can.py、gripper_tool.py | 夹爪伺服与CAN扫描/读取/标定 |
+| umi_infer/robot_io/rollout_rec.py | 逐帧rollout记录 |
+| urdf/flexiv_rizon4_dual_umi.urdf | 默认双臂名义URDF |
+| umi_infer/export_E.py | 从URDF导出左右E及来源记录 |
+| umi_infer/check_cam.py | 相机自检 |
+| tools/insta360_cli_dual.cc | 相机CLI,构建见[tools说明](tools/README.md) |
+
+## 安装与配置
+
+机器人电脑安装`.[robot]`;GPU环境按策略分别安装`.[pi05]`与相邻OpenPI项目,或`.[flux]`与相邻FLUX项目。Flexiv SDK另行安装:`flexivdrdk`需配合`flexivrdk` 1.9.x,2.x在`RobotPair.states()`存在崩溃问题;必须先导入flexivrdk。每台机器人仅接受一个RDK连接,运行前关闭其他连接。
+
+复制`configs/cell.env.example`为私有配置,填写机械臂与相机序列号、`UMI_INFER_DATA`(默认`data/`),再用`set -a; source cell.env; set +a`加载。标定目录需包含:
+
+| 文件 | 生成方式 |
+| --- | --- |
+| E_left.npy、E_right.npy、E_from_urdf.json | `python -m umi_infer.export_E`,URDF每次变化均需重导 |
+| gripper_calib.json | `python -m umi_infer.robot_io.gripper_tool calib --motor 0:8 --motor 1:8 --yes` |
+| anchor.json | 按实际起始姿态填写configs/anchor.example.json |
+
+CANalyst-II通道0为左臂、通道1为右臂;电机命令ID为0x08、反馈ID为0x18。`gripper_tool scan`扫描电机,`--help`提供udev访问说明。
+
+名义URDF由立柱悬挂的Rizon4/Rizon4R、FT03腕传感器和UMI夹爪构成,基座y=±0.25m,世界原点在法兰之间。机械臂mesh引用`package://flexiv_description/...`;夹爪只包含相机、TCP和指尖运动学坐标。相机外参为CAD值;使用实测运动学或手眼标定时,保留link名称并通过`FLEXIV_URDF`指定现场URDF。`E_from_urdf.json`记录CAD或标定来源。起始姿态应使腕相机视角接近训练episode起点。
+
+## 运行命令
+
+以下依次为安装、自检、GPU服务、机器人dry run、实机运行与测试命令;两种模型使用独立环境。
+
+```
+robot PC GPU box
+robot_agent ── Observation (2 wrist images, ──────> policy_server
+ FlexivRobotIO [prev, cur] TCP poses, grippers) pi05 | flux | mock
+ 100 Hz servo <─────── Action (chunk of flange ───
+ thread poses + gripper openings, dt)
+```
+
+```bash
+# robot PC (needs Flexiv flexivrdk 1.9.x + flexivdrdk, installed separately)
+pip install -e ".[robot]"
+# GPU box
+pip install -e ".[pi05]" && pip install -e ../openpi-umi # π0.5
+pip install -e ".[flux]" && pip install -e ../flux-umi # FLUX
+```
+
+```bash
+# 0. checks
+python -m umi_infer.check_cam --dataset /data/umi_v3/episode_0000 # both cameras, compare with training
+python -m umi_infer.robot_io.gripper_tool read --motor 0:8 --motor 1:8 # motors stay disabled; move the jaws by hand
+
+# 1. policy server (GPU box)
+python -m umi_infer.policy_server --policy pi05 --checkpoint-dir /ckpt/run/epoch_2 \
+ --eef-extrinsic-left data/E_left.npy --eef-extrinsic-right data/E_right.npy --prompt "fold the clothes"
+python -m umi_infer.policy_server --policy flux --flux-export /ckpt/flux_export \
+ --flux-resources /ckpt/flux_resources --flux-e-left data/E_left.npy --flux-e-right data/E_right.npy \
+ --flux-e-provenance data/E_from_urdf.json --flux-prompt "fold the clothes" \
+ --flux-sampler euler --flux-steps 4 --flux-shift 42 --flux-guidance 1.0 --flux-action-guidance 1.0
+
+# 2. robot agent (robot PC), dry run first: full pipeline, no motion commands
+python -m umi_infer.robot_agent --io flexiv --live-camera --server ws://127.0.0.1:8765 \
+ --record /tmp/run.csv
+# 3. live, with grippers. Keep a hand on the e-stop.
+python -m umi_infer.robot_agent --io flexiv --live-camera --live --gripper --server ws://127.0.0.1:8765
+```
+
+```bash
+pip install -e ".[mock,dev]"
+python -m pytest tests/test_flexiv_trace.py tests/test_rollout_rec.py # no hardware needed
+python -m pytest tests/test_flux_action_dual.py # needs torch + flux-umi
+```
+
+π0.5默认从`gs://big_vision`加载PaliGemma tokenizer;离线机器应通过`TOKENIZER_DIR`提供包含`paligemma-3b-pt-224/tokenizer.model`的目录。FLUX机器人端增加`--cam-format yuv420p --cam-kbps 30720`,由策略端按训练同样的PyAV路径将I420转RGB。服务默认绑定127.0.0.1,跨机器运行时设置`--host 0.0.0.0`。无硬件时使用`--policy mock`与`--io mock`。
+
+常用机器人参数:`--play-scale`(默认2.5)、`--first-steps`/`--steps`(执行每块前N步)、`--kx-ratio`(笛卡尔刚度)、`--nullspace-weight`(肘部刚度)、`--grip-offset-deg`(调整夹爪角度)。
+
+## 控制保护与约定
+
+| 保护 | 说明 |
+| --- | --- |
+| Dry run | 未指定--live时只作预检查与插值,不下发动作 |
+| 自碰撞监测 | SelfCollisionMonitor按link距离检查并停止双臂,不包含夹爪 |
+| 工具预检查 | 按夹爪点间距检查,参数--tool-min-dist |
+| 逐周期保护 | 故障、外部控制模式切换和TCP间距--min-dist |
+| 动作块检查 | 有限值、最大步长--max-step-mm、可达性--ik-check |
+| 关节限位 | 起始姿态距硬限位至少0.5° |
+| 夹爪力限制 | 目标角度限制在实测角度±lead,扭矩≤kp×lead |
+
+距离阈值默认2cm,新平台需调整;夹爪约超出法兰16cm,不包含在自碰撞模型中。进入力控前本次会话清零腕F/T传感器,否则可能出现Flexiv错误301004。
+
+`RobotPair.states().tcp_pose`与`SendCartesianMotionForce`共用世界系;TCP为法兰,控制器不设置工具偏移。Flexiv四元数为wxyz,传输为xyzw,仅在`_w2x`/`_x2w`转换。夹爪以度表示,0闭合、90全开;DRDK机械臂顺序均为(left,right)。
+
+## 记录、测试与许可
+
+`--record run.csv`记录每个伺服tick的命令/实测位姿,`run.chunks.jsonl`记录模型输出与预检查。未指定`--no-rollout`时,在`--rollout-root`下记录伺服频率低维数据与腕相机帧。服务器`--record-dir`保存收到的图像及逐次推理记录,双方通过seq关联。离线轨迹/记录测试不需要硬件;FLUX策略测试需要torch及flux-umi。
+
+许可证为Apache-2.0;Flexiv RDK、CameraSDK、OpenPI和FLUX保留各自许可。采样参数可在启动脚本中按模型与任务配置。名义URDF相机外参与rollout在1e-6内一致,但整文件哈希不同,现场完整运动学需核对。运行记录中的设备标识、时间与路径需在外发前清理。
+
+---
+
+
+
+# flexiv-umi-infer
+
+Real-robot inference for bimanual UMI policies on a Flexiv Rizon4 dual-arm cell with two Insta360 X4 Air
+wrist cameras and two Damiao-motor grippers. It runs policies trained with
+[openpi-umi](../openpi-umi) (π0.5) or [flux-umi](../flux-umi) (FLUX 3 Action).
+
+The nominal dual-arm URDF is included. Model weights, datasets, mesh assets and per-cell calibration files are not included. See the [installation and deployment guide](../README.md) for environments, model resources and launch scripts.
+
+## How it works
+
+Two processes talk over a websocket (msgpack, `umi_infer/protocol.py`):
+
+```
+robot PC GPU box
+robot_agent ── Observation (2 wrist images, ──────> policy_server
+ FlexivRobotIO [prev, cur] TCP poses, grippers) pi05 | flux | mock
+ 100 Hz servo <─────── Action (chunk of flange ───
+ thread poses + gripper openings, dt)
+```
+
+- **Sync inference (default).** The agent executes the whole chunk, takes a fresh observation and asks
+ for the next chunk, so the policy always plans from the current state.
+- **IK runs in the Flexiv controller.** The IO switches to `NRT_CARTESIAN_MOTION_FORCE` and streams
+ world-frame TCP poses. `flexivrdk.Model.reachable` is only used as a precheck before sending.
+- **Data frame vs. robot frame.** The dataset end effector is the wrist camera optical frame. The policy
+ side maps it to the flange with a per-arm extrinsic `E = inv(T_flange_cam)`:
+ inputs `T_cam = T_flange @ E^-1`, outputs `T_flange = T_cam @ E`.
+- **Motion window.** The observation carries two real proprio frames `[prev, cur]`, one native frame
+ (1/30 s) apart. "One frame" means executed progress, not wall-clock time, so slow playback does not
+ change what the model sees.
+- **Playback scale.** Each step is stretched on the wall clock (default 2.5×) so that model trajectories
+ stay within the controller's acceleration limits. `dt` and the state are unchanged.
+
+## Layout
+
+| Path | Contents |
+|---|---|
+| `umi_infer/policy_server.py` | websocket server, builds the policy |
+| `umi_infer/robot_agent.py` | control loop on the robot PC |
+| `umi_infer/protocol.py` | Observation / Action messages |
+| `umi_infer/policies/` | `umi_pi05_dual.py` (π0.5), `flux_action_dual.py` (FLUX), `mock.py` |
+| `umi_infer/codec/` | π0.5 inference core, relative-action decoding, spline upsampling |
+| `umi_infer/robot_io/flexiv.py` | Flexiv dual-arm IO: prechecks, servo thread, recording |
+| `umi_infer/robot_io/insta_live.py` | live wrist camera streams (CameraSDK CLI → fifo → ffmpeg) |
+| `umi_infer/robot_io/gripper_can.py`, `gripper_tool.py` | gripper servo and CAN tool (scan / read / calib) |
+| `umi_infer/robot_io/rollout_rec.py` | per-frame rollout recording |
+| `urdf/flexiv_rizon4_dual_umi.urdf` | default dual-arm URDF |
+| `umi_infer/export_E.py` | exports `E_left.npy` / `E_right.npy` from the URDF |
+| `umi_infer/check_cam.py` | camera self-check |
+| `tools/insta360_cli_dual.cc` | camera CLI source ([build](tools/README.md)) |
+
+## Install
+
+```bash
+# robot PC (needs Flexiv flexivrdk 1.9.x + flexivdrdk, installed separately)
+pip install -e ".[robot]"
+# GPU box
+pip install -e ".[pi05]" && pip install -e ../openpi-umi # π0.5
+pip install -e ".[flux]" && pip install -e ../flux-umi # FLUX
+```
+
+`flexivdrdk` must be paired with `flexivrdk` 1.9.x (2.x segfaults in `RobotPair.states()`). The code
+imports `flexivrdk` before `flexivdrdk`, which the bindings require. A robot accepts only one RDK
+connection at a time, so close Flexiv Elements sessions and other scripts first.
+
+## Configuration
+
+Copy `configs/cell.env.example` to `cell.env`, fill it in and load it with `set -a; source cell.env; set +a`.
+It sets the arm serials, the camera serials and the data directory (`UMI_INFER_DATA`,
+default `data/`). The data directory holds:
+
+| File | How to make it |
+|---|---|
+| `E_left.npy`, `E_right.npy`, `E_from_urdf.json` | `python -m umi_infer.export_E` (rerun after every URDF change) |
+| `gripper_calib.json` | `python -m umi_infer.robot_io.gripper_tool calib --motor 0:8 --motor 1:8 --yes` |
+| `anchor.json` | copy `configs/anchor.example.json` and fill in the start posture |
+
+Grippers: CANalyst-II channel 0 = left arm, channel 1 = right arm, motor command ID 0x08 (feedback 0x18).
+Run `gripper_tool scan` to find the motors, and `gripper_tool --help` for udev setup without sudo.
+
+`urdf/flexiv_rizon4_dual_umi.urdf` is the default model: two Rizon4/Rizon4R arms with FT03 wrist sensors,
+hung from a column (bases at y = ±0.25 m, world origin between the flanges), each with a UMI gripper.
+It uses the nominal Flexiv kinematics. Arm meshes are referenced as `package://flexiv_description/...`
+([flexiv_description](https://github.com/flexivrobotics/flexiv_description)); the gripper has kinematic
+frames only (`grip_camera_optical_frame`, `grip_tcp_link`, fingertips), which is all inference needs. The
+camera pose is the CAD value. For per-robot kinematics or a hand-eye calibrated camera, build your own URDF
+with the same link names and point `FLEXIV_URDF` at it (`export_E` records CAD vs. calibrated in
+`E_from_urdf.json`).
+
+The start posture decides what the model sees first, so pick one where the wrist views look like the
+start of your training episodes.
+
+## Run
+
+```bash
+# 0. checks
+python -m umi_infer.check_cam --dataset /data/umi_v3/episode_0000 # both cameras, compare with training
+python -m umi_infer.robot_io.gripper_tool read --motor 0:8 --motor 1:8 # motors stay disabled; move the jaws by hand
+
+# 1. policy server (GPU box)
+python -m umi_infer.policy_server --policy pi05 --checkpoint-dir /ckpt/run/epoch_2 \
+ --eef-extrinsic-left data/E_left.npy --eef-extrinsic-right data/E_right.npy --prompt "fold the clothes"
+python -m umi_infer.policy_server --policy flux --flux-export /ckpt/flux_export \
+ --flux-resources /ckpt/flux_resources --flux-e-left data/E_left.npy --flux-e-right data/E_right.npy \
+ --flux-e-provenance data/E_from_urdf.json --flux-prompt "fold the clothes" \
+ --flux-sampler euler --flux-steps 4 --flux-shift 42 --flux-guidance 1.0 --flux-action-guidance 1.0
+
+# 2. robot agent (robot PC), dry run first: full pipeline, no motion commands
+python -m umi_infer.robot_agent --io flexiv --live-camera --server ws://127.0.0.1:8765 \
+ --record /tmp/run.csv
+# 3. live, with grippers. Keep a hand on the e-stop.
+python -m umi_infer.robot_agent --io flexiv --live-camera --live --gripper --server ws://127.0.0.1:8765
+```
+
+π0.5 loads the PaliGemma tokenizer from `gs://big_vision` unless `TOKENIZER_DIR` points at a directory
+containing `paligemma-3b-pt-224/tokenizer.model` (set it on offline machines).
+
+For FLUX add `--cam-format yuv420p --cam-kbps 30720` to the agent: raw I420 planes are converted to RGB on
+the policy side with the same pyav call as training. The server binds `127.0.0.1` by default; pass
+`--host 0.0.0.0` when the agent runs on another machine.
+
+Without hardware, `--policy mock` and `--io mock` exercise the whole loop.
+
+Useful agent options: `--play-scale` (default 2.5), `--first-steps` / `--steps` (execute only the first N
+steps of each chunk), `--kx-ratio` (Cartesian stiffness), `--nullspace-weight` (elbow stiffness),
+`--grip-offset-deg` (subtract from model gripper openings so grasps saturate the force clamp).
+
+## Safety
+
+All protections are on by default and must be disabled explicitly.
+
+| Layer | Mechanism |
+|---|---|
+| Dry run | default without `--live`: prechecks and interpolation run, nothing is sent |
+| Self-collision monitor | Flexiv `SelfCollisionMonitor`, link to link, stops both arms (`--monitor-min-dist`). It does not see the gripper. |
+| Tool-aware precheck | arm-to-arm distance between gripper points before a chunk is sent (`--tool-min-dist`) |
+| Per-cycle guard | fault, control mode changed externally, measured TCP-to-TCP distance (`--min-dist`) |
+| Chunk prechecks | finite values, max step jump (`--max-step-mm`), vendor reachability (`--ik-check`) |
+| Joint limit margin | the start posture must stay ≥ 0.5° inside the hardware limits |
+| Gripper force bound | target angle stays within measured ± lead, so torque ≤ kp × lead |
+
+The distance thresholds default to 2 cm. Raise them for a new cell. The gripper reaches about 16 cm past
+the flange, and the monitor's collision model does not include it. Before entering force-control modes
+the IO zeroes the wrist F/T sensors in the current session (Flexiv error 301004 otherwise).
+
+## Conventions
+
+| | |
+|---|---|
+| world frame | `RobotPair.states().tcp_pose` and `SendCartesianMotionForce` share one frame |
+| TCP | the flange; no tool offset is configured in the controller |
+| quaternions | Flexiv is `wxyz`, the wire protocol is `xyzw`. The IO converts only in `_w2x` / `_x2w` |
+| gripper | dataset degrees, 0 = closed, 90 = fully open |
+| arm order | every DRDK call takes `(left, right)` |
+
+## Recording
+
+With `--record run.csv` the agent writes commanded vs. measured poses per servo tick and
+`run.chunks.jsonl` with the model output and precheck results of each chunk. Unless `--no-rollout` is
+given, `robot_io/rollout_rec.py` also records the run under `--rollout-root`: low-dimensional data at
+the servo rate, plus wrist frames. The server's `--record-dir` saves the received images and one line
+per inference. Both sides join on `seq`.
+
+## Tests
+
+```bash
+pip install -e ".[mock,dev]"
+python -m pytest tests/test_flexiv_trace.py tests/test_rollout_rec.py # no hardware needed
+python -m pytest tests/test_flux_action_dual.py # needs torch + flux-umi
+```
+
+## License
+
+Apache-2.0. Flexiv RDK, the Insta360 CameraSDK, openpi and FLUX 3 Action keep their own licenses.
+
+## Runtime configuration
+
+Set FLUX sampler parameters through the launch script for your model and task. The bundled URDF matches the rollout camera extrinsic numbers within 1e-6, but its full SHA-256 differs from the recorded URDF fingerprint; verify full kinematics for your cell. Runtime recordings include local device identifiers, timestamps and paths; remove private metadata before sharing them.
diff --git a/flexiv-umi-infer/configs/anchor.example.json b/flexiv-umi-infer/configs/anchor.example.json
new file mode 100644
index 0000000000000000000000000000000000000000..31c1c8f7a90834b75d93741966fdec1ce074c098
--- /dev/null
+++ b/flexiv-umi-infer/configs/anchor.example.json
@@ -0,0 +1,7 @@
+{
+ "note": "Start posture used by the robot agent. Copy to data/anchor.json and fill in your own values. Joint angles in degrees (7 per arm); gripper opening in dataset degrees (0 = closed, 90 = fully open). Keep every joint at least 0.5 deg away from the hardware limits, or the controller rejects the null-space posture.",
+ "left": [null, null, null, null, null, null, null],
+ "right": [null, null, null, null, null, null, null],
+ "left_grip": 0.0,
+ "right_grip": 0.0
+}
diff --git a/flexiv-umi-infer/configs/cell.env.example b/flexiv-umi-infer/configs/cell.env.example
new file mode 100644
index 0000000000000000000000000000000000000000..2852927f008c652b4e87fd36dda8d84307378efe
--- /dev/null
+++ b/flexiv-umi-infer/configs/cell.env.example
@@ -0,0 +1,26 @@
+# Per-cell configuration. Copy to cell.env, fill in, then `set -a; source cell.env; set +a`.
+
+# Flexiv arms (serial numbers as shown in Flexiv Elements)
+FLEXIV_LEFT_SN=
+FLEXIV_RIGHT_SN=
+# Dual-arm URDF (default: urdf/flexiv_rizon4_dual_umi.urdf)
+#FLEXIV_URDF=
+# Joint prefix of each arm inside the URDF (default: "left_" / "right_")
+#FLEXIV_URDF_PREFIX_LEFT=
+#FLEXIV_URDF_PREFIX_RIGHT=
+# Arm base translations in the shared world frame [m]
+#FLEXIV_BASE_XYZ={"left": [0.0, -0.25, 0.0], "right": [0.0, 0.25, 0.0]}
+# Gripper rigid points used by the tool-aware arm-to-arm distance check (URDF link names)
+#FLEXIV_TOOL_LINKS=flange,grip_base_link,grip_camera_link,grip_tcp_link,grip_left_fingertip_link,grip_right_fingertip_link
+
+# Insta360 wrist cameras: body serial per arm and which fisheye half faces the workspace
+INSTA360_LEFT_SN=
+INSTA360_RIGHT_SN=
+INSTA360_LEFT_HALF=right
+INSTA360_RIGHT_HALF=right
+# Directory with the Insta360 CameraSDK shared libraries; patched CLI (see tools/README.md)
+INSTA360_SDK_LIB=
+#INSTA360_CLI=tools/insta360_cli_dual
+
+# Per-cell data: anchor.json, gripper_calib.json, E_left.npy, E_right.npy, E_from_urdf.json
+UMI_INFER_DATA=data
diff --git a/flexiv-umi-infer/data/.gitkeep b/flexiv-umi-infer/data/.gitkeep
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/flexiv-umi-infer/pyproject.toml b/flexiv-umi-infer/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..cd8ae94ff89c5bb42b2e748525a4d06e37d62d2a
--- /dev/null
+++ b/flexiv-umi-infer/pyproject.toml
@@ -0,0 +1,24 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[project]
+name = "flexiv-umi-infer"
+version = "0.1.0"
+description = "Real-robot inference for bimanual UMI policies (pi0.5 / FLUX 3 Action) on a Flexiv Rizon4 dual-arm cell"
+requires-python = ">=3.10"
+license = "Apache-2.0"
+dependencies = ["numpy", "scipy", "msgpack>=1.0", "websockets>=15,<18"]
+
+[project.optional-dependencies]
+# Robot PC. flexivrdk (1.9.x) and flexivdrdk come from Flexiv and are installed separately.
+robot = ["yourdfpy", "opencv-python", "python-can", "canalystii"]
+# GPU box, pi0.5: also install openpi-umi (pip install -e ).
+pi05 = ["opencv-python", "pandas"]
+# GPU box, FLUX: also install flux-umi (pip install -e ).
+flux = ["av", "pillow"]
+mock = ["opencv-python", "pillow"]
+dev = ["pytest"]
+
+[tool.hatch.build.targets.wheel]
+packages = ["umi_infer"]
diff --git a/flexiv-umi-infer/tests/__init__.py b/flexiv-umi-infer/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/flexiv-umi-infer/tests/conftest.py b/flexiv-umi-infer/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad9c32735801a4923a9822331511848ce2d813bd
--- /dev/null
+++ b/flexiv-umi-infer/tests/conftest.py
@@ -0,0 +1,6 @@
+import os
+
+# Fake cell identity: the tests never touch hardware or load the URDF.
+os.environ.setdefault("FLEXIV_LEFT_SN", "TEST-LEFT")
+os.environ.setdefault("FLEXIV_RIGHT_SN", "TEST-RIGHT")
+os.environ.setdefault("FLEXIV_URDF", "test.urdf")
diff --git a/flexiv-umi-infer/tests/test_cloth_defaults.py b/flexiv-umi-infer/tests/test_cloth_defaults.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee0f2881e2ecbd8e40256b337682e4525f00ca73
--- /dev/null
+++ b/flexiv-umi-infer/tests/test_cloth_defaults.py
@@ -0,0 +1,17 @@
+"""CLI contract tests: no sockets, weights or hardware."""
+import unittest
+from unittest.mock import patch
+from umi_infer import policy_server as server
+async def no_server(*args,**kwargs):pass
+class ClothDefaultsTest(unittest.TestCase):
+ def test_both_cli_prompts_are_folding(self):
+ with patch('sys.argv',['policy_server']),patch.object(server,'_build_policy') as build,patch.object(server,'_serve',new=no_server):
+ server.main()
+ args=build.call_args.args[0]
+ self.assertEqual(args.prompt,'fold the clothes');self.assertEqual(args.flux_prompt,'fold the clothes')
+ def test_pi05_sampling_steps_reach_adapter(self):
+ with patch('sys.argv',['policy_server','--policy','pi05','--checkpoint-dir','fixture','--num-denoise-steps','7']),patch('umi_infer.policies.umi_pi05_dual.UmiPi05DualPolicy') as adapter,patch.object(server,'_serve',new=no_server):
+ server.main()
+ self.assertEqual(adapter.call_args.kwargs['num_denoise_steps'],7)
+ self.assertEqual(adapter.call_args.kwargs['prompt'],'fold the clothes')
+if __name__=='__main__':unittest.main()
diff --git a/flexiv-umi-infer/tests/test_flexiv_trace.py b/flexiv-umi-infer/tests/test_flexiv_trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..02aae17ae7bfca5f4ede66d2f0d8f5060680b3bc
--- /dev/null
+++ b/flexiv-umi-infer/tests/test_flexiv_trace.py
@@ -0,0 +1,165 @@
+"""Offline tests for FlexivRobotIO execution logs (CSV + chunks.jsonl): fake RobotPair / reachable, no robot.
+
+ python -m pytest tests/test_flexiv_trace.py
+"""
+import csv
+import json
+import os
+import tempfile
+import time
+import unittest
+from types import SimpleNamespace
+
+import numpy as np
+
+from umi_infer.protocol import Action
+from umi_infer.robot_io import flexiv as F
+
+SIDES = ("left", "right")
+ANCHOR = {"left": np.array([0.0, -0.4, -0.2, 1.0, 0.0, 0.0, 0.0]),
+ "right": np.array([0.0, 0.4, -0.2, 1.0, 0.0, 0.0, 0.0])}
+
+
+class FakeModel:
+ """Unreachable if |y|>0.35 in the arm base frame (right arm world y>0.6); otherwise returns seed as the solution."""
+ def reachable(self, pose, seed, _free):
+ return abs(pose[1]) < 0.35, list(seed)
+
+
+class FakePair:
+ """Measured pose = command lagging by 2mm (x)."""
+ def __init__(self):
+ self.cmd = [ANCHOR["left"].copy(), ANCHOR["right"].copy()]
+
+ def states(self):
+ out = []
+ for h in range(2):
+ p = np.array(self.cmd[h], float)
+ p[0] -= 0.002
+ out.append(SimpleNamespace(tcp_pose=p.tolist(), q=[0.1] * 7))
+ return out
+
+
+def make_io(path, **kw):
+ io = F.FlexivRobotIO(dry_run=True, record_path=path, play_scale=1.0, servo_rate_hz=200, **kw)
+ lt = io._load_lt()
+ io._pair = FakePair()
+ io._models = {s: FakeModel() for s in SIDES}
+ io._bridge = {s: np.eye(4) for s in SIDES}
+ io._bridge["left"][:3, 3] = lt.BASE_XYZ["left"]
+ io._bridge["right"][:3, 3] = lt.BASE_XYZ["right"]
+ io._anchor_w = {s: ANCHOR[s].copy() for s in SIDES}
+ io._anchor_q = {s: np.zeros(7) for s in SIDES}
+ return io
+
+
+def action(seq, n, y_end=0.4):
+ """Right arm moves along +y to y_end (tail unreachable beyond 0.6); left arm still. xyzw."""
+ traj = {"left": [[0.0, -0.4, -0.2, 0, 0, 0, 1]] * n,
+ "right": [[0.0, 0.4 + (y_end - 0.4) * i / (n - 1), -0.2, 0, 0, 0, 1]
+ for i in range(n)]}
+ return Action(seq=seq, stamp=time.time(), control="eef_pose",
+ eef_target={s: traj[s][0] for s in SIDES}, gripper={s: 0.0 for s in SIDES},
+ eef_traj=traj, gripper_traj={s: [0.0] * n for s in SIDES}, dt=1 / 30,
+ extra={"policy": "flux"})
+
+
+class TraceTest(unittest.TestCase):
+ def test_csv_and_chunks(self):
+ d = tempfile.mkdtemp()
+ path = os.path.join(d, "live.csv")
+ io = make_io(path)
+ # Only the recording part of start(); the rest needs a real robot
+ io._rec = open(path, "w", newline="", buffering=1)
+ cols = ["t", "seq", "idx", "phase"]
+ for s in SIDES:
+ cols += ["%s_cmd_%s" % (s, a) for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
+ cols += ["%s_act_%s" % (s, a) for a in ("x", "y", "z")]
+ cols += ["%s_grip_cmd" % s, "%s_grip_meas" % s]
+ cols += ["pair_dist_m"] + ["%s_act_%s" % (s, a) for s in SIDES
+ for a in ("qw", "qx", "qy", "qz")]
+ cols += ["%s_q%d" % (s, k) for s in SIDES for k in range(1, 8)] + ["knot"]
+ cols += ["%s_ext%s_%s" % (s, fr, a) for s in SIDES for fr in ("w", "tcp")
+ for a in ("fx", "fy", "fz", "mx", "my", "mz")]
+ io._rec_w = csv.writer(io._rec)
+ io._rec_w.writerow(cols)
+ io._trace = open(F.trace_path(path), "w", buffering=1)
+ pose0 = np.stack([io._anchor_w[s] for s in SIDES])
+ io._buf = F._Buf(pose_w=pose0[None], twist=np.zeros((1, 2, 6)), grip=np.zeros((1, 2)),
+ dt=0.01, start=time.perf_counter(), seq=-1)
+ io._last_cmd_w = pose0.copy()
+
+ io.apply_action(action(1, 6)) # all pass
+ import threading
+ th = threading.Thread(target=io._servo_loop, daemon=True)
+ th.start()
+ time.sleep(6 / 30 + F.HOLD_ROW_S + 0.2) # play out + hold rows
+ io.apply_action(action(2, 10, y_end=0.7)) # tail unreachable -> truncated
+ time.sleep(0.4)
+ io._stop_ev.set()
+ th.join(2)
+ io._rec.close()
+ io._trace.close()
+
+ with open(F.trace_path(path)) as f:
+ recs = [json.loads(ln) for ln in f]
+ c1, c2 = [r for r in recs if r.get("event") == "chunk"]
+ self.assertEqual((c1["status"], c1["keep"], c1["n_model"]), ("ok", 6, 6))
+ self.assertEqual(c2["status"], "truncated")
+ self.assertLess(c2["keep"], 10)
+ self.assertTrue(c2["why"].startswith("IK: sampled"))
+ self.assertIn(False, c2["ik"]["right"]["ok"])
+ self.assertEqual(len(c1["model"]["right"]), 6)
+ self.assertEqual(c1["ik"]["left"]["q"][0], [0.0] * 7)
+
+ with open(path, newline="") as f:
+ rows = list(csv.DictReader(f))
+ ph = [(int(r["seq"]), r["phase"]) for r in rows]
+ self.assertIn((1, "hold"), ph)
+ self.assertEqual(sorted({int(r["idx"]) for r in rows if r["seq"] == "1"}),
+ list(range(6)))
+ r = rows[-1]
+ self.assertAlmostEqual(float(r["left_cmd_x"]) - float(r["left_act_x"]), 0.002, 5)
+ self.assertEqual(r["right_act_qw"], "1.00000")
+ self.assertEqual(r["right_q7"], "0.10000")
+ self.assertNotIn(None, r) # column count matches header
+ self.assertIn((1, "wait"), ph) # cycles waiting for the next chunk are tagged
+ n1 = sum(1 for x in rows if x["seq"] == "1" and x["phase"] == "run")
+ self.assertGreater(n1, 6 * 3) # one row per servo cycle, not per step
+
+
+class FeedforwardTest(unittest.TestCase):
+ def test_end_velocity_zero_and_interpolated(self):
+ io = make_io(None)
+ pw = np.zeros((5, 2, 7)); pw[..., 3] = 1.0
+ pw[:, :, 0] = np.arange(5)[:, None] * 0.01 # constant 10mm/step along x
+ tw = io._twists(pw, 0.1)
+ np.testing.assert_allclose(tw[-1], 0.0) # last step = stop
+ self.assertGreater(tw[2, 0, 0], 0.0)
+ buf = F._Buf(pose_w=pw, twist=tw, grip=np.zeros((5, 2)), dt=0.1, start=0.0, seq=1)
+ np.testing.assert_allclose(io._ff_twist(buf, 1.5), (tw[1] + tw[2]) / 2) # interpolated between steps
+ np.testing.assert_allclose(io._ff_twist(buf, 4.0), 0.0) # finished
+ np.testing.assert_allclose(io._ff_twist(buf, 9.0), 0.0) # hold after finish (awaiting inference)
+
+ def test_nullspace_weight_range(self):
+ self.assertEqual(make_io(None, nullspace_weight=1.0).ns_weight, 1.0)
+ with self.assertRaises(ValueError):
+ make_io(None, nullspace_weight=2.0)
+
+
+class StepLimitTest(unittest.TestCase):
+ def test_first_and_later_chunk_step_limits(self):
+ io = make_io(None, first_steps=4, steps=7)
+ io._buf = F._Buf(pose_w=np.zeros((1, 2, 7)), twist=np.zeros((1, 2, 6)), grip=np.zeros((1, 2)),
+ dt=0.01, start=time.perf_counter(), seq=-1)
+ io._last_cmd_w = np.stack([ANCHOR[s] for s in SIDES])
+ io.apply_action(action(1, 10, y_end=0.45))
+ self.assertEqual(len(io._buf.pose_w), 4) # first chunk: 4 steps
+ io.apply_action(action(2, 10, y_end=0.45))
+ self.assertEqual(len(io._buf.pose_w), 7) # later chunks: 7 steps
+ io.apply_action(action(3, 5, y_end=0.45))
+ self.assertEqual(len(io._buf.pose_w), 5) # fewer than the cap: run all
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/flexiv-umi-infer/tests/test_flux_action_dual.py b/flexiv-umi-infer/tests/test_flux_action_dual.py
new file mode 100644
index 0000000000000000000000000000000000000000..5909b7debfad0fdfa69b5a55bf4b9de199dde6d9
--- /dev/null
+++ b/flexiv-umi-infer/tests/test_flux_action_dual.py
@@ -0,0 +1,278 @@
+"""CPU-only checks for the FLUX UMI bridge; no weights, GPU or robot IO."""
+
+import asyncio
+import io
+import json
+import unittest
+from types import SimpleNamespace
+
+import numpy as np
+import torch
+import websockets
+from PIL import Image
+
+from flux_action.config import PolicyConfig
+from flux_action.data.umi.representation import make_window, quaternion_matrix, relative_hand
+from umi_infer.policies.flux_action_dual import (FluxActionDualPolicy, _extrinsic,
+ _pose_matrix, decode_image, decode_targets,
+ encode_state, validate_extrinsics)
+from umi_infer.policy_server import _build_policy, _handle
+from umi_infer.protocol import CameraFrame, Observation, pack, unpack_action
+
+
+class FakeModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("placement", torch.empty(0))
+ bounds = {"q01": [-10.0] * 20, "q99": [10.0] * 20}
+ self.config = PolicyConfig(action_dim=20, chunk_size=32, fps=30,
+ camera_layout="side_by_side", camera_keys=list((
+ "images.left_ego", "images.right_ego")),
+ canvas_hw=[256, 512], gripper_flip_dims=[],
+ state_normalization=bounds, action_normalization=bounds)
+ self.reset_count = 0
+ self.last_batch = None
+ self.output = torch.zeros(1, 32, 20)
+ for offset in (0, 10):
+ self.output[0, :, offset + 3] = 1
+ self.output[0, :, offset + 7] = 1
+ self.output[0, :, offset + 9] = 42 + offset
+ self.output[0, :, 0] = 0.01
+ self.output[0, :, 10] = -0.02
+
+ def reset(self):
+ self.reset_count += 1
+
+ def predict_action_chunk(self, batch):
+ self.last_batch = batch
+ return self.output
+
+
+def frame(name, rgb):
+ image = Image.new("RGB", (40, 40), rgb)
+ data = io.BytesIO()
+ image.save(data, format="JPEG", quality=100)
+ return CameraFrame(name=name, format="jpeg", width=40, height=40, data=data.getvalue())
+
+
+def observation():
+ return Observation(seq=17, stamp=1.0,
+ images={"left_wrist": frame("left_wrist", (240, 10, 10)),
+ "right_wrist": frame("right_wrist", (10, 10, 240))},
+ eef={"left": [0.1, 0.2, 0.3, 0, 0, 0, 1],
+ "right": [-0.1, 0.2, 0.3, 0, 0, 0, 1]},
+ eef_prev={"left": [0.09, 0.2, 0.3, 0, 0, 0, 1],
+ "right": [-0.1, 0.2, 0.3, 0, 0, 0, 1]},
+ gripper={"left": 31.5, "right": 90.0})
+
+
+class GeometryTests(unittest.TestCase):
+ def test_training_state_and_inverse_with_nontrivial_rotation(self):
+ # xyzw on the wire, wxyz in FLUX's source states.
+ cur = np.array([0.4, -0.2, 0.8, 0.0, 0.0, 0.38268343, 0.92387953])
+ prev = np.array([0.39, -0.24, 0.81, 0.1, 0.0, 0.0, 0.99498744])
+ cur_train = np.r_[cur[:3], cur[6], cur[3:6], 15.0]
+ prev_train = np.r_[prev[:3], prev[6], prev[3:6], 8.0]
+ expected = relative_hand(cur_train, prev_train)
+ state, anchor = encode_state(cur, prev, 15.0, np.eye(4))
+ expected[-1] = 15.0
+ np.testing.assert_allclose(state, expected, atol=1e-6)
+ future = np.r_[[0.43, -0.19, 0.81], [0, 0.25881905, 0, 0.96592583], 62.0]
+ relative = relative_hand(cur_train, np.r_[future[:3], future[6], future[3:6], future[7]])
+ poses, grippers = decode_targets(anchor, relative[None], np.eye(4))
+ np.testing.assert_allclose(_pose_matrix(poses[0]), _pose_matrix(future[:7]), atol=1e-6)
+ self.assertAlmostEqual(grippers[0], 62.0)
+
+ def test_extrinsic_is_symmetric_and_rejects_nonrigid(self):
+ import tempfile
+ from pathlib import Path
+ with tempfile.TemporaryDirectory() as temp:
+ path = Path(temp) / "E.npy"
+ e = np.eye(4)
+ e[:3, 3] = [0.04, -0.01, 0.02]
+ np.save(path, e)
+ loaded = _extrinsic(path)
+ cur = [0, 0, 0, 0, 0, 0, 1]
+ _, anchor = encode_state(cur, cur, 1.0, np.linalg.inv(loaded))
+ relative = np.array([[0, 0, 0, 1, 0, 0, 0, 1, 0, 1]])
+ poses, _ = decode_targets(anchor, relative, loaded)
+ np.testing.assert_allclose(_pose_matrix(poses[0]), np.eye(4), atol=1e-6)
+ e[0, 0] = 2
+ np.save(path, e)
+ with self.assertRaises(ValueError):
+ _extrinsic(path)
+
+ def test_reject_bad_inputs(self):
+ with self.assertRaises(ValueError):
+ _pose_matrix([0, 0, 0, 0, 0, 0, 0])
+ with self.assertRaises(ValueError):
+ _pose_matrix([1e100, 0, 0, 0, 0, 0, 1])
+ with self.assertRaises(ValueError):
+ decode_targets(np.eye(4), [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], np.eye(4))
+ with self.assertRaises(ValueError):
+ decode_image(CameraFrame(name="x", format="jpeg", width=4, height=4, data=b"bad"))
+
+ def test_urdf_extrinsics_need_both_sides_and_matching_provenance(self):
+ import tempfile
+ from pathlib import Path
+ with tempfile.TemporaryDirectory() as temp:
+ root = Path(temp)
+ urdf = root / "robot.urdf"
+ urdf.write_text("")
+ matrices = {}
+ for side, shift in (("left", -0.07), ("right", 0.04)):
+ e = np.eye(4)
+ e[:3, :3] = quaternion_matrix([np.cos(np.pi / 4), 0, np.sin(np.pi / 4), 0])
+ e[:3, 3] = [shift, 0.03, -0.02]
+ np.save(root / f"E_{side}.npy", e)
+ matrices[side] = e
+ provenance = root / "E_from_urdf.json"
+ record = {"urdf": str(urdf), "camera_pose_source": "cad",
+ "sides": {side: {"npy": str(root / f"E_{side}.npy"),
+ "E_T_cam_flange": matrices[side].tolist()}
+ for side in ("left", "right")}}
+ provenance.write_text(json.dumps(record))
+ loaded = validate_extrinsics(root / "E_left.npy", root / "E_right.npy", provenance)
+ np.testing.assert_allclose(loaded["left"], matrices["left"])
+ with self.assertRaisesRegex(ValueError, "E_LEFT and E_RIGHT"):
+ validate_extrinsics(None, root / "E_right.npy", provenance)
+ with self.assertRaisesRegex(ValueError, "right E path"):
+ validate_extrinsics(root / "E_left.npy", root / "E_left.npy", provenance)
+ bad = matrices["right"].copy()
+ bad[0, 3] += 0.01
+ np.save(root / "E_right.npy", bad)
+ with self.assertRaisesRegex(ValueError, "right E differs"):
+ validate_extrinsics(root / "E_left.npy", root / "E_right.npy", provenance)
+ import os
+ before = urdf.stat().st_mtime_ns
+ os.utime(urdf, ns=(before, provenance.stat().st_mtime_ns + 1_000_000_000))
+ with self.assertRaisesRegex(ValueError, "older than"):
+ validate_extrinsics(root / "E_left.npy", root / "E_right.npy", provenance)
+
+ def test_training_window_roundtrip_through_both_flange_extrinsics(self):
+ states = np.zeros((35, 16), dtype=np.float32)
+ for hand in range(2):
+ base = hand * 8
+ states[:, base:base + 3] = (np.arange(35)[:, None] * [0.002, -0.001, 0.004]
+ + [hand * 0.2, 0.3, 0.4])
+ angles = np.arange(35) * (0.01 if hand == 0 else -0.018)
+ states[:, base + 3] = np.cos(angles / 2)
+ states[:, base + 6] = np.sin(angles / 2)
+ states[:, base + 7] = np.arange(35) * 0.1 + hand
+ expected_state, expected_actions = make_window(states, 1)
+ for hand in range(2):
+ base = hand * 8
+ offset = hand * 10
+ e = np.eye(4)
+ e[:3, :3] = quaternion_matrix([0.96, 0.1, 0.25, -0.07])
+ e[:3, 3] = [0.07, -0.04, 0.03]
+ def flange(row):
+ cam = np.eye(4)
+ cam[:3, :3] = quaternion_matrix(row[3:7])
+ cam[:3, 3] = row[:3]
+ flange_pose = cam @ e
+ from umi_infer.policies.flux_action_dual import _matrix_pose
+ return _matrix_pose(flange_pose)
+ state, anchor = encode_state(flange(states[1, base:base + 8]),
+ flange(states[0, base:base + 8]),
+ states[1, base + 7], np.linalg.inv(e))
+ np.testing.assert_allclose(state, expected_state[offset:offset + 10], atol=1e-6)
+ poses, grippers = decode_targets(anchor,
+ expected_actions[:, offset:offset + 10], e)
+ np.testing.assert_allclose(grippers, states[2:34, base + 7], atol=1e-6)
+ for index in range(32):
+ np.testing.assert_allclose(_pose_matrix(poses[index]),
+ _pose_matrix(flange(states[index + 2, base:base + 8])),
+ atol=1e-6)
+
+
+class PolicyTests(unittest.TestCase):
+ def make_policy(self):
+ import tempfile
+ from pathlib import Path
+ fake = FakeModel()
+ with tempfile.TemporaryDirectory() as temp:
+ identity = Path(temp) / "identity.npy"
+ np.save(identity, np.eye(4))
+ policy = FluxActionDualPolicy(export_dir="unused", source_dir="unused", device="cpu",
+ action_horizon=3, model=fake,
+ extrinsics={"left": identity, "right": identity})
+ return policy, fake
+
+ def test_missing_extrinsics_rejected_even_when_bypassing_startup(self):
+ import tempfile
+ from pathlib import Path
+ with tempfile.TemporaryDirectory() as temp:
+ identity = Path(temp) / "identity.npy"
+ np.save(identity, np.eye(4))
+ for extrinsics in (None, {"left": identity}, {"right": identity}):
+ with self.subTest(extrinsics=extrinsics):
+ with self.assertRaisesRegex(ValueError, "E_LEFT and E_RIGHT"):
+ FluxActionDualPolicy(export_dir="unused", source_dir="unused",
+ device="cpu", model=FakeModel(),
+ extrinsics=extrinsics)
+
+ def test_image_state_and_action(self):
+ policy, fake = self.make_policy()
+ action = policy.infer(observation())
+ self.assertEqual(action.seq, 17)
+ self.assertAlmostEqual(action.dt, 1 / 30)
+ self.assertEqual(len(action.eef_traj["left"]), 3)
+ self.assertEqual(len(action.eef_traj["right"]), 3)
+ self.assertAlmostEqual(action.eef_traj["left"][0][0], 0.11, places=5)
+ self.assertAlmostEqual(action.eef_traj["right"][0][0], -0.12, places=5)
+ self.assertAlmostEqual(action.gripper_traj["left"][0], 42)
+ self.assertAlmostEqual(action.gripper_traj["right"][0], 52)
+ self.assertEqual(fake.last_batch["state"].shape, (1, 20))
+ self.assertAlmostEqual(fake.last_batch["state"][0, 9].item(), 31.5)
+ self.assertAlmostEqual(fake.last_batch["state"][0, 19].item(), 90)
+ left = fake.last_batch["images.left_ego"]
+ right = fake.last_batch["images.right_ego"]
+ self.assertEqual(left.shape, (1, 3, 256, 256))
+ self.assertGreater(left[0, 0, 10, 10], left[0, 2, 10, 10])
+ self.assertGreater(right[0, 2, 10, 10], right[0, 0, 10, 10])
+ self.assertEqual(unpack_action(pack(action)).eef_traj, action.eef_traj)
+ self.assertEqual(fake.last_batch["task"], ["fold the clothes"])
+
+ def test_missing_camera_and_nan_output_rejected(self):
+ policy, fake = self.make_policy()
+ obs = observation()
+ obs.images.pop("right_wrist")
+ with self.assertRaises(ValueError):
+ policy.infer(obs)
+ fake.output[0, 0, 0] = float("nan")
+ with self.assertRaises(ValueError):
+ policy.infer(observation())
+
+ def test_previous_pose_fallback_is_explicit(self):
+ policy, fake = self.make_policy()
+ obs = observation()
+ obs.eef_prev = {}
+ action = policy.infer(obs)
+ self.assertEqual(action.extra["prev_src"], {"left": "current", "right": "current"})
+ self.assertAlmostEqual(fake.last_batch["state"][0, 0].item(), 0, places=6)
+
+ def test_old_mock_factory_unchanged(self):
+ args = SimpleNamespace(policy="mock", chunk_size=None, chunk_dt=None, policy_mode="hold")
+ self.assertEqual(type(_build_policy(args)).__name__, "MockPolicy")
+ args.policy = "flux"
+ args.flux_export = None
+ with self.assertRaises(SystemExit):
+ _build_policy(args)
+
+ def test_mock_websocket_roundtrip_without_robot(self):
+ async def run():
+ policy, fake = self.make_policy()
+ async with websockets.serve(lambda ws: _handle(ws, policy), "127.0.0.1", 0) as server:
+ port = server.sockets[0].getsockname()[1]
+ async with websockets.connect(f"ws://127.0.0.1:{port}") as ws:
+ await ws.send(pack(observation()))
+ action = unpack_action(await ws.recv())
+ self.assertEqual(action.seq, 17)
+ self.assertEqual(len(action.eef_traj["right"]), 3)
+ self.assertGreater(fake.reset_count, 1)
+ asyncio.run(run())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/flexiv-umi-infer/tests/test_rollout_rec.py b/flexiv-umi-infer/tests/test_rollout_rec.py
new file mode 100644
index 0000000000000000000000000000000000000000..39fde26842ba4f800807aa4ec9c17f62dfdfa37b
--- /dev/null
+++ b/flexiv-umi-infer/tests/test_rollout_rec.py
@@ -0,0 +1,139 @@
+"""Offline tests for the per-frame rollout recorder (robot_io/rollout_rec.py): fake RobotPair / cameras, no robot.
+
+ python -m pytest tests/test_rollout_rec.py
+"""
+import csv
+import glob
+import json
+import os
+import tempfile
+import time
+import unittest
+from types import SimpleNamespace
+
+import numpy as np
+
+from umi_infer.robot_io import flexiv as F
+from umi_infer.robot_io import rollout_rec as R
+from tests.test_flexiv_trace import ANCHOR, FakeModel, action
+
+SIDES = ("left", "right")
+Q_LEFT = np.radians([10.0, 20.0, 0.0, 90.0, 169.5, 60.0, 0.0]) # j5 only 0.5 deg from its 170 deg limit
+Q_RIGHT = np.radians([0.0] * 7)
+
+
+class FakePairFull:
+ """Measured = command (x lags 2mm); provides info / actions / torque and wrench fields."""
+ def __init__(self):
+ self.cmd = [ANCHOR["left"].copy(), ANCHOR["right"].copy()]
+
+ def states(self):
+ out = []
+ for h, q in enumerate((Q_LEFT, Q_RIGHT)):
+ p = np.array(self.cmd[h], float)
+ p[0] -= 0.002
+ out.append(SimpleNamespace(tcp_pose=p.tolist(), q=q.tolist(), dq=[0.0] * 7,
+ tau=[1.0] * 7, tau_ext=[0.1] * 7,
+ ext_wrench_in_world=[1, 2, 3, 0.1, 0.2, 0.3],
+ ext_wrench_in_tcp=[3, 2, 1, 0.3, 0.2, 0.1]))
+ return out
+
+ def actions(self):
+ return [SimpleNamespace(tcp_pose_d=list(self.cmd[h]), q_d=q.tolist())
+ for h, q in enumerate((Q_LEFT, Q_RIGHT))]
+
+ def info(self):
+ lim = np.radians(F.RQMAX)
+ return [SimpleNamespace(q_min=(-lim).tolist(), q_max=lim.tolist(),
+ K_x_nom=[10000.0] * 3 + [1500.0] * 3) for _ in range(2)]
+
+
+class FakeDual:
+ """yuv420p native half: (H*3/2, W) I420 planes (downsized here), stamp increases per call."""
+ def __init__(self):
+ self.n = 0
+
+ def get_frame(self, side):
+ self.n += 1
+ return np.full((96 * 3 // 2, 96), 128, np.uint8), time.time() + self.n * 1e-6
+
+ def stop(self):
+ pass
+
+
+class RolloutTest(unittest.TestCase):
+ def test_full_path(self):
+ root = tempfile.mkdtemp()
+ io = F.FlexivRobotIO(dry_run=True, play_scale=1.0, servo_rate_hz=200,
+ cam_format="yuv420p", rollout_root=root, rollout_cam_hz=20)
+ lt = io._load_lt()
+ io._pair = FakePairFull()
+ io._models = {s: FakeModel() for s in SIDES}
+ io._bridge = {s: np.eye(4) for s in SIDES}
+ io._bridge["left"][:3, 3] = lt.BASE_XYZ["left"]
+ io._bridge["right"][:3, 3] = lt.BASE_XYZ["right"]
+ io._anchor_w = {s: ANCHOR[s].copy() for s in SIDES}
+ io._anchor_q = {s: np.zeros(7) for s in SIDES}
+ io._dual = FakeDual()
+ io._open_rollout() # the same call start() makes
+ self.assertIsNotNone(io._rollout)
+ d = io._rollout.dir
+ pose0 = np.stack([io._anchor_w[s] for s in SIDES])
+ io._buf = F._Buf(pose_w=pose0[None], twist=np.zeros((1, 2, 6)), grip=np.zeros((1, 2)),
+ dt=0.01, start=time.perf_counter(), seq=-1)
+ io._last_cmd_w = pose0.copy()
+
+ import threading
+ io._servo = threading.Thread(target=io._servo_loop, daemon=True)
+ io._servo.start()
+ time.sleep(0.1)
+ obs = io.get_observation()
+ io.apply_action(action(obs.seq, 6))
+ time.sleep(6 / 30 + F.HOLD_ROW_S + 0.2)
+ io.stop()
+
+ with open(os.path.join(d, "servo.csv"), newline="") as f:
+ rows = list(csv.DictReader(f))
+ self.assertGreater(len(rows), 20)
+ with open(os.path.join(d, "servo.csv"), newline="") as f:
+ self.assertEqual(next(csv.reader(f)), R.servo_columns())
+ self.assertNotIn(None, rows[-1]) # column count matches header
+ r = rows[-1]
+ self.assertEqual(r["left_at_limit"], "1")
+ self.assertEqual(r["left_margin_joint"], "5")
+ self.assertAlmostEqual(float(r["left_margin_min"]), 0.5, 2)
+ self.assertEqual(r["right_at_limit"], "0")
+ self.assertAlmostEqual(float(r["left_q_d5"]), 169.5, 2) # controller desired joint
+ self.assertAlmostEqual(float(r["left_pos_err_mm"]), 2.0, 2)
+ self.assertEqual(r["left_extw_mz"], "0.3")
+ self.assertIn("run", {x["phase"] for x in rows})
+ self.assertIn("1", {x["seq"] for x in rows})
+
+ with open(os.path.join(d, "events.jsonl")) as f:
+ ev = [json.loads(ln) for ln in f]
+ kinds = {e["event"] for e in ev}
+ self.assertTrue({"obs", "chunk", "stop"} <= kinds, kinds)
+ ob = next(e for e in ev if e["event"] == "obs")
+ self.assertIn("eef_prev", ob)
+ self.assertTrue(glob.glob(os.path.join(d, "obs", "*.jpg"))) # model input images
+ for s in SIDES:
+ self.assertTrue(glob.glob(os.path.join(d, "cams", s, "*.jpg")), s) # live frames
+ with open(os.path.join(d, "meta.json")) as f:
+ meta = json.load(f)
+ self.assertEqual(meta["K_x"]["left"][3], 1500.0 * io.kx_ratio)
+ self.assertAlmostEqual(meta["q_max_deg"]["left"][4], 170.0, 4)
+ with open(os.path.join(d, "summary.json")) as f:
+ sm = json.load(f)
+ self.assertEqual(sm["dropped"], 0)
+ self.assertEqual(sm["arms"]["left"]["joint"], 5)
+ self.assertGreater(sm["arms"]["left"]["limit_frac"], 0.9)
+ self.assertEqual(sm["arms"]["right"]["limit_frac"], 0.0)
+
+ def test_disabled(self):
+ io = F.FlexivRobotIO(dry_run=True, rollout_root=None)
+ io._open_rollout()
+ self.assertIsNone(io._rollout)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/flexiv-umi-infer/tools/README.md b/flexiv-umi-infer/tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9e0071eb7a16bb68c9a2d67c34c918ace2929ef1
--- /dev/null
+++ b/flexiv-umi-infer/tools/README.md
@@ -0,0 +1,57 @@
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+# insta360_cli_dual
+
+基于Linux版Insta360 CameraSDK的非交互CLI。机器人IO使用`discover`和`stream`读取每台腕相机的实时H.264。
+
+- `--service-port=`在Open之前调用`Camera::SetServicePort(N)`。每个进程使用不同端口,否则第二台相机可能无法发现。
+- `INSTA360_VIDEO0_PATH`、`INSTA360_VIDEO1_PATH`指定视频流输出路径,可使用FIFO;每个数据包立即刷新。
+
+## 构建
+
+CameraSDK需向Insta360另行获取,解压后运行:
+
+```bash
+SDK=/path/to/CameraSDK--Linux
+g++ -std=c++17 -O2 -I$SDK/include tools/insta360_cli_dual.cc \
+ -L$SDK/lib -lCameraSDK -lpthread -Wl,-rpath,$SDK/lib -o tools/insta360_cli_dual
+export INSTA360_SDK_LIB=$SDK/lib
+tools/insta360_cli_dual discover # prints the serials of connected cameras as JSON
+```
+
+将相机USB模式设为Android(手机控制),安装SDK提供的udev规则,以便无需root即可访问设备。
+
+---
+
+
+
+# insta360_cli_dual
+
+A small non-interactive CLI around the Insta360 CameraSDK (Linux). The robot IO uses its `discover` and
+`stream` commands to pull live H.264 from each wrist camera.
+
+Two additions make two cameras stream at once into ffmpeg:
+
+- `--service-port=` calls `Camera::SetServicePort(N)` before `Open()`. Each process needs its own port,
+ otherwise the second camera is not found.
+- `INSTA360_VIDEO0_PATH` / `INSTA360_VIDEO1_PATH` set the output file of each video stream. Point them
+ at a fifo for real-time streaming; every packet is flushed.
+
+## Build
+
+The CameraSDK is not included. Request it from Insta360 and unpack it, then:
+
+```bash
+SDK=/path/to/CameraSDK--Linux
+g++ -std=c++17 -O2 -I$SDK/include tools/insta360_cli_dual.cc \
+ -L$SDK/lib -lCameraSDK -lpthread -Wl,-rpath,$SDK/lib -o tools/insta360_cli_dual
+export INSTA360_SDK_LIB=$SDK/lib
+tools/insta360_cli_dual discover # prints the serials of connected cameras as JSON
+```
+
+Set the camera USB mode to Android (phone control) mode and install the udev rule shipped with the SDK so
+the device is accessible without root.
diff --git a/flexiv-umi-infer/tools/insta360_cli_dual.cc b/flexiv-umi-infer/tools/insta360_cli_dual.cc
new file mode 100644
index 0000000000000000000000000000000000000000..324e01750e1cc28b7aa00c30d09a49a2363edb9a
--- /dev/null
+++ b/flexiv-umi-infer/tools/insta360_cli_dual.cc
@@ -0,0 +1,482 @@
+// Non-interactive CLI helper around Insta360 CameraSDK.
+// Output is JSON on stdout, errors are JSON-with-error or plain on stderr.
+//
+// Usage:
+// insta360_cli discover
+// insta360_cli info
+// insta360_cli battery
+// insta360_cli storage
+// insta360_cli record [resolution_enum] [bitrate_bps]
+// insta360_cli photo
+// insta360_cli files
+// insta360_cli stream // dumps h264 to ./01_*.h264 / ./02_*.h264
+// // and per-frame metadata to ./meta_*.jsonl
+// insta360_cli download
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace ic = ins_camera;
+
+// Optional serial filter set by --serial= on the command line.
+static std::string g_serial;
+// Set by --service-port=. When two processes each drive one camera they need different
+// ports, otherwise the second SDK service collides and GetAvailableDevices() reports serial_not_found.
+static int g_service_port = 0;
+
+static std::string ts_string() {
+ auto now = std::chrono::system_clock::now();
+ std::time_t t = std::chrono::system_clock::to_time_t(now);
+ std::tm tm{};
+ localtime_r(&t, &tm);
+ std::stringstream ss;
+ ss << std::put_time(&tm, "%Y%m%d_%H%M%S");
+ return ss.str();
+}
+
+static const char* camera_type_str(ic::CameraType t) {
+ switch (t) {
+ case ic::CameraType::Insta360OneX: return "Insta360OneX";
+ case ic::CameraType::Insta360OneR: return "Insta360OneR";
+ case ic::CameraType::Insta360OneRS: return "Insta360OneRS";
+ case ic::CameraType::Insta360OneX2: return "Insta360OneX2";
+ case ic::CameraType::Insta360X3: return "Insta360X3";
+ case ic::CameraType::Insta360X4: return "Insta360X4";
+ case ic::CameraType::Insta360X5: return "Insta360X5";
+ case ic::CameraType::Insta360X4Air: return "Insta360X4Air";
+ default: return "Unknown";
+ }
+}
+
+static const char* card_state_str(int s) {
+ switch (s) {
+ case ic::STOR_CS_PASS: return "OK";
+ case ic::STOR_CS_NOCARD: return "NO_CARD";
+ case ic::STOR_CS_NOSPACE: return "NO_SPACE";
+ case ic::STOR_CS_INVALID_FORMAT: return "INVALID_FORMAT";
+ case ic::STOR_CS_WPCARD: return "WRITE_PROTECTED";
+ default: return "ERROR";
+ }
+}
+
+static int cmd_discover() {
+ ic::DeviceDiscovery disc;
+ auto list = disc.GetAvailableDevices();
+ std::cout << "{\"devices\":[";
+ for (size_t i = 0; i < list.size(); ++i) {
+ const auto& d = list[i];
+ std::cout << (i ? "," : "")
+ << "{\"serial\":\"" << d.serial_number << "\","
+ << "\"name\":\"" << d.camera_name << "\","
+ << "\"type\":\"" << camera_type_str(d.camera_type) << "\","
+ << "\"fw\":\"" << d.fw_version << "\"}";
+ }
+ std::cout << "]}" << std::endl;
+ disc.FreeDeviceDescriptors(list);
+ return 0;
+}
+
+// Open a device. With --serial=, opens that specific camera; otherwise list[0].
+static std::shared_ptr open_first(ic::CameraType* type_out = nullptr) {
+ ic::DeviceDiscovery disc;
+ auto list = disc.GetAvailableDevices();
+ if (list.empty()) {
+ std::cerr << "{\"error\":\"no_device\"}" << std::endl;
+ return nullptr;
+ }
+ size_t pick = 0;
+ if (!g_serial.empty()) {
+ bool found = false;
+ for (size_t i = 0; i < list.size(); ++i) {
+ if (list[i].serial_number == g_serial) { pick = i; found = true; break; }
+ }
+ if (!found) {
+ std::cerr << "{\"error\":\"serial_not_found\",\"serial\":\"" << g_serial << "\"}" << std::endl;
+ disc.FreeDeviceDescriptors(list);
+ return nullptr;
+ }
+ }
+ auto cam = std::make_shared(list[pick].info);
+ // The SDK header requires SetServicePort to be called before Open().
+ if (g_service_port > 0) cam->SetServicePort(g_service_port);
+ if (!cam->Open()) {
+ std::cerr << "{\"error\":\"open_failed\"}" << std::endl;
+ disc.FreeDeviceDescriptors(list);
+ return nullptr;
+ }
+ if (type_out) *type_out = list[pick].camera_type;
+ disc.FreeDeviceDescriptors(list);
+ return cam;
+}
+
+static int cmd_info() {
+ ic::CameraType type;
+ auto cam = open_first(&type);
+ if (!cam) return 1;
+ auto preview = cam->GetPreviewParam();
+ auto enc = cam->GetVideoEncodeType();
+ std::cout << "{\"type\":\"" << camera_type_str(type) << "\","
+ << "\"name\":\"" << preview.camera_name << "\","
+ << "\"encode\":\"" << (enc == ic::VideoEncodeType::H265 ? "H265" : "H264") << "\","
+ << "\"sweep_time\":" << preview.sweep_time << ","
+ << "\"delay_timestamp\":" << preview.delay_timestamp
+ << "}" << std::endl;
+ cam->Close();
+ return 0;
+}
+
+static int cmd_battery() {
+ auto cam = open_first();
+ if (!cam) return 1;
+ ic::BatteryStatus bs{};
+ bool ok = cam->GetBatteryStatus(bs);
+ if (ok) {
+ std::cout << "{\"power_type\":\"" << (bs.power_type == ic::ADAPTER ? "ADAPTER" : "BATTERY") << "\","
+ << "\"level\":" << bs.battery_level << ","
+ << "\"scale\":" << bs.battery_scale << "}" << std::endl;
+ } else {
+ std::cerr << "{\"error\":\"get_battery_failed\"}" << std::endl;
+ }
+ cam->Close();
+ return ok ? 0 : 1;
+}
+
+static int cmd_storage() {
+ auto cam = open_first();
+ if (!cam) return 1;
+ ic::StorageStatus st{};
+ bool ok = cam->GetStorageState(st);
+ if (ok) {
+ std::cout << "{\"state\":\"" << card_state_str(st.state) << "\","
+ << "\"free\":" << st.free_space << ","
+ << "\"total\":" << st.total_space << "}" << std::endl;
+ } else {
+ std::cerr << "{\"error\":\"get_storage_failed\"}" << std::endl;
+ }
+ cam->Close();
+ return ok ? 0 : 1;
+}
+
+static int cmd_offset() {
+ auto cam = open_first();
+ if (!cam) return 1;
+ auto offsets = cam->GetCameraOffset();
+ auto preview = cam->GetPreviewParam();
+ std::cout << "{\"offset_count\":" << offsets.size();
+ for (size_t i = 0; i < offsets.size(); ++i) {
+ std::cout << ",\"offset_" << i << "\":\"" << offsets[i] << "\"";
+ }
+ // also dump preview_param.offset (may differ)
+ std::cout << ",\"preview_offset_count\":" << preview.offset.size();
+ for (size_t i = 0; i < preview.offset.size(); ++i) {
+ std::cout << ",\"preview_offset_" << i << "\":\"" << preview.offset[i] << "\"";
+ }
+ std::cout << ",\"lens_type\":" << static_cast(cam->GetCameraLensType());
+ std::cout << "}" << std::endl;
+ cam->Close();
+ return 0;
+}
+
+static int cmd_files() {
+ auto cam = open_first();
+ if (!cam) return 1;
+ auto files = cam->GetCameraFilesList();
+ std::cout << "{\"files\":[";
+ for (size_t i = 0; i < files.size(); ++i) {
+ std::cout << (i ? "," : "") << "\"" << files[i] << "\"";
+ }
+ std::cout << "]}" << std::endl;
+ cam->Close();
+ return 0;
+}
+
+static int cmd_record(int argc, char** argv) {
+ int seconds = 5;
+ int res_enum = static_cast(ic::VideoResolution::RES_3840_1920P30);
+ int bitrate = 1024 * 1024 * 40;
+ if (argc >= 3) seconds = std::atoi(argv[2]);
+ if (argc >= 4) res_enum = std::atoi(argv[3]);
+ if (argc >= 5) bitrate = std::atoi(argv[4]);
+
+ ic::CameraType type;
+ auto cam = open_first(&type);
+ if (!cam) return 1;
+
+ if (!cam->SetVideoSubMode(ic::SubVideoMode::VIDEO_NORMAL)) {
+ std::cerr << "{\"error\":\"set_submode_failed\"}" << std::endl;
+ cam->Close(); return 2;
+ }
+
+ ic::RecordParams rp{};
+ rp.resolution = static_cast(res_enum);
+ rp.bitrate = bitrate;
+ if (!cam->SetVideoCaptureParams(rp, ic::CameraFunctionMode::FUNCTION_MODE_NORMAL_VIDEO)) {
+ std::cerr << "{\"error\":\"set_capture_params_failed\"}" << std::endl;
+ cam->Close(); return 3;
+ }
+
+ if (!cam->StartRecording()) {
+ std::cerr << "{\"error\":\"start_record_failed\"}" << std::endl;
+ cam->Close(); return 4;
+ }
+
+ std::cerr << "{\"event\":\"recording\",\"seconds\":" << seconds << "}" << std::endl;
+ std::this_thread::sleep_for(std::chrono::seconds(seconds));
+
+ auto url = cam->StopRecording();
+ if (url.Empty()) {
+ std::cerr << "{\"error\":\"stop_record_failed\"}" << std::endl;
+ cam->Close(); return 5;
+ }
+ std::cout << "{\"urls\":[";
+ const auto& origins = url.OriginUrls();
+ for (size_t i = 0; i < origins.size(); ++i) {
+ std::cout << (i ? "," : "") << "\"" << origins[i] << "\"";
+ }
+ std::cout << "]}" << std::endl;
+ cam->Close();
+ return 0;
+}
+
+static int cmd_photo() {
+ auto cam = open_first();
+ if (!cam) return 1;
+ auto url = cam->TakePhoto();
+ if (url.Empty()) {
+ std::cerr << "{\"error\":\"take_photo_failed\"}" << std::endl;
+ cam->Close(); return 2;
+ }
+ std::cout << "{\"urls\":[";
+ const auto& o = url.OriginUrls();
+ for (size_t i = 0; i < o.size(); ++i) std::cout << (i ? "," : "") << "\"" << o[i] << "\"";
+ std::cout << "]}" << std::endl;
+ cam->Close();
+ return 0;
+}
+
+// Stream delegate. Writes H.264 streams to disk (per-lens) and emits NDJSON
+// metadata. The metadata target is configurable: file (--out) or stdout
+// (live-mode for Python consumers).
+//
+// Timestamps from the SDK callbacks are in MILLISECONDS (camera uptime since
+// boot, same domain across video/audio/gyro/exposure).
+class DumpDelegate : public ic::StreamDelegate {
+public:
+ enum class MetaSink { File, Stdout };
+
+ DumpDelegate(const std::string& tag, MetaSink sink) : sink_(sink) {
+ std::string base = "./" + tag;
+ // Output paths can be overridden by env; point them at a fifo to feed ffmpeg live.
+ // Unset keeps the original behavior (_0x.h264 in cwd).
+ const char* p1 = getenv("INSTA360_VIDEO0_PATH");
+ const char* p2 = getenv("INSTA360_VIDEO1_PATH");
+ fp1_ = fopen(p1 && *p1 ? p1 : (base + "_01.h264").c_str(), "wb");
+ fp2_ = fopen(p2 && *p2 ? p2 : (base + "_02.h264").c_str(), "wb");
+ // With a fifo the default 4KB buffer stalls downstream ffmpeg, so flush per packet.
+ fifo_ = (p1 && *p1) || (p2 && *p2);
+ if (sink_ == MetaSink::File) meta_.open(base + "_meta.jsonl");
+ }
+ ~DumpDelegate() {
+ if (fp1_) fclose(fp1_);
+ if (fp2_) fclose(fp2_);
+ if (meta_.is_open()) meta_.close();
+ }
+ void OnAudioData(const uint8_t*, size_t size, int64_t ts) override {
+ std::ostringstream s;
+ s << "{\"kind\":\"audio\",\"ts\":" << ts << ",\"size\":" << size << "}";
+ emit(s.str());
+ }
+ void OnVideoData(const uint8_t* data, size_t size, int64_t ts, uint8_t streamType, int idx) override {
+ if (idx == 0 && fp1_) { fwrite(data, 1, size, fp1_); if (fifo_) fflush(fp1_); }
+ if (idx == 1 && fp2_) { fwrite(data, 1, size, fp2_); if (fifo_) fflush(fp2_); }
+ std::ostringstream s;
+ s << "{\"kind\":\"video\",\"idx\":" << idx
+ << ",\"ts\":" << ts << ",\"size\":" << size
+ << ",\"stream_type\":" << static_cast(streamType) << "}";
+ emit(s.str());
+ }
+ void OnGyroData(const std::vector& d) override {
+ for (const auto& smp : d) {
+ std::ostringstream s;
+ s << "{\"kind\":\"gyro\",\"ts\":" << smp.timestamp
+ << ",\"ax\":" << smp.ax << ",\"ay\":" << smp.ay << ",\"az\":" << smp.az
+ << ",\"gx\":" << smp.gx << ",\"gy\":" << smp.gy << ",\"gz\":" << smp.gz
+ << "}";
+ emit(s.str());
+ }
+ }
+ void OnExposureData(const ic::ExposureData& e) override {
+ std::ostringstream s;
+ s << "{\"kind\":\"exposure\",\"ts\":" << e.timestamp
+ << ",\"exposure_time\":" << e.exposure_time << "}";
+ emit(s.str());
+ }
+private:
+ void emit(const std::string& line) {
+ std::lock_guard g(mu_);
+ if (sink_ == MetaSink::Stdout) {
+ std::cout << line << "\n";
+ std::cout.flush(); // line-buffered for live consumers
+ } else if (meta_.is_open()) {
+ meta_ << line << "\n";
+ }
+ }
+ MetaSink sink_;
+ FILE* fp1_ = nullptr;
+ FILE* fp2_ = nullptr;
+ bool fifo_ = false;
+ std::ofstream meta_;
+ std::mutex mu_;
+};
+
+static int cmd_stream(int argc, char** argv) {
+ // Args: insta360_cli stream [resolution_enum=2] [using_lrv=1]
+ // [bitrate_kbps=512] [enable_audio=0] [enable_gyro=1]
+ // [meta_to_stdout=0]
+ // Default uses RES_1920_960P30 + LRV proxy. On X4 Air this avoids the USB
+ // mass-storage mode switch we observed at higher panoramic resolutions.
+ // When meta_to_stdout=1, NDJSON lines are emitted to stdout in real time
+ // (Python consumers can readline() as packets arrive); the final summary
+ // line is still printed last.
+ int seconds = 5;
+ int res_enum = static_cast(ic::VideoResolution::RES_1920_960P30);
+ int using_lrv = 1;
+ int bitrate_kbps = 512;
+ int enable_audio = 0;
+ int enable_gyro = 1;
+ int meta_to_stdout = 0;
+ if (argc >= 3) seconds = std::atoi(argv[2]);
+ if (argc >= 4) res_enum = std::atoi(argv[3]);
+ if (argc >= 5) using_lrv = std::atoi(argv[4]);
+ if (argc >= 6) bitrate_kbps = std::atoi(argv[5]);
+ if (argc >= 7) enable_audio = std::atoi(argv[6]);
+ if (argc >= 8) enable_gyro = std::atoi(argv[7]);
+ if (argc >= 9) meta_to_stdout = std::atoi(argv[8]);
+
+ ic::CameraType type;
+ auto cam = open_first(&type);
+ if (!cam) return 1;
+
+ auto resolution = static_cast(res_enum);
+ if (type >= ic::CameraType::Insta360X4) {
+ if (!cam->SetVideoSubMode(ic::SubVideoMode::VIDEO_LIVEVIEW)) {
+ std::cerr << "{\"error\":\"set_liveview_submode_failed\"}" << std::endl;
+ cam->Close(); return 2;
+ }
+ ic::RecordParams rp{};
+ rp.resolution = resolution;
+ rp.bitrate = 0;
+ if (!cam->SetVideoCaptureParams(rp, ic::CameraFunctionMode::FUNCTION_MODE_LIVE_STREAM)) {
+ std::cerr << "{\"error\":\"set_liveview_params_failed\"}" << std::endl;
+ cam->Close(); return 3;
+ }
+ // Give the camera a brief settle window after mode switching.
+ std::this_thread::sleep_for(std::chrono::milliseconds(500));
+ }
+
+ auto tag = ts_string();
+ auto sink = meta_to_stdout ? DumpDelegate::MetaSink::Stdout
+ : DumpDelegate::MetaSink::File;
+ auto delegate = std::shared_ptr(new DumpDelegate(tag, sink));
+ cam->SetStreamDelegate(delegate);
+
+ ic::LiveStreamParam param{};
+ param.video_resolution = resolution;
+ param.lrv_video_resulution = ic::VideoResolution::RES_1440_720P30;
+ param.video_bitrate = static_cast(bitrate_kbps) * 1024;
+ param.lrv_video_bitrate = 512 * 1024;
+ param.enable_audio = enable_audio != 0;
+ param.using_lrv = using_lrv != 0;
+ param.enable_gyro = enable_gyro != 0;
+
+ std::cerr << "{\"event\":\"starting\",\"resolution\":" << res_enum
+ << ",\"using_lrv\":" << param.using_lrv
+ << ",\"bitrate_kbps\":" << bitrate_kbps
+ << ",\"audio\":" << param.enable_audio
+ << ",\"gyro\":" << param.enable_gyro << "}" << std::endl;
+
+ if (!cam->StartLiveStreaming(param)) {
+ std::cerr << "{\"error\":\"start_live_failed\"}" << std::endl;
+ cam->Close(); return 4;
+ }
+
+ std::cerr << "{\"event\":\"streaming\",\"seconds\":" << seconds << ",\"tag\":\"" << tag << "\"}" << std::endl;
+ std::this_thread::sleep_for(std::chrono::seconds(seconds));
+
+ cam->StopLiveStreaming();
+ // Settle so writes flush.
+ std::this_thread::sleep_for(std::chrono::milliseconds(300));
+ // Final summary line, always last on stdout, regardless of sink.
+ std::cout << "{\"kind\":\"summary\",\"tag\":\"" << tag << "\","
+ << "\"files\":[\"" << tag << "_01.h264\",\"" << tag << "_02.h264\","
+ << "\"" << tag << "_meta.jsonl\"]}" << std::endl;
+ cam->Close();
+ return 0;
+}
+
+static int cmd_download(int argc, char** argv) {
+ if (argc < 4) { std::cerr << "usage: insta360_cli download \n"; return 64; }
+ std::string remote = argv[2], local = argv[3];
+ auto cam = open_first();
+ if (!cam) return 1;
+ int64_t last_pct = -1;
+ bool ok = cam->DownloadCameraFile(remote, local, [&](int64_t cur, int64_t tot){
+ if (tot <= 0) return;
+ int64_t pct = cur * 100 / tot;
+ if (pct != last_pct) { std::cerr << "\rdownload " << pct << "%" << std::flush; last_pct = pct; }
+ });
+ std::cerr << std::endl;
+ cam->Close();
+ if (!ok) { std::cerr << "{\"error\":\"download_failed\"}" << std::endl; return 2; }
+ std::cout << "{\"local\":\"" << local << "\"}" << std::endl;
+ return 0;
+}
+
+int main(int argc, char** argv) {
+ ic::SetLogLevel(ic::LogLevel::ERR);
+ // Strip --serial= from anywhere in argv.
+ int out = 1;
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ if (a.rfind("--serial=", 0) == 0) { g_serial = a.substr(9); continue; }
+ if (a.rfind("--service-port=", 0) == 0) {
+ g_service_port = std::atoi(a.substr(15).c_str());
+ continue;
+ }
+ argv[out++] = argv[i];
+ }
+ argc = out;
+ if (argc < 2) {
+ std::cerr << "usage: insta360_cli_dual [--serial=] [--service-port=] ...\n"
+ << " env INSTA360_VIDEO0_PATH / INSTA360_VIDEO1_PATH: write idx0/idx1 h264 to the given path (may be a fifo)" << std::endl;
+ return 64;
+ }
+ std::string cmd = argv[1];
+ if (cmd == "discover") return cmd_discover();
+ if (cmd == "info") return cmd_info();
+ if (cmd == "battery") return cmd_battery();
+ if (cmd == "storage") return cmd_storage();
+ if (cmd == "files") return cmd_files();
+ if (cmd == "offset") return cmd_offset();
+ if (cmd == "photo") return cmd_photo();
+ if (cmd == "record") return cmd_record(argc, argv);
+ if (cmd == "stream") return cmd_stream(argc, argv);
+ if (cmd == "download") return cmd_download(argc, argv);
+ std::cerr << "unknown command: " << cmd << std::endl;
+ return 64;
+}
diff --git a/flexiv-umi-infer/umi_infer/__init__.py b/flexiv-umi-infer/umi_infer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/flexiv-umi-infer/umi_infer/check_cam.py b/flexiv-umi-infer/umi_infer/check_cam.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e892695c6f81c6162dd59ca7cf5984e943c1727
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/check_cam.py
@@ -0,0 +1,180 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Camera self-check: grab one frame per wrist camera and verify it matches the training setup.
+
+A wrong camera fails silently: the policy raises no error, it just moves wrongly (e.g. the
+rear lens was picked). This checks:
+ (1) body <-> arm: CAM_SERIAL (env INSTA360_LEFT_SN / INSTA360_RIGHT_SN) vs the camera_serial
+ in the hand-eye records (FLEXIV_HANDEYE_RUNS/{left,right}/poses.json).
+ (2) half: CAM_HALF (env INSTA360_LEFT_HALF / INSTA360_RIGHT_HALF) vs the img_half the
+ extrinsic E was solved on.
+ (3) size: CAM_OUT_SIZE vs observation.images.*_ego shape in the dataset meta/info.json.
+
+It also saves live frames next to the training first frame: very different framing means the
+images are out of distribution, where the policy tends to freeze or drift.
+
+Usage:
+ python -m umi_infer.check_cam [--dataset ] # grab + save + compare
+ python -m umi_infer.check_cam --no-compare # grab only
+ python -m umi_infer.check_cam --out-dir /tmp/camchk
+"""
+
+from __future__ import annotations
+
+import argparse
+import glob
+import json
+import os
+import sys
+import time
+
+import numpy as np
+
+from .robot_io.cam_ids import CAM_HALF, CAM_OUT_SIZE, CAM_SERIAL, HANDEYE_RUNS, SIDES
+
+DATA = "" # training LeRobot dataset root, set from --dataset
+
+
+def check_identity():
+ """Compare the configured camera mapping with the hand-eye records; a mismatch means one side changed."""
+ print("=== (1) camera body <-> arm ===")
+ if not HANDEYE_RUNS:
+ print(" FLEXIV_HANDEYE_RUNS not set, skipping")
+ return True
+ ok = True
+ for s in SIDES:
+ p = os.path.join(HANDEYE_RUNS, s, "poses.json")
+ if not os.path.exists(p):
+ print(" %-6s calibration record missing (%s), cannot verify" % (s, p))
+ ok = False
+ continue
+ d = json.load(open(p))
+ want = d["meta"].get("camera_serial")
+ got = CAM_SERIAL[s]
+ halves = {x.get("img_half") for x in d["items"]}
+ mark = "OK" if want == got else "FAIL"
+ print(" %s %-6s calibrated body %s | configured %s" % (mark, s, want, got))
+ if want != got:
+ ok = False
+ print(" -> E and images come from different cameras! Fix INSTA360_LEFT_SN / INSTA360_RIGHT_SN")
+ hm = "OK" if halves == {CAM_HALF[s]} else "FAIL"
+ print(" %s %-6s calibrated half %s | configured %r"
+ % (hm, s, halves, CAM_HALF[s]))
+ if halves != {CAM_HALF[s]}:
+ ok = False
+ return ok
+
+
+def check_dataset_shape():
+ print("\n=== (3) image size vs training ===")
+ if not DATA:
+ print(" no --dataset given, skipping")
+ return True
+ info = json.load(open(os.path.join(DATA, "meta", "info.json")))
+ for k in ("observation.images.left_ego", "observation.images.right_ego"):
+ shp = info["features"][k]["shape"]
+ mark = "OK" if shp[0] == CAM_OUT_SIZE == shp[1] else "FAIL"
+ print(" %s %-34s training %s | live %dx%d" % (mark, k, shp, CAM_OUT_SIZE, CAM_OUT_SIZE))
+ return True
+
+
+def training_first_frame(side, out_path):
+ """Decode a reference frame from the training set (first frame of the first episode)."""
+ import cv2
+ key = "left_ego" if side == "left" else "right_ego"
+ pats = [os.path.join(DATA, "videos", "**", "observation.images.%s" % key, "*.mp4"),
+ os.path.join(DATA, "videos", "**", "*%s*.mp4" % key)]
+ vids = []
+ for pat in pats:
+ vids = sorted(glob.glob(pat, recursive=True))
+ if vids:
+ break
+ if not DATA or not vids:
+ print(" %-6s no training video found (under %s/videos), skipping compare" % (side, DATA))
+ return None
+ # Decode with ffmpeg in software, not cv2.VideoCapture: training videos are AV1 and some
+ # cv2 builds try hardware decoding, fail, and return empty frames.
+ import subprocess
+ from .robot_io.insta_live import FFMPEG
+ r = subprocess.run([FFMPEG, "-v", "error", "-i", vids[0], "-frames:v", "1",
+ "-y", out_path], capture_output=True, text=True)
+ bgr = cv2.imread(out_path) if os.path.exists(out_path) else None
+ if bgr is None:
+ print(" %-6s cannot decode training video: %s (%s)"
+ % (side, vids[0], (r.stderr or "").strip()[:120]))
+ return None
+ print(" %-6s training first frame %s -> %s" % (side, os.path.basename(vids[0]), out_path))
+ return bgr
+
+
+def main():
+ ap = argparse.ArgumentParser(description="Wrist camera self-check")
+ ap.add_argument("--out-dir", default="/tmp/umi_camchk")
+ ap.add_argument("--dataset", default="", help="training LeRobot dataset root (size check + first-frame compare)")
+ ap.add_argument("--no-compare", action="store_true", help="skip comparison with the training first frame")
+ ap.add_argument("--warmup", type=float, default=8.0, help="seconds to wait for the first frame")
+ a = ap.parse_args()
+ global DATA
+ DATA = a.dataset
+ if not all(CAM_SERIAL.values()):
+ print("set INSTA360_LEFT_SN / INSTA360_RIGHT_SN first")
+ return 1
+ os.makedirs(a.out_dir, exist_ok=True)
+
+ id_ok = check_identity()
+ check_dataset_shape()
+
+ print("\n=== (2) live frame grab ===")
+ import cv2
+ from .robot_io.insta_live import InstaDualCamera
+ dual = InstaDualCamera(serials={s: CAM_SERIAL[s] for s in SIDES},
+ halves={s: CAM_HALF[s] for s in SIDES},
+ out_size=CAM_OUT_SIZE)
+ dual.start()
+ try:
+ if not dual.wait_ready(max(a.warmup, 20.0)):
+ print("FAIL: cameras not ready. Check: USB mode set to Android control / udev rules / "
+ "a leftover insta360_cli holding the device")
+ return 1
+ time.sleep(1.5)
+ got = {}
+ for s in SIDES:
+ rgb, stamp = dual.get_frame(s)
+ if rgb is None:
+ print(" FAIL %-6s no frame" % s)
+ continue
+ p = os.path.join(a.out_dir, "live_%s.png" % s)
+ cv2.imwrite(p, cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR))
+ got[s] = rgb
+ print(" OK %-6s %s %dx%d mean %.1f -> %s"
+ % (s, CAM_SERIAL[s], rgb.shape[1], rgb.shape[0], float(rgb.mean()), p))
+ print(" fps %.1f" % dual.fps(s))
+ if not a.no_compare and got:
+ print("\n=== side by side with training first frame (very different framing = out of distribution) ===")
+ for s in SIDES:
+ if s not in got:
+ continue
+ ref = training_first_frame(s, os.path.join(a.out_dir, "train_%s.png" % s))
+ if ref is None:
+ continue
+ live = cv2.cvtColor(got[s], cv2.COLOR_RGB2BGR)
+ if ref.shape[:2] != live.shape[:2]:
+ ref = cv2.resize(ref, (live.shape[1], live.shape[0]))
+ pair = np.hstack([ref, live])
+ cv2.putText(pair, "TRAIN", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
+ (0, 255, 0), 3)
+ cv2.putText(pair, "LIVE", (live.shape[1] + 20, 50),
+ cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 3)
+ p = os.path.join(a.out_dir, "cmp_%s.png" % s)
+ cv2.imwrite(p, pair)
+ print(" %-6s left=training right=live -> %s" % (s, p))
+ finally:
+ dual.stop()
+
+ print("\nbody/half check: %s" % ("PASS" if id_ok else "FAIL, fix before continuing"))
+ print("images saved to %s" % a.out_dir)
+ return 0 if id_ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/flexiv-umi-infer/umi_infer/codec/__init__.py b/flexiv-umi-infer/umi_infer/codec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/flexiv-umi-infer/umi_infer/codec/umi_decode.py b/flexiv-umi-infer/umi_infer/codec/umi_decode.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0e32313ec5e3cf72e8db9b1cdad0c61a4f3045f
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/codec/umi_decode.py
@@ -0,0 +1,199 @@
+#!/usr/bin/env python3
+"""Pure-numpy pose / rotation decode helpers for the UMI pi05 policy.
+
+Mirrors the openpi-umi training transforms so model output can be decoded
+without importing ``openpi`` (useful on a robot and in unit tests).
+
+Per hand, the pi05 UMI model emits a relative action chunk of shape (H, A):
+
+ rel_xyz(3) | rotation(rot_dim) | gripper(1) A = 3 + rot_dim + 1
+
+where ``rot_dim`` is 6 for ``rot6d`` (default), 4 for ``quat_xyzw`` and 3 for
+``axis_angle``. Each action is the next EEF pose expressed *relative to the
+current EEF frame*, so the world target is ``world = current @ rel``.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+
+__all__ = [
+ "rot_dim",
+ "rot6d_to_matrix",
+ "quat_xyzw_to_matrix",
+ "axis_angle_to_matrix",
+ "pose_xyzw_to_matrix",
+ "matrix_to_quat_xyzw",
+ "invert_transform",
+ "decode_actions_to_world",
+]
+
+
+def _unit(v: np.ndarray, eps: float = 1e-8) -> np.ndarray:
+ return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), eps)
+
+
+def rot_dim(rotation_repr: str) -> int:
+ """Number of rotation channels for a given representation."""
+ return {"rot6d": 6, "quat_xyzw": 4, "axis_angle": 3}[rotation_repr]
+
+
+def rot6d_to_matrix(rot6d: np.ndarray) -> np.ndarray:
+ """6-D continuous rotation (first two basis columns + Gram-Schmidt) -> (..., 3, 3)."""
+ rot6d = np.asarray(rot6d, dtype=np.float32)
+ a1 = rot6d[..., :3]
+ a2 = rot6d[..., 3:6]
+ b1 = _unit(a1)
+ b2 = _unit(a2 - np.sum(b1 * a2, axis=-1, keepdims=True) * b1)
+ b3 = np.cross(b1, b2)
+ return np.stack([b1, b2, b3], axis=-1).astype(np.float32)
+
+
+def quat_xyzw_to_matrix(quat: np.ndarray) -> np.ndarray:
+ """Quaternion [qx, qy, qz, qw] -> rotation matrix (..., 3, 3)."""
+ x, y, z, w = np.moveaxis(_unit(np.asarray(quat, dtype=np.float32)), -1, 0)
+ xx, yy, zz = x * x, y * y, z * z
+ xy, xz, yz = x * y, x * z, y * z
+ wx, wy, wz = w * x, w * y, w * z
+ m = np.empty((*np.asarray(quat).shape[:-1], 3, 3), dtype=np.float32)
+ m[..., 0, 0] = 1.0 - 2.0 * (yy + zz)
+ m[..., 0, 1] = 2.0 * (xy - wz)
+ m[..., 0, 2] = 2.0 * (xz + wy)
+ m[..., 1, 0] = 2.0 * (xy + wz)
+ m[..., 1, 1] = 1.0 - 2.0 * (xx + zz)
+ m[..., 1, 2] = 2.0 * (yz - wx)
+ m[..., 2, 0] = 2.0 * (xz - wy)
+ m[..., 2, 1] = 2.0 * (yz + wx)
+ m[..., 2, 2] = 1.0 - 2.0 * (xx + yy)
+ return m
+
+
+def axis_angle_to_matrix(axis_angle: np.ndarray) -> np.ndarray:
+ """Axis-angle (3-vector, magnitude=angle) -> rotation matrix (..., 3, 3)."""
+ axis_angle = np.asarray(axis_angle, dtype=np.float32)
+ angle = np.linalg.norm(axis_angle, axis=-1, keepdims=True)
+ axis = axis_angle / np.maximum(angle, 1e-8)
+ x, y, z = np.moveaxis(axis, -1, 0)
+ ca = np.cos(angle[..., 0])
+ sa = np.sin(angle[..., 0])
+ omc = 1.0 - ca
+ m = np.empty((*axis_angle.shape[:-1], 3, 3), dtype=np.float32)
+ m[..., 0, 0] = ca + x * x * omc
+ m[..., 0, 1] = x * y * omc - z * sa
+ m[..., 0, 2] = x * z * omc + y * sa
+ m[..., 1, 0] = y * x * omc + z * sa
+ m[..., 1, 1] = ca + y * y * omc
+ m[..., 1, 2] = y * z * omc - x * sa
+ m[..., 2, 0] = z * x * omc - y * sa
+ m[..., 2, 1] = z * y * omc + x * sa
+ m[..., 2, 2] = ca + z * z * omc
+ small = angle[..., 0] < 1e-8
+ if np.any(small):
+ m[small] = np.eye(3, dtype=np.float32)
+ return m
+
+
+def pose_xyzw_to_matrix(pose: np.ndarray) -> np.ndarray:
+ """7-D pose [x, y, z, qx, qy, qz, qw] -> homogeneous transform (..., 4, 4)."""
+ pose = np.asarray(pose, dtype=np.float32)
+ m = np.broadcast_to(np.eye(4, dtype=np.float32), (*pose.shape[:-1], 4, 4)).copy()
+ m[..., :3, 3] = pose[..., :3]
+ m[..., :3, :3] = quat_xyzw_to_matrix(pose[..., 3:7])
+ return m
+
+
+def matrix_to_quat_xyzw(matrix: np.ndarray) -> np.ndarray:
+ """Rotation matrix -> [qx, qy, qz, qw], canonicalised to qw >= 0."""
+ matrix = np.asarray(matrix, dtype=np.float32)
+ q = np.empty((*matrix.shape[:-2], 4), dtype=np.float32)
+ trace = np.trace(matrix, axis1=-2, axis2=-1)
+ for idx in np.ndindex(trace.shape):
+ m = matrix[idx]
+ tr = trace[idx]
+ if tr > 0:
+ s = np.sqrt(tr + 1.0) * 2.0
+ q[idx] = [(m[2, 1] - m[1, 2]) / s, (m[0, 2] - m[2, 0]) / s, (m[1, 0] - m[0, 1]) / s, 0.25 * s]
+ else:
+ axis = int(np.argmax(np.diag(m)))
+ if axis == 0:
+ s = np.sqrt(1.0 + m[0, 0] - m[1, 1] - m[2, 2]) * 2.0
+ q[idx] = [0.25 * s, (m[0, 1] + m[1, 0]) / s, (m[0, 2] + m[2, 0]) / s, (m[2, 1] - m[1, 2]) / s]
+ elif axis == 1:
+ s = np.sqrt(1.0 + m[1, 1] - m[0, 0] - m[2, 2]) * 2.0
+ q[idx] = [(m[0, 1] + m[1, 0]) / s, 0.25 * s, (m[1, 2] + m[2, 1]) / s, (m[0, 2] - m[2, 0]) / s]
+ else:
+ s = np.sqrt(1.0 + m[2, 2] - m[0, 0] - m[1, 1]) * 2.0
+ q[idx] = [(m[0, 2] + m[2, 0]) / s, (m[1, 2] + m[2, 1]) / s, 0.25 * s, (m[1, 0] - m[0, 1]) / s]
+ q = _unit(q)
+ q = np.where(q[..., 3:4] < 0, -q, q) # qw >= 0
+ return q.astype(np.float32)
+
+
+def _rel_rotation_to_matrix(rot: np.ndarray, rotation_repr: str) -> np.ndarray:
+ if rotation_repr == "rot6d":
+ return rot6d_to_matrix(rot)
+ if rotation_repr == "quat_xyzw":
+ return quat_xyzw_to_matrix(rot)
+ if rotation_repr == "axis_angle":
+ return axis_angle_to_matrix(rot)
+ raise ValueError(f"Unsupported rotation_repr: {rotation_repr}")
+
+
+def invert_transform(t: np.ndarray) -> np.ndarray:
+ """Inverse of a homogeneous SE(3) transform (..., 4, 4)."""
+ t = np.asarray(t, dtype=np.float32)
+ inv = np.broadcast_to(np.eye(4, dtype=np.float32), t.shape).copy()
+ r_t = np.swapaxes(t[..., :3, :3], -1, -2)
+ inv[..., :3, :3] = r_t
+ inv[..., :3, 3] = -np.einsum("...ij,...j->...i", r_t, t[..., :3, 3])
+ return inv
+
+
+def decode_actions_to_world(
+ current_pose_xyzw: np.ndarray,
+ actions: np.ndarray,
+ rotation_repr: str = "rot6d",
+ eef_extrinsic: np.ndarray | None = None,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Decode a relative action chunk to absolute world EEF targets.
+
+ Each action is the next pose expressed in the CURRENT gripper frame, so
+ ``world = current @ rel`` and the output lands in the SAME frame as
+ ``current_pose_xyzw``. Feed the robot's live base-frame gripper pose as
+ ``current`` and the targets come out in the base frame (the world-frame
+ UMI->base alignment ``M`` cancels).
+
+ Args:
+ current_pose_xyzw: current absolute EEF pose, 7-vec [x,y,z,qx,qy,qz,qw].
+ actions: (H, A) relative action chunk: rel_xyz(3) | rot(rot_dim) | gripper(1).
+ rotation_repr: "rot6d" (default), "quat_xyzw" or "axis_angle".
+ eef_extrinsic: optional (4,4) SE(3) ``E`` mapping the UMI gripper frame to
+ the robot's reported gripper frame (``current_robot = current_umi @ E``).
+ When given, each relative step is re-expressed in the robot frame by
+ conjugation ``rel' = E^-1 @ rel @ E`` before composing. Covers both a
+ gripper-orientation calibration AND a flange->TCP translation offset
+ (e.g. a flange->TCP offset ``[0,0,0.118]`` if FK reports the flange).
+ ``None`` (default) == identity == plain ``world = current @ rel``.
+
+ Returns:
+ world_pos: (H, 3) absolute positions.
+ world_quat: (H, 4) absolute orientations [qx,qy,qz,qw], qw >= 0.
+ gripper: (H,) absolute gripper command (model output, unscaled).
+ """
+ current = pose_xyzw_to_matrix(np.asarray(current_pose_xyzw, np.float32)) # (4,4)
+ actions = np.asarray(actions, dtype=np.float32)
+ rd = rot_dim(rotation_repr)
+ n = actions.shape[0]
+ rel = np.broadcast_to(np.eye(4, dtype=np.float32), (n, 4, 4)).copy()
+ rel[:, :3, 3] = actions[:, 0:3]
+ rel[:, :3, :3] = _rel_rotation_to_matrix(actions[:, 3:3 + rd], rotation_repr)
+ if eef_extrinsic is not None:
+ e = np.asarray(eef_extrinsic, dtype=np.float32).reshape(4, 4)
+ e_inv = invert_transform(e)
+ rel = np.einsum("ij,njk,kl->nil", e_inv, rel, e) # rel' = E^-1 @ rel @ E
+ world = np.einsum("ij,njk->nik", current, rel)
+ return (
+ world[:, :3, 3].astype(np.float32),
+ matrix_to_quat_xyzw(world[:, :3, :3]),
+ actions[:, 3 + rd].astype(np.float32),
+ )
diff --git a/flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py b/flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..de364c9936c9f94f1ee9823d9c1d8528a972579b
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/codec/umi_pi05_server.py
@@ -0,0 +1,472 @@
+#!/usr/bin/env python3
+# ruff: noqa: E402
+"""Server-side inference core for the pi05 UMI policy (single- or dual-hand).
+
+Inference only: transport (websocket / ROS / ...) lives elsewhere and calls in
+here. The policy is loaded once; each call returns ABSOLUTE target EEF poses and
+gripper commands.
+
+ from umi_infer.codec.umi_pi05_server import init_server, infer_target_eef
+
+ init_server(checkpoint_dir="/", config="pi05_umi_v3") # once
+ result = infer_target_eef(observation) # per request
+
+(or hold ``UmiPi05Server(checkpoint_dir=...)`` and call ``.infer(observation)``).
+
+openpi comes from the installed package, or from ``openpi_root`` / ``--openpi-root``
+pointing at a tree containing ``src/openpi``.
+
+The leading ``2`` below is the TIME window [previous, current] of the same hands;
+``nh`` = config ``num_hands`` (1 or 2). Every pose is the gripper's 6-DOF pose.
+
+observation (input):
+ "eef_pose": (2, nh, 7) x,y,z, qx,qy,qz,qw (always xyzw; (2, 7) ok for nh=1)
+ "gripper": (2, nh) gripper width
+ "images": {config_image_key: (H, W, 3) uint8 RGB} for every configured view,
+ or "image": one (H, W, 3) array for single-view configs
+ "prompt": str (optional), "upsample": int (optional)
+
+result (output; the leading nh axis is dropped when nh == 1):
+ "target_eef_pose": (nh, M, 7) spline-upsampled target poses (xyzw)
+ "target_gripper": (nh, M) absolute gripper command
+ "times": (M,) sample times in model-step units [0, H-1]
+ "target_eef_pose_raw", "target_gripper_raw": raw decoded chunk (H samples)
+ "rel_actions": (H, nh*10) raw relative chunk per hand: rel_xyz | rot6d | grip
+ "num_samples", "upsample", "num_hands", "horizon", "rotation_repr"
+
+Decode: each step is relative to the CURRENT gripper, so ``world = current @ rel``
+and the targets come out in the same frame as the input ``eef_pose``. The chunk is
+then upsampled to M = (H-1)*N+1 samples (cubic xyz, SO(3) RotationSpline, PCHIP
+gripper; N=1 disables). See umi_spline.py.
+
+Coordinate frames: feed the robot's live base-frame gripper pose (from FK). UMI
+training data uses a different world frame, but since actions are body-relative
+and composed onto the real current pose, that world alignment cancels and must
+NOT be applied here. The only remaining correction is the optional extrinsic E
+(UMI gripper frame -> robot gripper frame): ``target = current @ (E^-1 @ rel @ E)``,
+e.g. ``--tcp-offset`` when FK reports the flange instead of the TCP.
+Default E = identity.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+from pathlib import Path
+import sys
+import tempfile
+import time
+
+import numpy as np
+
+try:
+ from . import umi_decode, umi_spline
+except ImportError: # run as a plain script
+ import umi_decode
+ import umi_spline
+
+# Optional openpi source tree (/src/openpi). Empty = use the installed openpi package
+# (e.g. `pip install -e openpi-umi`).
+DEFAULT_OPENPI_ROOT = os.environ.get("OPENPI_ROOT", "")
+DEFAULT_CONFIG = "pi05_umi_v3"
+DEFAULT_PROMPT = "fold the clothes"
+# Cubic-spline upsample factor applied to the decoded chunk before it is returned to the
+# client: each of the H model steps is split into N sub-steps -> (H-1)*N+1 samples.
+# 1 disables interpolation (raw chunk passes through). Override per request via obs["upsample"].
+DEFAULT_UPSAMPLE = 4
+
+# Keep symlinked temp cwd (for the tokenizer) alive for the process lifetime.
+_TEMP_MODEL_CWDS: list[tempfile.TemporaryDirectory] = []
+
+
+# ----------------------------------------------------------------------------- openpi setup
+def add_openpi_to_path(openpi_root) -> None:
+ """Put ``/src`` first on sys.path; no-op when openpi_root is empty."""
+ if not openpi_root:
+ return
+ src = (Path(openpi_root) / "src").resolve()
+ if not (src / "openpi").is_dir():
+ raise FileNotFoundError(f"openpi package not found under {src}")
+ if str(src) not in sys.path:
+ sys.path.insert(0, str(src))
+
+
+def prepare_model_assets(model_dir: Path | None) -> None:
+ """Make OpenPI's fixed relative tokenizer path reachable (resolve real paths BEFORE calling)."""
+ if model_dir is None:
+ return
+ if Path("model/paligemma-3b-pt-224/tokenizer.model").exists():
+ return
+ source = Path(model_dir) / "paligemma-3b-pt-224" / "tokenizer.model"
+ if not source.exists():
+ print(f"[warn] tokenizer not found at {source}; continuing with current cwd", flush=True)
+ return
+ temp_cwd = tempfile.TemporaryDirectory(prefix="umi_server_")
+ _TEMP_MODEL_CWDS.append(temp_cwd)
+ root = Path(temp_cwd.name)
+ (root / "model").symlink_to(Path(model_dir).resolve(), target_is_directory=True)
+ os.chdir(root)
+ print(f"[info] tokenizer cwd: {root / 'model'} -> {model_dir}", flush=True)
+
+
+def resolve_norm_stats(checkpoint_dir: Path, explicit: Path | None) -> Path:
+ if explicit is not None:
+ return Path(explicit).resolve()
+ cand = sorted((Path(checkpoint_dir) / "assets").glob("*/norm_stats.json"))
+ if not cand:
+ raise FileNotFoundError(f"No norm_stats.json under {checkpoint_dir}/assets; pass norm_stats=")
+ return cand[0].resolve()
+
+
+def resolve_eef_extrinsic(spec) -> np.ndarray | None:
+ """Build the optional (4,4) gripper-frame extrinsic E (UMI gripper -> robot gripper).
+
+ Accepts: None (identity, no correction); a (4,4) array / nested list; a path to a
+ .npy holding a (4,4); or a single float z = a pure translation [0,0,z] (e.g. a
+ flange->TCP offset when FK reports the flange, not the gripper).
+ """
+ if spec is None:
+ return None
+ if isinstance(spec, (int, float)):
+ e = np.eye(4, dtype=np.float32)
+ e[2, 3] = float(spec)
+ return e
+ if isinstance(spec, (str, Path)):
+ e = np.load(Path(spec))
+ else:
+ e = np.asarray(spec, dtype=np.float32)
+ e = np.asarray(e, dtype=np.float32).reshape(4, 4)
+ return e
+
+
+# ----------------------------------------------------------------------------- server core
+class UmiPi05Server:
+ """Loads the trained policy once and turns observations into world EEF targets."""
+
+ def __init__(
+ self,
+ checkpoint_dir: str | Path,
+ config: str = DEFAULT_CONFIG,
+ openpi_root: str | Path = DEFAULT_OPENPI_ROOT,
+ norm_stats: str | Path | None = None,
+ device: str = "cuda:0",
+ num_denoise_steps: int = 10,
+ prompt: str = DEFAULT_PROMPT,
+ model_dir: str | Path | None = None,
+ rotation_repr: str | None = None,
+ image_key: str | None = None,
+ enable_torch_compile: bool = False,
+ gripper_min: float | None = None,
+ gripper_max: float | None = None,
+ eef_extrinsic=None,
+ upsample: int = DEFAULT_UPSAMPLE,
+ ):
+ add_openpi_to_path(openpi_root)
+
+ # Resolve real paths BEFORE prepare_model_assets may chdir into a temp dir.
+ checkpoint_dir = Path(checkpoint_dir).resolve()
+ norm_stats_path = resolve_norm_stats(checkpoint_dir, norm_stats)
+ if model_dir is None:
+ # Directory holding paligemma-3b-pt-224/tokenizer.model (offline machines).
+ model_dir = os.environ.get("TOKENIZER_DIR") or (Path(openpi_root) / "model" if openpi_root else None)
+ prepare_model_assets(model_dir if model_dir and Path(model_dir).exists() else None)
+
+ from openpi.policies import policy_config as _policy_config
+ from openpi.training import config as _config
+
+ train_config = _config.get_config(config)
+
+ # ---- state switch: toggle state input via env without a new config ----
+ # UMI_SEND_STATE=1 -> send state (state_dropout_prob=0.0)
+ # UMI_SEND_STATE=0 -> no state (state_dropout_prob=1.0, image-only)
+ # STATE_DROPOUT_PROB= -> explicit value (takes precedence)
+ # Avoid 0 1:
+ n_out = umi_spline.num_samples_for(self.horizon, self.upsample)
+ print(f"[info] spline upsample x{self.upsample}: {self.horizon} -> {n_out} samples/chunk "
+ f"(cubic xyz, SO(3) RotationSpline, PCHIP gripper)", flush=True)
+ else:
+ print("[info] spline upsample disabled (upsample=1; raw chunk returned)", flush=True)
+ if self.eef_extrinsic is not None:
+ print(f"[info] eef_extrinsic (UMI gripper -> robot gripper) =\n{self.eef_extrinsic.round(4)}", flush=True)
+ else:
+ print("[info] eef_extrinsic=identity (target = current @ rel; base frame in == base frame out)", flush=True)
+
+ if not enable_torch_compile:
+ import torch
+ torch.compile = lambda fn, *a, **k: fn # type: ignore[assignment]
+
+ self.policy = _policy_config.create_trained_policy(
+ train_config,
+ checkpoint_dir,
+ default_prompt=prompt,
+ norm_stats_path=norm_stats_path,
+ pytorch_device=device,
+ sample_kwargs={"num_steps": num_denoise_steps},
+ )
+
+ def _eef_for_model(self, eef_xyzw: np.ndarray) -> np.ndarray:
+ """Reorder xyzw poses to config.pose_format (model input only).
+
+ openpi reads xyz_quat_xyzw as (x,y,z,w) and xyz_quat_wxyz via
+ pose[..., [4,5,6,3]], so wxyz configs get (w,x,y,z) here.
+ """
+ if self.pose_format == "xyz_quat_xyzw":
+ return eef_xyzw
+ e = np.asarray(eef_xyzw, np.float32)
+ # (...,3:7) is (x,y,z,w) -> take [w,x,y,z]
+ return np.concatenate([e[..., :3], e[..., [6, 3, 4, 5]]], axis=-1).astype(np.float32)
+
+ def _clip_gripper(self, gripper: np.ndarray) -> np.ndarray:
+ if self.gripper_min is None and self.gripper_max is None:
+ return gripper
+ lo = -np.inf if self.gripper_min is None else self.gripper_min
+ hi = np.inf if self.gripper_max is None else self.gripper_max
+ return np.clip(gripper, lo, hi)
+
+ # ---- the per-request entry point ----
+ def infer(self, observation: dict) -> dict:
+ """observation -> {target_eef_pose (M,7), target_gripper (M,), rel_actions (H,A), ...}.
+
+ The decoded H-step chunk is cubic-spline upsampled to M = (H-1)*N+1 samples
+ before return (N = obs["upsample"] or the server default); ``target_eef_pose`` /
+ ``target_gripper`` are that smooth, denser trajectory (what the client tracks).
+ The raw model chunk stays available as ``*_raw``. Set upsample=1 to disable
+ (then M == H and the interpolated arrays equal the raw ones).
+
+ ``observation["eef_pose"]`` is always **xyzw** (see pose_format in __init__).
+ """
+ nh = self.num_hands
+ eef = np.asarray(observation["eef_pose"], dtype=np.float32).reshape(2, nh, 7)
+ grip = np.asarray(observation["gripper"], dtype=np.float32).reshape(2, nh)
+ prompt = observation.get("prompt", self.prompt)
+
+ obs = {
+ # Model input follows config.pose_format; umi_decode below still uses xyzw eef.
+ "observation.state.eef_pose": self._eef_for_model(eef),
+ "observation.state.gripper_width": grip,
+ "prompt": prompt,
+ }
+ # images: single-hand callers pass "image" (one array); dual-hand callers pass
+ # "images": {config_image_key: array} covering every configured view.
+ if "images" in observation:
+ for k in self.image_keys:
+ if k not in observation["images"]:
+ raise ValueError(f"observation['images'] missing configured view {k!r}")
+ obs[k] = np.asarray(observation["images"][k])
+ else:
+ obs[self.image_key] = np.asarray(observation["image"])
+ actions = np.asarray(self.policy.infer(obs)["actions"], dtype=np.float32) # (H, nh*10)
+
+ try:
+ upsample = max(int(observation.get("upsample", self.upsample)), 1)
+ except (TypeError, ValueError):
+ upsample = self.upsample
+
+ # per-hand eef_extrinsic: a single (4,4) applies to every hand; a list/tuple
+ # of length nh gives one per hand (entries may be None).
+ ee = self.eef_extrinsic
+ ee_per_hand = list(ee) if isinstance(ee, (list, tuple)) else [ee] * nh
+
+ raw_pose, raw_gripper, tgt_pose, tgt_grip, times = [], [], [], [], None
+ for h in range(nh):
+ acts_h = actions[:, 10 * h : 10 * h + 10]
+ pos, quat, gripper = umi_decode.decode_actions_to_world(
+ eef[1, h], acts_h, self.rotation_repr, eef_extrinsic=ee_per_hand[h]
+ )
+ gripper = self._clip_gripper(gripper)
+ raw_pose.append(np.concatenate([pos, quat], axis=-1).astype(np.float32))
+ raw_gripper.append(gripper.astype(np.float32))
+ pos_i, quat_i, grip_i, times = umi_spline.resample_pose_chunk(
+ pos, quat, gripper, upsample=upsample)
+ tgt_pose.append(np.concatenate([pos_i, quat_i], axis=-1).astype(np.float32))
+ tgt_grip.append(self._clip_gripper(grip_i).astype(np.float32))
+
+ if nh == 1: # single-hand callers keep the original (M,7)/(M,) shapes
+ tgt_pose, tgt_grip, raw_pose, raw_gripper = tgt_pose[0], tgt_grip[0], raw_pose[0], raw_gripper[0]
+ else: # dual: stacked (nh, M, 7) / (nh, M)
+ tgt_pose, tgt_grip = np.stack(tgt_pose), np.stack(tgt_grip)
+ raw_pose, raw_gripper = np.stack(raw_pose), np.stack(raw_gripper)
+
+ return {
+ "target_eef_pose": tgt_pose, # (M,7) or (nh,M,7) -> client tracks this
+ "target_gripper": tgt_grip, # (M,) or (nh,M)
+ "times": times.astype(np.float32), # (M,) sample times in model-step units [0, H-1]
+ "num_samples": int(times.shape[0]), # M
+ "upsample": upsample, # N actually applied this call
+ "num_hands": nh,
+ "target_eef_pose_raw": raw_pose, # raw decoded chunk (pre-interpolation)
+ "target_gripper_raw": raw_gripper,
+ "rel_actions": actions, # (H, nh*10) raw relative chunk
+ "horizon": int(actions.shape[0]), # H (model action horizon)
+ "rotation_repr": self.rotation_repr,
+ }
+
+
+# ----------------------------------------------------------------------------- module-level API
+_SERVER: UmiPi05Server | None = None
+
+
+def init_server(**kwargs) -> UmiPi05Server:
+ """Load the policy once. Pass the same kwargs as UmiPi05Server(...)."""
+ global _SERVER
+ _SERVER = UmiPi05Server(**kwargs)
+ return _SERVER
+
+
+def infer_target_eef(observation: dict) -> dict:
+ """Per-request inference. Requires init_server(...) to have been called once.
+
+ This is the function the transport layer is expected to call.
+ """
+ if _SERVER is None:
+ raise RuntimeError("call init_server(...) once before infer_target_eef(...)")
+ return _SERVER.infer(observation)
+
+
+# ----------------------------------------------------------------------------- self-test
+def run_selftest(server: UmiPi05Server) -> None:
+ print("[selftest] one inference on synthetic obs...", flush=True)
+ cur = np.array([0.4, 0.0, 0.3, 0.0, 0.0, 0.0, 1.0], dtype=np.float32)
+ prev = cur.copy()
+ prev[0] -= 0.01 # the previous frame was 1cm behind -> nonzero motion
+ obs = {
+ "image": np.zeros((480, 640, 3), dtype=np.uint8),
+ "eef_pose": np.stack([prev, cur], axis=0), # (2,7)
+ "gripper": np.array([0.05, 0.05], dtype=np.float32), # (2,)
+ "prompt": server.prompt,
+ }
+ t0 = time.time()
+ out = infer_target_eef(obs)
+ dt = (time.time() - t0) * 1000
+ print(f"[selftest] OK infer={dt:.0f}ms horizon={out['horizon']} repr={out['rotation_repr']}", flush=True)
+ print(f"[selftest] upsample x{out['upsample']}: raw{out['target_eef_pose_raw'].shape} -> "
+ f"interp{out['target_eef_pose'].shape} (num_samples={out['num_samples']})", flush=True)
+ print(f"[selftest] target_eef_pose{out['target_eef_pose'].shape} target_gripper{out['target_gripper'].shape}",
+ flush=True)
+ # Knot reproduction: the first/last interpolated samples must equal the raw chunk endpoints.
+ # Compare the quaternion block sign-agnostically (q and -q are the same rotation).
+ def _pose_close(a, b, atol=1e-4):
+ pos_ok = np.allclose(a[:3], b[:3], atol=atol)
+ q1, q2 = a[3:7], b[3:7]
+ quat_ok = np.allclose(q1, q2, atol=atol) or np.allclose(q1, -q2, atol=atol)
+ return pos_ok and quat_ok
+ assert _pose_close(out['target_eef_pose'][0], out['target_eef_pose_raw'][0])
+ assert _pose_close(out['target_eef_pose'][-1], out['target_eef_pose_raw'][-1])
+ qn = np.linalg.norm(out['target_eef_pose'][:, 3:7], axis=-1)
+ print(f"[selftest] quat |q| in [{qn.min():.5f}, {qn.max():.5f}] (should be ~1); "
+ f"endpoints match raw chunk OK", flush=True)
+ print(f"[selftest] first target pose={np.round(out['target_eef_pose'][0], 4)} "
+ f"grip={out['target_gripper'][0]:.4f}", flush=True)
+ print(f"[selftest] last target pose={np.round(out['target_eef_pose'][-1], 4)} "
+ f"grip={out['target_gripper'][-1]:.4f}", flush=True)
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="UMI pi05 inference server core (self-test / wiring helper)")
+ ap.add_argument("--checkpoint-dir", type=Path, required=True)
+ ap.add_argument("--config", default=DEFAULT_CONFIG)
+ ap.add_argument("--openpi-root", type=Path, default=DEFAULT_OPENPI_ROOT)
+ ap.add_argument("--norm-stats", type=Path, default=None)
+ ap.add_argument("--device", default="cuda:0")
+ ap.add_argument("--num-denoise-steps", type=int, default=10)
+ ap.add_argument("--prompt", default=DEFAULT_PROMPT)
+ ap.add_argument("--model-dir", type=Path, default=None)
+ ap.add_argument("--rotation-repr", default=None, choices=[None, "rot6d", "quat_xyzw", "axis_angle"])
+ ap.add_argument("--image-key", default=None)
+ ap.add_argument("--gripper-min", type=float, default=None)
+ ap.add_argument("--gripper-max", type=float, default=None)
+ ap.add_argument("--eef-extrinsic", type=Path, default=None,
+ help="path to a (4,4) .npy SE(3) E (UMI gripper -> robot gripper); default identity")
+ ap.add_argument("--tcp-offset", type=float, default=None,
+ help="shorthand: pure-translation extrinsic [0,0,z] (e.g. 0.118 if FK reports the flange)")
+ ap.add_argument("--upsample", type=int, default=DEFAULT_UPSAMPLE,
+ help="cubic-spline upsample factor N: H -> (H-1)*N+1 samples (1 disables; default 4)")
+ ap.add_argument("--selftest", action="store_true", help="run one inference on synthetic input (no transport)")
+ args = ap.parse_args()
+
+ eef_extrinsic = args.eef_extrinsic if args.eef_extrinsic is not None else args.tcp_offset
+
+ server = init_server(
+ checkpoint_dir=args.checkpoint_dir,
+ config=args.config,
+ openpi_root=args.openpi_root,
+ norm_stats=args.norm_stats,
+ device=args.device,
+ num_denoise_steps=args.num_denoise_steps,
+ prompt=args.prompt,
+ model_dir=args.model_dir,
+ rotation_repr=args.rotation_repr,
+ image_key=args.image_key,
+ gripper_min=args.gripper_min,
+ gripper_max=args.gripper_max,
+ eef_extrinsic=eef_extrinsic,
+ upsample=args.upsample,
+ )
+ if args.selftest:
+ run_selftest(server)
+ else:
+ print("[ready] model loaded. import init_server/infer_target_eef from this module, "
+ "or pass --selftest to verify.", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/flexiv-umi-infer/umi_infer/codec/umi_spline.py b/flexiv-umi-infer/umi_infer/codec/umi_spline.py
new file mode 100644
index 0000000000000000000000000000000000000000..e71b641d19de6ae1fe0b1203e8a44b319375d95d
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/codec/umi_spline.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Cubic-spline resampling of the decoded EEF target chunk before it is sent to the client.
+
+The pi05 UMI policy emits a chunk of ``H`` (=50) absolute gripper-EEF targets at the
+model's output step rate. A robot controller usually wants a *denser*, smooth trajectory
+to track. This module resamples the chunk onto a finer uniform time grid with a proper
+cubic spline:
+
+ position (xyz) -> scipy.interpolate.CubicSpline (C2, not-a-knot)
+ orientation (quat xyzw) -> scipy.spatial.transform.RotationSpline (C2 cubic on SO(3))
+ gripper (scalar) -> scipy.interpolate.PchipInterpolator (monotone, no overshoot)
+
+Rotation is interpolated **on the SO(3) manifold**, NOT componentwise on the quaternion
+(which would leave the unit sphere and distort the path / require ad-hoc renormalisation).
+``RotationSpline`` builds a C2 curve minimising angular acceleration — the rotational
+analogue of a cubic position spline. The gripper uses a shape-preserving PCHIP so the
+interpolant never overshoots past the commanded open/close range (a plain cubic can ring).
+
+The original ``H`` knots are reproduced exactly: with ``upsample=N`` the output grid is
+``t = 0, 1/N, 2/N, ..., H-1`` (``(H-1)*N + 1`` samples), so every integer step — an
+original model sample — lands on the grid and the splines pass through the raw poses there.
+``num_out`` overrides this with an explicit sample count (still spanning ``[0, H-1]``).
+"""
+
+from __future__ import annotations
+
+import numpy as np
+from scipy.interpolate import CubicSpline, PchipInterpolator
+from scipy.spatial.transform import Rotation, RotationSpline
+
+__all__ = ["resample_pose_chunk", "num_samples_for"]
+
+
+def _canon_quat_xyzw(quat: np.ndarray) -> np.ndarray:
+ """Unit-normalise and canonicalise [qx,qy,qz,qw] to qw >= 0 (matches umi_decode)."""
+ quat = np.asarray(quat, dtype=np.float32)
+ quat = quat / np.maximum(np.linalg.norm(quat, axis=-1, keepdims=True), 1e-8)
+ return np.where(quat[..., 3:4] < 0, -quat, quat).astype(np.float32)
+
+
+def num_samples_for(horizon: int, upsample: int = 4, num_out: int | None = None) -> int:
+ """How many samples ``resample_pose_chunk`` will emit for a given chunk (no compute).
+
+ Mirrors the same guards as ``resample_pose_chunk``: fewer than 2 knots, or a target
+ grid no denser than the chunk, is a no-op that returns the original ``horizon``.
+ """
+ if horizon < 2:
+ return int(horizon)
+ m = int(num_out) if num_out is not None else max(int(upsample), 1) * (horizon - 1) + 1
+ return m if m > horizon else int(horizon)
+
+
+def resample_pose_chunk(
+ pos: np.ndarray,
+ quat_xyzw: np.ndarray,
+ gripper: np.ndarray,
+ upsample: int = 4,
+ num_out: int | None = None,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Cubic-spline resample an EEF target chunk onto a denser uniform time grid.
+
+ Args:
+ pos: (H, 3) absolute positions.
+ quat_xyzw: (H, 4) absolute orientations [qx, qy, qz, qw].
+ gripper: (H,) absolute gripper command.
+ upsample: int N; output has ``(H-1)*N + 1`` samples (each model step split into
+ N sub-steps). ``N <= 1`` disables resampling (inputs returned as-is).
+ num_out: optional explicit output sample count; overrides ``upsample``.
+
+ Returns:
+ pos_i (M, 3) float32 positions,
+ quat_i (M, 4) float32 orientations [qx,qy,qz,qw] (unit, qw >= 0),
+ grip_i (M,) float32 gripper command,
+ times (M,) float32 sample times in original-step units [0, H-1].
+ ``M == H`` (inputs unchanged) when resampling is a no-op.
+ """
+ pos = np.asarray(pos, dtype=np.float32)
+ quat_xyzw = _canon_quat_xyzw(quat_xyzw)
+ gripper = np.asarray(gripper, dtype=np.float32).reshape(-1)
+ horizon = pos.shape[0]
+ t_src = np.arange(horizon, dtype=np.float64)
+
+ m = num_samples_for(horizon, upsample, num_out)
+
+ # Need >=2 knots to spline, and no work if the target grid isn't denser than the chunk.
+ if horizon < 2 or m <= horizon:
+ return pos, quat_xyzw, gripper, t_src.astype(np.float32)
+
+ t_dst = np.linspace(0.0, horizon - 1.0, m)
+ pos_i = CubicSpline(t_src, pos, axis=0)(t_dst).astype(np.float32)
+ rots = Rotation.from_quat(quat_xyzw) # scipy quaternions are scalar-last [x,y,z,w]
+ quat_i = _canon_quat_xyzw(RotationSpline(t_src, rots)(t_dst).as_quat())
+ grip_i = PchipInterpolator(t_src, gripper)(t_dst).astype(np.float32)
+ return pos_i, quat_i, grip_i, t_dst.astype(np.float32)
diff --git a/flexiv-umi-infer/umi_infer/config.py b/flexiv-umi-infer/umi_infer/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a2539fb85c4803346bc833aa1f892e702672fcb
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/config.py
@@ -0,0 +1,47 @@
+"""Shared configuration for the policy server and robot agent."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import List
+
+# Max websocket frame size. Camera payloads can be large; give plenty of headroom.
+MAX_WS_SIZE = 64 * 1024 * 1024
+
+
+@dataclass
+class Config:
+ # Network
+ host: str = "0.0.0.0" # server bind address
+ port: int = 8765
+
+ # Control loop
+ control_rate_hz: float = 8.0 # cap on inference-request cadence (min interval
+ # between obs->chunk requests); the fixed-rate
+ # servo loop stays ON the robot, not over the network
+ servo_rate_hz: float = 100.0 # robot-side EEF servo publish rate (local executor)
+ control_mode: str = "eef_pose" # 'eef_pose' | 'joint'
+
+ # Trajectory chunking + inference pacing
+ # The policy returns a K-step chunk (eef_traj + dt); the robot executes it
+ # locally at servo_rate and only requests the next chunk on a trigger.
+ inference_mode: str = "sync" # 'sync' | 'async'
+ # sync : run the whole chunk, hold, grab FRESH obs,
+ # infer, run next (VLA always sees current state).
+ # async: refill at refill_at_fraction and overlap
+ # inference with the chunk tail (smoother, but
+ # the obs the VLA sees is slightly in the past).
+ chunk_size: int = 50 # K steps per chunk (mock uses this)
+ chunk_dt: float = 0.02 # seconds between chunk steps (50Hz native -> 1.0s/chunk)
+ refill_at_fraction: float = 0.7 # async only: request next chunk at this consumed fraction
+ settle_s: float = 0.0 # sync only: extra dwell after a chunk ends before grabbing obs
+ max_stale_s: float = 1.5 # executor holds the last pose this long with no new chunk,
+ # then stops publishing.
+ # MUST exceed worst-case inference+RTT or sync holds misfire.
+
+ # Cameras the agent reports (mock uses these as names)
+ cameras: List[str] = field(default_factory=lambda: ["left_wrist", "right_wrist"])
+
+ # Connection behavior (agent)
+ reconnect: bool = True
+ connect_timeout_s: float = 10.0
diff --git a/flexiv-umi-infer/umi_infer/export_E.py b/flexiv-umi-infer/umi_infer/export_E.py
new file mode 100644
index 0000000000000000000000000000000000000000..21d04c54745e89c791b5459db53e7abfc9a910ed
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/export_E.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+"""Export the policy-side extrinsic E of each arm from the URDF, with self-checks.
+
+The policy convention is ``T_flange = T_cam @ E``:
+ T_flange = pose the robot reports (flange/TCP, shared world frame)
+ T_cam = the "end effector" of the dataset = the wrist camera optical frame
+so ``E = T_cam_flange = inv(T_flange_cam)``. Re-run this after every URDF change.
+
+The URDF camera pose is either CAD (identical on both arms relative to the gripper body) or
+per-arm hand-eye calibrated (arms differ by a few mm). The source is recorded in E_from_urdf.json so a run can always
+tell which one it used.
+
+Usage:
+ python -m umi_infer.export_E --urdf [--out-dir data]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+
+import numpy as np
+
+from .robot_io import kin_flexiv as K
+
+CAD, CALIBRATED = "cad", "calibrated"
+
+
+def main():
+ ap = argparse.ArgumentParser(description="export E = inv(T_flange_cam) from the URDF")
+ ap.add_argument("--urdf", default=K.URDF)
+ ap.add_argument("--out-dir", default=K.DATA_DIR)
+ a = ap.parse_args()
+ os.makedirs(a.out_dir, exist_ok=True)
+ print("URDF: %s camera link: %s" % (a.urdf, K.CAM_LINK))
+
+ summary = {"urdf": os.path.abspath(a.urdf), "cam_link": K.CAM_LINK, "sides": {}}
+ X, G = {}, {}
+ for side in ("left", "right"):
+ arm = K.Arm(side, urdf=a.urdf, robot=False, verbose=False) # FK only, no robot connection
+ X[side] = arm.T_flange_cam()
+ # Camera relative to the gripper body: equal on both arms for CAD values, even when the
+ # gripper is mounted at a different angle on each flange.
+ q0 = np.zeros(7)
+ G[side] = np.linalg.inv(arm.fk(q0, "grip_base_link")) @ arm.fk(q0, K.CAM_LINK)
+ E = np.linalg.inv(X[side])
+ resid = float(np.abs(X[side] @ E - np.eye(4)).max())
+ # The flange->camera transform must not depend on the joint angles.
+ drift_mm = float(np.abs(X[side] - arm.T_flange_cam(
+ np.radians([30., 60., -40., 100., 20., 80., -50.]))).max() * 1000)
+ if resid > 1e-9 or drift_mm > 1e-6:
+ raise SystemExit("%s: self-check failed (X*E-I %.2e, joint drift %.2e mm)" % (side, resid, drift_mm))
+ p = os.path.abspath(os.path.join(a.out_dir, "E_%s.npy" % side))
+ np.save(p, E.astype(np.float32))
+ t = X[side][:3, 3] * 1000
+ print("[%-5s] T_flange_cam t = [%+8.2f %+8.2f %+8.2f] mm -> %s" % (side, *t, p))
+ summary["sides"][side] = {"T_flange_cam": X[side].tolist(), "E_T_cam_flange": E.tolist(),
+ "t_flange_cam_mm": np.round(t, 3).tolist(), "npy": p}
+
+ diff_mm = float(np.linalg.norm(G["left"][:3, 3] - G["right"][:3, 3]) * 1000)
+ diff_deg = K.ang_between(G["left"][:3, :3], G["right"][:3, :3])
+ summary["camera_pose_source"] = CAD if diff_mm < 0.01 and diff_deg < 1e-3 else CALIBRATED
+ summary["two_arm_diff_mm"] = round(diff_mm, 4)
+ print("camera vs gripper body: arms differ by %.3f mm / %.3f deg -> camera pose source: %s"
+ % (diff_mm, diff_deg, summary["camera_pose_source"]))
+ j = os.path.join(a.out_dir, "E_from_urdf.json")
+ with open(j, "w") as f:
+ json.dump(summary, f, indent=1)
+ print("summary -> %s" % j)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/flexiv-umi-infer/umi_infer/policies/__init__.py b/flexiv-umi-infer/umi_infer/policies/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/flexiv-umi-infer/umi_infer/policies/base.py b/flexiv-umi-infer/umi_infer/policies/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1c6f6fd94cda47fc44837c5d86084426c9a5093
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/policies/base.py
@@ -0,0 +1,24 @@
+"""Policy interface. The real VLA model plugs in here."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+from ..protocol import Action, Observation
+
+
+class Policy(ABC):
+ """Maps an Observation to an Action.
+
+ SEAM: replace MockPolicy with your VLA here. ``infer`` runs inside the server's
+ asyncio handler, so if the model is heavy, run it in a thread/process executor
+ (the server can ``await loop.run_in_executor(...)``) to avoid blocking I/O.
+ """
+
+ @abstractmethod
+ def reset(self) -> None:
+ """Reset any internal state (called when a client connects)."""
+
+ @abstractmethod
+ def infer(self, obs: Observation) -> Action:
+ """Return the Action for this Observation (echo ``obs.seq`` into the Action)."""
diff --git a/flexiv-umi-infer/umi_infer/policies/flux_action_dual.py b/flexiv-umi-infer/umi_infer/policies/flux_action_dual.py
new file mode 100644
index 0000000000000000000000000000000000000000..041e045cdfc1f044bc60422e75ebcb40ce2876b1
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/policies/flux_action_dual.py
@@ -0,0 +1,350 @@
+"""FLUX Action dual-hand UMI adapter for the existing msgpack policy server.
+
+Input/output poses on the wire are xyzw flange poses. The FLUX training
+representation uses wxyz camera/gripper poses; E maps data frame to flange.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import sys
+import time
+from pathlib import Path
+
+import numpy as np
+
+from ..protocol import Action, Observation
+from ..codec import umi_decode
+from .base import Policy
+
+log = logging.getLogger("umi_infer.flux_action_dual")
+SIDES = ("left", "right")
+CAMERAS = ("images.left_ego", "images.right_ego")
+# Frozen video VAE + text encoder: /video_vae.safetensors and /text_encoder/.
+DEFAULT_RESOURCES = Path(os.environ.get("FLUX_RESOURCES", "weights/flux_resources"))
+
+
+def validate_model_contract(config):
+ """Accept only the verified 20-D UMI contract (flux-umi); never guess another channel layout."""
+ required = {"chunk_size": 32, "fps": 30, "camera_layout": "side_by_side",
+ "canvas_hw": [256, 512], "camera_keys": list(CAMERAS),
+ "torch_dtype": "bfloat16", "quantization": None,
+ "inference_profile": "default", "action_parameterization": "absolute"}
+ for key, expected in required.items():
+ value = config.get(key)
+ if isinstance(expected, list) and isinstance(value, tuple):
+ value = list(value)
+ if value != expected:
+ raise ValueError("unsupported FLUX UMI contract: " + key)
+ dim = config.get("action_dim")
+ if dim != 20 or config.get("gripper_flip_dims") or config.get("absolute_action_dims"):
+ raise ValueError("unsupported FLUX UMI action contract")
+ if config.get("cached_video_latents"):
+ raise ValueError("inference export must accept live images, not latent-cache training input")
+ for key in ("state_normalization", "action_normalization"):
+ stats = config.get(key) or {}
+ arrays = [np.asarray(stats.get(field), dtype=np.float64) for field in ("q01", "q99")]
+ if any(a.shape != (dim,) or not np.isfinite(a).all() for a in arrays):
+ raise ValueError("normalization shape/values do not match " + key)
+ if np.any(arrays[1] < arrays[0]):
+ raise ValueError("invalid quantile bounds")
+ return dim
+
+
+def _pose_matrix(pose):
+ value = np.asarray(pose, dtype=np.float64)
+ if value.shape != (7,) or not np.isfinite(value).all() or np.any(np.abs(value) > np.finfo(np.float32).max):
+ raise ValueError("expected finite xyzw pose (7,)")
+ norm = np.linalg.norm(value[3:])
+ if norm < 1e-8:
+ raise ValueError("zero pose quaternion")
+ return umi_decode.pose_xyzw_to_matrix(value.astype(np.float32)).astype(np.float64)
+
+
+def _matrix_pose(transform):
+ transform = np.asarray(transform, dtype=np.float64)
+ quat = umi_decode.matrix_to_quat_xyzw(transform[:3, :3].astype(np.float32))
+ return np.r_[transform[:3, 3], quat].astype(np.float32)
+
+
+def _extrinsic(spec):
+ if spec is None:
+ return np.eye(4, dtype=np.float64)
+ path = Path(spec)
+ if not path.is_file():
+ raise FileNotFoundError(f"extrinsic file not found: {path}")
+ e = np.asarray(np.load(path, allow_pickle=False), dtype=np.float64)
+ if (e.shape != (4, 4) or not np.isfinite(e).all()
+ or np.any(np.abs(e) > np.finfo(np.float32).max)):
+ raise ValueError(f"invalid extrinsic: {path}")
+ if not np.allclose(e[3], [0, 0, 0, 1], atol=1e-6) or not np.allclose(
+ e[:3, :3].T @ e[:3, :3], np.eye(3), atol=1e-4
+ ) or not np.isclose(np.linalg.det(e[:3, :3]), 1.0, atol=1e-4):
+ raise ValueError(f"extrinsic is not a rigid transform: {path}")
+ return e
+
+
+def validate_extrinsics(left, right, provenance=None):
+ """Require both flange extrinsics and check them against their saved URDF export."""
+ specs = {"left": left, "right": right}
+ if not all(specs.values()):
+ raise ValueError("FLUX needs E_LEFT and E_RIGHT; identity is only for offline tests")
+ matrices = {side: _extrinsic(path) for side, path in specs.items()}
+ if provenance is not None:
+ record = json.loads(Path(provenance).read_text())
+ if record.get("camera_pose_source") not in ("cad", "calibrated"):
+ raise ValueError("unknown E provenance: " + str(provenance))
+ urdf = Path(record["urdf"])
+ if not urdf.is_file() or urdf.stat().st_mtime_ns > Path(provenance).stat().st_mtime_ns:
+ raise ValueError("E provenance is older than or missing its URDF")
+ for side in SIDES:
+ saved = record["sides"][side]
+ if Path(saved["npy"]).resolve() != Path(specs[side]).resolve():
+ raise ValueError(f"{side} E path differs from URDF export")
+ if not np.allclose(matrices[side], saved["E_T_cam_flange"], rtol=0, atol=1e-6):
+ raise ValueError(f"{side} E differs from URDF export")
+ return matrices
+
+
+def encode_state(current, previous, gripper, e_inv):
+ """Mirror relative_hand(current, previous), using the current gripper."""
+ cur = _pose_matrix(current) @ e_inv
+ prev = _pose_matrix(previous) @ e_inv
+ if not np.isfinite(gripper) or abs(gripper) > np.finfo(np.float32).max:
+ raise ValueError("invalid gripper")
+ relative = np.linalg.inv(cur) @ prev
+ state = np.r_[relative[:3, 3], relative[:3, 0], relative[:3, 1], gripper].astype(np.float32)
+ if not np.isfinite(state).all():
+ raise ValueError("FLUX state overflowed during coordinate conversion")
+ return state, cur
+
+
+def decode_targets(anchor, relative, e):
+ """Invert the training's column-ordered rot6d and map targets to flange."""
+ values = np.asarray(relative, dtype=np.float64)
+ if (values.ndim != 2 or values.shape[1] != 10 or not np.isfinite(values).all()
+ or np.any(np.abs(values) > np.finfo(np.float32).max)):
+ raise ValueError("expected finite (steps, 10) targets")
+ a, b = values[:, 3:6], values[:, 6:9]
+ norm_a = np.linalg.norm(a, axis=-1, keepdims=True)
+ if np.any(norm_a < 1e-8):
+ raise ValueError("degenerate first rotation column")
+ a = a / norm_a
+ b = b - (a * b).sum(-1, keepdims=True) * a
+ norm_b = np.linalg.norm(b, axis=-1, keepdims=True)
+ if np.any(norm_b < 1e-8):
+ raise ValueError("degenerate second rotation column")
+ b = b / norm_b
+ transforms = np.broadcast_to(np.eye(4), (len(values), 4, 4)).copy()
+ transforms[:, :3, 3] = values[:, :3]
+ transforms[:, :3, :3] = np.stack((a, b, np.cross(a, b)), axis=-1)
+ absolute = anchor @ transforms @ e
+ poses = np.stack([_matrix_pose(t) for t in absolute])
+ grippers = values[:, 9].astype(np.float32)
+ if not np.isfinite(poses).all() or not np.isfinite(grippers).all():
+ raise ValueError("FLUX targets overflowed during coordinate conversion")
+ return poses, grippers
+
+
+def decode_yuv420p(frame, size=(256, 256)):
+ """I420 planes -> RGB via the same call the training cache uses:
+ pyav ``to_ndarray(rgb24, width, height)``. pyav ignores color tags
+ (bt709/601, tv/pc), so identical planes give bit-identical pixels."""
+ import av
+
+ h, w = int(frame.height), int(frame.width)
+ if h <= 0 or w <= 0 or h % 2 or w % 2 or len(frame.data) != h * w * 3 // 2:
+ raise ValueError("invalid yuv420p wrist frame")
+ planes = np.frombuffer(frame.data, np.uint8).reshape(h * 3 // 2, w)
+ video = av.VideoFrame.from_ndarray(planes, format="yuv420p")
+ height, width = size
+ return video.to_ndarray(format="rgb24", width=width, height=height)
+
+
+def decode_image(frame, size=(256, 256)):
+ """Match the training ffmpeg bilinear scale and RGB24 pixel conversion."""
+ if frame is not None and frame.format == "yuv420p":
+ return decode_yuv420p(frame, size)
+ from io import BytesIO
+ import subprocess
+
+ from PIL import Image, UnidentifiedImageError
+
+ if frame is None or frame.format != "jpeg" or not frame.data:
+ raise ValueError("FLUX requires a JPEG or yuv420p wrist frame")
+ if frame.height <= 0 or frame.width <= 0:
+ raise ValueError("invalid wrist frame dimensions")
+ try:
+ with Image.open(BytesIO(frame.data)) as image:
+ if image.size != (frame.width, frame.height):
+ raise ValueError("JPEG dimensions disagree with wire frame")
+ except (UnidentifiedImageError, OSError) as exc:
+ raise ValueError("invalid wrist JPEG") from exc
+ height, width = size
+ result = subprocess.run(
+ ["ffmpeg", "-nostdin", "-v", "error", "-threads", "1", "-filter_threads", "1",
+ "-f", "mjpeg", "-i", "pipe:0", "-frames:v", "1", "-fps_mode", "passthrough",
+ "-vf", f"scale={width}:{height}:flags=bilinear", "-f", "rawvideo", "-pix_fmt", "rgb24", "pipe:1"],
+ input=frame.data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10, check=True,
+ )
+ if len(result.stdout) != height * width * 3:
+ raise ValueError("wrist JPEG did not decode to the training frame size")
+ return np.frombuffer(result.stdout, dtype=np.uint8).reshape(height, width, 3)
+
+
+def _prewarm_context(policy, prompt, device, cpu_contexts=None):
+ """Never allow a cache miss to move the 4B encoder onto the occupied GPU."""
+ import torch
+ from flux_action.models.text_encoder import text_contexts
+ from flux_action.processing import packing
+ from flux_action.policy import VEC_DIM
+
+ policy.reset()
+ captions = [prompt, ""] if prompt else [""]
+ if cpu_contexts is None:
+ if policy.device.type != "cpu":
+ raise RuntimeError("prewarm before moving FLUX DiT to GPU")
+ if any(p.device.type != "cpu" for p in policy.text_encoder.parameters()):
+ raise RuntimeError("text encoder must remain on CPU during prewarm")
+ cpu_contexts = text_contexts(policy.text_encoder, captions, torch.device("cpu"))
+ policy.set_text_encoder_offload(True)
+ if policy.device != torch.device(device):
+ policy.to(device)
+ policy.eval()
+ for caption, context in zip(captions, cpu_contexts, strict=True):
+ context = context.to(device=device, dtype=policy.dtype_)
+ policy._ctx_cache[caption] = (context, packing.pack_text(context, VEC_DIM)["ctx_ids"])
+ if not all(c in policy._ctx_cache and policy._ctx_cache[c][0].device == torch.device(device)
+ for c in captions):
+ raise RuntimeError("FLUX caption cache prewarm failed; refusing GPU encoder fallback")
+ return tuple(captions), cpu_contexts
+
+
+class FluxActionDualPolicy(Policy):
+ def __init__(self, *, export_dir, source_dir=None, prompt="fold the clothes", device="cuda:0",
+ resources_dir=DEFAULT_RESOURCES, extrinsics=None, image_keys=None,
+ action_horizon=0, sampler="euler", steps=4, shift=5.0,
+ guidance=1.0, action_guidance=1.0, seed=0, model=None, e_provenance=None):
+ import torch
+
+ if model is None:
+ validate_model_contract(json.loads((Path(export_dir) / "config.json").read_text()))
+ # Optional flux_action source tree; by default the installed package is used.
+ if source_dir and str(source_dir) not in sys.path:
+ sys.path.insert(0, str(source_dir))
+ self.device = torch.device(device)
+ self.prompt = str(prompt)
+ if not self.prompt:
+ raise ValueError("FLUX task prompt must not be empty")
+ self.image_keys = image_keys or {"left": "left_wrist", "right": "right_wrist"}
+ if any(not self.image_keys.get(s) for s in SIDES):
+ raise ValueError("both wrist camera keys are required")
+ self.e = validate_extrinsics((extrinsics or {}).get("left"),
+ (extrinsics or {}).get("right"), e_provenance)
+ self.e_inv = {s: np.linalg.inv(self.e[s]) for s in SIDES}
+ self.horizon = int(action_horizon)
+ if not 0 <= self.horizon <= 32:
+ raise ValueError("action horizon must be 0..32")
+ if model is None:
+ from flux_action.models.text_encoder import load_text_encoder
+ from flux_action.models.video_vae import load_video_vae
+ from flux_action.policy import FluxActionPolicy
+
+ resources = Path(resources_dir)
+ vae = load_video_vae(str(resources / "video_vae.safetensors"))
+ encoder = load_text_encoder(str(resources / "text_encoder"))
+ model = FluxActionPolicy.from_pretrained(export_dir, video_vae=vae,
+ text_encoder=encoder, device="cpu")
+ self.model = model
+ cfg = model.config
+ self.action_dim = validate_model_contract(cfg.to_dict())
+ if cfg.torch_dtype != "bfloat16" or cfg.quantization is not None:
+ raise ValueError("FLUX UMI requires unquantized bfloat16 export")
+ if list(cfg.camera_order) != list(CAMERAS) or tuple(cfg.canvas_hw) != (256, 512):
+ raise ValueError("FLUX export camera contract differs from cloth-folding UMI")
+ if cfg.action_parameterization != "absolute" or list(cfg.gripper_flip_dims):
+ raise ValueError("FLUX export action contract differs from cloth-folding UMI")
+ if cfg.inference_profile != "default" or cfg.state_normalization is None or cfg.action_normalization is None:
+ raise ValueError("FLUX export lacks the UMI default profile or dataset statistics")
+ from flux_action.config import PolicyConfig
+ cfg = PolicyConfig(**{**cfg.to_dict(), "sampler": sampler,
+ "num_inference_steps": steps, "sampler_shift": shift,
+ "guidance_scale": guidance, "guidance_scale_action": action_guidance,
+ "inference_seed": seed})
+ cfg.validate_inference()
+ model.config = cfg
+ self.settings = {"sampler": sampler, "steps": steps, "shift": shift,
+ "guidance": guidance, "action_guidance": action_guidance, "seed": seed}
+ self.dt = 1.0 / cfg.fps
+ self._captions = ()
+ self._cpu_contexts = None
+ if self.device.type == "cuda" and hasattr(model, "text_encoder"):
+ # CPU encode before uploading the DiT, then seed the cache after .to() clears it.
+ self._captions, self._cpu_contexts = _prewarm_context(self.model, prompt, self.device)
+ elif self.device.type == "cuda":
+ raise ValueError("CUDA FLUX requires an encoder with a verifiable offload cache")
+ else:
+ self.model.to(self.device).eval()
+ self.model.reset()
+ log.info("FLUX UMI ready: export=%s settings=%s device=%s E=%s (frame equivalence unverified)",
+ export_dir, self.settings, self.device, {s: self.e[s].tolist() for s in SIDES})
+
+ def reset(self):
+ if self._captions:
+ self._captions, self._cpu_contexts = _prewarm_context(
+ self.model, self.prompt, self.device, self._cpu_contexts
+ )
+ else:
+ self.model.reset()
+
+ def infer(self, obs: Observation) -> Action:
+ import torch
+
+ batch = {"task": [self.prompt]}
+ anchors = {}
+ prev_sources = {}
+ states = []
+ for side, key in zip(SIDES, CAMERAS, strict=True):
+ image = decode_image((obs.images or {}).get(self.image_keys[side]))
+ batch[key] = torch.from_numpy(image.copy()).permute(2, 0, 1)[None].to(
+ device=self.device, dtype=torch.float32) / 255.0
+ current = (obs.eef or {}).get(side)
+ previous = (obs.eef_prev or {}).get(side)
+ prev_sources[side] = "obs" if previous is not None else "current"
+ if previous is None:
+ previous = current
+ gripper = (obs.gripper or {}).get(side)
+ if gripper is None:
+ raise ValueError(f"missing {side} gripper")
+ state, anchors[side] = encode_state(current, previous, float(gripper), self.e_inv[side])
+ states.append(state)
+ batch["state"] = torch.from_numpy(np.concatenate(states)[None]).to(self.device)
+ if self._captions and any(
+ c not in self.model._ctx_cache or self.model._ctx_cache[c][0].device != self.device
+ for c in self._captions
+ ):
+ raise RuntimeError("FLUX text cache missing; refusing GPU encoder fallback")
+ started = time.perf_counter()
+ with torch.no_grad():
+ output = self.model.predict_action_chunk(batch)
+ values = output.detach().float().cpu().numpy()
+ if values.shape != (1, 32, self.action_dim) or not np.isfinite(values).all():
+ raise ValueError("invalid FLUX action output")
+ keep = self.horizon or 32
+ trajectories, grippers = {}, {}
+ for hand, side in enumerate(SIDES):
+ offset = hand * 10
+ poses, grip = decode_targets(anchors[side], values[0, :keep, offset:offset+10],
+ self.e[side])
+ trajectories[side] = poses.tolist()
+ grippers[side] = grip.tolist()
+ log.info("FLUX seq=%s steps=%d ms=%.0f prev=%s", obs.seq, keep,
+ (time.perf_counter() - started) * 1000, prev_sources)
+ return Action(seq=obs.seq, stamp=time.time(), control="eef_pose",
+ eef_target={s: trajectories[s][0] for s in SIDES},
+ gripper={s: grippers[s][0] for s in SIDES},
+ eef_traj=trajectories, gripper_traj=grippers, dt=self.dt,
+ extra={"policy": "flux", "n_steps": keep, "prev_src": prev_sources,
+ "sampler": self.settings, "action_dim": self.action_dim})
diff --git a/flexiv-umi-infer/umi_infer/policies/mock.py b/flexiv-umi-infer/umi_infer/policies/mock.py
new file mode 100644
index 0000000000000000000000000000000000000000..3afb89b296dbbdbd9e7303f4d0883e388c568cf4
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/policies/mock.py
@@ -0,0 +1,128 @@
+"""Mock policy: stands in for the VLA so we can exercise the comm end-to-end.
+
+Modes:
+ - hold : echo the observed pose.
+ - wobble : hold + small sinusoid on the right EEF z.
+ - zero : send an all-zero pose.
+ - traj : a scripted dual-arm up/down EE trajectory with gripper commands.
+"""
+
+from __future__ import annotations
+
+import math
+import time
+
+from ..protocol import Action, Observation
+from .base import Policy
+
+
+class MockPolicy(Policy):
+ """Returns a safe, predictable Action.
+
+ modes:
+ - ``hold`` : echo the observed EEF pose as the target (no commanded motion).
+ Safe default — useful to confirm the round-trip without moving.
+ - ``wobble`` : hold, plus a small sinusoid added to the right EEF z. Proves the
+ loop is closed (the agent's next observation should follow it).
+ - ``zero`` : send an all-zero pose. NEVER use on hardware; for wire tests only.
+ """
+
+ def __init__(
+ self,
+ mode: str = "hold",
+ wobble_amp_m: float = 0.02,
+ wobble_hz: float = 0.25,
+ traj_offset_m: float = 0.06,
+ traj_hold_sec: float = 0.5,
+ traj_move_up_sec: float = 2.0,
+ traj_move_down_sec: float = 2.0,
+ chunk_size: int = 50,
+ chunk_dt: float = 0.02,
+ ):
+ self.mode = mode
+ self.amp = wobble_amp_m
+ self.hz = wobble_hz
+ self.traj_offset_m = traj_offset_m
+ self.traj_hold_sec = traj_hold_sec
+ self.traj_move_up_sec = traj_move_up_sec
+ self.traj_move_down_sec = traj_move_down_sec
+ # trajectory chunk shape: each infer() returns chunk_size future steps spaced chunk_dt
+ self.chunk_size = max(1, int(chunk_size))
+ self.chunk_dt = float(chunk_dt)
+ self._t0 = time.time()
+
+ def reset(self) -> None:
+ self._t0 = time.time()
+
+ def infer(self, obs: Observation) -> Action:
+ # Build a chunk of chunk_size future steps spaced chunk_dt, starting "now".
+ now = max(0.0, time.time() - self._t0)
+ dt = self.chunk_dt
+ eef_traj: dict = {}
+ gripper_traj: dict = {}
+ for i in range(self.chunk_size):
+ eef_i, grip_i = self._sample(obs, now + i * dt)
+ for side, pose in eef_i.items():
+ eef_traj.setdefault(side, []).append(pose)
+ for side, g in grip_i.items():
+ gripper_traj.setdefault(side, []).append(float(g))
+
+ # length-1 fallback fields (first step) so single-pose consumers still work
+ eef_target = {side: seq[0] for side, seq in eef_traj.items() if seq}
+ gripper = {side: seq[0] for side, seq in gripper_traj.items() if seq}
+
+ return Action(
+ seq=obs.seq,
+ stamp=time.time(),
+ control="eef_pose",
+ eef_target=eef_target,
+ gripper=gripper,
+ eef_traj=eef_traj,
+ gripper_traj=gripper_traj,
+ dt=dt,
+ extra={"policy": "mock", "mode": self.mode, "chunk": self.chunk_size, "dt": dt},
+ )
+
+ def _sample(self, obs: Observation, t: float):
+ """Return (eef:{side:[7]}, gripper:{side:float}) for the mode at elapsed time t."""
+ eef = {side: list(pose) for side, pose in obs.eef.items() if pose and len(pose) >= 3}
+ gripper = dict(obs.gripper)
+
+ if self.mode == "wobble":
+ r = eef.get("right")
+ if r and len(r) >= 3:
+ r[2] += self.amp * math.sin(2 * math.pi * self.hz * t)
+ elif self.mode == "zero":
+ eef = {side: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] for side in obs.eef}
+ elif self.mode == "traj":
+ dz, gripper = self._traj_dz_gripper(t)
+ for side, pose in eef.items():
+ if len(pose) == 7:
+ pose[2] += dz
+ # "hold" (default): echo current pose/gripper unchanged
+ return eef, gripper
+
+ def _traj_dz_gripper(self, t: float):
+ """The dual-arm up/hold/down dz curve + per-phase gripper at elapsed time t."""
+ t = max(0.0, t)
+ hold = self.traj_hold_sec
+ move_up = self.traj_move_up_sec
+ move_down = self.traj_move_down_sec
+ total = hold + move_up + hold + move_down
+
+ if t < hold:
+ return 0.0, {"left": 0.0, "right": 0.0}
+ if t < hold + move_up:
+ s = (t - hold) / move_up if move_up > 0 else 1.0
+ return self.traj_offset_m * _smoothstep(s), {"left": 1.0, "right": 0.0}
+ if t < hold + move_up + hold:
+ return self.traj_offset_m, {"left": 1.0, "right": 1.0}
+ if t < total:
+ s = (t - hold - move_up - hold) / move_down if move_down > 0 else 1.0
+ return self.traj_offset_m * (1.0 - _smoothstep(s)), {"left": 0.0, "right": 1.0}
+ return 0.0, {"left": 0.0, "right": 0.0}
+
+
+def _smoothstep(s: float) -> float:
+ s = max(0.0, min(1.0, s))
+ return s * s * (3.0 - 2.0 * s)
diff --git a/flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py b/flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba5e3efc8481d7952e48bf8af21985a539865a6a
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/policies/umi_pi05_dual.py
@@ -0,0 +1,373 @@
+"""Dual-hand pi05 UMI policy (robot-agnostic; config given by --config).
+
+Per inference cycle:
+
+ obs (both wrist images + per-side [prev,cur] hand pose + gripper, dataset scale)
+ -> E^-1 hop per side (robot hand frame -> data gripper/camera frame G)
+ -> umi_infer.codec.umi_pi05_server.infer_target_eef (num_hands=2)
+ -> per-side absolute G-frame target chunks (anchored at each side's current pose)
+ -> E hop back per side -> Action.eef_traj/gripper_traj {"left":..., "right":...}
+
+Image sources per side: 'live' decodes obs.images[_wrist]; 'replay' plays a
+dataset episode video; 'auto' prefers live. episode_parquet switches BOTH proprio
+sides to open-loop dataset state[16] rows (DRY-RUN model-reproduction mode: targets
+are anchored in the dataset world frame, not the robot base).
+
+Flexiv: this file only deals with ``obs.eef`` (reported hand pose, xyzw) and E.
+ * robot_io/flexiv.py reports the flange/TCP pose in the shared world frame,
+ already converted from Flexiv's native wxyz to xyzw.
+ * E = inv(T_flange_cam), exported from the URDF by umi_infer/export_E.py
+ (hand-eye calibration is baked into the URDF).
+ * Hence T_G = obs.eef @ E^-1 = T_world_cam, the frame of camera-pose datasets.
+
+Quaternion column order vs config.pose_format is handled in umi_pi05_server;
+everything in this file is xyzw.
+
+VLA_QUAT_PERM (default off)
+---------------------------
+Legacy workaround for checkpoints trained on wxyz labels read as xyzw (i.e. with
+pose_format=xyz_quat_xyzw on wxyz data), which trains in a permuted rotation space.
+That misread map P is not a group homomorphism, but it is a bijection on SO(3), so it
+can be compensated at deployment:
+ in: re-anchor poses to the session's first frame, then use the true wxyz as xyzw
+ out: invert the permutation, then undo the re-anchoring
+Re-anchoring is required: since P is not a homomorphism, relative quantities in the
+misread space depend on the reference frame. This only fixes the pipeline, not the
+distorted geometry the model learned; the real fix is re-exporting and retraining.
+
+Do not guess this switch from the checkpoint path; ``_quat_perm_advice()`` checks the
+checkpoint's own config. pose_format=xyz_quat_wxyz means it was read correctly at
+training time, so QUAT_PERM must be off.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from pathlib import Path
+import time
+
+import cv2
+import numpy as np
+
+from ..protocol import Action, Observation
+from .base import Policy
+
+log = logging.getLogger("umi_infer.umi_pi05_dual")
+
+SIDES = ("left", "right")
+POSE_SLICES = {"left": (0, 7), "right": (8, 15)} # merged dual-hand flat state[16]
+GRIP_INDEX = {"left": 7, "right": 15}
+# Default off; set to 1 only for checkpoints trained on misread wxyz labels (see module doc).
+QUAT_PERM = os.environ.get("VLA_QUAT_PERM", "0") == "1"
+
+
+def _quat_perm_advice(checkpoint_dir) -> None:
+ """Check VLA_QUAT_PERM against the checkpoint's metadata.pt and warn if it looks wrong.
+
+ pose_format == xyz_quat_wxyz -> read correctly at training time -> perm must be off
+ pose_format == xyz_quat_xyzw -> perm needed only if the data was actually wxyz;
+ the config alone cannot tell, so only advise.
+ If metadata.pt is unreadable, say so and do not guess.
+ """
+ md = Path(checkpoint_dir) / "metadata.pt"
+ pf = None
+ if md.exists():
+ try:
+ import torch
+ pf = torch.load(md, map_location="cpu", weights_only=False)[
+ "config"]["data"].get("pose_format")
+ except Exception as e: # noqa: BLE001
+ log.warning("failed to read %s (%s); cannot verify VLA_QUAT_PERM", md, e)
+ return
+ else:
+ log.warning("%s not found; cannot verify VLA_QUAT_PERM", md)
+ return
+
+ if pf == "xyz_quat_wxyz":
+ if QUAT_PERM:
+ log.error("VLA_QUAT_PERM=1 but this checkpoint has pose_format=xyz_quat_wxyz; "
+ "it was trained reading wxyz correctly, so the permutation corrupts orientation. "
+ "Unset VLA_QUAT_PERM.")
+ else:
+ log.info("VLA_QUAT_PERM=0 matches checkpoint (pose_format=xyz_quat_wxyz, "
+ "column order handled by umi_pi05_server per config)")
+ elif pf == "xyz_quat_xyzw":
+ log.info("checkpoint pose_format=xyz_quat_xyzw, VLA_QUAT_PERM=%s. "
+ "Enable only if the training data was wxyz but read as xyzw; "
+ "leave off if the data really is xyzw.", int(QUAT_PERM))
+ else:
+ log.warning("unknown checkpoint pose_format=%r; verify VLA_QUAT_PERM=%s manually",
+ pf, int(QUAT_PERM))
+
+
+def _decode_video_frames(path: Path) -> list:
+ cap = cv2.VideoCapture(str(path))
+ frames = []
+ while True:
+ ok, bgr = cap.read()
+ if not ok:
+ break
+ frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
+ cap.release()
+ if not frames:
+ raise RuntimeError(f"no frames decoded from {path}")
+ return frames
+
+
+class UmiPi05DualPolicy(Policy):
+ def __init__(
+ self,
+ checkpoint_dir: str,
+ config: str = "pi05_umi_v3",
+ openpi_root: str | None = None,
+ device: str = "cuda:0",
+ prompt: str = "fold the clothes",
+ upsample: int = 1,
+ chunk_fps: float = 30.0,
+ num_denoise_steps: int = 10,
+ action_horizon: int = 0,
+ episode_videos: "dict[str, str] | None" = None, # side -> mp4 (replay/auto fallback)
+ episode_parquet: str | None = None, # open-loop proprio (DRY-RUN)
+ eef_extrinsic: "dict[str, object] | None" = None, # side -> (4,4)/path/None
+ image_source: str = "auto",
+ image_obs_keys: "dict[str, str] | None" = None, # side -> obs.images key
+ record_dir: str | None = None,
+ ):
+ self.upsample = max(int(upsample), 1)
+ self.chunk_fps = float(chunk_fps)
+ self.dt = 1.0 / (self.chunk_fps * self.upsample)
+ self.action_horizon = max(0, int(action_horizon))
+ self.prompt = prompt
+ self.image_source = str(image_source).lower()
+ self.image_obs_keys = image_obs_keys or {"left": "left_wrist", "right": "right_wrist"}
+ self.record_dir = record_dir
+
+ from ..codec import umi_decode
+ from ..codec.umi_pi05_server import init_server, resolve_eef_extrinsic
+ self._dec = umi_decode
+
+ # E per side (robot hand frame -> data gripper frame G, T_hand = T_G @ E).
+ # Applied SYMMETRICALLY here (input x E^-1, output x E); the server decodes with identity.
+ self._E = {}
+ self._E_inv = {}
+ for s in SIDES:
+ e = resolve_eef_extrinsic((eef_extrinsic or {}).get(s))
+ self._E[s] = e
+ self._E_inv[s] = None if e is None else np.linalg.inv(e)
+ log.info("E[%s] = %s", s, "identity" if e is None else np.round(e, 4).tolist())
+
+ # replay videos per side
+ self._frames = {}
+ for s in SIDES:
+ p = (episode_videos or {}).get(s)
+ self._frames[s] = _decode_video_frames(Path(p).resolve()) if p else []
+ if self._frames[s]:
+ log.info("replay video[%s]: %d frames", s, len(self._frames[s]))
+ self._cursor = 0
+ self._last_live = {s: None for s in SIDES}
+
+ # open-loop parquet proprio (both sides from dataset state[16])
+ self._pq_state = None
+ self.input_source = "live"
+ if episode_parquet:
+ import pandas as pd
+ df = pd.read_parquet(Path(episode_parquet).resolve()).sort_values("frame_index")
+ self._pq_state = np.stack(df["observation.state"].to_numpy()).astype(np.float32)
+ self.input_source = "parquet"
+ log.info("open-loop PARQUET proprio: %s rows=%d", episode_parquet, len(self._pq_state))
+
+ # config's image keys, in the same left/right roles the model was trained with
+ srv = init_server(
+ checkpoint_dir=checkpoint_dir,
+ config=config,
+ openpi_root=openpi_root or "",
+ device=device,
+ num_denoise_steps=num_denoise_steps,
+ prompt=prompt,
+ upsample=self.upsample,
+ eef_extrinsic=None, # E handled symmetrically HERE
+ )
+ if srv.num_hands != 2:
+ raise ValueError(f"config {config} is not dual-hand (num_hands={srv.num_hands})")
+ from ..codec.umi_pi05_server import infer_target_eef
+ self._infer = infer_target_eef
+ # config image keys: order in srv.image_keys is (base, left, right) filtered
+ self._model_image_key = {"left": None, "right": None}
+ for k in srv.image_keys:
+ if "left" in k:
+ self._model_image_key["left"] = k
+ elif "right" in k:
+ self._model_image_key["right"] = k
+ if not all(self._model_image_key.values()):
+ raise ValueError(f"could not map config image keys {srv.image_keys} to left/right")
+
+ self._prev = {s: None for s in SIDES} # previous-cycle [pose7, grip] fallback
+ self._T0 = {s: None for s in SIDES} # session first frame, used only with QUAT_PERM
+ _quat_perm_advice(checkpoint_dir)
+ log.info("UmiPi05DualPolicy ready: config=%s ckpt=%s upsample=%d dt=%.4f source=%s quat_perm=%s",
+ config, checkpoint_dir, self.upsample, self.dt, self.input_source, QUAT_PERM)
+
+ # ------------------------------------------------------------------ helpers
+ def reset(self) -> None:
+ self._cursor = 0
+ self._prev = {s: None for s in SIDES}
+ self._T0 = {s: None for s in SIDES}
+
+ # ---- quaternion-order compensation (see VLA_QUAT_PERM in module doc) ----
+ def _to_read(self, poses: np.ndarray, T0: np.ndarray) -> np.ndarray:
+ """True (...,7) -> training read space: re-anchor to first frame, then use wxyz as xyzw."""
+ mats = np.linalg.inv(T0) @ self._dec.pose_xyzw_to_matrix(np.asarray(poses, np.float32))
+ q = self._dec.matrix_to_quat_xyzw(mats[..., :3, :3]) # (x,y,z,w)
+ return np.concatenate([mats[..., :3, 3], q[..., [3, 0, 1, 2]]], -1).astype(np.float32)
+
+ def _from_read(self, poses: np.ndarray, T0: np.ndarray) -> np.ndarray:
+ """Read space (...,7) -> true: invert the permutation, then undo re-anchoring."""
+ p = np.asarray(poses, np.float32)
+ mats = T0 @ self._dec.pose_xyzw_to_matrix(
+ np.concatenate([p[..., :3], p[..., 3:7][..., [1, 2, 3, 0]]], -1))
+ q = self._dec.matrix_to_quat_xyzw(mats[..., :3, :3])
+ return np.concatenate([mats[..., :3, 3], q], -1).astype(np.float32)
+
+ def _image(self, obs: Observation, side: str):
+ """live wrist frame if available/allowed, else replay video at the cursor."""
+ if self.image_source in ("live", "auto"):
+ frame = (obs.images or {}).get(self.image_obs_keys[side])
+ if frame is not None and getattr(frame, "data", None):
+ buf = np.frombuffer(frame.data, dtype=np.uint8)
+ bgr = cv2.imdecode(buf, cv2.IMREAD_COLOR)
+ if bgr is not None:
+ self._last_live[side] = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
+ if self._last_live[side] is not None:
+ return self._last_live[side], True
+ if self.image_source == "live":
+ raise RuntimeError(f"image_source=live but no {side} wrist frame yet")
+ frames = self._frames[side]
+ if not frames:
+ raise RuntimeError(f"no replay video for side {side} and no live frame")
+ return frames[min(self._cursor, len(frames) - 1)], False
+
+ def _compose(self, poses: np.ndarray, T: np.ndarray) -> np.ndarray:
+ """(...,7) poses @ T (right-multiply a fixed transform)."""
+ mats = self._dec.pose_xyzw_to_matrix(np.asarray(poses, np.float32))
+ out = mats @ T
+ pos = out[..., :3, 3]
+ quat = self._dec.matrix_to_quat_xyzw(out[..., :3, :3])
+ return np.concatenate([pos, quat], axis=-1).astype(np.float32)
+
+ def _proprio(self, obs: Observation, side: str):
+ """[prev, cur] pose (2,7) + gripper (2,), model G-frame, dataset gripper scale."""
+ if self._pq_state is not None:
+ i = min(self._cursor, len(self._pq_state) - 1)
+ p = max(i - 1, 0)
+ a, b = POSE_SLICES[side]
+ pose = self._pq_state[[p, i], a:b]
+ grip = self._pq_state[[p, i], GRIP_INDEX[side]]
+ return pose.astype(np.float32), grip.astype(np.float32), "parquet"
+ cur = np.asarray((obs.eef or {}).get(side), np.float32)
+ if cur is None or cur.shape != (7,):
+ raise RuntimeError(f"obs.eef[{side}] missing/bad")
+ cur_g = float((obs.gripper or {}).get(side, 0.0))
+ prev = (obs.eef_prev or {}).get(side)
+ if prev is not None and len(prev) == 7:
+ prev, src = np.asarray(prev, np.float32), "client"
+ elif self._prev[side] is not None:
+ prev, src = self._prev[side][0], "cycle"
+ else:
+ prev, src = cur.copy(), "cur"
+ prev_g = float((obs.gripper_prev or {}).get(side, self._prev[side][1] if self._prev[side] else cur_g))
+ pose = np.stack([prev, cur])
+ if self._E_inv[side] is not None: # hand frame -> G frame
+ pose = self._compose(pose, self._E_inv[side])
+ return pose.astype(np.float32), np.asarray([prev_g, cur_g], np.float32), src
+
+ # ------------------------------------------------------------------ main
+ def infer(self, obs: Observation) -> Action:
+ imgs, live_flags = {}, {}
+ for s in SIDES:
+ img, live = self._image(obs, s)
+ imgs[self._model_image_key[s]] = img
+ live_flags[s] = live
+
+ pose = np.zeros((2, 2, 7), np.float32) # [prev,cur] x [left,right] x 7
+ grip = np.zeros((2, 2), np.float32)
+ srcs = {}
+ for h, s in enumerate(SIDES):
+ p, g, src = self._proprio(obs, s)
+ pose[:, h], grip[:, h], srcs[s] = p, g, src
+
+ # Quaternion-order compensation: convert only the model input to read space.
+ # Do not modify pose in place: self._prev stores pose[1,h] as next cycle's prev.
+ pose_in = pose
+ if QUAT_PERM:
+ pose_in = pose.copy()
+ for h, s in enumerate(SIDES):
+ if self._T0[s] is None: # session first frame = per-episode training origin
+ self._T0[s] = self._dec.pose_xyzw_to_matrix(pose[1, h])
+ pose_in[:, h] = self._to_read(pose[:, h], self._T0[s])
+
+ t0 = time.time()
+ out = self._infer({"eef_pose": pose_in, "gripper": grip, "images": imgs,
+ "prompt": self.prompt, "upsample": self.upsample})
+ t_ms = (time.time() - t0) * 1e3
+
+ tgt = np.asarray(out["target_eef_pose"], np.float32) # (2, M, 7) G-frame
+ if QUAT_PERM: # read-space absolute targets -> true
+ for h, s in enumerate(SIDES):
+ tgt[h] = self._from_read(tgt[h], self._T0[s])
+ grp = np.asarray(out["target_gripper"], np.float32) # (2, M)
+ exec_frames = int(out.get("horizon", 0)) or max(1, tgt.shape[1] // self.upsample)
+ if self.action_horizon > 0 and tgt.shape[1] > 1:
+ keep = max(1, min(tgt.shape[1], self.action_horizon * self.upsample))
+ tgt, grp = tgt[:, :keep], grp[:, :keep]
+ exec_frames = min(exec_frames, self.action_horizon)
+
+ eef_traj, grip_traj = {}, {}
+ for h, s in enumerate(SIDES):
+ t = tgt[h]
+ if self._E[s] is not None: # G frame -> hand frame
+ t = self._compose(t, self._E[s])
+ eef_traj[s] = t.tolist()
+ grip_traj[s] = [float(g) for g in grp[h]]
+
+ action = Action(
+ seq=obs.seq,
+ stamp=time.time(),
+ control="eef_pose",
+ eef_target={s: eef_traj[s][0] for s in SIDES},
+ gripper={s: grip_traj[s][0] for s in SIDES},
+ eef_traj=eef_traj,
+ gripper_traj=grip_traj,
+ dt=self.dt,
+ extra={
+ "policy": "umi_pi05_dual",
+ "n_steps": int(tgt.shape[1]),
+ "horizon": int(out.get("horizon", 0)),
+ "model_ms": round(t_ms, 1),
+ "input_source": self.input_source,
+ "prev_src": srcs,
+ "image_live": live_flags,
+ "cursor": self._cursor,
+ },
+ )
+
+ # advance per-cycle state
+ for h, s in enumerate(SIDES):
+ self._prev[s] = (pose[1, h].copy(), float(grip[1, h]))
+ self._cursor += exec_frames
+ if self.record_dir:
+ try:
+ rd = Path(self.record_dir)
+ rd.mkdir(parents=True, exist_ok=True)
+ for s in SIDES:
+ img = imgs[self._model_image_key[s]]
+ cv2.imwrite(str(rd / f"seq{obs.seq:04d}_{s}.jpg"),
+ cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR))
+ np.savez_compressed(rd / f"seq{obs.seq:04d}_obs.npz",
+ pose_in=pose, grip_in=grip, tgt_G=tgt,
+ grip_traj=grp) # (2,M) per-step gripper targets, for visualization
+ except Exception as e:
+ log.warning("record failed: %s", e)
+ log.info("chunk seq=%d steps=%d model=%.0fms src=%s live=%s cursor=%d",
+ obs.seq, tgt.shape[1], t_ms, srcs, live_flags, self._cursor)
+ return action
diff --git a/flexiv-umi-infer/umi_infer/policy_server.py b/flexiv-umi-infer/umi_infer/policy_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..875c7da041eca155d1e7d8fdcd1851de467bb8ad
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/policy_server.py
@@ -0,0 +1,226 @@
+"""Policy server -- runs on the GPU box.
+
+Hosts a Policy behind a websocket. For every Observation it receives it runs
+``policy.infer`` and returns an Action (a trajectory chunk).
+
+Run:
+ python -m umi_infer.policy_server --policy mock --policy-mode hold
+ python -m umi_infer.policy_server --policy pi05 --checkpoint-dir \
+ --eef-extrinsic-left data/E_left.npy --eef-extrinsic-right data/E_right.npy
+ python -m umi_infer.policy_server --policy flux --flux-export \
+ --flux-e-left data/E_left.npy --flux-e-right data/E_right.npy
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import logging
+import os
+import time
+
+import websockets
+
+from .config import MAX_WS_SIZE, Config
+from .policies.base import Policy
+from .policies.mock import MockPolicy
+from .protocol import pack, unpack_observation, wire_log_payload
+
+log = logging.getLogger("policy_server")
+
+
+# One summary line per chunk by default; UMI_WIRE_LOG=1 logs the full action payload.
+WIRE_LOG = bool(int(os.environ.get("UMI_WIRE_LOG", "0")))
+
+
+def _action_brief(a) -> str:
+ """One-line chunk summary: steps / dt / first point and path length per arm / gripper range."""
+ tr = getattr(a, "eef_traj", None) or {}
+ gt = getattr(a, "gripper_traj", None) or {}
+ n = max([len(v) for v in tr.values()] + [0])
+ bits = ["%d steps" % n, "dt=%.4f" % float(getattr(a, "dt", 0.0) or 0.0)]
+ for s in ("left", "right"):
+ v = tr.get(s) or []
+ if v:
+ d = sum(sum((v[i + 1][k] - v[i][k]) ** 2 for k in range(3)) ** 0.5
+ for i in range(len(v) - 1))
+ bits.append("%s(%.3f,%.3f,%.3f) path %.0fmm"
+ % (s[0].upper(), v[0][0], v[0][1], v[0][2], d * 1000))
+ g = gt.get(s) or []
+ if g:
+ bits.append("%s grip %.1f~%.1f deg" % (s[0].upper(), min(g), max(g)))
+ return " ".join(bits)
+
+
+async def _handle(ws, policy: Policy, path=None) -> None:
+ peer = getattr(ws, "remote_address", "?")
+ log.info("client connected: %s", peer)
+ policy.reset()
+ n = 0
+ t_stat = time.time()
+ loop = asyncio.get_running_loop()
+ try:
+ async for msg in ws:
+ obs = unpack_observation(msg)
+ if WIRE_LOG:
+ log.info("recv obs len=%d %s", len(msg), wire_log_payload(obs))
+ action = await loop.run_in_executor(None, policy.infer, obs)
+ action_bytes = pack(action)
+ await ws.send(action_bytes)
+ if WIRE_LOG:
+ log.info("send action len=%d %s", len(action_bytes),
+ wire_log_payload(action))
+ else:
+ log.info("send seq=%s len=%d %s", action.seq, len(action_bytes),
+ _action_brief(action))
+ n += 1
+ if n % 50 == 0:
+ dt = time.time() - t_stat
+ t_stat = time.time()
+ log.info("served %d (%.1f Hz) last seq=%d imgs=%d",
+ n, (50 / dt if dt > 0 else 0.0), obs.seq, len(obs.images))
+ except websockets.ConnectionClosed:
+ log.info("client disconnected: %s (served %d)", peer, n)
+
+
+async def _serve(cfg: Config, policy: Policy) -> None:
+ async def handler(ws, path=None):
+ await _handle(ws, policy, path)
+
+ async with websockets.serve(handler, cfg.host, cfg.port, max_size=MAX_WS_SIZE):
+ log.info("policy server listening on ws://%s:%d (policy=%s)",
+ cfg.host, cfg.port, type(policy).__name__)
+ await asyncio.Future() # run forever
+
+
+def _build_policy(args) -> Policy:
+ if args.policy == "flux":
+ from .policies.flux_action_dual import FluxActionDualPolicy
+
+ if not args.flux_export:
+ raise SystemExit("--policy flux requires --flux-export (an inference export directory)")
+ return FluxActionDualPolicy(
+ export_dir=args.flux_export,
+ source_dir=args.flux_source,
+ resources_dir=args.flux_resources,
+ prompt=args.flux_prompt,
+ device=args.device,
+ extrinsics={"left": args.flux_e_left, "right": args.flux_e_right},
+ e_provenance=args.flux_e_provenance,
+ image_keys={"left": args.flux_image_left, "right": args.flux_image_right},
+ action_horizon=args.flux_horizon,
+ sampler=args.flux_sampler,
+ steps=args.flux_steps,
+ shift=args.flux_shift,
+ guidance=args.flux_guidance,
+ action_guidance=args.flux_action_guidance,
+ seed=args.flux_seed,
+ )
+ if args.policy == "pi05":
+ from .policies.umi_pi05_dual import UmiPi05DualPolicy
+
+ if not args.checkpoint_dir:
+ raise SystemExit("--policy pi05 requires --checkpoint-dir")
+ videos = {}
+ if args.episode_video_left:
+ videos["left"] = args.episode_video_left
+ if args.episode_video_right:
+ videos["right"] = args.episode_video_right
+ return UmiPi05DualPolicy(
+ checkpoint_dir=args.checkpoint_dir,
+ config=args.config,
+ num_denoise_steps=args.num_denoise_steps,
+ openpi_root=args.openpi_root,
+ device=args.device,
+ prompt=args.prompt,
+ upsample=args.upsample,
+ chunk_fps=args.chunk_fps,
+ action_horizon=args.action_horizon,
+ episode_videos=videos or None,
+ episode_parquet=args.episode_parquet,
+ eef_extrinsic={"left": args.eef_extrinsic_left, "right": args.eef_extrinsic_right},
+ image_source=args.image_source,
+ record_dir=args.record_dir,
+ )
+ cfg = Config()
+ chunk_size = args.chunk_size if args.chunk_size is not None else cfg.chunk_size
+ chunk_dt = args.chunk_dt if args.chunk_dt is not None else cfg.chunk_dt
+ return MockPolicy(mode=args.policy_mode, chunk_size=chunk_size, chunk_dt=chunk_dt)
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="UMI policy server")
+ ap.add_argument("--host", default="127.0.0.1")
+ ap.add_argument("--port", type=int, default=8765)
+ ap.add_argument("--policy", default="mock", choices=["mock", "pi05", "flux"])
+ ap.add_argument("--device", default="cuda:0", help="torch device for the model")
+ # ---- mock ----
+ g = ap.add_argument_group("mock")
+ g.add_argument("--policy-mode", default="hold", choices=["hold", "wobble", "zero", "traj"],
+ help="mock behavior (hold = echo the observed pose, a safe no-op)")
+ g.add_argument("--chunk-size", type=int, default=None, help="steps per trajectory chunk")
+ g.add_argument("--chunk-dt", type=float, default=None, help="seconds between chunk steps")
+ # ---- pi05 (openpi-umi) ----
+ g = ap.add_argument_group("pi05 (openpi-umi)")
+ g.add_argument("--checkpoint-dir", default=None, help="trained checkpoint step dir")
+ g.add_argument("--config", default="pi05_umi_v3", help="openpi train config name")
+ g.add_argument("--num-denoise-steps", type=int, default=10, help="pi05 flow-sampling steps")
+ g.add_argument("--openpi-root", default=None,
+ help="optional openpi source tree (/src/openpi, /model for the tokenizer); "
+ "default = the installed openpi package")
+ g.add_argument("--prompt", default="fold the clothes", help="task prompt")
+ g.add_argument("--upsample", type=int, default=1, help="spline upsample factor of the decoded chunk")
+ g.add_argument("--chunk-fps", type=float, default=30.0, help="native chunk fps (dt = 1/(fps*upsample))")
+ g.add_argument("--action-horizon", type=int, default=0,
+ help="return only the first N model frames of each chunk (0 = full chunk)")
+ g.add_argument("--eef-extrinsic-left", default=None,
+ help="LEFT E: .npy 4x4 (data camera frame -> flange, T_flange = T_cam @ E); none = identity")
+ g.add_argument("--eef-extrinsic-right", default=None, help="RIGHT E, same format")
+ g.add_argument("--image-source", default="live", choices=["live", "replay", "auto"],
+ help="live = obs.images; replay = episode videos; auto = live if present else replay")
+ g.add_argument("--episode-video-left", default=None, help="LEFT episode mp4 for replay/auto")
+ g.add_argument("--episode-video-right", default=None, help="RIGHT episode mp4 for replay/auto")
+ g.add_argument("--episode-parquet", default=None,
+ help="replay proprio from a dataset episode (fully open loop; output is in the dataset "
+ "frame, use with a dry-run client only)")
+ g.add_argument("--record-dir", default=None,
+ help="write // with meta.json, received images and one JSON line per "
+ "inference (joins the client --record CSV on seq)")
+ # ---- flux (flux-umi) ----
+ g = ap.add_argument_group("flux (flux-umi)")
+ g.add_argument("--flux-export", default=None, help="FLUX inference export (config.json + model.safetensors)")
+ g.add_argument("--flux-source", default=None,
+ help="optional flux_action source dir put on sys.path; default = the installed package")
+ g.add_argument("--flux-resources", default=None,
+ help="dir with video_vae.safetensors and text_encoder/ (default: $FLUX_RESOURCES)")
+ g.add_argument("--flux-prompt", default="fold the clothes")
+ g.add_argument("--flux-e-left", default=None, help="LEFT E .npy (required)")
+ g.add_argument("--flux-e-right", default=None, help="RIGHT E .npy (required)")
+ g.add_argument("--flux-e-provenance", default=None,
+ help="E_from_urdf.json written by export_E; checks both E files against it")
+ g.add_argument("--flux-image-left", default="left_wrist")
+ g.add_argument("--flux-image-right", default="right_wrist")
+ g.add_argument("--flux-horizon", type=int, default=0, help="first N frames, 0 = all 32")
+ g.add_argument("--flux-sampler", choices=["euler", "cosmos_unipc"], default="euler")
+ g.add_argument("--flux-steps", type=int, default=4)
+ g.add_argument("--flux-shift", type=float, default=42.0,
+ help="sampler shift; matching the training timestep shift worked better than 5.0")
+ g.add_argument("--flux-guidance", type=float, default=1.0)
+ g.add_argument("--flux-action-guidance", type=float, default=1.0)
+ g.add_argument("--flux-seed", type=int, default=0)
+ args = ap.parse_args()
+ if args.flux_resources is None:
+ from .policies.flux_action_dual import DEFAULT_RESOURCES
+ args.flux_resources = DEFAULT_RESOURCES
+ logging.basicConfig(level=logging.INFO,
+ format="%(asctime)s %(name)s %(levelname)s %(message)s")
+ cfg = Config(host=args.host, port=args.port)
+ policy = _build_policy(args)
+ try:
+ asyncio.run(_serve(cfg, policy))
+ except KeyboardInterrupt:
+ log.info("shutting down")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/flexiv-umi-infer/umi_infer/protocol.py b/flexiv-umi-infer/umi_infer/protocol.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f714ba0563aea91cd02b69e166a2c087480f2b8
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/protocol.py
@@ -0,0 +1,228 @@
+"""Wire protocol between the robot agent and the VLA policy server.
+
+Two message types travel over a websocket, serialized with msgpack:
+
+ Observation robot agent --> policy server
+ Action policy server --> robot agent
+
+Images are carried as raw bytes; the ``format`` field says how to decode them
+(``jpeg`` / ``h264`` in production, ``raw_rgb`` from the mock). For compressed
+bitstreams the frame dimensions may be unknown at transport time and can be set
+to ``0``. This module is intentionally dependency-light (only msgpack) so it
+imports cleanly on both the robot PC and the GPU box.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import Any, Dict, List
+
+import msgpack
+
+PROTOCOL_VERSION = 3 # v2: Action.eef_traj/gripper_traj/dt; v3: Observation.eef_prev/gripper_prev
+ # (the [prev,cur] motion window -- prev is the same proprio ~pose_dt earlier;
+ # all optional, wire back-compat)
+
+
+@dataclass
+class CameraFrame:
+ name: str
+ format: str # 'jpeg' | 'h264' | 'raw_rgb' | 'mock'
+ height: int
+ width: int
+ data: bytes
+ stamp: float = 0.0 # epoch seconds when the frame was captured
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "name": self.name,
+ "format": self.format,
+ "height": self.height,
+ "width": self.width,
+ "data": self.data,
+ "stamp": self.stamp,
+ }
+
+ @staticmethod
+ def from_dict(d: Dict[str, Any]) -> "CameraFrame":
+ return CameraFrame(
+ name=d["name"],
+ format=d["format"],
+ height=d["height"],
+ width=d["width"],
+ data=d["data"],
+ stamp=d.get("stamp", 0.0),
+ )
+
+
+@dataclass
+class Observation:
+ """One time-step of robot state sent up to the policy."""
+
+ seq: int
+ stamp: float
+ images: Dict[str, CameraFrame] = field(default_factory=dict)
+ # end-effector cartesian pose in base frame: side -> [x, y, z, qx, qy, qz, qw]
+ eef: Dict[str, List[float]] = field(default_factory=dict)
+ # joint positions in rad: joint_name -> value
+ qpos: Dict[str, float] = field(default_factory=dict)
+ # gripper opening; SCALE is defined by the IO/policy PATH (not a fixed unit):
+ # flexiv<->umi path = DATASET scale in degrees (0 = closed, 90 = fully open), same scale
+ # BOTH directions -- also Action.gripper / Action.gripper_traj;
+ # mock path = normalized [0,1] (0=open, 1=closed).
+ gripper: Dict[str, float] = field(default_factory=dict)
+ # PREVIOUS frame of the motion window (~pose_dt before `eef`/`gripper`): the
+ # client samples two real proprio frames a short delta apart so the policy can
+ # read motion direction from [prev, cur]. Same shapes/sides as eef/gripper.
+ eef_prev: Dict[str, List[float]] = field(default_factory=dict)
+ gripper_prev: Dict[str, float] = field(default_factory=dict)
+ # actual achieved seconds between prev and cur (target is pose_dt; 0 if no prev)
+ pose_dt: float = 0.0
+ extra: Dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "v": PROTOCOL_VERSION,
+ "type": "obs",
+ "seq": self.seq,
+ "stamp": self.stamp,
+ "images": {k: v.to_dict() for k, v in self.images.items()},
+ "eef": self.eef,
+ "qpos": self.qpos,
+ "gripper": self.gripper,
+ "eef_prev": self.eef_prev,
+ "gripper_prev": self.gripper_prev,
+ "pose_dt": self.pose_dt,
+ "extra": self.extra,
+ }
+
+ @staticmethod
+ def from_dict(d: Dict[str, Any]) -> "Observation":
+ return Observation(
+ seq=d["seq"],
+ stamp=d["stamp"],
+ images={k: CameraFrame.from_dict(v) for k, v in d.get("images", {}).items()},
+ eef=d.get("eef", {}),
+ qpos=d.get("qpos", {}),
+ gripper=d.get("gripper", {}),
+ eef_prev=d.get("eef_prev", {}),
+ gripper_prev=d.get("gripper_prev", {}),
+ pose_dt=d.get("pose_dt", 0.0),
+ extra=d.get("extra", {}),
+ )
+
+
+@dataclass
+class Action:
+ """One control command returned by the policy.
+
+ The policy may return either a single target (``eef_target``/``gripper``) or a
+ short *trajectory chunk* (``eef_traj``/``gripper_traj`` + ``dt``) of K future
+ steps that the robot executes locally at a fixed rate. ``eef_target``/``gripper``
+ stay as a length-1 fallback so single-pose policies keep working unchanged.
+ """
+
+ seq: int # echoes the Observation.seq this action responds to
+ stamp: float
+ control: str = "eef_pose" # 'eef_pose' | 'joint'
+ # cartesian targets in base frame: side -> [x, y, z, qx, qy, qz, qw]
+ eef_target: Dict[str, List[float]] = field(default_factory=dict)
+ # gripper command; SCALE is defined by the IO/policy PATH, same as Observation.gripper
+ # (flexiv<->umi = DATASET scale in degrees; mock = normalized [0,1]): side -> value
+ gripper: Dict[str, float] = field(default_factory=dict)
+ # joint targets in rad (used when control == 'joint'): joint_name -> value
+ joint_target: Dict[str, float] = field(default_factory=dict)
+ # trajectory chunk: side -> [ [x,y,z,qx,qy,qz,qw], ... K steps ]
+ eef_traj: Dict[str, List[List[float]]] = field(default_factory=dict)
+ # per-step gripper aligned with eef_traj: side -> [ g0, g1, ... ]
+ gripper_traj: Dict[str, List[float]] = field(default_factory=dict)
+ # seconds between consecutive trajectory steps (0 => single-step fallback)
+ dt: float = 0.0
+ extra: Dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "v": PROTOCOL_VERSION,
+ "type": "action",
+ "seq": self.seq,
+ "stamp": self.stamp,
+ "control": self.control,
+ "eef_target": self.eef_target,
+ "gripper": self.gripper,
+ "joint_target": self.joint_target,
+ "eef_traj": self.eef_traj,
+ "gripper_traj": self.gripper_traj,
+ "dt": self.dt,
+ "extra": self.extra,
+ }
+
+ @staticmethod
+ def from_dict(d: Dict[str, Any]) -> "Action":
+ return Action(
+ seq=d["seq"],
+ stamp=d["stamp"],
+ control=d.get("control", "eef_pose"),
+ eef_target=d.get("eef_target", {}),
+ gripper=d.get("gripper", {}),
+ joint_target=d.get("joint_target", {}),
+ eef_traj=d.get("eef_traj", {}),
+ gripper_traj=d.get("gripper_traj", {}),
+ dt=d.get("dt", 0.0),
+ extra=d.get("extra", {}),
+ )
+
+ def as_steps(self) -> "tuple[List[Dict[str, Any]], float]":
+ """Normalize to ``(steps, dt)`` for the robot-side executor.
+
+ Each step is ``{"eef": {side: [7]}, "gripper": {side: float}}``. When a
+ trajectory is present it is expanded step-by-step (sides/gripper of unequal
+ length are clamped to their last value); otherwise a single step is built
+ from ``eef_target``/``gripper`` with ``dt = 0``.
+ """
+ if self.eef_traj:
+ sides = [s for s, seq in self.eef_traj.items() if seq]
+ k = max((len(self.eef_traj[s]) for s in sides), default=0)
+ steps: List[Dict[str, Any]] = []
+ for i in range(k):
+ eef = {s: self.eef_traj[s][i if i < len(self.eef_traj[s]) else -1] for s in sides}
+ grip = {
+ s: float(g[i if i < len(g) else -1])
+ for s, g in self.gripper_traj.items() if g
+ }
+ steps.append({"eef": eef, "gripper": grip})
+ return steps, float(self.dt)
+ return [{"eef": dict(self.eef_target), "gripper": dict(self.gripper)}], 0.0
+
+
+def pack(obj: "Observation | Action") -> bytes:
+ """Serialize an Observation or Action to msgpack bytes."""
+ return msgpack.packb(obj.to_dict(), use_bin_type=True)
+
+
+def unpack_observation(b: bytes) -> Observation:
+ return Observation.from_dict(msgpack.unpackb(b, raw=False))
+
+
+def unpack_action(b: bytes) -> Action:
+ return Action.from_dict(msgpack.unpackb(b, raw=False))
+
+
+def _sanitize_for_wire_log(value: Any) -> Any:
+ if isinstance(value, bytes):
+ return {
+ "bytes": len(value),
+ "prefix_hex": value[:8].hex(),
+ }
+ if isinstance(value, dict):
+ return {k: _sanitize_for_wire_log(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_sanitize_for_wire_log(v) for v in value]
+ if isinstance(value, tuple):
+ return [_sanitize_for_wire_log(v) for v in value]
+ return value
+
+
+def wire_log_payload(obj: Observation | Action) -> str:
+ """Return a compact JSON string for wire-level logging."""
+ return json.dumps(_sanitize_for_wire_log(obj.to_dict()), ensure_ascii=False, sort_keys=True)
diff --git a/flexiv-umi-infer/umi_infer/robot_agent.py b/flexiv-umi-infer/umi_infer/robot_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc8c2fccc70b5d22c44007b9ed72baa1c74fcac7
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_agent.py
@@ -0,0 +1,232 @@
+"""Robot agent -- runs on the robot PC.
+
+Drives the control loop: grab an Observation from RobotIO, send it to the policy
+server, receive an Action, apply it. The servo loop runs locally on the robot;
+policy inference is paced separately. Reconnects if the server drops.
+
+Run:
+ python -m umi_infer.robot_agent --io mock # no hardware
+ python -m umi_infer.robot_agent --io flexiv --live-camera # dry run (no motion)
+ python -m umi_infer.robot_agent --io flexiv --live-camera --live --gripper # moves!
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import logging
+import os
+import time
+
+import websockets
+
+from .config import MAX_WS_SIZE, Config
+from .protocol import pack, unpack_action, wire_log_payload
+from .robot_io.base import RobotIO
+
+log = logging.getLogger("robot_agent")
+
+
+async def _run_session(uri: str, io: RobotIO, cfg: Config) -> None:
+ """Pace inference by the local executor's buffer, not a fixed network loop.
+
+ The robot-side executor (RobotIO) runs the trajectory chunk at a fixed local
+ rate. This loop only decides *when* to ask the policy for the next chunk:
+ - sync : wait until the whole chunk is consumed (frac=1.0, + settle), then
+ grab a FRESH observation -> the VLA always plans from current state.
+ - async: refill at ``refill_at_fraction`` and overlap inference with the tail.
+ ``control_rate_hz`` is a cap on request cadence (matters only for degenerate
+ single-step chunks, where ``needs_refill`` is always True).
+ """
+ frac = 1.0 if cfg.inference_mode == "sync" else cfg.refill_at_fraction
+ min_interval = 1.0 / cfg.control_rate_hz if cfg.control_rate_hz > 0 else 0.0
+ async with websockets.connect(uri, max_size=MAX_WS_SIZE, proxy=None) as ws:
+ log.info("connected to %s (inference_mode=%s frac=%.2f)", uri, cfg.inference_mode, frac)
+ n = 0
+ t_stat = time.time()
+ while True:
+ # trigger: wait until the local executor needs the next chunk
+ while not io.needs_refill(frac):
+ await asyncio.sleep(0.005)
+
+ t0 = time.perf_counter()
+ obs = io.get_observation()
+ obs_bytes = pack(obs)
+ log.debug("send obs len=%d %s", len(obs_bytes), wire_log_payload(obs))
+ await ws.send(obs_bytes)
+ action_bytes = await ws.recv()
+ action = unpack_action(action_bytes)
+ log.debug("recv action len=%d %s", len(action_bytes), wire_log_payload(action))
+ rtt_ms = (time.perf_counter() - t0) * 1e3
+ io.apply_action(action)
+
+ n += 1
+ if n % 50 == 0:
+ dt = time.time() - t_stat
+ t_stat = time.time()
+ log.info("cycle %d rate=%.1fHz rtt=%.1fms action.seq=%d ctrl=%s",
+ n, (50 / dt if dt > 0 else 0.0), rtt_ms, action.seq, action.control)
+
+ # rate cap: never request faster than control_rate_hz
+ elapsed = time.perf_counter() - t0
+ if min_interval > elapsed:
+ await asyncio.sleep(min_interval - elapsed)
+
+
+async def _main(uri: str, io: RobotIO, cfg: Config) -> None:
+ io.start() # the Flexiv IO moves both arms to the start posture here
+ try:
+ while True:
+ try:
+ await _run_session(uri, io, cfg)
+ except (OSError, websockets.WebSocketException) as e:
+ log.warning("connection error: %s", e)
+ if not cfg.reconnect:
+ break
+ log.info("reconnecting in 1s ...")
+ await asyncio.sleep(1.0)
+ finally:
+ io.stop()
+
+
+def _make_io(kind: str, cfg: Config, dry_run: bool = False, pose_dt: float = 0.033, record_path=None,
+ live_camera: bool = False, flexiv_kw: dict | None = None,
+ mock_images: dict | None = None) -> RobotIO:
+ if kind == "flexiv":
+ from .robot_io.flexiv import FlexivRobotIO
+ return FlexivRobotIO(dry_run=dry_run, servo_rate_hz=cfg.servo_rate_hz,
+ pose_dt=pose_dt, record_path=record_path,
+ live_camera=live_camera,
+ **(flexiv_kw or {}))
+ if kind == "mock":
+ from .robot_io.mock import MockRobotIO
+ return MockRobotIO(cameras=cfg.cameras, image_files=mock_images)
+ raise ValueError(f"unknown io kind: {kind}")
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="UMI robot agent")
+ ap.add_argument("--server", default="ws://127.0.0.1:8765", help="policy server ws:// URI")
+ ap.add_argument("--rate", type=float, default=2.0, help="cap on inference-request Hz")
+ ap.add_argument("--servo-rate", type=float, default=100.0, help="robot-side servo Hz")
+ ap.add_argument("--inference-mode", default="sync", choices=["sync", "async"],
+ help="sync: run the whole chunk then re-infer from fresh state; "
+ "async: refill early and overlap inference with the chunk tail")
+ ap.add_argument("--refill-fraction", type=float, default=0.7,
+ help="async only: request the next chunk at this consumed fraction")
+ ap.add_argument("--io", default="mock", choices=["mock", "flexiv"])
+ ap.add_argument("--no-reconnect", action="store_true")
+ ap.add_argument("--pose-dt", type=float, default=0.033,
+ help="target delta (s) between the two proprio frames [prev, cur] sent to the "
+ "policy (0.033 = one frame at 30 fps)")
+ ap.add_argument("--record", default=None,
+ help="CSV of commanded vs measured EEF/gripper per servo tick "
+ "(+ .chunks.jsonl with per-chunk model output and prechecks)")
+ ap.add_argument("--live-camera", action="store_true",
+ help="stream both wrist cameras into obs.images (needed for real inference)")
+ ap.add_argument("--mock-image-left", default=None, help="--io mock: JPEG sent as the left wrist image")
+ ap.add_argument("--mock-image-right", default=None, help="--io mock: JPEG sent as the right wrist image")
+ g = ap.add_argument_group("Flexiv dual arm (--io flexiv)")
+ g.add_argument("--left-sn", default=None, help="left arm serial (default $FLEXIV_LEFT_SN)")
+ g.add_argument("--right-sn", default=None, help="right arm serial (default $FLEXIV_RIGHT_SN)")
+ g.add_argument("--urdf", default=None, help="combined dual-arm URDF (default $FLEXIV_URDF)")
+ g.add_argument("--live", action="store_true",
+ help="actually move the arms. Without it the agent is a DRY RUN "
+ "(full pipeline, no motion commands)")
+ g.add_argument("--gripper", action="store_true", help="drive both grippers from the model's gripper channel")
+ g.add_argument("--play-scale", type=float, default=None,
+ help="stretch each step on the wall clock by this factor (default 2.5). Does not change dt, "
+ "so the motion seen in the state is unaffected. At 1x about 30%% of model points "
+ "exceed max_linear_acc=2.0 and get clipped by the controller; slowing by k cuts "
+ "acceleration by k^2")
+ g.add_argument("--nullspace-weight", type=float, default=0.5,
+ help="weight pulling the elbow (null space) to the start posture [0.1, 1.0]: "
+ "0.1 soft / 0.5 default / 1.0 stiff")
+ g.add_argument("--first-steps", type=int, default=0,
+ help="execute only the first N steps of the first chunk (0 = all)")
+ g.add_argument("--steps", type=int, default=0,
+ help="execute only the first N steps of every later chunk (0 = all)")
+ g.add_argument("--reach-scale-right", type=float, default=None,
+ help="scale right-arm displacement within a chunk (1.0 = off); origin = measured "
+ "position at observation time, orientation unchanged")
+ g.add_argument("--grip-offset-deg", type=float, default=None,
+ help="subtract this from every model gripper opening before executing (default 3.0; "
+ "0 = pass through). Lets a grasp saturate the lead clamp so force is kp*lead")
+ g.add_argument("--anchor-deg", type=float, nargs=7, default=None,
+ help="start posture for both arms [deg] (default: data/anchor.json)")
+ g.add_argument("--anchor-deg-left", type=float, nargs=7, default=None)
+ g.add_argument("--anchor-deg-right", type=float, nargs=7, default=None)
+ g.add_argument("--monitor-min-dist", type=float, default=0.02,
+ help="Flexiv SelfCollisionMonitor threshold [m], link to link. It does NOT see the "
+ "gripper, which reaches ~16 cm past the flange")
+ g.add_argument("--min-dist", type=float, default=0.02,
+ help="per-cycle measured TCP-to-TCP minimum distance [m]")
+ g.add_argument("--tool-min-dist", type=float, default=0.02,
+ help="arm-to-arm distance including gripper geometry [m]; the only check that sees the grippers")
+ g.add_argument("--max-step-mm", type=float, default=60.0, help="max jump between adjacent chunk steps [mm]")
+ g.add_argument("--ik-check", default="truncate", choices=["off", "warn", "truncate", "abort"],
+ help="what to do when the vendor reachability precheck fails")
+ g.add_argument("--no-monitor", action="store_true", help="disable the self-collision monitor (not recommended)")
+ g.add_argument("--no-feedforward", action="store_true", help="do not send feed-forward velocity")
+ g.add_argument("--kx-ratio", type=float, default=0.6, help="Cartesian stiffness = ratio x K_x_nom")
+ g.add_argument("--zx", type=float, default=0.7, help="Cartesian damping ratio [0.3, 0.8]")
+ g.add_argument("--cam-format", default="jpeg", choices=["jpeg", "yuv420p"],
+ help="wrist image transport: jpeg (pi05) / yuv420p raw planes (FLUX, converted on the "
+ "policy side with the same pyav call as training)")
+ g.add_argument("--cam-kbps", type=int, default=512, help="camera live-stream bitrate, kbps (dual-fisheye frame)")
+ g.add_argument("--rollout-root", default=os.environ.get("FLEXIV_ROLLOUT_ROOT", "rollouts"),
+ help="per-frame rollout recording root; one subdirectory per run (robot_io/rollout_rec.py)")
+ g.add_argument("--no-rollout", action="store_true", help="do not record the rollout")
+ g.add_argument("--rollout-cam-hz", type=float, default=10.0,
+ help="rate of live wrist frames in the rollout; 0 = only the frames sent to the model")
+ args = ap.parse_args()
+ for _n in ("websockets", "websockets.client", "websockets.server", "can"):
+ logging.getLogger(_n).setLevel(logging.WARNING)
+ logging.basicConfig(level=logging.INFO,
+ format="%(asctime)s %(name)s %(levelname)s %(message)s")
+ dry_run = args.io == "flexiv" and not args.live
+ if dry_run:
+ log.warning("DRY-RUN: robot will NOT move (no motion commands)")
+ elif args.io == "flexiv":
+ log.warning("LIVE: the robot WILL move. Keep a hand on the e-stop!")
+ cfg = Config(control_rate_hz=args.rate, servo_rate_hz=args.servo_rate,
+ reconnect=not args.no_reconnect, inference_mode=args.inference_mode,
+ refill_at_fraction=args.refill_fraction)
+ flexiv_kw = None
+ if args.io == "flexiv":
+ anchor = None
+ if args.anchor_deg or args.anchor_deg_left or args.anchor_deg_right:
+ base = args.anchor_deg or args.anchor_deg_left or args.anchor_deg_right
+ anchor = {"left": args.anchor_deg_left or args.anchor_deg or base,
+ "right": args.anchor_deg_right or args.anchor_deg or base}
+ if args.grip_offset_deg is not None:
+ os.environ["FLEXIV_GRIP_OFFSET_DEG"] = "%.3f" % args.grip_offset_deg
+ if args.reach_scale_right is not None:
+ os.environ["FLEXIV_REACH_SCALE_RIGHT"] = "%.3f" % args.reach_scale_right
+ flexiv_kw = dict(
+ cam_format=args.cam_format, cam_kbps=args.cam_kbps,
+ gripper=args.gripper, anchor_deg=anchor,
+ monitor_min_dist=args.monitor_min_dist,
+ min_dist=args.min_dist, tool_min_dist=args.tool_min_dist,
+ max_step_mm=args.max_step_mm, ik_check=args.ik_check,
+ no_monitor=args.no_monitor, feedforward=not args.no_feedforward,
+ kx_ratio=args.kx_ratio, zx=args.zx,
+ first_steps=args.first_steps, steps=args.steps,
+ nullspace_weight=args.nullspace_weight,
+ rollout_root=None if args.no_rollout else args.rollout_root,
+ rollout_cam_hz=args.rollout_cam_hz)
+ for k, v in (("left_sn", args.left_sn), ("right_sn", args.right_sn), ("urdf", args.urdf),
+ ("play_scale", args.play_scale)):
+ if v is not None:
+ flexiv_kw[k] = v
+ io = _make_io(args.io, cfg, dry_run=dry_run, pose_dt=args.pose_dt, record_path=args.record,
+ live_camera=args.live_camera, flexiv_kw=flexiv_kw,
+ mock_images={"left_wrist": args.mock_image_left, "right_wrist": args.mock_image_right})
+ try:
+ asyncio.run(_main(args.server, io, cfg))
+ except KeyboardInterrupt:
+ log.info("stopped")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/flexiv-umi-infer/umi_infer/robot_io/__init__.py b/flexiv-umi-infer/umi_infer/robot_io/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/flexiv-umi-infer/umi_infer/robot_io/base.py b/flexiv-umi-infer/umi_infer/robot_io/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2be5aacf4c9d786fe83edb0d00f8bf72da1b396
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/base.py
@@ -0,0 +1,37 @@
+"""RobotIO interface. Hardware integrations (robot_io/flexiv.py) implement it."""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+
+from ..protocol import Action, Observation
+
+
+class RobotIO(ABC):
+ """Abstraction over the physical robot, used by the robot agent.
+
+ All methods run ON the robot PC. ``MockRobotIO`` needs no hardware;
+ ``FlexivRobotIO`` drives the dual-arm cell. Methods are synchronous
+ and should be quick; the agent calls them once per control cycle.
+ """
+
+ @abstractmethod
+ def start(self) -> None:
+ """Initialize hardware / SDK connection."""
+
+ @abstractmethod
+ def get_observation(self) -> Observation:
+ """Grab the latest cameras + EEF pose + joint/gripper state."""
+
+ @abstractmethod
+ def apply_action(self, action: Action) -> None:
+ """Hand a returned Action (a trajectory chunk) to the local executor."""
+
+ def needs_refill(self, fraction: float) -> bool:
+ """Whether the local executor's buffer is consumed past ``fraction`` and a
+ new chunk should be requested. Default: always ready (no local buffering),
+ which makes the agent request as fast as its rate cap allows."""
+ return True
+
+ def stop(self) -> None:
+ """Release resources (optional)."""
diff --git a/flexiv-umi-infer/umi_infer/robot_io/cam_ids.py b/flexiv-umi-infer/umi_infer/robot_io/cam_ids.py
new file mode 100644
index 0000000000000000000000000000000000000000..de05a6a2c4dbe034bfbd582641dd205682cac8fa
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/cam_ids.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+"""Wrist camera identity. Kept free of relative imports so standalone tools can import it too.
+
+Each arm's camera serial and fisheye half must be the ones its extrinsic E was calibrated with.
+Pairing E from one camera with images from another raises no error; the policy just moves wrongly.
+"""
+
+import os
+
+SIDES = ("left", "right")
+
+# Camera body serial per arm (printed by `insta360_cli_dual discover`).
+CAM_SERIAL = {"left": os.environ.get("INSTA360_LEFT_SN", ""),
+ "right": os.environ.get("INSTA360_RIGHT_SN", "")}
+
+# Which 960x960 half of the 1920x960 dual-fisheye frame to use ("left" or "right").
+# Pick the lens that faces the workspace.
+CAM_HALF = {"left": os.environ.get("INSTA360_LEFT_HALF", "right"),
+ "right": os.environ.get("INSTA360_RIGHT_HALF", "right")}
+
+# Observation keys the policy side expects.
+CAM_OBS_KEY = {"left": "left_wrist", "right": "right_wrist"}
+
+# Output size. 960 = native half, no resize: training images are raw 960x960 fisheye and the
+# policy resizes to its input size, the same preprocessing chain as in training.
+CAM_OUT_SIZE = int(os.environ.get("FLEXIV_CAM_SIZE", "960"))
+
+# Optional hand-eye capture records ({left,right}/poses.json) that check_cam.py cross-checks against.
+HANDEYE_RUNS = os.environ.get("FLEXIV_HANDEYE_RUNS", "")
diff --git a/flexiv-umi-infer/umi_infer/robot_io/flexiv.py b/flexiv-umi-infer/umi_infer/robot_io/flexiv.py
new file mode 100644
index 0000000000000000000000000000000000000000..408beb3c6003b9337bb6f635152439d26a5deaa5
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/flexiv.py
@@ -0,0 +1,1567 @@
+"""RobotIO for a Flexiv Rizon4/Rizon4R dual-arm cell with UMI grippers (robot side of the bridge).
+
+IK is not solved here. Flexiv has an onboard Cartesian controller: in
+NRT_CARTESIAN_MOTION_FORCE we send world-frame TCP poses and the controller does IK,
+null-space posture control and impedance tracking. There is no PyBullet on this path;
+`flexivrdk.Model.reachable` is only used as a pre-send reachability check (reject/truncate).
+
+Pipeline (paired with policies/umi_pi05_dual.py):
+
+ get_observation : TCP poses cached by the servo thread (shared world frame) -> protocol (xyzw)
+ + [prev, cur] motion window (from the servo thread's continuous pose history)
+ + measured gripper opening (dataset scale) + two wrist cameras
+ apply_action : the policy sends flange pose targets (E already applied on the policy side)
+ -> pre-checks (finite / jump / reachability / tool-aware arm distance)
+ -> pose trajectory buffer -> servo thread interpolates at servo_rate
+
+Frames (all verified on hardware):
+ * Reported and commanded poses are both shared-world TCP poses, i.e. the same frame as
+ `RobotPair.states().tcp_pose` and `SendCartesianMotionForce` (difference is 0 at rest).
+ * Robot TCP == URDF flange (measured offset 0.022 mm / 0.011 deg).
+ * Policy-side E = inv(T_flange_cam), exported from the URDF by umi_infer/export_E.py (hand-eye
+ calibration is baked into the URDF). So T_G = obs.eef @ E^-1 = T_world_cam = dataset frame.
+ Do not add any extra hand-tuned rotation on top of it.
+ * Quaternions: Flexiv is wxyz, the protocol is xyzw. Convert only in `_w2x`/`_x2w`.
+
+Camera identity: serials come from env vars via cam_ids.py.
+
+Safety (all on by default; disabling must be explicit):
+ * `SelfCollisionMonitor` at 100 Hz, default 5 cm, stops both arms below threshold.
+ WARNING: its collision model only has arm links, not the UMI grippers, so there is an
+ extra tool-aware pre-check (pose_math.pair_distance_tools).
+ * Per-cycle guard: fault / control mode changed / measured arm distance.
+ * `dry_run=True` is the default: everything runs (pre-checks, interpolation) but no motion
+ command is sent.
+"""
+
+from __future__ import annotations
+
+import csv
+import json
+import logging
+import os
+import sys
+import threading
+import time
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional
+
+import numpy as np
+
+from ..protocol import Action, CameraFrame, Observation
+from .base import RobotIO
+
+log = logging.getLogger("umi_infer.flexiv")
+
+SIDES = ("left", "right")
+IDX = {"left": 0, "right": 1} # all DRDK APIs take (left, right) in this order
+ARM_DOF = 7
+
+
+# ---- Camera identity --------------------------------------------------------------
+# Constants live in cam_ids.py (no relative imports there; check_cam.py uses it too).
+from .cam_ids import CAM_HALF, CAM_OBS_KEY, CAM_OUT_SIZE, CAM_SERIAL # noqa: E402
+from .kin_flexiv import DATA_DIR, SN as DEFAULT_SN, URDF as DEFAULT_URDF # noqa: E402
+
+# ---- Start posture (anchor) ---------------------------------------------------------
+# The start posture decides what the model sees first, and policies are sensitive to it.
+# No built-in fallback: it comes from data/anchor.json (in this tree) or the CLI flags.
+ANCHOR_FILE = os.environ.get("FLEXIV_ANCHOR_FILE", os.path.join(DATA_DIR, "anchor.json"))
+
+
+def load_anchor():
+ """Read data/anchor.json -> ({side: 7 joint deg}, {side: gripper opening}); (None, zeros) if unreadable."""
+ try:
+ with open(ANCHOR_FILE) as f:
+ d = json.load(f)
+ q = {s: [float(v) for v in d[s]] for s in SIDES}
+ if any(len(q[s]) != 7 for s in SIDES):
+ raise ValueError("expected 7 joint angles")
+ g = {s: float(d.get(s + "_grip", 0.0)) for s in SIDES}
+ log.info("anchor loaded from %s", ANCHOR_FILE)
+ return q, g
+ except Exception as e: # noqa: BLE001
+ log.warning("failed to read anchor file (%s: %s); need --anchor-deg-left/right or %s",
+ type(e).__name__, e, ANCHOR_FILE)
+ return None, {"left": 0.0, "right": 0.0}
+
+
+ANCHOR_DEG, ANCHOR_GRIP_FROM_FILE = load_anchor()
+# Gripper opening at the anchor (dataset scale, deg). The gripper is an observed column too,
+# so a random start value is out of distribution from the first frame.
+# Measured on the training set: grippers start almost closed (first-frame median ~0.2-0.3 deg).
+ANCHOR_GRIP_DEG = ANCHOR_GRIP_FROM_FILE
+
+# ---- Gripper ------------------------------------------------------------------------
+GRIP_CALIB = os.environ.get("FLEXIV_GRIP_CALIB", os.path.join(DATA_DIR, "gripper_calib.json"))
+# Calibrated mechanical travel is 0-90 deg (90 = fully open). Clamping to that range only
+# rejects outliers beyond the mechanical limit; it does not narrow the model's range.
+# (Training-data gripper range is roughly -1.6..17 deg, so the clamp rarely matters.)
+# Command lower bound: let negative openings through (= "slightly past the calibrated closed
+# position"). The model does output small negative values (down to about -0.3 deg); clamping
+# at 0 would drop them. -2.0 covers the training range plus margin; this is pass-through.
+# NOTE: passing them through does not mean a firm grip: -0.3 deg x kp36 is only ~0.18 Nm.
+# The model carries no force information (labels only see opening angle).
+# Constant offset subtracted from every model opening before execution.
+# Rationale: without it the model never asks for enough squeeze to hold an object. With a
+# 3 deg offset the error hits the lead=5 deg clamp when grasping -> force capped at
+# kp*rad(5) = 3.14 Nm.
+# WARNING: this shifts the position target, so open commands also shrink by 3 deg, and model
+# openings below 3 deg push an empty gripper into the soft limit (stall up to 3.14 Nm, heats).
+GRIP_OFFSET_DEG = float(os.environ.get("FLEXIV_GRIP_OFFSET_DEG", "3.0"))
+# Reach scaling: step position = start + k*(model target - start), start = measured position at
+# observation time; orientation unchanged. Default 1.0 = off. Scaled targets still go through
+# the pre-checks (IK / limits / collision).
+REACH_SCALE = {"left": 1.0, "right": float(os.environ.get("FLEXIV_REACH_SCALE_RIGHT", "1.0"))}
+# Command lower bound must accommodate -(offset), otherwise the offset is silently clamped away.
+GRIP_CMD_MIN_DEG = float(os.environ.get(
+ "FLEXIV_GRIP_CMD_MIN_DEG", "%.3f" % (-(GRIP_OFFSET_DEG + 2.0))))
+GRIP_MAX_DEG = float(os.environ.get("FLEXIV_GRIP_MAX_DEG", "90.0"))
+
+# Joint hard limits from the robot's info() (deg), same as kin_flexiv.py (5 deg narrower than URDF).
+# Postures at the limit are rejected by SetNullSpacePosture ("outside the valid range"), so keep a margin.
+RQMIN = np.array([-160., -130., -170., -107., -170., -80., -170.])
+RQMAX = np.array([160., 130., 170., 154., 170., 260., 170.])
+ANCHOR_MARGIN_DEG = float(os.environ.get("FLEXIV_ANCHOR_MARGIN_DEG", "0.5"))
+
+# ---------------------------------------------------------------- prev selection (train/infer consistency)
+# Native fps = dataset fps (30). Progress counting and prev lookback are in native frames, so
+# slow-motion playback is absorbed automatically (at 4x slow, one native frame ~ 133 ms wall).
+NATIVE_FPS = float(os.environ.get("FLEXIV_NATIVE_FPS", "30.0"))
+# Max allowed deviation (native frames) when finding prev by progress; beyond it, fall back to wall clock.
+PROGRESS_MAX_GAP_F = float(os.environ.get("FLEXIV_PROGRESS_MAX_GAP", "0.3"))
+# 1 = look back by executed progress (default); 0 = by wall-clock time (old behavior, for A/B)
+PREV_BY_PROGRESS = bool(int(os.environ.get("FLEXIV_PREV_BY_PROGRESS", "1")))
+# 10th percentile of per-frame motion in the training set:
+# translation p10=0.213mm median=1.419mm rotation p10=0.090deg median=0.381deg
+# Warn when observed motion is below this; warning only, no behavior change.
+TRAIN_P10_MM = float(os.environ.get("FLEXIV_TRAIN_P10_MM", "0.213"))
+TRAIN_P10_DEG = float(os.environ.get("FLEXIV_TRAIN_P10_DEG", "0.090"))
+# Lower bound of the gripper value *reported to the model*, separate from the command bound.
+# If commands are ever pushed further negative to squeeze harder, the reported value must not
+# follow: the model would see out-of-distribution values, keep asking to close, and the
+# gripper would never reopen (positive feedback).
+# How long to keep logging phase=hold rows after a chunk finishes (settling error). In sync mode inference is usually slower.
+HOLD_ROW_S = 0.3
+GRIP_OBS_MIN_DEG = float(os.environ.get("FLEXIV_GRIP_OBS_MIN_DEG", "-2.0"))
+# Legacy alias
+GRIP_MIN_DEG = GRIP_CMD_MIN_DEG
+
+# ================================ pose7 layout conversion ================================
+# Flexiv: [x,y,z, qw,qx,qy,qz] protocol/umi_decode: [x,y,z, qx,qy,qz,qw]
+# Convert only in these two functions; a missing or double conversion looks like a calibration error.
+def _w2x(p7) -> np.ndarray:
+ """Flexiv wxyz -> protocol xyzw."""
+ p = np.asarray(p7, float).reshape(7)
+ return np.concatenate([p[:3], p[[4, 5, 6, 3]]])
+
+
+def _x2w(p7) -> np.ndarray:
+ """Protocol xyzw -> Flexiv wxyz (normalizes the quaternion; commands must be unit quaternions)."""
+ p = np.asarray(p7, float).reshape(7)
+ q = p[[6, 3, 4, 5]]
+ n = float(np.linalg.norm(q))
+ if not np.isfinite(n) or n < 1e-9:
+ raise ValueError("invalid quaternion: %s" % p[3:7].tolist())
+ return np.concatenate([p[:3], q / n])
+
+
+def trace_path(record_path: str) -> str:
+ """Per-chunk trace path: x.csv -> x.chunks.jsonl."""
+ return os.path.splitext(record_path)[0] + ".chunks.jsonl"
+
+
+@dataclass
+class _Buf:
+ """Execution state of one action chunk in the servo thread."""
+ pose_w: np.ndarray # (M, 2, 7) Flexiv wxyz, shared world frame
+ twist: np.ndarray # (M, 2, 6) feedforward twist [v, w]
+ grip: np.ndarray # (M, 2) gripper opening, dataset scale
+ dt: float
+ start: float # perf_counter reference
+ seq: int
+ n_ik_bad: int = 0
+ truncated_from: int = 0
+ meta: dict = field(default_factory=dict)
+
+
+class FlexivRobotIO(RobotIO):
+ def __init__(
+ self,
+ left_sn: str = DEFAULT_SN["left"],
+ right_sn: str = DEFAULT_SN["right"],
+ urdf: str = DEFAULT_URDF,
+ dry_run: bool = True,
+ servo_rate_hz: float = 100.0,
+ pose_dt: float = 0.033,
+ play_scale: float = 2.5,
+ max_stale_s: float = 2.0,
+ record_path: Optional[str] = None,
+ live_camera: bool = False,
+ jpeg_quality: int = 90,
+ cam_format: str = "jpeg",
+ cam_kbps: int = 512,
+ gripper: bool = False,
+ grip_calib: str = GRIP_CALIB,
+ grip_kp: float = 36.0,
+ grip_kd: float = 0.8,
+ grip_lead_deg: float = 5.0,
+ grip_rate_hz: float = 200.0,
+ anchor_deg: Optional[Dict[str, List[float]]] = None,
+ anchor_grip_deg: Optional[Dict[str, float]] = None,
+ # Safety: three distance guards, each covering part of the problem:
+ # monitor_min_dist link<->link (Flexiv monitor, real time, cannot see the grippers)
+ # min_dist measured TCP<->TCP (our per-cycle check)
+ # tool_min_dist 6 end-effector rigid points (our pre-send check; the only one that sees the grippers)
+ monitor_min_dist: float = 0.05,
+ min_dist: float = 0.02,
+ tool_min_dist: float = 0.02,
+ max_step_mm: float = 60.0,
+ ik_check: str = "truncate", # off | warn | truncate | abort
+ ik_max_calls: int = 24, # max reachable() calls per chunk (~6.4 ms each)
+ no_monitor: bool = False,
+ # impedance / speed limits
+ kx_ratio: float = 0.6,
+ zx: float = 0.7,
+ max_contact_wrench=(40.0, 40.0, 40.0, 10.0, 10.0, 10.0),
+ max_lin_vel: float = 0.5,
+ max_ang_vel: float = 1.5,
+ max_lin_acc: float = 2.0,
+ max_ang_acc: float = 5.0,
+ feedforward: bool = True,
+ # steps executed per chunk (first N of the model output; 0 = all). First chunk set separately
+ first_steps: int = 0,
+ steps: int = 0,
+ # Null-space (elbow) pull toward the reference posture, SDK range [0.1, 1.0].
+ # kx only covers the 6 end-effector DoF; the redundant elbow DoF is governed by this alone
+ nullspace_weight: float = 0.5,
+ # per-frame rollout recording (rollout_rec.py): root dir, empty = off; live wrist frame rate (0 = model inputs only)
+ rollout_root: Optional[str] = None,
+ rollout_cam_hz: float = 10.0,
+ ):
+ self.sn = {"left": left_sn, "right": right_sn}
+ if not all(self.sn.values()) or not urdf:
+ raise ValueError("need both arm serial numbers "
+ "(--left-sn/--right-sn or FLEXIV_LEFT_SN/FLEXIV_RIGHT_SN)")
+ self.urdf = urdf
+ self.dry_run = bool(dry_run)
+ self.servo_rate_hz = float(servo_rate_hz)
+ self.pose_dt = float(pose_dt)
+ # Playback slowdown: each step is stretched by this factor in wall time. dt itself is
+ # unchanged (it is the dataset frame length; progress and prev lookback depend on it).
+ # Default 2.5: at 1x ~30% of trajectory points exceed max_linear_acc=2.0; slowing by k
+ # cuts acceleration by k^2, and at 2.5 the peak (1.72) stays under the limit.
+ self.play_scale = max(1.0, float(play_scale))
+ self.max_stale_s = float(max_stale_s)
+ self.record_path = record_path
+ self.live_camera = bool(live_camera)
+ self.jpeg_quality = int(jpeg_quality)
+ # jpeg: legacy path. yuv420p: send decoded I420 planes; the policy side converts to RGB and
+ # resizes with the same pyav call as training (no lossy JPEG, one less color conversion).
+ if cam_format not in ("jpeg", "yuv420p"):
+ raise ValueError("cam_format must be jpeg / yuv420p: %r" % cam_format)
+ self.cam_format = cam_format
+ # Live stream bitrate (full dual-fisheye frame, kbps). 512 is ~256 kbps per lens, far below
+ # the training videos (~8.7 Mbps AV1 per 960x960 view).
+ self.cam_kbps = int(cam_kbps)
+ self.use_gripper = bool(gripper)
+ self.grip_cfg = dict(calib=grip_calib, kp=grip_kp, kd=grip_kd,
+ lead_deg=grip_lead_deg, rate_hz=grip_rate_hz)
+ self.monitor_min_dist = float(monitor_min_dist)
+ self.min_dist = float(min_dist)
+ self.tool_min_dist = float(tool_min_dist)
+ self.max_step_mm = float(max_step_mm)
+ self.ik_check = str(ik_check).lower()
+ self.ik_max_calls = max(2, int(ik_max_calls))
+ self.no_monitor = bool(no_monitor)
+ self.kx_ratio, self.zx = float(kx_ratio), float(zx)
+ self.max_contact_wrench = list(max_contact_wrench)
+ self.vel_caps = dict(max_linear_vel=(max_lin_vel,) * 2,
+ max_angular_vel=(max_ang_vel,) * 2,
+ max_linear_acc=(max_lin_acc,) * 2,
+ max_angular_acc=(max_ang_acc,) * 2)
+ self.feedforward = bool(feedforward)
+ self.first_steps, self.steps = max(0, int(first_steps)), max(0, int(steps))
+ self.ns_weight = float(nullspace_weight)
+ if not 0.1 <= self.ns_weight <= 1.0:
+ raise ValueError("nullspace_weight must be in [0.1, 1.0]")
+ if self.ik_check not in ("off", "warn", "truncate", "abort"):
+ raise ValueError("ik_check must be off/warn/truncate/abort")
+
+ self._lt = None # pose_math module
+ self._pair = None
+ self._monitor = None
+ self._grip = None
+ self._dual = None
+ self._models = {} # side -> flexivrdk.Model (Flexiv IK, pre-check only)
+ self._bridge = {} # side -> T_world_sdkbase (pre-check maps world to per-arm base)
+ self._tool_X = None # tool rigid points in TCP frame, for the tool-aware pre-check
+
+ self._seq = 0
+ self._obs_pos = {} # obs seq -> {side: measured world position}, origin for reach scaling
+ self._buf: Optional[_Buf] = None
+ self._lock = threading.Lock() # guards _buf / cached state / history
+ self._stop_ev = threading.Event()
+ self._servo = None
+ self._rec = self._rec_w = None
+ # Per-chunk trace (.chunks.jsonl): raw model output / IK solution / truncation,
+ # complements the per-step cmd/act CSV. Written by both apply_action and the servo thread
+ self._trace = None
+ self._trace_lock = threading.Lock()
+ self._ik_trace = None # IK samples from the last _precheck
+ self.rollout_root, self.rollout_cam_hz = rollout_root, float(rollout_cam_hz)
+ self._rollout = None # RolloutRecorder; opened in start(), closed in stop()
+ self._rollout_actions = True # stop calling actions() for q_d after the first failure
+
+ # Latest state cached by the servo thread. get_observation reads only this and never
+ # touches the SDK (RobotPair is not guaranteed thread-safe).
+ self._st_pose_w = {s: None for s in SIDES} # Flexiv wxyz
+ self._st_q = {s: None for s in SIDES}
+ self._st_t = 0.0
+ # Continuous history [(t, progress, {side: pose_w}, {side: grip_raw})].
+ # progress = native frames executed so far; prev is looked up by it.
+ self._hist: List = []
+ self._plan_progress = 0.0 # executed trajectory progress, in native frames
+ self._plan_knot_last = None # knot of the last sent step; None = rebuild baseline
+ self._prev_by_progress = PREV_BY_PROGRESS
+ self._degen_warn = 0.0 # throttle timestamp for low-motion warning
+ self._stale_obs_warn = 0.0 # throttle timestamp for stale-state warning
+ self._last_cmd_w = None # (2,7) last command sent
+ self._anchor_w = {} # anchor poses (world, wxyz)
+ self._anchor_q = None
+ self._grip_ds = {s: 0.0 for s in SIDES}
+ # range of model gripper commands, diagnostics only (is there any open/close signal?); no decisions use it
+ self._grip_seen = {"lo": {s: float("inf") for s in SIDES},
+ "hi": {s: float("-inf") for s in SIDES}}
+ self._last_ik_q = None # chained seed for the reachability pre-check
+ self._ik_warned = False
+ self._stale_warn = 0.0
+ self._health = {"chunks": 0, "ik_bad": 0, "truncated": 0, "rejected": 0,
+ "min_pair_m": np.inf, "abort": None}
+ self.anchor_deg = anchor_deg
+ self.anchor_grip_deg = dict(anchor_grip_deg or ANCHOR_GRIP_DEG)
+
+ # ------------------------------------------------------------------ helpers
+ def _pair_t(self, d):
+ """{side: x} -> (left, right)."""
+ return (d["left"], d["right"])
+
+ def _sd(self, t):
+ """DRDK (left, right) -> {side: x}."""
+ return {"left": t[0], "right": t[1]}
+
+ def _load_lt(self):
+ if self._lt is None:
+ from . import pose_math
+ self._lt = pose_math
+ return self._lt
+
+ def _anchor_q_rad(self):
+ """Start posture (data/anchor.json or CLI). Per side: the two arms may differ."""
+ src = self.anchor_deg or ANCHOR_DEG
+ if src is None:
+ raise RuntimeError("no start posture: write %s (see configs/anchor.example.json) "
+ "or pass --anchor-deg-left/--anchor-deg-right" % ANCHOR_FILE)
+ for side in SIDES:
+ q = np.asarray(src[side], float)
+ lo, hi = q - RQMIN, RQMAX - q
+ m = float(min(lo.min(), hi.min()))
+ if m < ANCHOR_MARGIN_DEG:
+ bad = [("j%d=%.2fdeg (limit %.0f..%.0f, margin %.2fdeg)"
+ % (i + 1, q[i], RQMIN[i], RQMAX[i],
+ min(q[i] - RQMIN[i], RQMAX[i] - q[i])))
+ for i in range(7)
+ if min(q[i] - RQMIN[i], RQMAX[i] - q[i]) < ANCHOR_MARGIN_DEG]
+ raise ValueError(
+ "anchor[%s] too close to joint hard limit (margin %.2fdeg < %.2fdeg): %s\n"
+ " -> the robot will reject the null-space reference posture (SDK: 'outside the valid range'); "
+ "move that joint back by ~1 deg. Edit %s."
+ % (side, m, ANCHOR_MARGIN_DEG, "; ".join(bad), ANCHOR_FILE))
+ return {s: np.radians(src[s]) for s in SIDES}
+
+ # ------------------------------------------------------------------ lifecycle
+ def start(self) -> None:
+ import flexivdrdk
+ import flexivrdk
+ from flexivrdk import Mode
+ lt = self._load_lt()
+ self._Mode = Mode
+ self._CART = Mode.NRT_CARTESIAN_MOTION_FORCE
+
+ log.info("connecting arms: left %s | right %s (base world offset left %s right %s)",
+ self.sn["left"], self.sn["right"], lt.BASE_XYZ["left"], lt.BASE_XYZ["right"])
+ self._pair = flexivdrdk.RobotPair(
+ [self.sn["left"], self.sn["right"]],
+ [lt.BASE_XYZ["left"], lt.BASE_XYZ["right"]])
+ for s, info in self._sd(self._pair.info()).items():
+ log.info(" [%-5s] %s DoF=%d", s, info.model_name, info.DoF)
+ if info.DoF != ARM_DOF:
+ raise RuntimeError("%s arm DoF=%d; only 7-DoF arms without external axes are supported" % (s, info.DoF))
+
+ # Flexiv IK: build a Model from the pair's underlying Robots (no extra connection;
+ # RobotPair has no kinematics API, but instances() exposes the two Robots)
+ inst = self._sd(self._pair.instances())
+ for s in SIDES:
+ self._models[s] = flexivrdk.Model(inst[s])
+ log.info("kinematics models ready (pre-send reachability check only; the controller solves IK)")
+
+ if self.dry_run:
+ log.warning("DRY-RUN: full pipeline runs, but no motion commands are sent")
+
+ if not self.dry_run:
+ self._enable()
+ self._monitor = self._start_monitor()
+
+ # grippers: bring them up before the arms move (separate bus)
+ if self.use_gripper:
+ self._start_gripper()
+
+ if not self.dry_run:
+ self._move_to_anchor()
+ self._zero_ft()
+ log.info("switching to NRT_CARTESIAN_MOTION_FORCE (controller solves IK)...")
+ self._pair.SwitchMode(self._CART)
+ self._setup_impedance()
+
+ # anchor + bridge + tool geometry: all needed by the pre-checks
+ self._read_anchor()
+ self._measure_bridge()
+ self._prepare_tool_geometry()
+ self._selftest_quat()
+ self._selftest_reachable()
+
+ if self.live_camera:
+ self._start_cameras()
+
+ if self.record_path:
+ self._rec = open(self.record_path, "w", newline="", buffering=1) # line-buffered so it can be tailed live
+ cols = ["t", "seq", "idx", "phase"]
+ for s in SIDES:
+ cols += ["%s_cmd_%s" % (s, a) for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
+ cols += ["%s_act_%s" % (s, a) for a in ("x", "y", "z")]
+ cols += ["%s_grip_cmd" % s, "%s_grip_meas" % s]
+ cols += ["pair_dist_m"]
+ # measured orientation / joints appended at the end so positional readers keep working
+ for s in SIDES:
+ cols += ["%s_act_%s" % (s, a) for a in ("qw", "qx", "qy", "qz")]
+ for s in SIDES:
+ cols += ["%s_q%d" % (s, k) for k in range(1, ARM_DOF + 1)]
+ cols += ["knot"] # exact in-chunk progress of the servo (fractional step), for alignment
+ # External wrench (RDK ext_wrench_in_world / ext_wrench_in_tcp, N / Nm), to see whether
+ # max_contact_wrench was hit. Also appended at the end; nan if unavailable
+ for s in SIDES:
+ for fr in ("w", "tcp"):
+ cols += ["%s_ext%s_%s" % (s, fr, a) for a in ("fx", "fy", "fz", "mx", "my", "mz")]
+ self._rec_w = csv.writer(self._rec)
+ self._rec_w.writerow(cols)
+ self._trace = open(trace_path(self.record_path), "w", buffering=1)
+ self._trace_write({"event": "start", "dry_run": self.dry_run,
+ "play_scale": self.play_scale, "ik_check": self.ik_check,
+ "kx_ratio": self.kx_ratio, "zx": self.zx,
+ "nullspace_weight": self.ns_weight,
+ "first_steps": self.first_steps, "steps": self.steps,
+ "anchor": {s: self._anchor_w[s].tolist() for s in SIDES}})
+ self._open_rollout()
+
+ # initial buffer = hold at anchor (servo needs something to send before the first chunk)
+ pose0 = np.stack([self._anchor_w[s] for s in SIDES]) # (2,7)
+ with self._lock:
+ self._buf = _Buf(pose_w=pose0[None], twist=np.zeros((1, 2, 6)),
+ grip=np.zeros((1, 2)), dt=1.0 / self.servo_rate_hz,
+ start=time.perf_counter(), seq=-1,
+ meta={"anchor_hold": True})
+ self._last_cmd_w = pose0.copy()
+
+ if self.use_gripper:
+ log.info("gripper = model output minus %.1fdeg (command clamp [%.1f,%.0f]deg, report clamp "
+ "[%.1f,%.0f]deg, grasp force cap %.2f Nm)",
+ GRIP_OFFSET_DEG, GRIP_CMD_MIN_DEG, GRIP_MAX_DEG,
+ GRIP_OBS_MIN_DEG, GRIP_MAX_DEG,
+ self.grip_cfg["kp"] * np.radians(self.grip_cfg["lead_deg"]))
+ log.info(" WARNING: open commands also shrink by %.1fdeg; below %.1fdeg an empty gripper stalls at the soft limit (heats)",
+ GRIP_OFFSET_DEG, GRIP_OFFSET_DEG)
+ log.info(" NOTE: the calibrated closed position was set at 0.52 Nm (calib meta), so a 0deg command"
+ " is only a light touch")
+
+ self._servo = threading.Thread(target=self._servo_loop, daemon=True)
+ self._servo.start()
+ log.info("FlexivRobotIO ready (dry_run=%s servo=%.0fHz playback=%.2fx slower gripper=%s camera=%s)",
+ self.dry_run, self.servo_rate_hz, self.play_scale,
+ self.use_gripper, self.live_camera)
+ log.info(" steps per chunk: first %s / then %s (first N of the model output)",
+ self.first_steps or "all", self.steps or "all")
+ log.info(" playback x%.2f: %.4fs per step (wall), velocity /%.2f, acceleration /%.2f "
+ "(at 1x ~30%% of points exceed max_linear_acc=2.0)",
+ self.play_scale, self.pose_dt * self.play_scale,
+ self.play_scale, self.play_scale ** 2)
+ log.info(" prev lookup = %s (back %.0f native frames @ %.0fHz, tolerance %.1f frames)",
+ "by executed progress" if self._prev_by_progress else "by wall clock (old behavior)",
+ max(1.0, round(self.pose_dt * NATIVE_FPS)), NATIVE_FPS,
+ PROGRESS_MAX_GAP_F)
+
+ def stop(self) -> None:
+ self._stop_ev.set()
+ if self._servo:
+ self._servo.join(timeout=3.0)
+ if self._rollout is not None:
+ self._rollout.stop_cameras() # stop grab threads before cameras close
+ if self._pair is not None and not self.dry_run:
+ try:
+ if self._pair.operational():
+ self._pair.Stop()
+ t0 = time.time()
+ while not self._pair.stopped() and time.time() - t0 < 5.0:
+ time.sleep(0.1)
+ except Exception as e: # noqa: BLE001
+ log.error("Stop() failed: %s", e)
+ if self._grip is not None:
+ try:
+ self._grip.close() # release torque + disable, fingers back-drivable
+ except Exception as e: # noqa: BLE001
+ log.error("gripper shutdown failed: %s", e)
+ if self._monitor is not None:
+ try:
+ self._monitor.Stop()
+ except Exception: # noqa: BLE001
+ pass
+ if self._dual is not None:
+ try:
+ self._dual.stop()
+ except Exception: # noqa: BLE001
+ pass
+ if self._rec:
+ self._rec.close()
+ h = self._health
+ self._trace_write({"event": "stop", "chunks": h["chunks"], "ik_bad": h["ik_bad"],
+ "truncated": h["truncated"], "rejected": h["rejected"],
+ "abort": h["abort"]})
+ if self._trace:
+ with self._trace_lock:
+ self._trace.close()
+ self._trace = None
+ if self._rollout is not None:
+ self._rollout.close() # drain queue + write summary.json
+ self._rollout = None
+ log.info("summary: chunks %d, unreachable steps %d, truncated %d, rejected %d, "
+ "min arm distance %.3f m%s",
+ h["chunks"], h["ik_bad"], h["truncated"], h["rejected"],
+ h["min_pair_m"],
+ (" abort reason: " + h["abort"]) if h["abort"] else "")
+ if self.use_gripper and all(
+ self._grip_seen["hi"][s] > self._grip_seen["lo"][s] for s in SIDES):
+ for s in SIDES:
+ lo, hi = self._grip_seen["lo"][s], self._grip_seen["hi"][s]
+ log.info(" gripper[%s] raw model output %.2f ~ %.2fdeg (span %.2fdeg) "
+ "-> minus %.1fdeg, sent %.2f ~ %.2fdeg",
+ s, lo, hi, hi - lo, GRIP_OFFSET_DEG,
+ max(lo - GRIP_OFFSET_DEG, GRIP_CMD_MIN_DEG),
+ min(hi - GRIP_OFFSET_DEG, GRIP_MAX_DEG))
+
+ # ------------------------------------------------------------------ enable / safety
+ def _open_rollout(self) -> None:
+ """Open per-frame rollout recording (off if rollout_root is empty). Failures only warn."""
+ if not self.rollout_root:
+ return
+ from .rollout_rec import open_recorder
+ qmin = {s: RQMIN.copy() for s in SIDES}
+ qmax = {s: RQMAX.copy() for s in SIDES}
+ info = {}
+ try:
+ # prefer limits reported by the robot (RobotInfo.q_min/q_max, rad); fall back to RQMIN/RQMAX
+ info = self._sd(self._pair.info())
+ for s in SIDES:
+ lo = np.degrees(np.asarray(info[s].q_min, float))
+ hi = np.degrees(np.asarray(info[s].q_max, float))
+ if lo.shape == (ARM_DOF,) and hi.shape == (ARM_DOF,) and np.isfinite([lo, hi]).all():
+ qmin[s], qmax[s] = lo, hi
+ except Exception as e: # noqa: BLE001
+ log.warning("rollout: failed to read RobotInfo limits (%s), using RQMIN/RQMAX", e)
+ cam_hz = self.rollout_cam_hz if self._dual is not None else 0.0
+ self._rollout = open_recorder(self.rollout_root, tag="dry" if self.dry_run else "live",
+ cam_hz=cam_hz, q_min_deg=qmin, q_max_deg=qmax)
+ if self._rollout is None:
+ return
+ K = {}
+ for s, inf in (info or {}).items():
+ try:
+ K[s] = (np.asarray(inf.K_x_nom, float) * self.kx_ratio).tolist()
+ except Exception: # noqa: BLE001
+ pass
+ anchor_q = getattr(self, "_anchor_q", None) or {}
+ self._rollout.write_meta({
+ "started": time.strftime("%Y-%m-%d %H:%M:%S"), "argv": sys.argv,
+ "dry_run": self.dry_run, "sn": self.sn, "servo_rate_hz": self.servo_rate_hz,
+ "pose_dt": self.pose_dt, "play_scale": self.play_scale,
+ "kx_ratio": self.kx_ratio, "zx": self.zx, "K_x": K,
+ "nullspace_weight": self.ns_weight, "max_contact_wrench": self.max_contact_wrench,
+ "vel_caps": self.vel_caps, "feedforward": self.feedforward,
+ "first_steps": self.first_steps, "steps": self.steps, "ik_check": self.ik_check,
+ "max_step_mm": self.max_step_mm, "min_dist": self.min_dist,
+ "tool_min_dist": self.tool_min_dist, "cam_format": self.cam_format,
+ "cam_kbps": self.cam_kbps, "gripper": self.use_gripper,
+ "grip_offset_deg": GRIP_OFFSET_DEG, "prev_by_progress": self._prev_by_progress,
+ "record_path": self.record_path,
+ "anchor_w": {s: np.asarray(v).tolist() for s, v in self._anchor_w.items()},
+ "anchor_q_deg": {s: np.degrees(np.asarray(v, float)).tolist()
+ for s, v in anchor_q.items()},
+ })
+ if cam_hz > 0:
+ self._rollout.start_cameras(self._dual.get_frame)
+ log.info("rollout recording -> %s (live wrist frames %.0fHz, limit warning <%.1fdeg)",
+ self._rollout.dir, cam_hz, float(os.environ.get("FLEXIV_ROLLOUT_LIMIT_DEG", "3.0")))
+
+ def _rollout_servo(self, st, pose_w, q, cmd, buf, i, n, phase, hold, sent, pair_d, t_cycle):
+ """Hand one servo row to the rollout recorder. Controller targets (q_d / tcp_pose_d) are only read when recording."""
+ des, q_d = {}, {}
+ if self._rollout_actions:
+ try:
+ ac = self._sd(self._pair.actions())
+ for s in SIDES:
+ des[s] = np.asarray(ac[s].tcp_pose_d, float)
+ q_d[s] = np.asarray(ac[s].q_d, float)
+ except Exception as e: # noqa: BLE001
+ self._rollout_actions = False
+ log.warning("rollout: reading actions().q_d failed (%s: %s); des/q_d columns set to nan",
+ type(e).__name__, e)
+ tag = ("hold" if hold else "wait" if (buf.seq >= 0 and phase > n - 1)
+ else buf.meta.get("phase", "run"))
+ attr = lambda a: {s: getattr(st[s], a, None) for s in SIDES} # noqa: E731
+ self._rollout.servo(
+ t=time.time(), seq=buf.seq, idx=i, phase=tag, knot=float(np.clip(phase, 0.0, n - 1)),
+ sent=sent, cycle_ms=(time.perf_counter() - t_cycle) * 1000.0, pair_dist=pair_d,
+ cmd={s: cmd[IDX[s]] for s in SIDES}, des=des, act=pose_w, q=q, q_d=q_d,
+ dq=attr("dq"), tau=attr("tau"), tau_ext=attr("tau_ext"),
+ extw=attr("ext_wrench_in_world"), exttcp=attr("ext_wrench_in_tcp"),
+ grip_cmd={s: buf.grip[i, IDX[s]] for s in SIDES},
+ grip_meas={s: self._grip_ds[s] for s in SIDES})
+
+ def _trace_write(self, rec: dict) -> None:
+ """Append one record to chunks.jsonl. Failures only warn and never affect control."""
+ if self._rollout is not None:
+ self._rollout.event(rec)
+ if self._trace is None:
+ return
+ rec = {"t": round(time.time(), 4), **rec}
+ try:
+ line = json.dumps(rec, ensure_ascii=False)
+ with self._trace_lock:
+ if self._trace is not None:
+ self._trace.write(line + "\n")
+ except (OSError, TypeError, ValueError) as e:
+ log.warning("trace write failed (%s): %s", type(e).__name__, e)
+
+ def _enable(self):
+ p = self._pair
+ if p.fault():
+ w = p.which_fault()
+ log.warning("fault detected (left=%s right=%s), trying to clear ...", w[0], w[1])
+ r = p.ClearFault()
+ if not (r[0] and r[1]):
+ raise RuntimeError("fault cannot be cleared; check Flexiv Elements")
+ if not all(p.estop_released()):
+ raise RuntimeError("E-stop engaged; release it first")
+ log.info("enabling arms ...")
+ p.Enable()
+ t0 = time.time()
+ while not p.operational():
+ if time.time() - t0 > 60.0:
+ import flexivrdk
+ st = self._sd(p.operational_status())
+ hint = ""
+ if any(v == flexivrdk.OperationalStatus.IN_MANUAL_MODE for v in st.values()):
+ hint = "; an arm is in manual mode, switch the mode selector to Auto"
+ raise RuntimeError("timed out waiting for operational: left=%s right=%s%s" % (st["left"], st["right"], hint))
+ time.sleep(0.5)
+ log.info("arms operational")
+
+ def _start_monitor(self):
+ import flexivdrdk
+ if self.no_monitor:
+ log.warning("self-collision monitor disabled: no link-distance protection!")
+ return None
+ m = flexivdrdk.SelfCollisionMonitor(self._pair, [])
+ m.SetMinDistance(self.monitor_min_dist)
+ m.Start(10)
+ log.info("self-collision monitor started: %.0f cm / 10 ms "
+ "(WARNING: arm links only, not the UMI grippers, which extend 161 mm past the flange; "
+ "at %.0f cm link distance the grippers may already touch; covered by the %.0f cm tool-aware pre-check)",
+ self.monitor_min_dist * 100, self.monitor_min_dist * 100,
+ self.tool_min_dist * 100)
+ log.info(" other guards: measured TCP<->TCP %.0f cm (per cycle) / tool-aware pre-check %.0f cm (before send)",
+ self.min_dist * 100, self.tool_min_dist * 100)
+ return m
+
+ def _move_to_anchor(self):
+ q_d = self._anchor_q_rad()
+ for s in SIDES:
+ log.info(" [%-5s] anchor joints [deg] = %s", s,
+ np.round(np.degrees(q_d[s]), 2).tolist())
+ z = [0.0] * ARM_DOF
+ self._pair.SwitchMode(self._Mode.NRT_JOINT_POSITION)
+ self._pair.SendJointPosition(
+ self._pair_t({s: q_d[s].tolist() for s in SIDES}), (z, z),
+ ([0.3] * ARM_DOF,) * 2, ([0.8] * ARM_DOF,) * 2)
+ t0 = time.time()
+ while True:
+ st = self._sd(self._pair.states())
+ err = {s: float(np.abs(np.asarray(st[s].q) - q_d[s]).max()) for s in SIDES}
+ if max(err.values()) <= 0.01:
+ break
+ if self._pair.fault():
+ raise RuntimeError("fault while moving to anchor")
+ if time.time() - t0 > 90.0:
+ raise RuntimeError("timed out moving to anchor, residual [rad] left=%.4f right=%.4f"
+ % (err["left"], err["right"]))
+ time.sleep(0.05)
+ self._anchor_q = q_d
+ log.info("both arms at anchor")
+
+ def _zero_ft(self):
+ """Force-control modes require ZeroFTSensor in this RDK session (otherwise error 301004)."""
+ log.info("zeroing wrist F/T sensor ...")
+ self._pair.SwitchMode(self._Mode.NRT_PRIMITIVE_EXECUTION)
+ self._pair.ExecutePrimitive(("ZeroFTSensor", "ZeroFTSensor"), (dict(), dict()))
+ t0 = time.time()
+ while not all(s["terminated"] for s in self._pair.primitive_states()):
+ if time.time() - t0 > 30.0:
+ raise RuntimeError("ZeroFTSensor timed out")
+ time.sleep(0.2)
+ log.info("wrist F/T sensor zeroed")
+
+ def _setup_impedance(self):
+ off = [False] * 6
+ self._pair.SetForceControlAxis((off, off)) # pure motion = Cartesian impedance tracking
+ K = {}
+ for s, info in self._sd(self._pair.info()).items():
+ nom = np.asarray(info.K_x_nom, float)
+ K[s] = nom * self.kx_ratio
+ log.info(" [%-5s] K_x = %s Z_x = %.2f", s, np.round(K[s], 1).tolist(), self.zx)
+ Z = [self.zx] * 6
+ self._pair.SetCartesianImpedance(
+ self._pair_t({s: K[s].tolist() for s in SIDES}), (Z, Z))
+ q_ns = self._anchor_q_rad()
+ self._pair.SetNullSpacePosture(
+ self._pair_t({s: np.asarray(q_ns[s]).tolist() for s in SIDES}))
+ # must be set after SwitchMode: re-entering the mode resets it to the default 0.5
+ w = self.ns_weight
+ self._pair.SetNullSpaceObjectives((0.0, 0.0), (0.0, 0.0), (w, w))
+ self._pair.SetMaxContactWrench((self.max_contact_wrench, self.max_contact_wrench))
+ log.info(" null-space reference = anchor, weight %.2f (0.1 soft / 0.5 default / 1.0 stiff); "
+ "max contact wrench = %s", w, self.max_contact_wrench)
+
+ # ------------------------------------------------------------------ anchor / bridge / tool
+ def _read_anchor(self):
+ """Anchor pose P0 (shared world frame). In Cartesian mode prefer actions().tcp_pose_d."""
+ lt = self._load_lt()
+ time.sleep(0.5)
+ st = self._sd(self._pair.states())
+ src = "states"
+ pose = {s: lt.normalize_pose7(np.asarray(st[s].tcp_pose, float)) for s in SIDES}
+ if not self.dry_run:
+ ac = self._sd(self._pair.actions())
+ des = {s: np.asarray(ac[s].tcp_pose_d, float) for s in SIDES}
+ if all(abs(np.linalg.norm(des[s][3:7]) - 1.0) < 1e-3 for s in SIDES) and \
+ all(np.linalg.norm(des[s][:3] - pose[s][:3]) < 0.01 for s in SIDES):
+ pose = {s: lt.normalize_pose7(des[s]) for s in SIDES}
+ src = "actions"
+ self._anchor_w = pose
+ if self._anchor_q is None:
+ self._anchor_q = {s: np.asarray(st[s].q, float) for s in SIDES}
+ for s in SIDES:
+ p = pose[s]
+ log.info(" [%-5s] anchor P0 (world, from %s) xyz=[%+.4f %+.4f %+.4f] "
+ "quat_wxyz=[%+.4f %+.4f %+.4f %+.4f]", s, src, *p)
+
+ def _measure_bridge(self):
+ """Measure T_world_sdkbase; Flexiv IK takes poses in the single-arm base frame.
+
+ URDF-independent: read the pair tcp_pose (world) and the single-arm tcp_pose (arm base)
+ at the same time, `T_world_sdkbase = T_world_tcp @ inv(T_sdkbase_tcp)`.
+ It must be a pure translation equal to BASE_XYZ; otherwise the frame convention changed, so fail.
+ """
+ lt = self._load_lt()
+ from scipy.spatial.transform import Rotation as Rot
+ inst = self._sd(self._pair.instances())
+ st_w = self._sd(self._pair.states())
+ for s in SIDES:
+ T_w = lt.pose7_to_T(lt.normalize_pose7(np.asarray(st_w[s].tcp_pose, float)))
+ T_b = lt.pose7_to_T(lt.normalize_pose7(np.asarray(inst[s].states().tcp_pose, float)))
+ B = T_w @ np.linalg.inv(T_b)
+ rot_deg = float(np.degrees(np.linalg.norm(Rot.from_matrix(B[:3, :3]).as_rotvec())))
+ want = np.asarray(lt.BASE_XYZ[s], float)
+ dt_mm = float(np.linalg.norm(B[:3, 3] - want) * 1000)
+ log.info(" [%-5s] world<-arm base: translation %s m (expected %s, diff %.2f mm), rotation %.4fdeg",
+ s, np.round(B[:3, 3], 5).tolist(), want.tolist(), dt_mm, rot_deg)
+ if rot_deg > 0.5 or dt_mm > 5.0:
+ raise RuntimeError(
+ "%s arm world<->base bridge is not the expected pure translation (rotation %.3fdeg, translation diff %.1f mm); "
+ "frame convention changed and the reachability pre-check would be wrong" % (s, rot_deg, dt_mm))
+ self._bridge[s] = B
+
+ def _prepare_tool_geometry(self):
+ """Rigid tool points for the gripper-aware arm distance pre-check.
+
+ FK uses kin_flexiv (yourdfpy, no PyBullet) on the same URDF and kinematics parameters
+ synced from the robot (SyncKinematicsYAML). The tool is rigidly fixed to the flange, so the
+ transform is joint-independent: compute it at q=0 and verify at a second posture.
+ """
+ self._load_lt()
+ if self.tool_min_dist <= 0:
+ log.warning("tool_min_dist<=0: tool-aware distance pre-check disabled; the monitor cannot see the grippers (not recommended)")
+ return
+ lt = self._lt
+ try:
+ from . import kin_flexiv as K
+ links = list(lt.DEFAULT_TOOL_LINKS)
+ arms = {s: K.Arm(s, urdf=self.urdf, robot=False, verbose=False,
+ pre=K.prefix(s, self.sn[s])) for s in SIDES}
+ q0 = np.zeros(7)
+ q1 = np.radians([25., 50., -35., 95., 15., 70., -40.]) # check joint independence
+ out, drift = {}, 0.0
+ for lk in links:
+ out[lk] = {}
+ for s in SIDES:
+ inv0 = np.linalg.inv(arms[s].fk(q0, "flange"))
+ X0 = inv0 @ arms[s].fk(q0, lk)
+ X1 = np.linalg.inv(arms[s].fk(q1, "flange")) @ arms[s].fk(q1, lk)
+ drift = max(drift, float(np.abs(X0 - X1).max() * 1000))
+ out[lk][s] = X0
+ if drift > 1e-6:
+ raise RuntimeError("tool points move with joint angles (drift %.2e mm); "
+ "is the gripper not fixed to the flange in the URDF?" % drift)
+ self._tool_X = out
+ log.info("tool-aware pre-check enabled (FK=yourdfpy): %d rigid points %s, "
+ "threshold %.0f cm, joint-independent (drift %.1e mm)",
+ len(out), links, self.tool_min_dist * 100, drift)
+ except Exception as e: # noqa: BLE001
+ raise RuntimeError(
+ "failed to get tool geometry (%s): %s; the self-collision monitor ignores the grippers, so without "
+ "this check gripper-gripper contact is unprotected. Fix the URDF or set tool_min_dist=0 explicitly."
+ % (type(e).__name__, e))
+
+ # ------------------------------------------------------------------ startup self-tests
+ def _selftest_quat(self):
+ """wxyz <-> xyzw round trip must be exact.
+
+ A wrong mapping looks like a bad hand-eye calibration, so test it explicitly. Uses a
+ measured pose, not identity (identity is a fixed point of many wrong mappings).
+ """
+ worst = 0.0
+ for s in SIDES:
+ p = self._anchor_w[s]
+ back = _x2w(_w2x(p))
+ # q and -q are the same rotation; align signs before comparing
+ if float(np.dot(back[3:7], p[3:7])) < 0:
+ back[3:7] = -back[3:7]
+ worst = max(worst, float(np.abs(back - p).max()))
+ if worst > 1e-12:
+ raise RuntimeError("wxyz<->xyzw round trip not exact (max %.2e): conversion is wrong" % worst)
+ log.info("self-test quaternion round trip: exact (max diff %.1e, on measured anchor pose)", worst)
+
+ def _selftest_reachable(self):
+ """End-to-end test of the pre-check chain (world -> arm base -> Model.reachable).
+
+ The current measured pose must be reachable and solve back to the current joints;
+ if not, the bridge or call is wrong. Also reports per-call latency.
+ """
+ if self.ik_check == "off":
+ log.info("ik_check=off: skipping reachability pre-check")
+ return
+ t0 = time.perf_counter()
+ n_ok = 0
+ for s in SIDES:
+ q_now = np.asarray(self._st_q[s] if self._st_q[s] is not None
+ else self._anchor_q[s], float)
+ ok, _ = self._reachable(s, self._anchor_w[s], q_now)
+ if ok is None:
+ log.error("reachable() call failed; reachability pre-check disabled (other checks still active)")
+ return
+ if not ok:
+ raise RuntimeError(
+ "%s arm: even the current measured pose is unreachable; the bridge or call is wrong. "
+ "Refusing to run with a broken pre-check (it would truncate valid targets)" % s)
+ dq = float(np.abs(np.degrees(self._last_ik_q - q_now)).max())
+ n_ok += 1
+ log.info("self-test reachable [%-5s]: reachable, max joint diff to current %.3fdeg", s, dq)
+ ms = (time.perf_counter() - t0) / max(n_ok, 1) * 1000
+ log.info("self-test reachable: %.2f ms per call -> ~%.0f ms per 50-step dual-arm chunk "
+ "(chunk 1.7s, %.1f%%)", ms, ms * 100, ms * 100 / 1700 * 100)
+
+ # ------------------------------------------------------------------ gripper / camera
+ def _start_gripper(self):
+ from . import gripper_can
+ g = gripper_can.GripperPair(self.grip_cfg["calib"], kp=self.grip_cfg["kp"],
+ kd=self.grip_cfg["kd"],
+ lead_deg=self.grip_cfg["lead_deg"],
+ rate_hz=self.grip_cfg["rate_hz"], gain=1.0)
+ self._grip = g.open()
+ meas = {s: self._grip.measured_deg(s) for s in SIDES}
+ want = {s: float(np.clip(self.anchor_grip_deg[s], GRIP_MIN_DEG, GRIP_MAX_DEG))
+ for s in SIDES}
+ log.info("gripper bus open, measured opening left %.2fdeg right %.2fdeg (calib %s)",
+ meas["left"], meas["right"], os.path.basename(self.grip_cfg["calib"]))
+ log.info("anchor gripper opening left %.2fdeg right %.2fdeg",
+ want["left"], want["right"])
+ # Second floor: gripper_can.target_q applies max(deg, floor) and q >= q_closed+floor/dpr.
+ # floor defaults to 0; unless lowered too, the command lower bound is clamped back to 0 at the motor.
+ self._grip.set_floor_all({s: GRIP_CMD_MIN_DEG for s in SIDES})
+ log.info("gripper command floor set to %.2fdeg (to fit the -%.1fdeg offset; "
+ "otherwise target_q clamps it to 0)",
+ GRIP_CMD_MIN_DEG, GRIP_OFFSET_DEG)
+ if not self.dry_run:
+ # pin to the measured position before enabling; a large error at enable would snap the gripper
+ self._grip.set_all({s: float(np.clip(meas[s], GRIP_MIN_DEG, GRIP_MAX_DEG))
+ for s in SIDES})
+ self._grip.enable()
+ time.sleep(0.3)
+ # then ramp to the anchor opening over 1 s
+ n = 20
+ for i in range(1, n + 1):
+ a = i / n
+ self._grip.set_all({s: (1 - a) * meas[s] + a * want[s] for s in SIDES})
+ time.sleep(1.0 / n)
+ self._grip_ds = dict(want)
+ log.info("gripper at anchor opening, measured left %.2fdeg right %.2fdeg",
+ self._grip.measured_deg("left"), self._grip.measured_deg("right"))
+ log.info("gripper enabled (kp=%.0f kd=%.1f, command lead <= %.1fdeg => max torque ~%.1f Nm)",
+ self.grip_cfg["kp"], self.grip_cfg["kd"], self.grip_cfg["lead_deg"],
+ self.grip_cfg["kp"] * np.radians(self.grip_cfg["lead_deg"]))
+ else:
+ log.info("dry-run: gripper read-only, not enabled (doubles as wiring check)")
+
+ def _start_cameras(self):
+ from .insta_live import InstaDualCamera, kill_stale_cameras
+ if not all(CAM_SERIAL.values()):
+ raise RuntimeError("set INSTA360_LEFT_SN / INSTA360_RIGHT_SN for --live-camera")
+ # stale-process cleanup + discovery happen in InstaDualCamera.start()
+ last_err = None
+ for attempt in (1, 2, 3):
+ self._dual = InstaDualCamera(
+ serials={s: CAM_SERIAL[s] for s in SIDES},
+ halves={s: CAM_HALF[s] for s in SIDES},
+ out_size=CAM_OUT_SIZE, bitrate_kbps=self.cam_kbps,
+ pix_fmt="yuv420p" if self.cam_format == "yuv420p" else "rgb24")
+ try:
+ self._dual.start()
+ if self._dual.wait_ready(60.0):
+ break
+ last_err = "wait_ready timed out"
+ except Exception as e: # noqa: BLE001
+ last_err = "%s: %s" % (type(e).__name__, e)
+ # clean up fully before retrying; a half-dead process causes serial_not_found next time
+ log.warning("camera start attempt %d failed (%s), cleaning up and retrying ...", attempt, last_err)
+ try:
+ self._dual.stop()
+ except Exception: # noqa: BLE001
+ pass
+ self._dual = None
+ kill_stale_cameras(CAM_SERIAL.values(), "retry %d" % attempt)
+ if self._dual is None:
+ raise RuntimeError(
+ "wrist cameras failed to start 3 times (%s). Check: (1) camera USB mode set to Android control "
+ "(2) udev rule 99-insta360.rules (3) another process holding the device" % last_err)
+ log.info("wrist cameras ready: %s, half=%s, %dpx",
+ {s: CAM_SERIAL[s] for s in SIDES}, CAM_HALF, CAM_OUT_SIZE)
+
+ def _grab_images(self) -> "Dict[str, CameraFrame]":
+ import cv2
+ out: Dict[str, CameraFrame] = {}
+ now = time.time()
+ for s in SIDES:
+ rgb, stamp = self._dual.get_frame(s)
+ if rgb is None:
+ continue
+ if self.cam_format == "yuv420p":
+ h = rgb.shape[0] * 2 // 3
+ out[CAM_OBS_KEY[s]] = CameraFrame(
+ name=CAM_OBS_KEY[s], format="yuv420p", height=h, width=int(rgb.shape[1]),
+ data=rgb.tobytes(), stamp=float(stamp or now))
+ continue
+ ok, enc = cv2.imencode(".jpg", cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR),
+ [int(cv2.IMWRITE_JPEG_QUALITY), self.jpeg_quality])
+ if not ok:
+ continue
+ out[CAM_OBS_KEY[s]] = CameraFrame(
+ name=CAM_OBS_KEY[s], format="jpeg",
+ height=int(rgb.shape[0]), width=int(rgb.shape[1]),
+ data=enc.tobytes(), stamp=float(stamp or now))
+ return out
+
+ # ------------------------------------------------------------------ observation
+ def get_observation(self) -> Observation:
+ now = time.time()
+ with self._lock:
+ cur = {s: None if self._st_pose_w[s] is None else self._st_pose_w[s].copy()
+ for s in SIDES}
+ hist = list(self._hist)
+ prog = float(self._plan_progress)
+ st_age = now - self._st_t if self._st_t else np.inf
+ if any(cur[s] is None for s in SIDES):
+ raise RuntimeError("no robot state yet (servo thread just started?); retry shortly")
+ if st_age > 0.5 and now - self._stale_obs_warn > 2.0:
+ # throttled: if the servo thread dies this would fire every observation
+ self._stale_obs_warn = now
+ log.warning("robot state is stale by %.2fs: servo thread dead or stuck (look above for "
+ "Exception in thread)", st_age)
+
+ # [prev, cur] motion window: key to train/infer consistency.
+ # By default look back 1 native frame of *executed trajectory progress*, not wall time.
+ # With wall-clock lookback, a stationary arm yields near-zero motion (far below the
+ # training distribution). Progress does not advance while chunks are rejected / holding
+ # anchor / finished, so prev is always the last actually executed frame and motion has
+ # training-like magnitude. Time mismatch is harmless: the model does not see time.
+ # One native frame equals one chunk step only when upsample=1; dt*NATIVE_FPS handles the rest.
+ lookback_f = max(1.0, round(self.pose_dt * NATIVE_FPS)) # seconds -> native frames
+ prev, achieved = dict(cur), self.pose_dt
+ grip_prev_raw = {s: None for s in SIDES}
+ src, knots, sel = "cold", 0.0, None
+ if self._prev_by_progress and hist and prog >= lookback_f:
+ tgt = prog - lookback_f
+ cand = min(hist, key=lambda e: abs(e[1] - tgt))
+ if abs(cand[1] - tgt) <= PROGRESS_MAX_GAP_F:
+ sel, src = cand, "progress"
+ if sel is None:
+ # fallback = wall-clock lookback, labeled (cold = not enough progress yet, wallclock = explicitly disabled)
+ src = "cold" if self._prev_by_progress else "wallclock"
+ if hist:
+ tgt_t = now - self.pose_dt * self.play_scale
+ sel = min(hist, key=lambda e: abs(e[0] - tgt_t))
+ if sel is not None:
+ prev = {s: sel[2][s].copy() for s in SIDES}
+ grip_prev_raw = sel[3]
+ achieved = max(now - sel[0], 1e-3)
+ knots = round(prog - sel[1], 3)
+
+ eef, eef_prev, grip, grip_prev = {}, {}, {}, {}
+ for s in SIDES:
+ eef[s] = [float(x) for x in _w2x(cur[s])] # Flexiv wxyz -> protocol xyzw
+ eef_prev[s] = [float(x) for x in _w2x(prev[s])]
+ g = self._read_grip(s)
+ grip[s] = g
+ # Gripper prev = measured value at the selected frame; fall back to current if missing/NaN.
+ # Clamp with the OBS bound to stay in distribution.
+ gp = grip_prev_raw.get(s)
+ grip_prev[s] = (float(np.clip(gp, GRIP_OBS_MIN_DEG, GRIP_MAX_DEG))
+ if gp is not None and np.isfinite(gp) else g)
+ self._warn_if_degenerate(cur, prev, src)
+ self._seq += 1
+ self._obs_pos[self._seq] = {s: cur[s][:3].copy() for s in SIDES}
+ for k in [k for k in self._obs_pos if k < self._seq - 8]: # keep only the last few
+ del self._obs_pos[k]
+ obs = Observation(seq=self._seq, stamp=now,
+ images=self._grab_images() if self._dual else {},
+ eef=eef, gripper=grip, eef_prev=eef_prev,
+ gripper_prev=grip_prev, pose_dt=achieved,
+ extra={"prev": {"source": src, "knots": knots,
+ "dt": round(achieved, 4)},
+ "pose_dt_target": self.pose_dt,
+ "plan_progress": round(prog, 3)})
+ if self._rollout is not None:
+ # exactly what the model gets: state + images (saved in background as obs/_.jpg)
+ self._rollout.event({"event": "obs", "seq": obs.seq, "eef": eef, "eef_prev": eef_prev,
+ "gripper": grip, "gripper_prev": grip_prev,
+ "pose_dt": achieved, "prev": obs.extra["prev"],
+ "plan_progress": round(prog, 3),
+ "img_stamp": {k: f.stamp for k, f in obs.images.items()}})
+ self._rollout.obs_images(obs.seq, obs.images)
+ return obs
+
+ def _warn_if_degenerate(self, cur, prev, src) -> None:
+ """Warn when observed motion falls below the training p10 (TRAIN_P10_*). Warning only, throttled 2s."""
+ from scipy.spatial.transform import Rotation as Rot
+ bad = []
+ for s in SIDES:
+ mm = float(np.linalg.norm(cur[s][:3] - prev[s][:3]) * 1000)
+ r0 = Rot.from_quat(cur[s][[4, 5, 6, 3]]) # pose7 wxyz -> xyzw
+ r1 = Rot.from_quat(prev[s][[4, 5, 6, 3]])
+ dg = float(np.degrees((r1.inv() * r0).magnitude()))
+ if mm < TRAIN_P10_MM or dg < TRAIN_P10_DEG:
+ bad.append("%s %.3fmm/%.4fdeg" % (s[0].upper(), mm, dg))
+ if not bad:
+ return
+ t = time.time()
+ if t - self._degen_warn > 2.0:
+ self._degen_warn = t
+ log.warning("low observed motion %s (training per-frame p10=%.3fmm/%.3fdeg median=1.42mm/0.38deg) "
+ "prev source=%s; the model's motion cue may be useless",
+ " ".join(bad), TRAIN_P10_MM, TRAIN_P10_DEG, src)
+
+ def _grip_meas_raw(self, side: str):
+ """Measured gripper opening (unclamped) for history; reads a cached field, cheap."""
+ if self._grip is None:
+ return None
+ try:
+ v = float(self._grip.measured_deg(side))
+ except Exception: # noqa: BLE001
+ return None
+ return v if np.isfinite(v) else None
+
+ def _read_grip(self, side: str) -> float:
+ """Measured gripper opening (dataset scale: 0 = closed, 90 = fully open)."""
+ if self._grip is None:
+ return float(self._grip_ds[side])
+ try:
+ v = float(self._grip.measured_deg(side))
+ except Exception: # noqa: BLE001
+ return float(self._grip_ds[side])
+ # Clamp to the training range before reporting, using the OBS bound (not the command bound),
+ # so the model never sees out-of-distribution values (see constants above).
+ v = float(np.clip(v, GRIP_OBS_MIN_DEG, GRIP_MAX_DEG))
+ self._grip_ds[side] = v
+ return v
+
+ # ------------------------------------------------------------------ action
+ def apply_action(self, action: Action) -> None:
+ lt = self._load_lt()
+ traj = {s: np.asarray(action.eef_traj.get(s, []), float) for s in SIDES}
+ grips = {s: np.asarray(action.gripper_traj.get(s, []), float) for s in SIDES}
+ M = max(len(traj[s]) for s in SIDES)
+ if M == 0:
+ log.warning("seq=%d empty action chunk", action.seq)
+ return
+ self._health["chunks"] += 1
+
+ # ---- protocol (xyzw) -> Flexiv (wxyz), rejecting invalid quaternions ----
+ pose_w = np.zeros((M, 2, 7))
+ for h, s in enumerate(SIDES):
+ t = traj[s]
+ for i in range(M):
+ p = t[min(i, len(t) - 1)]
+ if not np.all(np.isfinite(p)):
+ log.error("seq=%d %s arm step %d has non-finite values -> chunk rejected: %s",
+ action.seq, s, i, p.tolist())
+ self._health["rejected"] += 1
+ self._trace_write({"event": "chunk", "seq": action.seq, "n_model": M,
+ "keep": 0, "status": "rejected",
+ "why": "%s arm step %d non-finite" % (s, i),
+ "policy": (action.extra or {}).get("policy")})
+ return
+ pose_w[i, h] = _x2w(p)
+
+ # ---- reach scaling: origin = measured position at this chunk's observation ----
+ o = self._obs_pos.pop(action.seq, None)
+ for h, s in enumerate(SIDES):
+ k = REACH_SCALE[s]
+ if k != 1.0 and o is not None:
+ pose_w[:, h, :3] = o[s] + k * (pose_w[:, h, :3] - o[s])
+
+ grip_t = np.zeros((M, 2))
+ for h, s in enumerate(SIDES):
+ g = grips[s]
+ for i in range(M):
+ raw = (float(g[min(i, len(g) - 1)]) if len(g)
+ else self._grip_ds[s] + GRIP_OFFSET_DEG)
+ # track the raw model output (before offset)
+ self._grip_seen["lo"][s] = min(self._grip_seen["lo"][s], raw)
+ self._grip_seen["hi"][s] = max(self._grip_seen["hi"][s], raw)
+ grip_t[i, h] = float(np.clip(raw - GRIP_OFFSET_DEG,
+ GRIP_CMD_MIN_DEG, GRIP_MAX_DEG))
+
+ # ---- steps per chunk: keep the first N model steps (first chunk separate), drop the rest ----
+ n_raw = M
+ lim = self.first_steps if self._health["chunks"] == 1 else self.steps
+ if lim and M > lim:
+ pose_w, grip_t, M = pose_w[:lim], grip_t[:lim], lim
+
+ self._ik_trace = None
+ keep, why = self._precheck(action.seq, pose_w, lt)
+ # model output before truncation (world-frame flange poses, wxyz)
+ trace = {"event": "chunk", "seq": action.seq, "n_raw": n_raw, "n_model": M,
+ "keep": int(max(keep, 0)),
+ "why": why, "dt": float(action.dt or 1.0 / 30.0),
+ "play_scale": self.play_scale,
+ "policy": (action.extra or {}).get("policy"),
+ "reach_scale": REACH_SCALE, # model is already reach-scaled (what is sent)
+ "model": {s: np.round(pose_w[:, IDX[s]], 5).tolist() for s in SIDES},
+ "ik": self._ik_trace}
+ if keep <= 0:
+ self._health["rejected"] += 1
+ log.warning("seq=%d pre-check failed -> holding until next inference: %s", action.seq, why)
+ self._trace_write({**trace, "status": "rejected"})
+ return
+ if keep < M:
+ self._health["truncated"] += 1
+ log.warning("seq=%d pre-check truncated: keeping first %d/%d steps (%s)", action.seq, keep, M, why)
+ pose_w, grip_t = pose_w[:keep], grip_t[:keep]
+ M = keep
+
+ dt = float(action.dt or 1.0 / 30.0)
+ twist = self._twists(pose_w, dt) if self.feedforward else np.zeros((M, 2, 6))
+
+ # ---- chunk seam: start the new chunk at the point closest to the last command ----
+ # The policy anchors a chunk at the pose at observation time. In sync mode the seam is ~0;
+ # in async mode the anchor is stale and starting at step 0 would jump backwards.
+ # No crossfade on top of k0; the residual seam goes straight to the arm, so it is logged.
+ # NOTE: k0 is picked by nearest position, not time; it can pick wrong when the path revisits
+ # a position, and has no bound beyond half a chunk. Better: k0 = latency/dt, position for refinement.
+ now_pc = time.perf_counter()
+ with self._lock:
+ last = None if self._last_cmd_w is None else self._last_cmd_w.copy()
+ k0, seam_mm = 0, None
+ if last is not None and M > 1:
+ half = max(1, M // 2) # search only the first half to avoid matching the far tail
+ d = np.linalg.norm(pose_w[:half, :, :3] - last[None, :, :3], axis=(1, 2))
+ k0 = int(np.argmin(d))
+ # seam residual (per arm, mm): position jump the arm takes at the switch
+ seam_mm = np.linalg.norm(pose_w[k0, :, :3] - last[:, :3], axis=1) * 1000.0
+ with self._lock:
+ self._buf = _Buf(pose_w=pose_w, twist=twist, grip=grip_t, dt=dt,
+ start=now_pc - k0 * dt * self.play_scale,
+ seq=action.seq,
+ truncated_from=keep,
+ meta=dict(action.extra or {}))
+ # new chunk = rebuild baseline: first send records the knot without counting, so the k0 skip is not counted as progress
+ self._plan_knot_last = None
+ log.info("seq=%d chunk %d steps%s dt=%.4f x%.2f slower (plays %.2fs) start k0=%d seam %s%s",
+ action.seq, M, "" if n_raw == M else " (model gave %d, took first %d)" % (n_raw, M),
+ dt, self.play_scale,
+ (M - 1) * dt * self.play_scale, k0,
+ "-" if seam_mm is None else ("left %.2f right %.2f mm" % tuple(seam_mm)),
+ " [dry-run, not sent]" if self.dry_run else "")
+ self._trace_write({**trace, "status": "truncated" if keep < trace["n_model"] else "ok",
+ "k0": k0,
+ "seam_mm": None if seam_mm is None else np.round(seam_mm, 2).tolist()})
+
+ def _twists(self, pose_w, dt):
+ """Feedforward twist [v(3), w(3)] from a pose chunk (central differences, one-sided at ends)."""
+ from scipy.spatial.transform import Rotation as Rot
+ M = pose_w.shape[0]
+ tw = np.zeros((M, 2, 6))
+ if M < 2 or dt <= 0:
+ return tw
+ for h in range(2):
+ p = pose_w[:, h, :3]
+ q = pose_w[:, h, 3:7][:, [1, 2, 3, 0]] # wxyz -> xyzw (scipy)
+ R = Rot.from_quat(q)
+ for i in range(M):
+ a, b = max(i - 1, 0), min(i + 1, M - 1)
+ span = (b - a) * dt
+ if span <= 0:
+ continue
+ tw[i, h, :3] = (p[b] - p[a]) / span
+ tw[i, h, 3:] = (R[b] * R[a].inv()).as_rotvec() / span
+ # The last step is where the arm must stop (sync mode waits for inference), so its velocity
+ # must be 0; a one-sided difference here makes position and feedforward fight -> oscillation.
+ tw[-1] = 0.0
+ return tw / self.play_scale # slowed playback scales velocity down; scale feedforward too
+
+ @staticmethod
+ def _ff_twist(buf, phase):
+ """Feedforward twist for this servo cycle: linearly interpolated like position; 0 once the chunk ends."""
+ n = len(buf.twist)
+ if phase >= n - 1:
+ return np.zeros((2, 6))
+ i = int(np.clip(phase, 0, n - 1))
+ a = float(np.clip(phase - i, 0.0, 1.0))
+ return (1 - a) * buf.twist[i] + a * buf.twist[min(i + 1, n - 1)]
+
+ def _precheck(self, seq, pose_w, lt):
+ """Check the whole chunk before sending. Returns (steps to execute, reason).
+
+ Independent failure modes, checked and reported separately:
+ (1) step jump - occasional model outliers; large jumps leave the gap unsupervised
+ (2) reachability - flexivrdk.Model.reachable; do not send what the robot's IK rejects
+ (3) tool distance - the self-collision monitor cannot see the UMI grippers
+ The earliest cut point wins.
+ """
+ M = pose_w.shape[0]
+ first_bad, reasons = M, []
+
+ def cut(i, why):
+ nonlocal first_bad
+ if i < first_bad:
+ first_bad = i
+ reasons.append(why)
+
+ # (1) step jump
+ if M > 1:
+ step = np.linalg.norm(np.diff(pose_w[:, :, :3], axis=0), axis=2) * 1000 # (M-1,2)
+ bad = np.where(step.max(axis=1) > self.max_step_mm)[0]
+ if len(bad):
+ cut(int(bad[0]) + 1, "step %d jump %.0f mm > %.0f"
+ % (bad[0] + 1, step[bad[0]].max(), self.max_step_mm))
+
+ # (2) reachability (robot's own IK), sampled rather than per step:
+ # `Model.reachable` takes ~6.4 ms ([Blocking], goes through the controller); checking all 50
+ # dual-arm steps would take ~38% of a chunk and may contend with the 100 Hz command stream.
+ # So check ik_max_calls points, always including first and last (the last is farthest).
+ # Unsampled steps have no reachability result; other checks do not replace it.
+ if self.ik_check != "off":
+ n_bad, first_ik, last_good = 0, None, 0
+ seed = {s: np.asarray(self._st_q[s] if self._st_q[s] is not None
+ else self._anchor_q[s], float) for s in SIDES}
+ per_arm = max(2, self.ik_max_calls // 2)
+ idxs = sorted(set(np.linspace(0, M - 1, min(per_arm, M)).astype(int).tolist()))
+ t_ik = time.perf_counter()
+ ik_tr = {"idx": idxs, **{s: {"ok": [], "q": []} for s in SIDES}}
+ for i in idxs:
+ step_ok = True
+ for s in SIDES:
+ ok, q_sol = self._reachable(s, pose_w[i, IDX[s]], seed[s])
+ ik_tr[s]["ok"].append(ok)
+ ik_tr[s]["q"].append(None if not ok else np.round(q_sol, 5).tolist())
+ if ok is None: # call failed; not treated as unreachable
+ continue
+ if not ok:
+ n_bad += 1
+ step_ok = False
+ if first_ik is None:
+ first_ik = i
+ elif self._last_ik_q is not None:
+ seed[s] = self._last_ik_q # chained seed: keeps solutions continuous, no branch jumps
+ if step_ok:
+ last_good = i
+ ik_ms = (time.perf_counter() - t_ik) * 1000
+ self._ik_trace = ik_tr
+ if n_bad:
+ self._health["ik_bad"] += n_bad
+ # conservative: cut at the last checked-and-passed point; unsampled steps are not assumed good
+ msg = ("IK: sampled %d points (of %d steps), %d arm-steps unreachable, first at step %d; "
+ "cut at last checked step %d" % (len(idxs), M, n_bad, first_ik, last_good))
+ if self.ik_check == "warn":
+ log.warning("seq=%d %s (ik_check=warn, sending anyway)", seq, msg)
+ elif self.ik_check == "abort":
+ cut(0, msg)
+ else:
+ cut(int(last_good), msg)
+ elif ik_ms > 250:
+ log.warning("reachability pre-check took %.0f ms (%d points); slow, use --ik-check off to skip",
+ ik_ms, len(idxs))
+
+ # (3) tool-aware arm distance
+ if self._tool_X is not None:
+ abs_p = {s: pose_w[:, IDX[s], :] for s in SIDES}
+ try:
+ # returns (per-frame min distance [M], global min, closest frame, (left link, right link))
+ per_frame, dmin, f_min, pair_lk = lt.pair_distance_tools(abs_p, self._tool_X)
+ bad = np.where(np.asarray(per_frame) < self.tool_min_dist)[0]
+ if len(bad):
+ cut(int(bad[0]),
+ "with gripper geometry: step %d arm distance %.3f m < %.3f (closest pair %s<->%s, frame %d)"
+ % (bad[0], float(per_frame[bad[0]]), self.tool_min_dist,
+ pair_lk[0], pair_lk[1], f_min))
+ except Exception as e: # noqa: BLE001
+ log.error("tool-aware distance pre-check failed (%s): %s; treating chunk as unsafe", type(e).__name__, e)
+ cut(0, "tool-aware distance pre-check failed")
+
+ return first_bad, "; ".join(reasons) if reasons else "all passed"
+
+ def _reachable(self, side, pose_w7, seed_q):
+ """Flexiv reachable(). Input: world-frame (wxyz) flange pose. Returns (reachable?, joints rad or None).
+
+ Model is built from the single-arm Robot and takes arm-base poses; map via the measured bridge.
+ The residual cannot be recomputed from the solution (the T() Python binding is broken:
+ Unregistered type), so only reachability is reported; joints are recorded in the trace.
+ """
+ lt = self._lt
+ try:
+ T_b = np.linalg.inv(self._bridge[side]) @ lt.pose7_to_T(pose_w7)
+ ok, sol = self._models[side].reachable(
+ [float(v) for v in lt.T_to_pose7(T_b)],
+ [float(v) for v in np.asarray(seed_q, float)], False)
+ if ok:
+ self._last_ik_q = np.asarray(sol, float)
+ return bool(ok), (self._last_ik_q if ok else None)
+ except Exception as e: # noqa: BLE001
+ if not getattr(self, "_ik_warned", False):
+ self._ik_warned = True
+ log.warning("reachable() call failed (%s: %s); not reporting again. "
+ "Reachability pre-check disabled, other checks still active", type(e).__name__, e)
+ return None, None
+
+ def needs_refill(self, fraction: float) -> bool:
+ with self._lock:
+ buf = self._buf
+ if buf is None or buf.seq < 0:
+ return True # still at anchor, need the first chunk now
+ n = len(buf.pose_w)
+ if n <= 1:
+ return True
+ elapsed = time.perf_counter() - buf.start
+ return elapsed >= fraction * (n - 1) * buf.dt * self.play_scale
+
+ # ------------------------------------------------------------------ servo
+ def _servo_loop(self):
+ from scipy.spatial.transform import Rotation as Rot, Slerp
+ lt = self._lt
+ period = 1.0 / self.servo_rate_hz
+ zero6 = [0.0] * 6
+ last_idx, last_log = -1, 0.0
+ last_seq, hold_seq = None, None
+ while not self._stop_ev.is_set():
+ t_cycle = time.perf_counter()
+ with self._lock:
+ buf = self._buf
+ if buf is None:
+ time.sleep(period)
+ continue
+
+ n = len(buf.pose_w)
+ slow_dt = buf.dt * self.play_scale
+ phase = ((time.perf_counter() - buf.start) / slow_dt) if slow_dt > 0 else 0.0
+ i = int(np.clip(phase, 0, n - 1))
+ j = min(i + 1, n - 1)
+ a = float(np.clip(phase - i, 0.0, 1.0))
+
+ # ---- interpolation: linear position + Slerp orientation ----
+ # Not zero-order hold: low-rate step commands through a stiff loop cause visible jitter.
+ cmd = np.zeros((2, 7))
+ for h in range(2):
+ p0, p1 = buf.pose_w[i, h], buf.pose_w[j, h]
+ pos = (1 - a) * p0[:3] + a * p1[:3]
+ if i == j or a <= 0:
+ quat_w = p0[3:7]
+ else:
+ R01 = Rot.from_quat(np.stack([p0[3:7][[1, 2, 3, 0]],
+ p1[3:7][[1, 2, 3, 0]]]))
+ Rm = Slerp([0.0, 1.0], R01)(a).as_matrix()
+ quat_w = lt.R_to_quat_wxyz(Rm)
+ cmd[h] = np.concatenate([pos, quat_w])
+
+ tw = self._ff_twist(buf, phase) if self.feedforward else np.zeros((2, 6))
+
+ # ---- send + read state ----
+ st = None
+ sent = True # dry-run counts as accepted (simulated successful send)
+ if not self.dry_run:
+ try:
+ self._pair.SendCartesianMotionForce(
+ (cmd[0].tolist(), cmd[1].tolist()),
+ velocities=(tw[0].tolist(), tw[1].tolist()),
+ **self.vel_caps)
+ except Exception as e: # noqa: BLE001
+ sent = False
+ log.error("SendCartesianMotionForce failed: %s", e)
+
+ # ---- advance trajectory progress (native frames) ----
+ # Counts only successful sends; anchor hold (seq<0) and failed sends do not count (and
+ # rebuild the baseline). After a chunk ends phase is clamped, so progress stops.
+ # This is what lets prev skip pauses; think before changing it.
+ with self._lock:
+ if buf.seq < 0 or not sent:
+ self._plan_knot_last = None
+ else:
+ knot = float(np.clip(phase, 0.0, n - 1)) * buf.dt * NATIVE_FPS
+ if self._plan_knot_last is not None:
+ self._plan_progress += max(0.0, knot - self._plan_knot_last)
+ self._plan_knot_last = knot
+ try:
+ st = self._sd(self._pair.states())
+ except Exception as e: # noqa: BLE001
+ log.error("reading state failed: %s", e)
+
+ if st is not None:
+ pose_w = {s: lt.normalize_pose7(np.asarray(st[s].tcp_pose, float))
+ for s in SIDES}
+ q = {s: np.asarray(st[s].q, float) for s in SIDES}
+ with self._lock:
+ for s in SIDES:
+ self._st_pose_w[s] = pose_w[s]
+ self._st_q[s] = q[s]
+ self._st_t = time.time()
+ self._last_cmd_w = cmd.copy()
+ self._hist.append((time.time(), float(self._plan_progress),
+ {s: pose_w[s].copy() for s in SIDES},
+ {s: self._grip_meas_raw(s) for s in SIDES}))
+ if len(self._hist) > 1200:
+ del self._hist[:600]
+
+ reason, pair_d = self._guard(pose_w)
+ self._health["min_pair_m"] = min(self._health["min_pair_m"], pair_d)
+ if reason is not None:
+ self._health["abort"] = reason
+ log.error("per-cycle guard abort: %s", reason)
+ self._trace_write({"event": "abort", "seq": buf.seq, "idx": i,
+ "reason": reason})
+ self._emergency_stop()
+ return
+
+ # One row per servo cycle (100Hz, so tracking-error peaks are not missed). phase column:
+ # run = chunk playing; wait = chunk done, command held at last point;
+ # hold = one extra row HOLD_ROW_S after the end; its act = final settled pose
+ hold = (buf.seq >= 0 and hold_seq != buf.seq
+ and (phase - (n - 1)) * slow_dt >= HOLD_ROW_S)
+ if self._rec_w is not None:
+ if hold:
+ hold_seq = buf.seq
+ tag = ("hold" if hold else "wait" if (buf.seq >= 0 and phase > n - 1)
+ else buf.meta.get("phase", "run"))
+ row = ["%.4f" % time.time(), buf.seq, i, tag]
+ for h, s in enumerate(SIDES):
+ row += ["%.5f" % v for v in cmd[h]]
+ row += ["%.5f" % v for v in pose_w[s][:3]]
+ row += ["%.2f" % buf.grip[i, h], "%.2f" % self._grip_ds[s]]
+ row += ["%.4f" % pair_d]
+ for s in SIDES:
+ row += ["%.5f" % v for v in pose_w[s][3:7]]
+ for s in SIDES:
+ row += ["%.5f" % v for v in q[s]]
+ row += ["%.3f" % float(np.clip(phase, 0.0, n - 1))]
+ for s in SIDES:
+ for attr in ("ext_wrench_in_world", "ext_wrench_in_tcp"):
+ ext = getattr(st[s], attr, None)
+ row += (["%.2f" % v for v in ext]
+ if ext is not None and len(ext) == 6 else ["nan"] * 6)
+ self._rec_w.writerow(row)
+ if self._rollout is not None:
+ self._rollout_servo(st, pose_w, q, cmd, buf, i, n, phase, hold, sent,
+ pair_d, t_cycle)
+
+ now = time.time()
+ if now - last_log > 1.0:
+ last_log = now
+ log.info(" seq=%d %d/%d arm dist %.3f m%s",
+ buf.seq, i, n, pair_d,
+ (" gripper " + self._grip.status_line()) if self._grip else "")
+
+ # ---- gripper: pass model output through ----
+ # Only the mechanical-travel clamp (done in apply_action); no grasp logic here.
+ if self._grip is not None and not self.dry_run:
+ try:
+ self._grip.set_all({s: float(buf.grip[i, IDX[s]]) for s in SIDES})
+ except Exception as e: # noqa: BLE001
+ log.error("gripper command failed: %s", e)
+
+ last_idx, last_seq = i, buf.seq
+ # Chunk expired: hold the last command, do not stop. Holding a reached pose in Cartesian
+ # mode is static; Stop() would change mode and require re-entering + re-setting impedance.
+ over_s = (phase - (n - 1)) * slow_dt
+ if buf.seq >= 0 and over_s > self.max_stale_s:
+ t_now = time.time()
+ if t_now - getattr(self, "_stale_warn", 0.0) > 2.0:
+ self._stale_warn = t_now
+ log.warning("chunk seq=%d finished %.1fs ago, no new chunk; holding last pose. "
+ "Is the inference server down?", buf.seq, over_s)
+ time.sleep(max(0.0, period - (time.perf_counter() - t_cycle)))
+
+ def _guard(self, pose_w):
+ """Per-cycle safety check. Returns (abort reason or None, arm distance m)."""
+ act = {s: pose_w[s][:3] for s in SIDES}
+ pair_d = float(np.linalg.norm(act["left"] - act["right"]))
+ if self.dry_run:
+ return None, pair_d
+ try:
+ if self._pair.fault():
+ w = self._pair.which_fault()
+ return "fault (left=%s right=%s)" % (w[0], w[1]), pair_d
+ m = self._pair.mode()
+ if m[0] != self._CART or m[1] != self._CART:
+ return ("control mode changed externally (left=%s right=%s); likely a self-collision monitor stop"
+ % (m[0], m[1])), pair_d
+ except Exception as e: # noqa: BLE001
+ return "reading fault/mode failed: %s" % e, pair_d
+ if pair_d < self.min_dist:
+ return ("measured arm distance %.3f m < %.3f" % (pair_d, self.min_dist)), pair_d
+ return None, pair_d
+
+ def _emergency_stop(self):
+ try:
+ if self._pair is not None and self._pair.operational():
+ self._pair.Stop()
+ except Exception as e: # noqa: BLE001
+ log.error("emergency stop failed: %s", e)
+ try:
+ if self._grip is not None:
+ self._grip.close()
+ except Exception: # noqa: BLE001
+ pass
diff --git a/flexiv-umi-infer/umi_infer/robot_io/gripper_can.py b/flexiv-umi-infer/umi_infer/robot_io/gripper_can.py
new file mode 100644
index 0000000000000000000000000000000000000000..865658c448fa550d5c751d6af7cef029a7cb57aa
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/gripper_can.py
@@ -0,0 +1,323 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Position servo for two grippers (Damiao motors on a CANalyst-II box).
+
+Wiring: CAN1 = channel 0 = left gripper, CAN2 = channel 1 = right gripper; command ID 0x08 on both.
+Codec, enable frames and bus I/O are reused from gripper_tool.
+
+Scale: opening (dataset deg) = (q - q_closed_rad) * deg_per_rad, from the calibration file
+ (default data/gripper_calib.json). Datasets may use only part of the 0-90 deg range.
+
+Bounded force: the command is clamped to [closed - overclose, open], then to measured +/- lead,
+ so max force ~= kp x rad(lead). Defaults kp=36 / kd=0.8, lead=5 deg -> ~3.1 Nm.
+
+"Commanded closed" is not "gripping": position-control force = kp x position error. Commanding
+ 0 deg targets q_closed, so the error is only as large as the object pushes the jaws open.
+ To grip, command past contact (below q_closed): set_floor(side, floor_deg) allows a negative
+ floor, hard-capped by OVERCLOSE_MAX_DEG. The inference-side close latch decides when.
+
+Self-test (grippers only, arms untouched):
+ python -m umi_infer.robot_io.gripper_can --data --replay-episode 0
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import sys
+import threading
+import time
+
+from .gripper_tool import ( # noqa: E402 reuse low-level driver
+ DISABLE_FRAME, ENABLE_FRAME, IDLE, Motor,
+ drain, open_bus, pack_mit_command, send, wait_feedback,
+)
+
+SIDES = ("left", "right")
+CHANNEL = {"left": 0, "right": 1} # CAN1 left, CAN2 right
+CMD_ID = {"left": 0x08, "right": 0x08}
+DEFAULT_CALIB = os.environ.get("FLEXIV_GRIP_CALIB", os.path.join(
+ os.environ.get("UMI_INFER_DATA", "data"), "gripper_calib.json"))
+# Hard cap on overclose (below calibrated closed), dataset deg; more would push into the hard stop.
+# Force is still bounded by lead (kp x rad(lead)); overclose only lets the error reach that bound.
+OVERCLOSE_MAX_DEG = 8.0
+D = math.degrees
+R = math.radians
+
+
+class GripperPair:
+ """Position servo for both grippers. set_deg() stores the target; a thread sends MIT frames at rate_hz."""
+
+ def __init__(self, calib_path=DEFAULT_CALIB, kp=36.0, kd=0.8, lead_deg=5.0,
+ rate_hz=200.0, gain=1.0, logger=None):
+ with open(calib_path) as f:
+ cal = json.load(f)
+ missing = [s for s in SIDES if s not in cal]
+ if missing:
+ raise ValueError("calibration %s missing %s" % (calib_path, missing))
+ self.calib_path = calib_path
+ self.q_closed = {s: float(cal[s]["q_closed_rad"]) for s in SIDES}
+ self.q_open = {s: float(cal[s]["q_open_rad"]) for s in SIDES}
+ self.dpr = {s: float(cal[s]["deg_per_rad"]) for s in SIDES}
+ self.open_deg = {s: float(cal[s].get("open_deg",
+ abs(self.q_open[s] - self.q_closed[s]) * self.dpr[s]))
+ for s in SIDES}
+ self.kp, self.kd = float(kp), float(kd)
+ self.lead = R(float(lead_deg))
+ self.rate_hz = float(rate_hz)
+ self.gain = float(gain)
+ self.log = logger
+ self.motors = {s: Motor(CHANNEL[s], CMD_ID[s], CMD_ID[s] + 0x10) for s in SIDES}
+ self._by_key = {m.key: m for m in self.motors.values()}
+ self._target = {s: 0.0 for s in SIDES} # dataset deg
+ # Per-side floor (dataset deg). 0 = calibrated closed; negative = allow overclose.
+ self._floor = {s: 0.0 for s in SIDES}
+ self._sent = {s: None for s in SIDES} # last command actually sent (rad)
+ self._lock = threading.Lock()
+ self._stop = threading.Event()
+ self._thread = None
+ self.bus = None
+ self.enabled = False
+
+ # ---------------- lifecycle ----------------
+ def _info(self, msg):
+ if self.log is not None:
+ self.log.info(msg)
+ else:
+ print(msg, flush=True)
+
+ def _warn(self, msg):
+ if self.log is not None:
+ self.log.warn(msg)
+ else:
+ print("[warn] " + msg, flush=True)
+
+ def open(self):
+ """Open the bus and require feedback from both motors. Not enabled; jaws can still be moved by hand."""
+ self.bus = open_bus(set(CHANNEL.values()), 1_000_000, 0)
+ ms = list(self.motors.values())
+ if not wait_feedback(self.bus, ms, self._by_key, timeout=2.0):
+ bad = [s for s in SIDES if self.motors[s].q is None]
+ self.close()
+ raise RuntimeError("no gripper feedback: %s; check CAN wiring / motor power, or run "
+ "gripper_tool scan" % ", ".join(bad))
+ self._info("gripper calibration %s" % self.calib_path)
+ for s in SIDES:
+ self._info(" %-5s opening %6.2f deg (closed %+.5f / open %+.5f rad, full open %.2f deg)"
+ % (s, self.measured_deg(s), self.q_closed[s], self.q_open[s],
+ self.open_deg[s]))
+ self._thread = threading.Thread(target=self._loop, daemon=True)
+ self._thread.start()
+ return self
+
+ def enable(self):
+ """Enable motors. Before this the thread only sends zero-torque frames (for feedback)."""
+ for s in SIDES:
+ with self._lock:
+ for _ in range(3):
+ send(self.bus, self.motors[s], ENABLE_FRAME)
+ time.sleep(0.01)
+ self.enabled = True
+ self._info("grippers enabled: kp=%.1f kd=%.2f lead %.1f deg (~%.2f Nm) @ %.0f Hz gain %.2f"
+ % (self.kp, self.kd, D(self.lead), self.kp * self.lead,
+ self.rate_hz, self.gain))
+
+ def close(self):
+ """Release torque, disable, close bus. Safe to call twice."""
+ self._stop.set()
+ if self._thread is not None:
+ self._thread.join(timeout=1.0)
+ self._thread = None
+ if self.bus is None:
+ return
+ try:
+ for s in SIDES:
+ for _ in range(5): # release torque first to avoid a jerk
+ send(self.bus, self.motors[s], IDLE)
+ time.sleep(0.005)
+ send(self.bus, self.motors[s], DISABLE_FRAME)
+ except Exception as e:
+ self._warn("gripper release/disable error: %s: %s" % (type(e).__name__, e))
+ finally:
+ try:
+ self.bus.shutdown()
+ except Exception:
+ pass
+ self.bus = None
+ self.enabled = False
+ self._info("grippers released and disabled")
+
+ def __enter__(self):
+ return self.open()
+
+ def __exit__(self, *exc):
+ self.close()
+ return False
+
+ # ---------------- command / readback ----------------
+ def set_deg(self, side, dataset_deg):
+ """Target opening in dataset deg. Non-blocking."""
+ self._target[side] = float(dataset_deg)
+
+ def set_all(self, degs):
+ for s in SIDES:
+ self._target[s] = float(degs[s])
+
+ def set_floor(self, side, floor_deg):
+ """Set one gripper's floor (negative = past calibrated closed -> grip force).
+
+ 0 = default (calibrated closed). Capped by OVERCLOSE_MAX_DEG. See module docstring.
+ """
+ f = float(floor_deg)
+ self._floor[side] = max(min(f, 0.0), -OVERCLOSE_MAX_DEG)
+
+ def set_floor_all(self, floors):
+ for s in SIDES:
+ self.set_floor(s, floors[s])
+
+ def floor_deg(self, side):
+ return float(self._floor[side])
+
+ def set_lead_deg(self, lead_deg):
+ """Change the force bound (kp x rad(lead)) at runtime; raise this for more grip, not overclose."""
+ self.lead = R(max(0.5, float(lead_deg)))
+
+ def measured_deg(self, side):
+ q = self.motors[side].q
+ return float("nan") if q is None else (q - self.q_closed[side]) * self.dpr[side]
+
+ def commanded_deg(self, side):
+ q = self._sent[side]
+ return float("nan") if q is None else (q - self.q_closed[side]) * self.dpr[side]
+
+ def status_line(self):
+ def one(s):
+ # Tag from the actual command, not the floor: floor<0 only allows overclose.
+ c = self.commanded_deg(s)
+ tag = "" if not (c == c and c < 0) else "[overclose %.2f deg]" % (-c)
+ return "%s cmd%5.1f/meas%5.1f deg%s" % (s[0].upper(), c,
+ self.measured_deg(s), tag)
+ return " ".join(one(s) for s in SIDES)
+
+ def target_q(self, side):
+ """Dataset deg -> motor angle (rad). Floor set by set_floor (default calibrated closed)."""
+ lo_deg = self._floor[side] # 0 or negative (overclose)
+ deg = min(max(self.gain * self._target[side], lo_deg), self.open_deg[side])
+ q = self.q_closed[side] + deg / self.dpr[side]
+ # Travel clamp: lower bound follows floor, upper bound fixed
+ q_floor = self.q_closed[side] + lo_deg / self.dpr[side]
+ lo, hi = sorted((q_floor, self.q_open[side]))
+ return min(hi, max(lo, q))
+
+ # ---------------- background servo ----------------
+ def _loop(self):
+ interval = 1.0 / self.rate_hz
+ nxt = time.monotonic()
+ while not self._stop.is_set():
+ now = time.monotonic()
+ if now < nxt:
+ time.sleep(min(interval * 0.25, max(0.0, nxt - now)))
+ continue
+ nxt = now + interval
+ try:
+ with self._lock:
+ drain(self.bus, self._by_key)
+ for s in SIDES:
+ m = self.motors[s]
+ if not self.enabled or m.q is None:
+ send(self.bus, m, IDLE) # not enabled: zero torque, feedback only
+ continue
+ q = self.target_q(s)
+ # Force bound: command may not lead measurement by more than lead
+ q = min(m.q + self.lead, max(m.q - self.lead, q))
+ self._sent[s] = q
+ send(self.bus, m, pack_mit_command(q, 0.0, self.kp, self.kd, 0.0))
+ except Exception as e:
+ self._warn("gripper servo thread error: %s: %s" % (type(e).__name__, e))
+ return
+
+
+# ---------------- self-test: grippers only, arms untouched ----------------
+def _episode_grip(data_root, episode):
+ """Read the two gripper columns and fps directly from parquet."""
+ import glob
+
+ import numpy as np
+ import pyarrow.parquet as pq
+
+ pat = os.path.join(data_root, "data", "**", "episode_%06d.parquet" % episode)
+ fs = glob.glob(pat, recursive=True)
+ if not fs:
+ raise FileNotFoundError("not found: %s" % pat)
+ st = np.stack(pq.read_table(fs[0], columns=["observation.state"])
+ ["observation.state"].to_numpy())
+ with open(os.path.join(data_root, "meta", "info.json")) as f:
+ fps = float(json.load(f).get("fps", 30))
+ return {"left": st[:, 7].astype(float), "right": st[:, 15].astype(float)}, fps
+
+
+def main(argv=None):
+ import argparse
+
+ ap = argparse.ArgumentParser(description="Gripper ground-truth self-test: drives the two grippers only, not the arms")
+ ap.add_argument("--replay-episode", type=int, required=True, help="episode whose gripper ground truth to replay")
+ ap.add_argument("--data", required=True, help="LeRobot dataset root")
+ ap.add_argument("--calib", default=DEFAULT_CALIB)
+ ap.add_argument("--speed", type=float, default=0.3, help="time scale (default 0.3 = slowed down)")
+ ap.add_argument("--kp", type=float, default=36.0)
+ ap.add_argument("--kd", type=float, default=0.8)
+ ap.add_argument("--lead-deg", type=float, default=5.0)
+ ap.add_argument("--rate", type=float, default=200.0)
+ ap.add_argument("--gain", type=float, default=1.0)
+ ap.add_argument("--yes", action="store_true", help="confirm actually driving the grippers")
+ args = ap.parse_args(argv)
+
+ grip_src, fps = _episode_grip(args.data, args.replay_episode)
+ n = len(grip_src["left"])
+ dur = (n - 1) / fps / args.speed
+ print("ep%04d %d frames @ %.0f fps speed %.2f -> %.1f s" % (args.replay_episode, n, fps,
+ args.speed, dur))
+ for s in SIDES:
+ g = grip_src[s]
+ print(" %-5s ground truth %.2f ~ %.2f deg range %.2f deg" % (s, g.min(), g.max(), g.max() - g.min()))
+ if not args.yes:
+ sys.exit("This drives the grippers. Make sure nobody touches the jaws, then rerun with --yes.")
+
+ g = GripperPair(args.calib, kp=args.kp, kd=args.kd, lead_deg=args.lead_deg,
+ rate_hz=args.rate, gain=args.gain)
+ with g:
+ g.set_all({s: grip_src[s][0] for s in SIDES})
+ print("\nWARNING: hands off the jaws. Enter to start, Ctrl-C to stop.", end="")
+ try:
+ input()
+ except (EOFError, KeyboardInterrupt):
+ print("\ncancelled")
+ return 1
+ g.enable()
+ time.sleep(0.5) # settle at first-frame opening
+ t0 = time.monotonic()
+ last_i, last_log = -1, 0.0
+ try:
+ while True:
+ t = (time.monotonic() - t0) * args.speed
+ i = int(round(t * fps))
+ if i >= n:
+ break
+ if i != last_i:
+ last_i = i
+ g.set_all({s: grip_src[s][i] for s in SIDES})
+ now = time.monotonic()
+ if now - last_log >= 0.2:
+ last_log = now
+ print(" t=%6.2fs %5d/%d %s " % (t / args.speed, i, n,
+ g.status_line()), end="\r", flush=True)
+ time.sleep(0.002)
+ print("\nreplay done")
+ except KeyboardInterrupt:
+ print("\nCtrl-C")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py b/flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc8efcecaa31071e4f0c159508f820fa14f85aae
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/gripper_tool.py
@@ -0,0 +1,647 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Standalone gripper motor tool (CANalyst-II + Damiao MIT protocol).
+
+Touches only the gripper motors: no flexivrdk import, no arm connection.
+scan / read keep motors DISABLED (zero-torque frames only, to get feedback); jaws can be
+moved by hand. Only sweep / goto enable motors, and require --yes plus Enter.
+
+Motor zero is not assumed to be "closed", so sweep/goto limits are relative to the start position.
+
+Motor spec: :[:] fb_id defaults to cmd_id + 0x10
+CAN box CAN1 = channel 0 = left gripper, CAN2 = channel 1 = right gripper:
+ 0:8 CAN1 left, cmd 0x08, feedback 0x18
+ 1:8 CAN2 right
+ 0:8:0x18 explicit feedback ID
+
+Bounded force: the target is always clamped to measured +/- lead, so max force ~= kp x lead (rad),
+printed at start. Hitting a hard stop is a soft push, not a slam.
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+import os
+import sys
+import time
+
+# ── Damiao MIT codec ──────────────────────────────────────────────────────────
+P_MAX, V_MAX, T_MAX = 12.5, 30.0, 10.0 # command range = DM4310 Limit_Param
+F_P_MAX, F_V_MAX, F_T_MAX = 12.5, 30.0, 10.0 # feedback range
+KP_MAX, KD_MAX = 500.0, 5.0
+ENABLE_FRAME = bytes([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC])
+DISABLE_FRAME = bytes([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD])
+
+
+def _limit(x, lo, hi):
+ return lo if x < lo else hi if x > hi else x
+
+
+def _f2u(x, lo, hi, bits):
+ x = _limit(x, lo, hi)
+ return int(round((x - lo) * ((1 << bits) - 1) / (hi - lo)))
+
+
+def _u2f(x, lo, hi, bits):
+ return float(x) * (hi - lo) / ((1 << bits) - 1) + lo
+
+
+def pack_mit_command(q, dq, kp, kd, tau) -> bytes:
+ p_int = _f2u(q, -P_MAX, P_MAX, 16)
+ v_int = _f2u(dq, -V_MAX, V_MAX, 12)
+ kp_int = _f2u(kp, 0.0, KP_MAX, 12)
+ kd_int = _f2u(kd, 0.0, KD_MAX, 12)
+ t_int = _f2u(tau, -T_MAX, T_MAX, 12)
+ d = bytearray(8)
+ d[0] = (p_int >> 8) & 0xFF
+ d[1] = p_int & 0xFF
+ d[2] = (v_int >> 4) & 0xFF
+ d[3] = ((v_int & 0x0F) << 4) | ((kp_int >> 8) & 0x0F)
+ d[4] = kp_int & 0xFF
+ d[5] = (kd_int >> 4) & 0xFF
+ d[6] = ((kd_int & 0x0F) << 4) | ((t_int >> 8) & 0x0F)
+ d[7] = t_int & 0xFF
+ return bytes(d)
+
+
+def parse_mit_feedback(data):
+ p_int = (data[1] << 8) | data[2]
+ v_int = (data[3] << 4) | (data[4] >> 4)
+ t_int = ((data[4] & 0x0F) << 8) | data[5]
+ return (_u2f(p_int, -F_P_MAX, F_P_MAX, 16),
+ _u2f(v_int, -F_V_MAX, F_V_MAX, 12),
+ _u2f(t_int, -F_T_MAX, F_T_MAX, 12))
+
+
+IDLE = pack_mit_command(0.0, 0.0, 0.0, 0.0, 0.0) # zero torque: motor replies with feedback even when disabled
+D = math.degrees
+R = math.radians
+
+
+# ── motors ────────────────────────────────────────────────────────────────────
+# CAN box CAN1/CAN2 = software channel 0/1. Wiring: CAN1 left gripper, CAN2 right gripper.
+SIDE = {0: "left", 1: "right"}
+
+
+class Motor:
+ def __init__(self, ch, cmd_id, fb_id, name=""):
+ self.ch, self.cmd_id, self.fb_id = ch, cmd_id, fb_id
+ self.name = name or "%s gripper (CAN%d 0x%02X)" % (SIDE.get(ch, "?"), ch + 1, cmd_id)
+ self.q = self.dq = self.tau = None
+ self.n = 0
+ self.t_last = 0.0
+ self.enabled = False
+ # control state
+ self.q_start = None
+ self.q_des = None
+ self.dirn = 1
+ self.q_ref = None
+ self.q_ref_t = 0.0
+ self.done = False
+ self.why = ""
+ self.rev = [] # one entry per reversal: (angle, direction, real stop or travel cap)
+
+ @property
+ def key(self):
+ return (self.ch, self.fb_id)
+
+ def __str__(self):
+ return self.name
+
+
+def parse_motor(spec):
+ parts = spec.split(":")
+ if not 2 <= len(parts) <= 3:
+ raise argparse.ArgumentTypeError("motor spec must be channel:cmd_id[:fb_id], got %r" % spec)
+ ch = int(parts[0], 0)
+ cmd = int(parts[1], 0)
+ fb = int(parts[2], 0) if len(parts) == 3 else cmd + 0x10
+ if ch not in (0, 1):
+ raise argparse.ArgumentTypeError("CANalyst-II has only channels 0/1, got %d" % ch)
+ return Motor(ch, cmd, fb)
+
+
+# ── bus ───────────────────────────────────────────────────────────────────────
+def open_bus(channels, bitrate, device):
+ try:
+ import can
+ except ImportError:
+ sys.exit("python-can missing. Install: pip "
+ "install python-can canalystii")
+ try:
+ return can.Bus(interface="canalystii", channel=tuple(sorted(channels)),
+ bitrate=bitrate, device=device)
+ except Exception as e:
+ sys.exit("cannot open CANalyst-II (channels %s): %s\n"
+ "-> most likely USB permissions: run with sudo, or see the udev rule in --help."
+ % (sorted(channels), e))
+
+
+def send(bus, m, data):
+ import can
+ bus.send(can.Message(arbitration_id=m.cmd_id, is_extended_id=False,
+ data=data, channel=m.ch))
+
+
+def drain(bus, by_key, limit=512, unknown=None):
+ """Dispatch received frames to their motors. Returns the number of matched frames."""
+ got = 0
+ for _ in range(limit):
+ msg = bus.recv(timeout=0.0)
+ if msg is None:
+ break
+ m = by_key.get((msg.channel, msg.arbitration_id))
+ if m is not None and msg.dlc == 8:
+ m.q, m.dq, m.tau = parse_mit_feedback(msg.data)
+ m.n += 1
+ m.t_last = time.time()
+ got += 1
+ elif unknown is not None:
+ unknown.setdefault((msg.channel, msg.arbitration_id), 0)
+ unknown[(msg.channel, msg.arbitration_id)] += 1
+ return got
+
+
+def wait_feedback(bus, motors, by_key, timeout=2.0):
+ """Query current angles with zero-torque frames. Motors stay disabled."""
+ t0 = time.time()
+ while time.time() - t0 < timeout:
+ for m in motors:
+ send(bus, m, IDLE)
+ time.sleep(0.02)
+ drain(bus, by_key)
+ if all(m.q is not None for m in motors):
+ return True
+ return False
+
+
+# ── scan: channels x IDs, find motors online ──────────────────────────────────
+def cmd_scan(args):
+ ids = range(args.id_min, args.id_max + 1)
+ chans = args.channels
+ bus = open_bus(chans, args.bitrate, args.device)
+ print("scanning channels %s, cmd ID 0x%02X..0x%02X, feedback ID default = cmd ID + 0x10"
+ % (list(chans), args.id_min, args.id_max))
+ print("motors stay disabled, zero-torque frames only; jaws will not move\n")
+ try:
+ # Listen quietly for 0.4 s first: any unsolicited traffic?
+ quiet = {}
+ t0 = time.time()
+ while time.time() - t0 < 0.4:
+ drain(bus, {}, unknown=quiet)
+ time.sleep(0.01)
+ if quiet:
+ print("unsolicited traffic already on the bus:")
+ for (ch, aid), n in sorted(quiet.items()):
+ print(" ch%d ID 0x%03X %d frames" % (ch, aid, n))
+ print()
+
+ found = []
+ for ch in chans:
+ for cid in ids:
+ m = Motor(ch, cid, cid + 0x10)
+ by_key = {}
+ seen = {}
+ # Record replies on any ID (feedback ID is not always +0x10)
+ t0 = time.time()
+ while time.time() - t0 < args.dwell:
+ send(bus, m, IDLE)
+ time.sleep(0.01)
+ drain(bus, by_key, unknown=seen)
+ if seen:
+ for (rch, aid), n in sorted(seen.items()):
+ tag = " (= cmd ID+0x10)" if aid == cid + 0x10 else ""
+ print("OK ch%d cmd 0x%02X -> feedback ch%d ID 0x%03X %d frames%s"
+ % (ch, cid, rch, aid, n, tag))
+ found.append((ch, cid, rch, aid))
+ print()
+ if not found:
+ print("No motor responded. Check: (1) motor 24V power (2) CAN_H/CAN_L and ground (3) termination resistor/DIP "
+ "(4) bitrate (now %d) (5) which CANalyst channel the cable is on" % args.bitrate)
+ else:
+ print("%d motor(s) online:" % len(found))
+ for ch, cid, rch, aid in found:
+ print(" --motor %d:0x%02X%s" % (ch, cid, "" if aid == cid + 0x10
+ else ":0x%02X" % aid))
+ chs = {ch for ch, _, _, _ in found}
+ cids = {cid for _, cid, _, _ in found}
+ if len(found) >= 2 and len(chs) == 1 and len(cids) == 1:
+ print("\nWARNING: only one ID seen on one channel. Two grippers both at 0x08 on the same channel"
+ "\n collide on the bus; change one ID (or move it to the other channel).")
+ finally:
+ bus.shutdown()
+ return 0
+
+
+# ── read: passive angle readout (motors disabled) ─────────────────────────────
+def cmd_read(args):
+ motors = args.motor
+ by_key = {m.key: m for m in motors}
+ bus = open_bus({m.ch for m in motors}, args.bitrate, args.device)
+ print("passive read %s; motors disabled, zero torque, move jaws by hand. Ctrl-C to exit\n"
+ % ", ".join(str(m) for m in motors))
+ interval = 1.0 / args.rate_hz
+ t_end = time.time() + args.seconds if args.seconds > 0 else None
+ last_cmd = last_print = 0.0
+ try:
+ while t_end is None or time.time() < t_end:
+ now = time.time()
+ if now - last_cmd >= interval:
+ for m in motors:
+ send(bus, m, IDLE)
+ last_cmd = now
+ drain(bus, by_key)
+ if now - last_print >= 0.1:
+ last_print = now
+ cols = []
+ for m in motors:
+ if m.q is None:
+ cols.append("%s no feedback" % m)
+ else:
+ cols.append("%s %+8.2f deg dq%+6.2f tau%+5.2f" % (m, D(m.q), m.dq, m.tau))
+ print(" " + " | ".join(cols) + " ", end="\r", flush=True)
+ time.sleep(0.0005)
+ except KeyboardInterrupt:
+ pass
+ finally:
+ print()
+ for m in motors:
+ print("%s: received %d frames%s" % (m, m.n,
+ "" if m.q is None else ", last %+.2f deg" % D(m.q)))
+ bus.shutdown()
+ return 0
+
+
+# ── shared control loop (motors enabled) ──────────────────────────────────────
+def drive(bus, motors, by_key, args, mode):
+ """mode='sweep': back-and-forth; mode='goto': move to relative target. Force bound kp*lead."""
+ lead = R(args.lead_deg)
+ speed = R(args.speed_deg)
+ eps = R(args.progress_deg)
+ interval = 1.0 / args.rate_hz
+
+ print("\nparams: kp=%.1f kd=%.2f lead=%.1f deg -> max force ~= %.2f Nm, speed %.0f deg/s"
+ % (args.kp, args.kd, args.lead_deg, args.kp * lead, args.speed_deg))
+ for m in motors:
+ m.q_start = m.q
+ m.q_des = m.q
+ m.q_ref = m.q
+ m.q_ref_t = time.time()
+ if mode == "sweep":
+ m.lo, m.hi = m.q - R(args.range_deg), m.q + R(args.range_deg)
+ m.dirn = -1 if getattr(args, "start_dir", "close") == "close" else 1
+ print(" %s start %+.2f deg, travel cap [%+.1f, %+.1f] deg, first toward %s"
+ % (m, D(m.q), D(m.lo) - D(m.q_start), D(m.hi) - D(m.q_start),
+ "close (neg)" if m.dirn < 0 else "open (pos)"))
+ else:
+ tgt = m.q + R(args.delta_deg)
+ m.lo, m.hi = min(m.q, tgt) - R(2.0), max(m.q, tgt) + R(2.0)
+ m.dirn = 1 if args.delta_deg >= 0 else -1
+ print(" %s start %+.2f deg -> target %+.2f deg (relative %+.1f deg)"
+ % (m, D(m.q), D(tgt), args.delta_deg))
+ if abs(m.q) > 11.0:
+ print(" WARNING: %s at %+.2f rad is near the +/-12.5 rad feedback wrap-around; turn it back by hand first"
+ % (m, m.q))
+ return 1
+
+ print("\nWARNING: hands off the jaws. Enter to start, Ctrl-C to stop (releases torque, then disables).", end="")
+ try:
+ input()
+ except (EOFError, KeyboardInterrupt):
+ print("\ncancelled, motors not enabled.")
+ return 1
+
+ for m in motors:
+ for _ in range(3):
+ send(bus, m, ENABLE_FRAME)
+ time.sleep(0.01)
+ m.enabled = True
+ print("enabled, moving.\n")
+
+ last_cmd = time.time()
+ t0 = time.time()
+ last_print = 0.0
+ while True:
+ now = time.time()
+ drain(bus, by_key)
+ if args.timeout > 0 and now - t0 > args.timeout:
+ print("\ntimeout %.0fs reached, stopping." % args.timeout)
+ break
+ if all(m.done for m in motors):
+ break
+ if now - last_cmd >= interval:
+ dt = now - last_cmd
+ last_cmd = now
+ for m in motors:
+ if m.done or m.q is None:
+ continue
+ if now - m.t_last > 0.3:
+ m.done, m.why = True, "feedback lost"
+ continue
+ m.q_des += m.dirn * speed * dt
+ m.q_des = min(m.q + lead, max(m.q - lead, m.q_des)) # force bound
+ m.q_des = min(m.hi, max(m.lo, m.q_des)) # absolute travel cap
+ # Progress watchdog: pushing and no net motion for a while -> at a stop
+ if abs(m.q - m.q_ref) >= eps:
+ m.q_ref, m.q_ref_t = m.q, now
+ stuck = (now - m.q_ref_t) >= args.stall_time
+ err = m.q_des - m.q
+ pushing = (err >= 0.8 * lead) if m.dirn > 0 else (err <= -0.8 * lead)
+ at_edge = (m.q_des >= m.hi - 1e-4) if m.dirn > 0 else (m.q_des <= m.lo + 1e-4)
+ if mode == "sweep":
+ if at_edge or (pushing and stuck):
+ why = "travel cap" if at_edge else "hit hard stop"
+ m.rev.append((m.q, m.dirn, not at_edge))
+ print(" %s reversal #%d @ %+7.2f deg tau%+5.2f Nm (%s)"
+ % (m, len(m.rev), D(m.q), m.tau, why))
+ m.dirn = -m.dirn
+ m.q_des, m.q_ref, m.q_ref_t = m.q, m.q, now
+ need = getattr(args, "reversals", 0)
+ if need and len(m.rev) >= need:
+ m.done, m.why = True, "done after %d reversals" % len(m.rev)
+ else:
+ reached = (abs(m.q_des - (m.q_start + R(args.delta_deg))) < 1e-4
+ and abs(m.q - m.q_des) < R(args.tol_deg))
+ if reached:
+ m.done, m.why = True, "reached"
+ elif pushing and stuck:
+ m.done, m.why = True, "blocked (hard stop or object)"
+ send(bus, m, pack_mit_command(m.q_des, 0.0, args.kp, args.kd, 0.0))
+ if now - last_print >= 0.2:
+ last_print = now
+ print(" " + " | ".join(
+ "%s %+8.2f deg (rel %+7.2f deg) tau%+5.2f%s"
+ % (m, D(m.q), D(m.q - m.q_start), m.tau,
+ " [%s]" % m.why if m.done else "")
+ for m in motors if m.q is not None) + " ", end="\r", flush=True)
+ time.sleep(0.0005)
+ print()
+ for m in motors:
+ print("%s: stopped at %+.2f deg (rel to start %+.2f deg) %s"
+ % (m, D(m.q), D(m.q - m.q_start), m.why))
+ if args.hold > 0:
+ print("holding %.1fs ..." % args.hold)
+ t1 = time.time()
+ while time.time() - t1 < args.hold:
+ for m in motors:
+ send(bus, m, pack_mit_command(m.q_des, 0.0, args.kp, args.kd, 0.0))
+ time.sleep(interval)
+ drain(bus, by_key)
+ return 0
+
+
+def relax_and_disable(bus, motors):
+ for m in motors:
+ if not m.enabled:
+ continue
+ try:
+ for _ in range(5): # release torque before disabling to avoid a jerk
+ send(bus, m, IDLE)
+ time.sleep(0.005)
+ send(bus, m, DISABLE_FRAME)
+ except Exception:
+ pass
+ print("torque released + disabled; jaws can be moved by hand.")
+
+
+def _run_active(args, mode, post=None):
+ if not args.yes:
+ sys.exit("This drives the grippers. Make sure nobody touches the jaws, then rerun with --yes.")
+ motors = args.motor
+ by_key = {m.key: m for m in motors}
+ bus = open_bus({m.ch for m in motors}, args.bitrate, args.device)
+ rc = 1
+ try:
+ if not wait_feedback(bus, motors, by_key):
+ bad = [str(m) for m in motors if m.q is None]
+ print("no feedback: %s -> run scan first to check channel/ID" % ", ".join(bad))
+ return 1
+ rc = drive(bus, motors, by_key, args, mode)
+ except KeyboardInterrupt:
+ print("\n\nCtrl-C interrupted")
+ finally:
+ relax_and_disable(bus, motors)
+ bus.shutdown()
+ if post is not None:
+ rc = post(args, motors) or rc
+ return rc
+
+
+def cmd_sweep(args):
+ return _run_active(args, "sweep")
+
+
+# ── calib: push both ends at low force, take the stops = recalibrate open/close ──
+JSON_SIDE = {0: "left", 1: "right"}
+
+
+def write_calib(args, motors):
+ """Turn reversal angles into closed/open positions. Convention: negative direction = closing."""
+ import json
+ import os
+
+ out = {"meta": {"created": time.strftime("%Y-%m-%d %H:%M:%S"),
+ "script": os.path.basename(__file__),
+ "convention": "negative angle = closing; CAN1 (ch0) = left gripper, CAN2 (ch1) = right gripper",
+ "kp": args.kp, "lead_deg": args.lead_deg,
+ "max_force_Nm": round(args.kp * R(args.lead_deg), 3),
+ "scale": ("full open = measured travel in deg (deg_per_rad = 57.2958, i.e. opening = "
+ "true motor angle from closed)" if not args.open_deg else
+ "full open = given %.1f deg (external scale)" % args.open_deg),
+ "gripper_deg": "(q8 - q_closed_rad) * deg_per_rad"}}
+ bad = False
+ print()
+ for m in motors:
+ side = JSON_SIDE.get(m.ch, "ch%d" % m.ch)
+ closed = [q for q, d, _ in m.rev if d < 0] # blocked moving negative = closed end
+ opened = [q for q, d, _ in m.rev if d > 0]
+ soft = [r for r in m.rev if not r[2]]
+ if not closed or not opened:
+ print("%s calibration failed: closed end %d hits / open end %d hits; need at least one at each end"
+ % (m, len(closed), len(opened)))
+ bad = True
+ continue
+ q_closed = sum(closed) / len(closed)
+ q_open = sum(opened) / len(opened)
+ travel = q_open - q_closed
+ sp_c = D(max(closed) - min(closed)) if len(closed) > 1 else 0.0
+ sp_o = D(max(opened) - min(opened)) if len(opened) > 1 else 0.0
+ # Default scale = measured travel (deg_per_rad = 57.2958);
+ # --open-deg defines full open on an external scale (e.g. 90).
+ open_deg = args.open_deg if args.open_deg else D(travel)
+ rec = {"q_closed_rad": round(q_closed, 6), "q_open_rad": round(q_open, 6),
+ "travel_rad": round(travel, 6), "open_deg": round(open_deg, 4),
+ "deg_per_rad": round(open_deg / travel, 4) if travel else None,
+ "n_closed_hits": len(closed), "n_open_hits": len(opened),
+ "repeat_closed_deg": round(sp_c, 2), "repeat_open_deg": round(sp_o, 2)}
+ out[side] = rec
+ print("%s closed %+.5f rad (%+7.2f deg) open %+.5f rad (%+7.2f deg) travel %.2f deg"
+ % (m, q_closed, D(q_closed), q_open, D(q_open), D(travel)))
+ print(" repeatability closed +/-%.2f deg open +/-%.2f deg full open %.2f deg -> 1 rad = %.4f deg"
+ % (sp_c, sp_o, open_deg, open_deg / travel if travel else float("nan")))
+ if max(sp_c, sp_o) > args.spread_tol:
+ print(" WARNING: repeatability worse than %.1f deg; force too low / pause mistaken for a stop, raise --kp and redo"
+ % args.spread_tol)
+ bad = True
+ if travel <= 0:
+ print(" WARNING: negative travel; closing direction is reversed, redo with --start-dir open")
+ bad = True
+ if soft:
+ print(" WARNING: %d reversal(s) hit the --range-deg cap instead of a hard stop; raise --range-deg"
+ % len(soft))
+ bad = True
+ if len(out) > 1:
+ os.makedirs(os.path.dirname(args.out), exist_ok=True)
+ with open(args.out, "w") as f:
+ json.dump(out, f, indent=1, ensure_ascii=False)
+ print("\nwrote %s%s" % (args.out, " (with warnings, see above)" if bad else ""))
+ return 1 if bad else 0
+
+
+def cmd_calib(args):
+ return _run_active(args, "sweep", post=write_calib)
+
+
+def cmd_recompute(args):
+ """Recompute the scale only, no hardware; measured closed/open/travel are kept as is."""
+ import json
+
+ with open(args.file) as f:
+ cal = json.load(f)
+ for side in ("left", "right"):
+ rec = cal.get(side)
+ if not rec:
+ continue
+ travel = rec["travel_rad"]
+ open_deg = args.open_deg if args.open_deg else D(travel)
+ rec["open_deg"] = round(open_deg, 4)
+ rec["deg_per_rad"] = round(open_deg / travel, 4)
+ print("%-5s travel %.2f deg full open set to %.2f deg -> 1 rad = %.4f deg"
+ % (side, D(travel), open_deg, open_deg / travel))
+ cal.setdefault("meta", {}).pop("jaw_travel_deg", None) # drop legacy 90-deg assumption
+ cal["meta"]["scale"] = (
+ "full open = measured travel in deg (deg_per_rad = 57.2958, i.e. opening = true motor angle from closed)"
+ if not args.open_deg else "full open = given %.1f deg (external scale)" % args.open_deg)
+ cal["meta"]["scale_recomputed"] = time.strftime("%Y-%m-%d %H:%M:%S")
+ out = args.out or args.file
+ with open(out, "w") as f:
+ json.dump(cal, f, indent=1, ensure_ascii=False)
+ print("wrote %s" % out)
+ return 0
+
+
+def cmd_goto(args):
+ return _run_active(args, "goto")
+
+
+# ── CLI ───────────────────────────────────────────────────────────────────────
+EXAMPLES = """
+Examples (USB access may need sudo, or the udev rule below):
+
+ # 1) Scan: which motors are online, on which channel, which ID (disabled, no motion)
+ python -m umi_infer.robot_io.gripper_tool scan
+
+ # 2) Passive read: move the jaws by hand and watch the angle -> channel/ID/codec OK
+ python -m umi_infer.robot_io.gripper_tool read --motor 0:8 --motor 1:8 # 0=CAN1 left, 1=CAN2 right
+
+ # 3) Small test move on the left gripper: -15 deg from current position, gentle
+ python -m umi_infer.robot_io.gripper_tool goto --motor 0:8 --delta-deg -15 --kp 8 --lead-deg 4 --yes
+
+ # 4) Sweep full travel (auto-reverse at stops), both grippers
+ python -m umi_infer.robot_io.gripper_tool sweep --motor 0:8 --motor 1:8 --yes
+
+ # 5) Recalibrate: hit each end twice, write data/gripper_calib.json
+ python -m umi_infer.robot_io.gripper_tool calib --motor 0:8 --motor 1:8 --yes
+
+Optional udev rule to avoid sudo (run once as root, your user must be in plugdev):
+ echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="0053", MODE="0660", GROUP="plugdev"' \\
+ | sudo tee /etc/udev/rules.d/99-canalystii.rules
+ sudo udevadm control --reload-rules && sudo udevadm trigger
+ (then replug the CAN box)
+"""
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(
+ description="Standalone gripper motor CAN tool (does not touch the arms)",
+ epilog=EXAMPLES, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--bitrate", type=int, default=1_000_000, help="CAN bitrate (default 1 Mbit)")
+ ap.add_argument("--device", type=int, default=0, help="CANalyst device index (default 0)")
+ ap.add_argument("--rate-hz", type=float, default=200.0, help="send/control rate (default 200)")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+
+ ps = sub.add_parser("scan", help="scan channels x IDs for online motors (disabled, no motion)")
+ ps.add_argument("--channels", type=int, nargs="+", default=[0, 1])
+ ps.add_argument("--id-min", type=lambda x: int(x, 0), default=0x01)
+ ps.add_argument("--id-max", type=lambda x: int(x, 0), default=0x0E)
+ ps.add_argument("--dwell", type=float, default=0.12, help="query time per ID (s)")
+ ps.set_defaults(func=cmd_scan)
+
+ pr = sub.add_parser("read", help="passive angle read (disabled, movable by hand)")
+ pr.add_argument("--motor", type=parse_motor, action="append", required=True,
+ help="channel:cmd_id[:fb_id], repeatable")
+ pr.add_argument("--seconds", type=float, default=0, help="duration, 0 = until Ctrl-C")
+ pr.set_defaults(func=cmd_read)
+
+ def _active(p):
+ p.add_argument("--motor", type=parse_motor, action="append", required=True,
+ help="channel:cmd_id[:fb_id], repeatable")
+ p.add_argument("--yes", action="store_true", help="confirm actually driving the grippers")
+ p.add_argument("--kp", type=float, default=5.0, help="MIT position gain (default 5; raise if it does not move)")
+ p.add_argument("--kd", type=float, default=0.5, help="MIT damping gain (default 0.5)")
+ p.add_argument("--lead-deg", type=float, default=3.0,
+ help="max target lead over measured, deg -> max force ~= kp*rad(lead) (default 3 -> 0.26 Nm)")
+ p.add_argument("--speed-deg", type=float, default=15.0, help="target speed deg/s (default 15)")
+ p.add_argument("--stall-time", type=float, default=0.5, help="blocked time that counts as a stop (default 0.5s)")
+ p.add_argument("--progress-deg", type=float, default=1.0,
+ help="min net motion still counted as moving (deg, default 1)")
+ p.add_argument("--timeout", type=float, default=30.0, help="max run time s (default 30)")
+ p.add_argument("--hold", type=float, default=0.0, help="hold force for N s after finishing (default 0)")
+
+ pw = sub.add_parser("sweep", help="sweep travel, auto-reverse at stops (enables motors)")
+ _active(pw)
+ pw.add_argument("--range-deg", type=float, default=60.0,
+ help="travel cap +/- deg relative to start position (default 60)")
+ pw.add_argument("--start-dir", choices=["close", "open"], default="close",
+ help="initial direction (default close = negative)")
+ pw.add_argument("--reversals", type=int, default=0, help="stop after N reversals, 0 = forever")
+ pw.set_defaults(func=cmd_sweep)
+
+ pc = sub.add_parser("calib", help="recalibrate: hit both ends at low force, write calibration json")
+ _active(pc)
+ pc.add_argument("--range-deg", type=float, default=60.0,
+ help="travel cap +/- deg relative to start position (default 60)")
+ pc.add_argument("--start-dir", choices=["close", "open"], default="close",
+ help="initial direction (default close = negative = closing)")
+ pc.add_argument("--reversals", type=int, default=4,
+ help="number of reversals; 4 = each end twice for repeatability (default 4)")
+ pc.add_argument("--open-deg", type=float, default=None,
+ help="degrees for full open (scale). Default: measured travel (opening = true motor angle); "
+ "a number maps to an external scale (e.g. 90)")
+ pc.add_argument("--spread-tol", type=float, default=2.0,
+ help="max spread between hits at one end before it is untrusted (deg, default 2)")
+ pc.add_argument("--out", default=os.path.join(os.environ.get("UMI_INFER_DATA", "data"), "gripper_calib.json"),
+ help="calibration output json")
+ # 4 reversals x ~90 deg travel @ 15 deg/s ~= 25 s; the 30 s default is too tight
+ pc.set_defaults(func=cmd_calib, timeout=90.0)
+
+ pg = sub.add_parser("goto", help="move by a relative angle from current position (enables motors)")
+ _active(pg)
+ pg.add_argument("--delta-deg", type=float, required=True, help="relative move in deg")
+ pg.add_argument("--tol-deg", type=float, default=1.0, help="arrival tolerance (default 1 deg)")
+ pg.set_defaults(func=cmd_goto)
+
+ pr2 = sub.add_parser("recompute", help="recompute the scale in a calibration json, no hardware")
+ pr2.add_argument("--file", default=os.path.join(os.environ.get("UMI_INFER_DATA", "data"), "gripper_calib.json"))
+ pr2.add_argument("--out", default=None, help="default: overwrite in place")
+ pr2.add_argument("--open-deg", type=float, default=None,
+ help="degrees for full open; default: measured travel")
+ pr2.set_defaults(func=cmd_recompute)
+
+ args = ap.parse_args(argv)
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/flexiv-umi-infer/umi_infer/robot_io/insta_live.py b/flexiv-umi-infer/umi_infer/robot_io/insta_live.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfe943172dae083ce142cf0a6d93fea2031be14d
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/insta_live.py
@@ -0,0 +1,350 @@
+"""Real-time Insta360 X4 Air -> latest cropped/scaled RGB frame for live policy observations.
+
+Each InstaLiveCamera runs a persistent `insta360_cli stream` whose idx0 dual-fisheye
+H.264 is redirected (INSTA360_VIDEO0_PATH) into a fifo, piped through ffmpeg which
+crops ONE fisheye half (the dual-fisheye frame is 1920x960 = two 960x960 lenses
+side by side) and scales it to out_size, emitting raw rgb24 on stdout. A reader
+thread keeps the most recent frame.
+
+Default out_size is 960 (native half, no resize): training images are raw 960x960
+fisheye halves and the policy resizes them itself, so this matches the training
+preprocessing chain pixel for pixel.
+
+Camera serials and halves come from robot_io/cam_ids.py (env INSTA360_LEFT_SN /
+INSTA360_RIGHT_SN / INSTA360_LEFT_HALF / INSTA360_RIGHT_HALF). The half must be the one
+the hand-eye extrinsic was calibrated on; images and extrinsics must change together.
+"""
+from __future__ import annotations
+
+import logging
+import os
+import signal
+import subprocess
+import threading
+import time
+from typing import Optional, Tuple
+
+import numpy as np
+
+log = logging.getLogger("umi_infer.insta_live")
+
+# Patched Insta360 CameraSDK CLI (build it from tools/insta360_cli_dual.cc, see tools/README.md).
+CLI = os.environ.get("INSTA360_CLI", os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
+ "tools", "insta360_cli_dual"))
+
+# One SDK service port per camera process; they must differ or the second camera is not found.
+CAM_SERVICE_PORT = {"left": 9701, "right": 9702}
+# Directory with the CameraSDK shared libraries (libCameraSDK.so ...), prepended to LD_LIBRARY_PATH.
+SDK_LIB = os.environ.get("INSTA360_SDK_LIB", "")
+
+HALF = 960 # each fisheye lens is 960x960 within the 1920x960 dual frame
+NATIVE = HALF # out_size == NATIVE means no resize (same size as training images)
+
+# ffmpeg binary: env FLEXIV_FFMPEG (e.g. one that lives only in a conda env/bin), else PATH.
+FFMPEG = os.environ.get("FLEXIV_FFMPEG", "")
+if not FFMPEG:
+ from shutil import which as _which
+ FFMPEG = _which("ffmpeg") or "ffmpeg"
+
+
+def kill_stale_cameras(want_serials=(), reason: str = "") -> bool:
+ """Kill leftover insta360_cli processes, wait for USB release, then verify via discover.
+
+ CameraSDK often crashes during teardown and leaves orphans holding the USB channel; the
+ next start then fails with `serial_not_found`. The kernel needs ~6 s to release USB, and
+ pkill + sleep alone is not always enough, so we only succeed once discover lists every
+ wanted serial. Idempotent: with no leftovers it costs one discover call.
+ """
+ import glob
+ import json as _json
+ import signal
+ import subprocess
+
+ def _pids():
+ out = set()
+ for pat in ("insta360_cli",):
+ try:
+ r = subprocess.run(["pgrep", "-f", pat], capture_output=True, text=True)
+ out |= {int(x) for x in (r.stdout or "").split() if x.isdigit()}
+ except Exception: # noqa: BLE001
+ pass
+ out.discard(os.getpid())
+ return out
+
+ n0 = len(_pids())
+ if n0:
+ log.warning("Found %d leftover camera processes%s, cleaning up ...", n0,
+ (" [" + reason + "]") if reason else "")
+ for sig, wait in ((signal.SIGTERM, 1.5), (signal.SIGTERM, 1.5), (signal.SIGKILL, 1.0)):
+ cur = _pids()
+ if not cur:
+ break
+ for pid in cur:
+ try: # kill the process group: the CLI runs under setsid, children would survive
+ os.killpg(os.getpgid(pid), sig)
+ except Exception: # noqa: BLE001
+ try:
+ os.kill(pid, sig)
+ except Exception: # noqa: BLE001
+ pass
+ time.sleep(wait)
+ for f in glob.glob("/tmp/insta_*.h264.fifo"):
+ try:
+ os.unlink(f)
+ except OSError:
+ pass
+ if n0:
+ log.warning(" waiting 6s for the kernel to release USB ...")
+ time.sleep(6.0)
+
+ want = set(want_serials or ())
+ if not want:
+ return True
+ env = dict(os.environ)
+ env["LD_LIBRARY_PATH"] = SDK_LIB + ":" + env.get("LD_LIBRARY_PATH", "")
+ t0 = time.time()
+ while True:
+ seen = set()
+ try:
+ r = subprocess.run([CLI, "discover"], capture_output=True, text=True,
+ timeout=20, env=env, cwd=os.path.dirname(CLI))
+ seen = {d.get("serial")
+ for d in _json.loads(r.stdout or "{}").get("devices", [])}
+ except Exception as e: # noqa: BLE001
+ log.warning(" discover failed: %s", repr(e)[:80])
+ if want <= seen:
+ log.info("Cameras visible (discover): %s", sorted(seen & want))
+ return True
+ if time.time() - t0 > 30.0:
+ log.error("WARNING: discover only sees %s, missing %s; not a leftover process. "
+ "Check: camera powered on / USB mode set to Android control / cable",
+ sorted(seen) or "none", sorted(want - seen))
+ return False
+ time.sleep(2.0)
+
+
+def _read_exact(stream, n: int) -> Optional[bytes]:
+ buf = bytearray()
+ while len(buf) < n:
+ chunk = stream.read(n - len(buf))
+ if not chunk:
+ return None
+ buf.extend(chunk)
+ return bytes(buf)
+
+
+class InstaLiveCamera:
+ """Persistent live stream from one camera (by serial) -> newest RGB frame."""
+
+ def __init__(self, serial: str, *, half: str = "left", out_size: int = 480,
+ resolution: int = 2, bitrate_kbps: int = 512,
+ stream_seconds: int = 86400, service_port: int = 0,
+ cli: str = CLI, sdk_lib: str = SDK_LIB, pix_fmt: str = "rgb24"):
+ assert half in ("left", "right"), half
+ # yuv420p = raw decoded planes, no color conversion here (the policy side converts
+ # with the same call used in training)
+ assert pix_fmt in ("rgb24", "yuv420p"), pix_fmt
+ assert pix_fmt == "rgb24" or out_size == HALF, "yuv420p only supports the native half, no resize"
+ self.pix_fmt = pix_fmt
+ self.serial = serial
+ self.service_port = int(service_port)
+ self.half = half
+ self.out_size = int(out_size)
+ self.resolution = resolution
+ self.bitrate_kbps = bitrate_kbps
+ self.stream_seconds = stream_seconds
+ self.cli = cli
+ self.sdk_lib = sdk_lib
+ self.fifo = f"/tmp/insta_{serial}.h264.fifo"
+
+ self._proc_cli: Optional[subprocess.Popen] = None
+ self._proc_ff: Optional[subprocess.Popen] = None
+ self._reader: Optional[threading.Thread] = None
+ self._stop = threading.Event()
+ self._lock = threading.Lock()
+ self._latest: Optional[np.ndarray] = None
+ self._stamp: float = 0.0
+ self._nframes = 0
+
+ def start(self) -> None:
+ try:
+ os.remove(self.fifo)
+ except FileNotFoundError:
+ pass
+ os.mkfifo(self.fifo)
+
+ env = dict(os.environ)
+ env["LD_LIBRARY_PATH"] = self.sdk_lib + ":" + env.get("LD_LIBRARY_PATH", "")
+
+ x = 0 if self.half == "left" else HALF
+ # No scale filter at out_size == 960 (native half): a 960->960 resample only blurs,
+ # and training images are raw 960 halves.
+ vf = f"crop={HALF}:{HALF}:{x}:0"
+ if self.out_size != HALF:
+ vf += f",scale={self.out_size}:{self.out_size}:flags=area"
+ ff_argv = [FFMPEG, "-nostdin", "-hide_banner", "-loglevel", "error",
+ "-fflags", "nobuffer", "-flags", "low_delay",
+ "-f", "h264", "-i", self.fifo,
+ "-vf", vf, "-f", "rawvideo", "-pix_fmt", self.pix_fmt, "-"]
+ self._proc_ff = subprocess.Popen(
+ ff_argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
+ stdin=subprocess.DEVNULL) # no terminal stdin: ffmpeg would eat keystrokes as commands
+
+ # ffmpeg must open the fifo read end before the writer opens the write end.
+ time.sleep(0.3)
+
+ env_cli = dict(env)
+ env_cli["INSTA360_VIDEO0_PATH"] = self.fifo
+ cli_argv = [self.cli, f"--serial={self.serial}"]
+ if self.service_port > 0:
+ cli_argv.append(f"--service-port={self.service_port}")
+ cli_argv += ["stream", str(self.stream_seconds), str(self.resolution), "1",
+ str(self.bitrate_kbps), "0", "1", "0"]
+ self._proc_cli = subprocess.Popen(
+ cli_argv, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
+ env=env_cli, preexec_fn=os.setsid, stdin=subprocess.DEVNULL)
+
+ self._reader = threading.Thread(target=self._read_loop, daemon=True)
+ self._reader.start()
+ log.info("InstaLiveCamera %s (half=%s, %dpx) started", self.serial, self.half, self.out_size)
+
+ def _read_loop(self) -> None:
+ s = self.out_size
+ shape = (s, s, 3) if self.pix_fmt == "rgb24" else (s * 3 // 2, s) # I420: Y followed by U, V
+ nbytes = shape[0] * shape[1] * (3 if self.pix_fmt == "rgb24" else 1)
+ stdout = self._proc_ff.stdout
+ while not self._stop.is_set():
+ buf = _read_exact(stdout, nbytes)
+ if buf is None:
+ log.warning("InstaLiveCamera %s: ffmpeg stream ended", self.serial)
+ break
+ frame = np.frombuffer(buf, np.uint8).reshape(shape)
+ with self._lock:
+ self._latest = frame
+ self._stamp = time.time()
+ self._nframes += 1
+
+ def get_frame(self) -> Tuple[Optional[np.ndarray], float]:
+ """Return (frame copy, capture_stamp) or (None, 0.0).
+
+ rgb24: HxWx3; yuv420p: (H*3/2)xW I420 planes."""
+ with self._lock:
+ if self._latest is None:
+ return None, 0.0
+ return self._latest.copy(), self._stamp
+
+ def wait_ready(self, timeout_s: float = 30.0) -> bool:
+ t0 = time.time()
+ while time.time() - t0 < timeout_s:
+ with self._lock:
+ if self._latest is not None:
+ return True
+ if self._proc_cli and self._proc_cli.poll() is not None:
+ err = ""
+ if self._proc_cli.stderr:
+ try:
+ err = self._proc_cli.stderr.read().decode(errors="replace")[-400:]
+ except Exception:
+ pass
+ log.error("InstaLiveCamera %s: cli exited early rc=%s %s",
+ self.serial, self._proc_cli.returncode, err)
+ return False
+ time.sleep(0.2)
+ return False
+
+ def fps(self) -> float:
+ with self._lock:
+ return float(self._nframes)
+
+ def stop(self) -> None:
+ self._stop.set()
+ if self._proc_cli and self._proc_cli.poll() is None:
+ try:
+ os.killpg(os.getpgid(self._proc_cli.pid), signal.SIGTERM)
+ self._proc_cli.wait(timeout=3)
+ except Exception:
+ try:
+ self._proc_cli.kill()
+ except Exception:
+ pass
+ if self._proc_ff and self._proc_ff.poll() is None:
+ try:
+ self._proc_ff.terminate()
+ self._proc_ff.wait(timeout=3)
+ except Exception:
+ try:
+ self._proc_ff.kill()
+ except Exception:
+ pass
+ try:
+ os.remove(self.fifo)
+ except FileNotFoundError:
+ pass
+
+
+class InstaDualCamera:
+ """Two cameras = two independent InstaLiveCamera processes, each with its own service port.
+
+ The SDK has no ready-made way to drive two cameras from one process; two processes with
+ different --service-port values (9701/9702) stream both at 960x960.
+ API: get_frame(side) / wait_ready / fps(side) / stop.
+ """
+
+ def __init__(self, serials, halves, *, out_size=NATIVE, resolution=2,
+ bitrate_kbps=512, stream_seconds=86400, cli=CLI, sdk_lib=SDK_LIB,
+ service_ports=None, pix_fmt="rgb24"):
+ self.serials = dict(serials)
+ self.halves = dict(halves)
+ self.out_size = int(out_size)
+ self.sides = list(serials.keys())
+ ports = dict(service_ports or CAM_SERVICE_PORT)
+ self.cams = {
+ s: InstaLiveCamera(serials[s], half=halves[s], out_size=out_size,
+ resolution=resolution, bitrate_kbps=bitrate_kbps,
+ stream_seconds=stream_seconds,
+ service_port=int(ports.get(s, 0)), cli=cli, sdk_lib=sdk_lib,
+ pix_fmt=pix_fmt)
+ for s in self.sides}
+ self._ports = ports
+
+ def start(self):
+ # Clean up leftovers and confirm cameras are visible; otherwise serial_not_found
+ # shows up intermittently (see kill_stale_cameras).
+ kill_stale_cameras(self.serials.values(), "InstaDualCamera.start")
+ # Start one at a time with a gap: concurrent SDK init fails with serial_not_found more often.
+ for k, s in enumerate(self.sides):
+ if k:
+ time.sleep(2.0)
+ self.cams[s].start()
+ log.info("InstaDualCamera started: %s (service ports %s, half %s, %dpx)",
+ self.serials, self._ports, self.halves, self.out_size)
+
+ def get_frame(self, side):
+ return self.cams[side].get_frame()
+
+ def wait_ready(self, timeout_s=60.0):
+ t0 = time.time()
+ pending = set(self.sides)
+ while pending and time.time() - t0 < timeout_s:
+ for s in list(pending):
+ left = timeout_s - (time.time() - t0)
+ if left <= 0:
+ break
+ if self.cams[s].wait_ready(min(2.0, left)):
+ pending.discard(s)
+ log.info(" camera ready: %s (%s)", s, self.serials[s])
+ if pending:
+ log.error("Cameras not ready: %s", sorted(pending))
+ return False
+ return True
+
+ def fps(self, side):
+ return self.cams[side].fps()
+
+ def stop(self):
+ for s in self.sides:
+ try:
+ self.cams[s].stop()
+ except Exception: # noqa: BLE001
+ pass
diff --git a/flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py b/flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py
new file mode 100644
index 0000000000000000000000000000000000000000..602457bde96b73bf2018859e716337af138a5dcd
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/kin_flexiv.py
@@ -0,0 +1,225 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Flexiv kinematics: FK via yourdfpy on the URDF, IK via vendor flexivrdk.Model.reachable.
+
+FK does not use the vendor `Model.T()`: its Python binding fails with
+`TypeError: Unregistered type` (Eigen::Transform; flexivrdk 1.9.3). The URDF should carry
+kinematic parameters synced from the robot (SyncKinematicsYAML), i.e. the same numbers as the vendor model.
+
+Frame conventions (verified on hardware):
+ * URDF world == shared world of DRDK `RobotPair.states().tcp_pose` (fit: 0.11 mm / 0.011 deg).
+ * Single-arm `Robot.states().tcp_pose` is in that arm's own base frame, which differs from
+ world by a pure translation (0, -/+0.25, 0). Do not compare against URDF `base_link` (90 deg off).
+ * Vendor IK is built from a single-arm Robot and takes flange poses in that arm's base frame.
+
+Each construction runs a round-trip self-test (camera pose -> flange -> arm base -> reachable -> seed q).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+
+import numpy as np
+from scipy.spatial.transform import Rotation as Rot
+
+# Site identity. Set these for your cell (see README "Configuration").
+# Default: the bundled dual-arm URDF (nominal Flexiv kinematics, gripper frames without meshes).
+URDF = os.environ.get("FLEXIV_URDF", os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
+ "urdf", "flexiv_rizon4_dual_umi.urdf"))
+SN = {"left": os.environ.get("FLEXIV_LEFT_SN", ""), "right": os.environ.get("FLEXIV_RIGHT_SN", "")}
+# Joint/link name prefix of each arm in the URDF ("left_" / "right_" in the bundled one).
+def prefix(side, sn):
+ return os.environ.get("FLEXIV_URDF_PREFIX_" + side.upper(), "%s_" % side)
+
+
+PRE = {s: prefix(s, SN[s]) for s in SN}
+# Directory holding per-cell data: anchor.json, gripper_calib.json, E_left.npy, E_right.npy, E_from_urdf.json.
+DATA_DIR = os.environ.get("UMI_INFER_DATA", os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "data"))
+CAM_LINK = "grip_camera_optical_frame"
+# Hardware joint limits from robot info() (5 deg tighter than the URDF).
+RQMIN = np.array([-160., -130., -170., -107., -170., -80., -170.])
+RQMAX = np.array([160., 130., 170., 154., 170., 260., 170.])
+_URDF_CACHE = {}
+
+
+def load_urdf(path=URDF):
+ try:
+ import yourdfpy
+ except ImportError as exc:
+ raise ImportError("URDF FK requires the robot extra: pip install -e .[robot]") from exc
+ if not path:
+ raise ValueError("no URDF: pass --urdf or set FLEXIV_URDF")
+ if path not in _URDF_CACHE:
+ _URDF_CACHE[path] = yourdfpy.URDF.load(path, load_meshes=False,
+ build_scene_graph=True)
+ return _URDF_CACHE[path]
+
+
+def pose7_to_T(p):
+ """[x,y,z,qw,qx,qy,qz] -> 4x4 (Flexiv RDK pose order)."""
+ p = np.asarray(p, float)
+ w, x, y, z = p[3:7] / np.linalg.norm(p[3:7])
+ T = np.eye(4)
+ T[:3, :3] = Rot.from_quat([x, y, z, w]).as_matrix()
+ T[:3, 3] = p[:3]
+ return T
+
+
+def T_to_pose7(T):
+ q = Rot.from_matrix(np.asarray(T)[:3, :3]).as_quat() # xyzw
+ return list(np.asarray(T)[:3, 3]) + [q[3], q[0], q[1], q[2]]
+
+
+def ang_between(Ra, Rb):
+ c = (np.trace(np.asarray(Ra).T @ np.asarray(Rb)) - 1.0) / 2.0
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def limit_margin(q_deg):
+ """Margin to hardware joint limits (deg); negative if out of range."""
+ d = np.asarray(q_deg, float)
+ return float(min(np.min(d - RQMIN), np.min(RQMAX - d)))
+
+
+class Arm:
+ """FK/IK for one arm. robot=False gives FK only (no connection, no IK)."""
+
+ def __init__(self, side, urdf=URDF, robot=True, bridge_json=None, verbose=True, pre=None):
+ if side not in SN:
+ raise ValueError("side must be left/right")
+ self.side, self.pre, self.verbose = side, pre or PRE[side], verbose
+ self.U = load_urdf(urdf)
+ self.urdf = urdf
+ self.r = self.m = None
+ self.B = None # T_world_sdkbase
+ self.q_now = None
+ if bridge_json and os.path.exists(bridge_json):
+ with open(bridge_json) as f:
+ self.B = np.asarray(json.load(f)[side]["T_world_sdkbase"], float)
+ self._say("bridge loaded from cache %s" % bridge_json)
+ if robot:
+ self._connect()
+ if self.B is None:
+ self._measure_bridge()
+ self.selftest()
+
+ # ---------- internal ----------
+ def _say(self, msg):
+ if self.verbose:
+ print("[kin %s] %s" % (self.side, msg), flush=True)
+
+ def _connect(self):
+ import flexivrdk
+ self.r = flexivrdk.Robot(SN[self.side])
+ self.m = flexivrdk.Model(self.r)
+ st = self.r.states()
+ self.q_now = np.asarray(st.q, float)
+ self.tcp_now = np.asarray(st.tcp_pose, float)
+ self._say("connected %s, current q (deg) %s"
+ % (SN[self.side], np.round(np.degrees(self.q_now), 2).tolist()))
+
+ def _measure_bridge(self):
+ """Measure T_world_sdkbase from FK at current q and the single-arm tcp_pose."""
+ T_w_f = self.fk(self.q_now, "flange")
+ self.B = T_w_f @ np.linalg.inv(pose7_to_T(self.tcp_now))
+ rv = Rot.from_matrix(self.B[:3, :3]).as_rotvec()
+ self._say("world<-arm base: translation %s m, rotation %.4f deg (expect ~pure translation (0,-/+0.25,0))"
+ % (np.round(self.B[:3, 3], 6).tolist(), np.degrees(np.linalg.norm(rv))))
+ if np.degrees(np.linalg.norm(rv)) > 0.5:
+ raise RuntimeError("bridge rotation %.3f deg is too large; frame convention changed, check setup"
+ % np.degrees(np.linalg.norm(rv)))
+
+ # ---------- FK ----------
+ def fk(self, q_rad, link="flange"):
+ """Joint angles (rad) -> 4x4 pose of link in URDF world."""
+ q = np.asarray(q_rad, float)
+ self.U.update_cfg({self.pre + "joint%d" % k: float(q[k - 1]) for k in range(1, 8)})
+ return np.asarray(self.U.get_transform(self.pre + link, "world"), float)
+
+ def fk_cam(self, q_rad):
+ return self.fk(q_rad, CAM_LINK)
+
+ def T_flange_cam(self, q_rad=None):
+ """Fixed flange->camera transform (URDF/CAD); independent of q."""
+ q = np.zeros(7) if q_rad is None else q_rad
+ return np.linalg.inv(self.fk(q, "flange")) @ self.fk(q, CAM_LINK)
+
+ # ---------- IK (vendor) ----------
+ def ik_flange(self, T_world_flange, seed_q_rad, free_orientation=False):
+ """Vendor reachable(). Input: flange pose in world. Returns (q, reachable)."""
+ if self.m is None:
+ raise RuntimeError("not connected to robot, no IK")
+ T_sdk = np.linalg.inv(self.B) @ np.asarray(T_world_flange, float)
+ ok, sol = self.m.reachable(T_to_pose7(T_sdk), list(np.asarray(seed_q_rad, float)),
+ bool(free_orientation))
+ return (np.asarray(sol, float) if ok else None), bool(ok)
+
+ def ik_cam(self, T_world_cam, seed_q_rad, free_orientation=False):
+ """Solve for a camera optical-frame pose. Returns (q, pos_err_mm, rot_err_deg) or None.
+
+ Vendor IK solves the flange; the camera pose is converted to a flange pose, and the
+ result is re-checked with FK to report the actual error.
+ """
+ T_world_cam = np.asarray(T_world_cam, float)
+ X = self.T_flange_cam()
+ q, ok = self.ik_flange(T_world_cam @ np.linalg.inv(X), seed_q_rad,
+ free_orientation)
+ if not ok:
+ return None
+ T_got = self.fk_cam(q)
+ pe = float(np.linalg.norm(T_got[:3, 3] - T_world_cam[:3, 3]) * 1000)
+ ae = ang_between(T_got[:3, :3], T_world_cam[:3, :3])
+ return q, pe, ae
+
+ # ---------- self-test ----------
+ def selftest(self, tol_deg=0.6):
+ """Round trip: camera pose at current q -> IK -> should return current q."""
+ got = self.ik_cam(self.fk_cam(self.q_now), self.q_now)
+ if got is None:
+ raise RuntimeError("self-test failed: current pose is not solvable; bridge or frame error")
+ q, pe, ae = got
+ d = float(np.abs(np.degrees(q - self.q_now)).max())
+ self._say("self-test round trip: max joint diff %.4f deg, cam pos diff %.3f mm, rot diff %.4f deg" % (d, pe, ae))
+ if d > tol_deg:
+ m = limit_margin(np.degrees(self.q_now))
+ extra = " (joint-limit margin is only %.2f deg; near a limit IK can only back off)" % m if m < 1 else ""
+ raise RuntimeError("self-test round-trip joint diff %.3f deg > %.1f deg%s" % (d, tol_deg, extra))
+ return d
+
+ def close(self):
+ self.m = None
+ self.r = None
+
+
+def measure_bridges(out=None, urdf=URDF):
+ """Measure and save bridges for both arms, for later offline FK-only use."""
+ res = {}
+ for s in ("left", "right"):
+ a = Arm(s, urdf=urdf, robot=True)
+ res[s] = {"T_world_sdkbase": a.B.tolist(),
+ "q_measured_deg": np.degrees(a.q_now).tolist(),
+ "T_flange_cam": a.T_flange_cam().tolist()}
+ a.close()
+ if out:
+ with open(out, "w") as f:
+ json.dump(res, f, indent=1, ensure_ascii=False)
+ print("bridge ->", out)
+ return res
+
+
+if __name__ == "__main__":
+ import argparse
+ ap = argparse.ArgumentParser(description="FK (yourdfpy) + vendor IK (reachable) self-test")
+ ap.add_argument("--side", default=None, choices=("left", "right"))
+ ap.add_argument("--out", default="kin_bridge.json")
+ a = ap.parse_args()
+ if a.side:
+ arm = Arm(a.side)
+ X = arm.T_flange_cam()
+ print("T_flange_cam (CAD) translation mm = %s" % np.round(X[:3, 3] * 1000, 2).tolist())
+ arm.close()
+ else:
+ measure_bridges(out=a.out)
diff --git a/flexiv-umi-infer/umi_infer/robot_io/mock.py b/flexiv-umi-infer/umi_infer/robot_io/mock.py
new file mode 100644
index 0000000000000000000000000000000000000000..98bfabc73375b24ca56c8a6da0d25df4036ef95b
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/mock.py
@@ -0,0 +1,57 @@
+"""Mock RobotIO: no hardware. Holds a pose per arm and jumps to the last step of each chunk.
+
+Wrist images are JPEG files given per camera, or a plain gray JPEG. Real policies accept them,
+so `--policy pi05|flux` can be smoke-tested end to end without a robot.
+"""
+
+from __future__ import annotations
+
+import time
+
+from ..protocol import Action, CameraFrame, Observation
+from .base import RobotIO
+
+_START = {"left": [0.6, -0.2, 0.3, 0.0, 0.0, 0.0, 1.0], "right": [0.6, 0.2, 0.3, 0.0, 0.0, 0.0, 1.0]}
+
+
+def _jpeg(path, hw):
+ import cv2
+ import numpy as np
+
+ if path:
+ img = cv2.imread(path)
+ if img is None:
+ raise FileNotFoundError(path)
+ else:
+ img = np.full((hw[0], hw[1], 3), 128, np.uint8)
+ ok, buf = cv2.imencode(".jpg", img)
+ assert ok
+ return buf.tobytes(), img.shape[0], img.shape[1]
+
+
+class MockRobotIO(RobotIO):
+ def __init__(self, cameras=("left_wrist", "right_wrist"), image_hw=(960, 960), image_files=None):
+ self.cameras = list(cameras)
+ self.frames = {c: _jpeg((image_files or {}).get(c), image_hw) for c in self.cameras}
+ self.eef = {s: list(p) for s, p in _START.items()}
+ self.grip = {"left": 0.0, "right": 0.0}
+ self.seq = 0
+
+ def start(self) -> None:
+ pass
+
+ def get_observation(self) -> Observation:
+ self.seq += 1
+ now = time.time()
+ return Observation(
+ seq=self.seq, stamp=now,
+ images={c: CameraFrame(c, "jpeg", h, w, data, now) for c, (data, h, w) in self.frames.items()},
+ eef={s: list(p) for s, p in self.eef.items()}, gripper=dict(self.grip),
+ eef_prev={s: list(p) for s, p in self.eef.items()}, gripper_prev=dict(self.grip),
+ pose_dt=0.0)
+
+ def apply_action(self, action: Action) -> None:
+ steps, _ = action.as_steps()
+ if steps:
+ self.eef.update({s: list(p) for s, p in steps[-1]["eef"].items()})
+ self.grip.update(steps[-1]["gripper"])
diff --git a/flexiv-umi-infer/umi_infer/robot_io/pose_math.py b/flexiv-umi-infer/umi_infer/robot_io/pose_math.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1c0fbe86e38017a4cb7658c03d64a8e94859802
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/pose_math.py
@@ -0,0 +1,85 @@
+"""Pose helpers for the Flexiv IO. Poses are pose7 = [x, y, z, qw, qx, qy, qz] (Flexiv order)."""
+
+from __future__ import annotations
+
+import json
+import os
+
+import numpy as np
+from scipy.spatial.transform import Rotation
+
+SIDES = ("left", "right")
+
+# Translation of each arm base in the shared world frame of RobotPair (column mount, bases 0.5 m apart).
+# Override with FLEXIV_BASE_XYZ='{"left": [x, y, z], "right": [x, y, z]}'.
+BASE_XYZ = json.loads(os.environ.get(
+ "FLEXIV_BASE_XYZ", '{"left": [0.0, -0.25, 0.0], "right": [0.0, 0.25, 0.0]}'))
+
+# Rigid points of the gripper (fixed to the flange) used by the tool-aware arm-to-arm distance check.
+# Names must exist in your URDF. Override with FLEXIV_TOOL_LINKS="link_a,link_b,...".
+DEFAULT_TOOL_LINKS = tuple(os.environ.get(
+ "FLEXIV_TOOL_LINKS",
+ "flange,grip_base_link,grip_camera_link,grip_tcp_link,"
+ "grip_left_fingertip_link,grip_right_fingertip_link").split(","))
+
+
+def quat_wxyz_to_R(q):
+ q = np.asarray(q, float)
+ return Rotation.from_quat([q[1], q[2], q[3], q[0]]).as_matrix()
+
+
+def R_to_quat_wxyz(R):
+ x, y, z, w = Rotation.from_matrix(np.asarray(R, float)).as_quat()
+ return np.array([w, x, y, z])
+
+
+def pose7_to_T(p):
+ p = np.asarray(p, float)
+ T = np.eye(4)
+ T[:3, :3] = quat_wxyz_to_R(p[3:7])
+ T[:3, 3] = p[:3]
+ return T
+
+
+def T_to_pose7(T):
+ T = np.asarray(T, float)
+ return np.concatenate([T[:3, 3], R_to_quat_wxyz(T[:3, :3])])
+
+
+def normalize_pose7(p):
+ """Unit quaternion with qw >= 0 (a unique representation, so poses compare directly)."""
+ p = np.asarray(p, float).copy()
+ n = np.linalg.norm(p[3:7])
+ if n < 1e-9:
+ raise ValueError(f"pose7 has a zero quaternion: {p}")
+ p[3:7] /= n
+ if p[3] < 0.0:
+ p[3:7] *= -1.0
+ return p
+
+
+def pair_distance_tools(abs_poses, tool_X):
+ """Minimum distance between the left and right tool point sets along a trajectory.
+
+ abs_poses: {side: (M, 7) pose7 TCP trajectory in world}.
+ tool_X: {link: {side: 4x4}} constant transforms of each tool point in the TCP frame.
+ Returns (per_frame_min[M], overall_min, argmin_frame, (left_link, right_link)).
+ """
+ links = list(tool_X)
+ m = min(len(abs_poses[s]) for s in SIDES)
+ pts = {}
+ for s in SIDES:
+ T = np.stack([pose7_to_T(abs_poses[s][i]) for i in range(m)])
+ pts[s] = np.stack([(T @ tool_X[lk][s])[:, :3, 3] for lk in links], axis=1)
+ d = np.linalg.norm(pts["left"][:, :, None, :] - pts["right"][:, None, :, :], axis=-1)
+ f, i, j = np.unravel_index(int(d.argmin()), d.shape)
+ return d.reshape(m, -1).min(axis=1), float(d.min()), int(f), (links[i], links[j])
+
+
+if __name__ == "__main__":
+ p = normalize_pose7([0.1, -0.2, 0.3, -0.5, 0.5, 0.5, 0.5])
+ assert p[3] >= 0 and np.allclose(normalize_pose7(T_to_pose7(pose7_to_T(p))), p)
+ X = {"a": {s: np.eye(4) for s in SIDES}}
+ traj = {"left": np.array([[0, -0.1, 0, 1, 0, 0, 0]]), "right": np.array([[0, 0.1, 0, 1, 0, 0, 0]])}
+ assert abs(pair_distance_tools(traj, X)[1] - 0.2) < 1e-12
+ print("ok")
diff --git a/flexiv-umi-infer/umi_infer/robot_io/rollout_rec.py b/flexiv-umi-infer/umi_infer/robot_io/rollout_rec.py
new file mode 100644
index 0000000000000000000000000000000000000000..974c87abe03ff2210c9accd64891c344e9e3da4e
--- /dev/null
+++ b/flexiv-umi-infer/umi_infer/robot_io/rollout_rec.py
@@ -0,0 +1,313 @@
+"""Per-frame rollout recorder: one directory per client run, for post-hoc debugging
+(sagging, tracking lag).
+
+ /[_tag]/
+ meta.json full client config + joint limits + nominal stiffness (RobotInfo)
+ servo.csv one row per servo cycle (~100Hz): commanded pose / controller desired
+ q_d / measured q / joint vel, torque / external wrench / per-joint limit
+ margin / at-limit flag / tracking error
+ events.jsonl per chunk: model output (before truncation), sampled IK solutions,
+ pre-check verdict, k0, seam; per observation: eef / eef_prev / gripper /
+ prev source sent to the model; start / stop / abort
+ obs/_.jpg the exact wrist image sent to the model (original size)
+ cams//.jpg live wrist camera frames (default 10Hz, resized to cam_size)
+ cams/index.csv t_wall, side, cam_stamp, file
+ summary.json final stats (rows, dropped, time at joint limit, max tracking error)
+
+Constraint: recording must never slow the servo thread. It only pushes into a bounded queue
+(drop and count when full); encoding and disk I/O run in a background thread. Recording
+errors are warned once and never raised into the control loop.
+"""
+from __future__ import annotations
+
+import csv
+import json
+import logging
+import os
+import queue
+import threading
+import time
+from typing import Callable, Dict, List, Optional, Sequence
+
+import numpy as np
+
+log = logging.getLogger(__name__)
+
+SIDES = ("left", "right")
+DOF = 7
+# at_limit=1 when a joint is closer than this many degrees to its hard limit (margin can go negative)
+LIMIT_WARN_DEG = float(os.environ.get("FLEXIV_ROLLOUT_LIMIT_DEG", "3.0"))
+
+
+def servo_columns() -> List[str]:
+ """servo.csv header. servo() emits values in the same order; keep them in sync."""
+ cols = ["t", "seq", "idx", "phase", "knot", "sent", "cycle_ms", "pair_dist_m"]
+ for s in SIDES:
+ p = s + "_"
+ cols += [p + "cmd_" + a for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
+ cols += [p + "des_" + a for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
+ cols += [p + "act_" + a for a in ("x", "y", "z", "qw", "qx", "qy", "qz")]
+ cols += [p + "pos_err_mm", p + "rot_err_deg"]
+ for name in ("q", "q_d", "dq", "tau", "tau_ext"):
+ cols += ["%s%s%d" % (p, name, k) for k in range(1, DOF + 1)]
+ cols += ["%smargin%d" % (p, k) for k in range(1, DOF + 1)]
+ cols += [p + "margin_min", p + "margin_joint", p + "at_limit", p + "q_d_margin_min"]
+ cols += [p + "extw_" + a for a in ("fx", "fy", "fz", "mx", "my", "mz")]
+ cols += [p + "exttcp_" + a for a in ("fx", "fy", "fz", "mx", "my", "mz")]
+ cols += [p + "grip_cmd", p + "grip_meas"]
+ return cols
+
+
+def _rot_err_deg(qa, qb) -> float:
+ d = abs(float(np.dot(np.asarray(qa, float), np.asarray(qb, float))))
+ return float(np.degrees(2.0 * np.arccos(min(1.0, d))))
+
+
+def _vec(x, n) -> np.ndarray:
+ """SDK field -> fixed-length float array; all nan if missing (None / wrong length)."""
+ try:
+ a = np.asarray(x, float).reshape(-1)
+ if a.shape[0] == n:
+ return a
+ except (TypeError, ValueError):
+ pass
+ return np.full(n, np.nan)
+
+
+class RolloutRecorder:
+ def __init__(self, root: str, tag: str = "", cam_hz: float = 10.0, cam_size: int = 480,
+ jpeg_quality: int = 85, q_min_deg=None, q_max_deg=None, max_queue: int = 30000):
+ stamp = time.strftime("%Y%m%d_%H%M%S")
+ self.dir = os.path.join(root, stamp + ("_" + tag if tag else ""))
+ os.makedirs(os.path.join(self.dir, "obs"), exist_ok=True)
+ for s in SIDES:
+ os.makedirs(os.path.join(self.dir, "cams", s), exist_ok=True)
+ self.cam_hz = float(cam_hz)
+ self.cam_size = int(cam_size)
+ self.jpeg_quality = int(jpeg_quality)
+ # Per arm (models may differ, so limits may differ): {side: (7,) degrees}
+ self.q_min = {s: np.asarray(q_min_deg[s], float) for s in SIDES}
+ self.q_max = {s: np.asarray(q_max_deg[s], float) for s in SIDES}
+ self._cols = servo_columns()
+ self._q: "queue.Queue" = queue.Queue(maxsize=max_queue)
+ self._stop = threading.Event()
+ self._dropped = 0
+ self._warned = set()
+ self._stats = {s: {"rows": 0, "limit_rows": 0, "margin_min": np.inf, "joint": None,
+ "rot_err_max": 0.0, "pos_err_max": 0.0, "ext_m_max": 0.0}
+ for s in SIDES}
+ self._t0 = time.time()
+ self._servo_f = open(os.path.join(self.dir, "servo.csv"), "w", newline="")
+ self._servo_w = csv.writer(self._servo_f)
+ self._servo_w.writerow(self._cols)
+ self._events_f = open(os.path.join(self.dir, "events.jsonl"), "w")
+ self._cam_f = open(os.path.join(self.dir, "cams", "index.csv"), "w", newline="")
+ self._cam_w = csv.writer(self._cam_f)
+ self._cam_w.writerow(["t_wall", "side", "cam_stamp", "file"])
+ self._writer = threading.Thread(target=self._write_loop, name="rollout-writer",
+ daemon=True)
+ self._writer.start()
+ self._cam_thread = None
+
+ # ------------------------------------------------------------------ public (any thread)
+ def write_meta(self, meta: dict) -> None:
+ meta = {**meta, "dir": self.dir, "limit_warn_deg": LIMIT_WARN_DEG,
+ "q_min_deg": {s: v.tolist() for s, v in self.q_min.items()},
+ "q_max_deg": {s: v.tolist() for s, v in self.q_max.items()},
+ "cam_hz": self.cam_hz, "cam_size": self.cam_size}
+ try:
+ with open(os.path.join(self.dir, "meta.json"), "w") as f:
+ json.dump(meta, f, ensure_ascii=False, indent=1, default=_json_default)
+ except Exception as e: # noqa: BLE001
+ self._warn("meta", e)
+
+ def event(self, rec: dict) -> None:
+ self._put(("event", rec))
+
+ def obs_images(self, seq: int, images: Dict[str, object]) -> None:
+ """Images sent to the model (CameraFrame), queued as-is; decoded and saved as jpg later."""
+ for key, fr in (images or {}).items():
+ self._put(("obs_img", seq, key, fr))
+
+ def servo(self, *, t, seq, idx, phase, knot, sent, cycle_ms, pair_dist,
+ cmd, des, act, q, q_d, dq, tau, tau_ext, extw, exttcp, grip_cmd, grip_meas):
+ """Called by the servo thread once per cycle. Light array math + enqueue only. Args: {side: array}."""
+ try:
+ row = [round(t, 4), seq, idx, phase, round(float(knot), 3), int(bool(sent)),
+ round(float(cycle_ms), 2), round(float(pair_dist), 4)]
+ for s in SIDES:
+ c, d, a = _vec(cmd[s], 7), _vec(des.get(s), 7), _vec(act[s], 7)
+ qs, qds = np.degrees(_vec(q[s], DOF)), np.degrees(_vec(q_d.get(s), DOF))
+ margin = np.minimum(qs - self.q_min[s], self.q_max[s] - qs)
+ j = int(np.nanargmin(margin)) if np.isfinite(margin).any() else -1
+ mmin = float(margin[j]) if j >= 0 else float("nan")
+ qd_m = np.minimum(qds - self.q_min[s], self.q_max[s] - qds)
+ qd_min = float(np.nanmin(qd_m)) if np.isfinite(qd_m).any() else float("nan")
+ pos_err = float(np.linalg.norm(c[:3] - a[:3]) * 1000.0)
+ rot_err = _rot_err_deg(c[3:7], a[3:7])
+ ew, et = _vec(extw.get(s), 6), _vec(exttcp.get(s), 6)
+ at_lim = int(mmin < LIMIT_WARN_DEG) if j >= 0 else 0
+ row += [*np.round(c, 5), *np.round(d, 5), *np.round(a, 5),
+ round(pos_err, 2), round(rot_err, 3)]
+ row += [*np.round(qs, 3), *np.round(qds, 3), *np.round(np.degrees(_vec(dq[s], DOF)), 3),
+ *np.round(_vec(tau[s], DOF), 3), *np.round(_vec(tau_ext[s], DOF), 3)]
+ row += [*np.round(margin, 3), round(mmin, 3), j + 1, at_lim, round(qd_min, 3)]
+ row += [*np.round(ew, 3), *np.round(et, 3),
+ round(float(grip_cmd[s]), 2), round(float(grip_meas[s]), 2)]
+ st = self._stats[s]
+ st["rows"] += 1
+ st["limit_rows"] += at_lim
+ if j >= 0 and mmin < st["margin_min"]:
+ st["margin_min"], st["joint"] = mmin, j + 1
+ st["rot_err_max"] = max(st["rot_err_max"], rot_err)
+ st["pos_err_max"] = max(st["pos_err_max"], pos_err)
+ if np.isfinite(ew[3:]).all():
+ st["ext_m_max"] = max(st["ext_m_max"], float(np.linalg.norm(ew[3:])))
+ self._put(("servo", row))
+ except Exception as e: # noqa: BLE001
+ self._warn("servo_row", e)
+
+ def start_cameras(self, get_frame: Callable[[str], tuple]) -> None:
+ """Grab live wrist frames at cam_hz in the background. get_frame(side) -> (frame, stamp), as InstaDualCamera."""
+ if self.cam_hz <= 0:
+ return
+ self._cam_thread = threading.Thread(target=self._cam_loop, args=(get_frame,),
+ name="rollout-cam", daemon=True)
+ self._cam_thread.start()
+
+ def stop_cameras(self) -> None:
+ """Call before closing the cameras, otherwise the grab thread reads a closed camera."""
+ self._stop.set()
+ if self._cam_thread is not None:
+ self._cam_thread.join(timeout=2.0)
+ self._cam_thread = None
+
+ def close(self) -> None:
+ self.stop_cameras()
+ self._put(("close",), block=True)
+ self._writer.join(timeout=30.0)
+ for f in (self._servo_f, self._events_f, self._cam_f):
+ try:
+ f.close()
+ except Exception: # noqa: BLE001
+ pass
+ summary = {"dir": self.dir, "duration_s": round(time.time() - self._t0, 2),
+ "dropped": self._dropped, "limit_warn_deg": LIMIT_WARN_DEG,
+ "arms": {s: {**v, "margin_min": (None if not np.isfinite(v["margin_min"])
+ else round(v["margin_min"], 3)),
+ "limit_frac": round(v["limit_rows"] / max(1, v["rows"]), 4)}
+ for s, v in self._stats.items()}}
+ try:
+ with open(os.path.join(self.dir, "summary.json"), "w") as f:
+ json.dump(summary, f, ensure_ascii=False, indent=1, default=_json_default)
+ except Exception as e: # noqa: BLE001
+ self._warn("summary", e)
+ log.info("rollout saved: %s (dropped %d; left at-limit %.1f%% min margin %s deg j%s / "
+ "right at-limit %.1f%% min margin %s deg j%s)", self.dir, self._dropped,
+ 100 * summary["arms"]["left"]["limit_frac"], summary["arms"]["left"]["margin_min"],
+ summary["arms"]["left"]["joint"],
+ 100 * summary["arms"]["right"]["limit_frac"], summary["arms"]["right"]["margin_min"],
+ summary["arms"]["right"]["joint"])
+
+ # ------------------------------------------------------------------ internal
+ def _put(self, item, block=False) -> None:
+ try:
+ self._q.put(item, block=block, timeout=5.0 if block else None)
+ except queue.Full:
+ self._dropped += 1
+
+ def _warn(self, key, e) -> None:
+ if key not in self._warned:
+ self._warned.add(key)
+ log.warning("rollout recording [%s] error (reported once, control unaffected): %s: %s",
+ key, type(e).__name__, e)
+
+ def _cam_loop(self, get_frame) -> None:
+ period = 1.0 / self.cam_hz
+ last = {s: None for s in SIDES}
+ while not self._stop.is_set():
+ t0 = time.time()
+ for s in SIDES:
+ try:
+ fr, stamp = get_frame(s)
+ except Exception as e: # noqa: BLE001
+ self._warn("cam_get", e)
+ continue
+ if fr is None or stamp == last[s]:
+ continue
+ last[s] = stamp
+ self._put(("cam", t0, s, float(stamp or 0.0), fr))
+ self._stop.wait(max(0.0, period - (time.time() - t0)))
+
+ def _to_bgr(self, arr: np.ndarray, fmt: str) -> np.ndarray:
+ import cv2
+ if fmt == "yuv420p":
+ return cv2.cvtColor(arr, cv2.COLOR_YUV2BGR_I420)
+ return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
+
+ def _write_loop(self) -> None:
+ import cv2
+ enc = [int(cv2.IMWRITE_JPEG_QUALITY), self.jpeg_quality]
+ n_servo = 0
+ while True:
+ item = self._q.get()
+ kind = item[0]
+ try:
+ if kind == "close":
+ break
+ if kind == "servo":
+ self._servo_w.writerow(item[1])
+ n_servo += 1
+ if n_servo % 200 == 0:
+ self._servo_f.flush()
+ elif kind == "event":
+ rec = {"t": round(time.time(), 4), **item[1]}
+ self._events_f.write(json.dumps(rec, ensure_ascii=False,
+ default=_json_default) + "\n")
+ self._events_f.flush()
+ elif kind == "obs_img":
+ _, seq, key, fr = item
+ path = os.path.join(self.dir, "obs", "%05d_%s.jpg" % (seq, key))
+ if fr.format == "jpeg":
+ with open(path, "wb") as f:
+ f.write(fr.data)
+ else:
+ h = fr.height * 3 // 2 if fr.format == "yuv420p" else fr.height
+ shape = (h, fr.width) if fr.format == "yuv420p" else (fr.height, fr.width, 3)
+ arr = np.frombuffer(fr.data, np.uint8).reshape(shape)
+ cv2.imwrite(path, self._to_bgr(arr, fr.format), enc)
+ elif kind == "cam":
+ _, t_wall, s, stamp, fr = item
+ fmt = "yuv420p" if fr.ndim == 2 else "rgb24"
+ img = self._to_bgr(fr, fmt)
+ if self.cam_size and img.shape[0] != self.cam_size:
+ img = cv2.resize(img, (self.cam_size, self.cam_size),
+ interpolation=cv2.INTER_AREA)
+ name = "%d.jpg" % int(t_wall * 1000)
+ cv2.imwrite(os.path.join(self.dir, "cams", s, name), img, enc)
+ self._cam_w.writerow([round(t_wall, 4), s, round(stamp, 4),
+ os.path.join(s, name)])
+ except Exception as e: # noqa: BLE001
+ self._warn("write_" + kind, e)
+
+
+def _json_default(o):
+ if isinstance(o, np.ndarray):
+ return o.tolist()
+ if isinstance(o, (np.floating, np.integer)):
+ return o.item()
+ return str(o)
+
+
+def open_recorder(root: Optional[str], *, tag: str = "", cam_hz: float = 10.0,
+ q_min_deg: Dict[str, Sequence[float]], q_max_deg: Dict[str, Sequence[float]],
+ cam_size: int = 480) -> Optional[RolloutRecorder]:
+ """Empty root = no recording. If setup fails, warn and return None (inference continues)."""
+ if not root:
+ return None
+ try:
+ return RolloutRecorder(root, tag=tag, cam_hz=cam_hz, cam_size=cam_size,
+ q_min_deg=q_min_deg, q_max_deg=q_max_deg)
+ except Exception as e: # noqa: BLE001
+ log.warning("rollout recorder failed to start (%s: %s); inference continues without recording", type(e).__name__, e)
+ return None
diff --git a/flexiv-umi-infer/urdf/flexiv_rizon4_dual_umi.urdf b/flexiv-umi-infer/urdf/flexiv_rizon4_dual_umi.urdf
new file mode 100644
index 0000000000000000000000000000000000000000..6b1a55cb2dab4279a81a56f54f69bc93f40535c5
--- /dev/null
+++ b/flexiv-umi-infer/urdf/flexiv_rizon4_dual_umi.urdf
@@ -0,0 +1,755 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/flux-umi/.github/workflows/cpu.yml b/flux-umi/.github/workflows/cpu.yml
new file mode 100644
index 0000000000000000000000000000000000000000..b91e18e6d528f6ced2df325398ccdc45962828b1
--- /dev/null
+++ b/flux-umi/.github/workflows/cpu.yml
@@ -0,0 +1,14 @@
+name: CPU validation
+on: [push, pull_request]
+permissions:
+ contents: read
+jobs:
+ cpu:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: astral-sh/setup-uv@v6
+ - run: uv sync --locked --extra data --extra serve --python 3.12
+ - run: uv run ruff check .
+ - run: uv run ruff format --check .
+ - run: uv run pytest -q
diff --git a/flux-umi/.gitignore b/flux-umi/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..ea505cdc6b596611c967b01f6f10f7f302c19d43
--- /dev/null
+++ b/flux-umi/.gitignore
@@ -0,0 +1,10 @@
+.venv/
+__pycache__/
+.pytest_cache/
+.ruff_cache/
+*.egg-info/
+dist/
+outputs/
+*.safetensors
+*.pt
+.DS_Store
diff --git a/flux-umi/LICENSE b/flux-umi/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/flux-umi/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/flux-umi/NOTICE b/flux-umi/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..437db428f80b2c2f64160c0b1a0b52fa540811f6
--- /dev/null
+++ b/flux-umi/NOTICE
@@ -0,0 +1,8 @@
+FLUX Action
+Copyright 2026 Black Forest Labs
+
+Model components retain their Black Forest Labs copyright and Apache-2.0 notices.
+Model weights and datasets are separate artifacts; this repository includes neither.
+
+This fork (flux-umi) adds UMI post-training, data preparation and training-speed changes;
+those modifications are Copyright 2026 the flux-umi contributors, also under Apache-2.0.
diff --git a/flux-umi/README.md b/flux-umi/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b7c3b39ad622e4c8f2f2561518b5601dc950244e
--- /dev/null
+++ b/flux-umi/README.md
@@ -0,0 +1,145 @@
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+# flux-umi · 双臂UMI叠衣服
+
+基于[FLUX Action](https://github.com/black-forest-labs/flux-action),将LeRobot v3双臂UMI演示适配到衣物折叠后训练。以下是数据准备与可调整训练模板,不承诺仅用本次样例复现展示视频。
+
+## 数据与动作表示
+
+`DATA_ROOT`下每条episode为独立LeRobot v3目录,本次样例指向`sample_data/demonstrations/`。两路腕相机键为`observation.images.left_ego/right_ego`,30fps;任务文本作为caption。原始state为float32[16]、左臂在前,每臂`[x,y,z,qw,qx,qy,qz,gripper_deg]`,单位为米、wxyz四元数及夹爪角度。
+
+适配器构造20维状态和32×20动作块;每手为相对平移3、旋转矩阵前两列6、夹爪1。状态取前帧相对当前帧位姿及当前夹爪;动作取未来帧相对当前帧位姿。两手各有独立当前锚点。
+
+## 环境与训练
+
+训练使用Linux、NVIDIA GPU、Python3.12。依赖及公开基础资源见[setup.md](docs/setup.md),可选优化内核验证栈见[training-environment.md](docs/training-environment.md)。默认锁选择CUDA12.8,优化栈验证于CUDA13.0,不能混同。源码不含权重、编码器和已训练checkpoint。
+
+先运行数据准备,再启动优化训练;下方命令保留完整配置示例。每次准备使用新的PREPARED_ROOT;工具原地索引源视频,写出states.npy、training_manifest.json、statistics.json及train_config.json,计算q01/q99归一化。训练期间源视频路径需保持可用;可通过`--cuts`提供保留区间。配置文件名`umi_posttrain_16g.json`为兼容保留,实际调度按数据规模和world-size重算。
+
+```bash
+export DATA_ROOT=/path/to/sample_data/demonstrations
+export PREPARED_ROOT=/path/to/prepared_fold_clothes
+export NUM_GPUS=8
+
+python tools/prepare_umi_lerobot_v3.py \
+ --roots "$DATA_ROOT" \
+ --out "$PREPARED_ROOT" \
+ --config-template configs/umi/umi_posttrain_16g.json \
+ --world-size "$NUM_GPUS"
+```
+
+```bash
+export FLUX_CONFIG="$PREPARED_ROOT/train_config.json"
+export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
+bash tools/train_umi.sh \
+ --override 'output_dir="/path/to/runs/fold_clothes"'
+```
+
+```bash
+bash tools/train_umi.sh \
+ --override 'output_dir="/path/to/runs/fold_clothes"' \
+ --override 'initialize_from="/path/to/compatible_checkpoint/step-N"'
+```
+
+NUM_GPUS为所有节点总进程数,数据准备和启动world-size需一致;多机rendezvous变量见环境说明。`initialize_from`只加载模型权重,重新建立优化器/EMA和数据统计,不是完整训练状态恢复。
+
+其他支持的CUDA栈可使用参考路径:在生成配置副本中关闭policy下TRAINING_PERF_FLAGS包含的vae_*、dit_*等训练性能开关,保持相同数据表示;用torch.distributed.run直接启动flux_action.cli train,不通过会强制优化内核的tools/train_umi.sh。
+
+## 推理范围
+
+项目包含`flux-action infer`离线推理、`export-checkpoint`和通用RoboLab服务。推理导出需config.json、model.safetensors、manifest.json及VAE/文本编码器;采样器、步数、guidance和shift需在推理配置指定,训练模板不预设。
+
+通用RoboLab相机/关节输入不同于双臂UMI,项目本身不负责Flexiv SDK、相机采集或实机坐标标定;机器人部署使用相邻flexiv-umi-infer。推理需用前帧/当前帧构造20维相对状态,保存本块当前锚点还原相对动作,并进行rot6d、相机/末端/机器人坐标及夹爪单位转换。配置`action_parameterization="absolute"`不表示UMI结果已成为机器人世界系绝对目标。
+
+保留[LICENSE](LICENSE)与上游声明。模型加载与资源配置见[folding-checkpoint.md](docs/folding-checkpoint.md),模型权重需单独配置。
+
+---
+
+
+
+# flux-umi: bimanual UMI cloth-folding training
+
+This fork of [FLUX Action](https://github.com/black-forest-labs/flux-action) adapts LeRobot v3.0 bimanual UMI demonstrations for cloth-folding post-training. The instructions below cover cloth-folding data preparation and a configurable training template. Training behavior depends on the selected dataset, base checkpoint and configuration.
+
+## Data and action representation
+
+`DATA_ROOT` contains one independent LeRobot v3.0 directory per cloth-folding episode. For the released sample, point it to the extracted `demonstrations/` directory.
+
+- Two wrist videos: `observation.images.left_ego` and `observation.images.right_ego`, 30 fps.
+- Raw `observation.state`: float32[16], left arm first; each arm is `[x, y, z, qw, qx, qy, qz, gripper_deg]`. Positions are metres, quaternions are wxyz, and gripper values are degrees.
+- A per-episode task instruction is used as the caption.
+- The UMI adapter constructs a 20-D state and 32 × 20 action chunk. Each arm contributes relative translation (3), rotation6d (6: the first two rotation-matrix columns), and gripper (1).
+- The state uses the previous pose relative to the current pose, plus the current gripper value. Targets use future poses relative to the current pose. Left and right arms use their own current anchors.
+
+## Environment
+
+Python 3.12, Linux and an NVIDIA GPU are required for the training path. See [setup.md](docs/setup.md) for dependencies and public base weights, and [training-environment.md](docs/training-environment.md) for the exact stack used to validate the optional optimized kernels.
+
+The default dependency lock selects CUDA 12.8 wheels, while the validated optimized stack uses CUDA 13.0. Installing the default lock alone does not establish compatibility with the optimized launcher. Either match the documented optimized stack or use the reference path described below. This source package does not include weights, encoder files or an already-trained folding checkpoint.
+
+## Cloth-folding post-training
+
+The following is a **configuration template** for training on cloth-folding data. The existing `umi_posttrain_16g.json` filename is retained for compatibility; the preparation command recalculates the schedule for the actual data size and `--world-size`.
+
+### 1. Prepare the folding dataset and normalization statistics
+
+Run from the repository root in the prepared Python environment:
+
+```bash
+export DATA_ROOT=/path/to/sample_data/demonstrations
+export PREPARED_ROOT=/path/to/prepared_fold_clothes
+export NUM_GPUS=8
+
+python tools/prepare_umi_lerobot_v3.py \
+ --roots "$DATA_ROOT" \
+ --out "$PREPARED_ROOT" \
+ --config-template configs/umi/umi_posttrain_16g.json \
+ --world-size "$NUM_GPUS"
+```
+
+Use a new `PREPARED_ROOT` for each preparation run. The tool indexes the original videos in place, writes `states.npy`, `training_manifest.json`, `statistics.json`, and `train_config.json`, and calculates q01/q99 state/action normalization. Keep the source video paths available during training. Optional keep ranges can be supplied with `--cuts /path/to/keep_ranges.json`.
+
+### 2. Launch with the validated optimized stack
+
+```bash
+export FLUX_CONFIG="$PREPARED_ROOT/train_config.json"
+export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
+bash tools/train_umi.sh \
+ --override 'output_dir="/path/to/runs/fold_clothes"'
+```
+
+Set `NUM_GPUS` to the total number of workers across all nodes and configure the same world size for data preparation and launch. For multiple nodes, use the rendezvous variables documented in [training-environment.md](docs/training-environment.md).
+
+To continue from compatible action-model weights, additionally set:
+
+```bash
+bash tools/train_umi.sh \
+ --override 'output_dir="/path/to/runs/fold_clothes"' \
+ --override 'initialize_from="/path/to/compatible_checkpoint/step-N"'
+```
+
+`initialize_from` loads model weights with a fresh optimizer/EMA and the new data statistics; it is not an exact training-state resume. Choose the checkpoint matching your experiment.
+
+### Reference path on another supported CUDA stack
+
+First disable all training performance flags under `policy` (`vae_*`, `dit_*`, and other training-only flags listed in `TRAINING_PERF_FLAGS`) in a copy of the generated config, retaining the same data and action representation. Launch `flux_action.cli train` with `torch.distributed.run` directly, rather than `tools/train_umi.sh`, which enables hard kernel requirements.
+
+## What inference code is included
+
+The package retains generic offline inference (`flux-action infer`), checkpoint export (`flux-action export-checkpoint`), and a generic RoboLab server. An inference export uses `config.json`, `model.safetensors`, and `manifest.json`, plus the required VAE/text encoders. Sampler, inference steps, guidance and sampler shift must be specified in the inference configuration; the training template leaves them unset.
+
+The existing RoboLab adapter expects a different camera/joint-state contract. It is not a ready-to-use bimanual UMI or Flexiv adapter. No Flexiv/Rizon-specific SDK calls, camera acquisition, robot-coordinate calibration, or action-execution client were found in this package.
+
+For UMI inference, construct the same 20-D relative state from previous/current poses, and decode each predicted relative pose using the current anchor saved for that chunk. After rot6d conversion, apply the relevant camera/EEF and robot-frame transforms and gripper-unit mapping before execution. `action_parameterization="absolute"` in the model config does not mean the UMI output has already been converted to a robot-world absolute pose.
+
+## License
+
+See the upstream [LICENSE](LICENSE) and source notices. Model resources and dependencies retain their respective licenses.
+
+## Model resources
+
+See [folding-checkpoint.md](docs/folding-checkpoint.md) for model loading and resource configuration. Configure model weights separately.
diff --git a/flux-umi/configs/droid/public_sample.lock.json b/flux-umi/configs/droid/public_sample.lock.json
new file mode 100644
index 0000000000000000000000000000000000000000..2363ff4d6039ce6c91a5a0ef1179e805ed632340
--- /dev/null
+++ b/flux-umi/configs/droid/public_sample.lock.json
@@ -0,0 +1,19 @@
+{
+ "format_version": 1,
+ "dataset_id": "nvidia/Cosmos3-DROID",
+ "dataset_revision": "5c11a20accb11497270a5247a7f1e66ad04c956c",
+ "filter_repo_id": "KarlP/droid",
+ "filter_repo_type": "model",
+ "filter_revision": "bcb840c3b496533e0adf548a54b51f2f00057837",
+ "filter_file": "keep_ranges_1_0_1.json",
+ "files": {
+ "keep_ranges_1_0_1.json": "efee695f8228fe19d4f01767b95ab612084c499c8a59421c5f3d2c7ad5f3625e",
+ "success/data/chunk-000/file-000.parquet": "f1853148a9ccdef22f075167776340d46e9a05ddce3d8f73b3efde6ee0e64157",
+ "success/meta/episodes/chunk-000/file-000.parquet": "34c4593b97aa4696580ef974b77c711395cec22ed22ae99ef70b2bf4101b9917",
+ "success/meta/info.json": "bde3ee8b4c6a437ad530630bb8a6954ba9eafb80e3fdfc0e983252aeaff2d30a",
+ "success/meta/tasks.parquet": "497e5b675bc75460fae7fc6e81d6689a7a1ce85b6cdd136e14616f4b72cf7f44",
+ "success/videos/observation.image.exterior_image_1_left/chunk-000/file-000.mp4": "b166618fe3c4599edccbfda885c78376eb670f4c9fbdd7153f848c24d9c21892",
+ "success/videos/observation.image.exterior_image_2_left/chunk-000/file-000.mp4": "83d705aeac355a638aa174c21be36a8462e280edce11b28fa40d2eacaf35fc64",
+ "success/videos/observation.image.wrist_image_left/chunk-000/file-000.mp4": "4ba025bedd6c73dc73bd67e7adff9bf757c5a066f758ced9675038a2842c1d07"
+ }
+}
diff --git a/flux-umi/configs/droid/train.json b/flux-umi/configs/droid/train.json
new file mode 100644
index 0000000000000000000000000000000000000000..e0811cfa220660faa25b51a833c1159351760058
--- /dev/null
+++ b/flux-umi/configs/droid/train.json
@@ -0,0 +1,36 @@
+{
+ "source_root": "outputs/droid/source",
+ "index_dir": "outputs/droid/index",
+ "output_dir": "outputs/droid/run-seed42",
+ "policy": {
+ "action_modality": "action_prediction_droid",
+ "trunk_weights": "outputs/weights/flux-3-action-base.safetensors",
+ "video_vae_id": "outputs/weights/video_vae.safetensors",
+ "text_encoder_id": "outputs/weights/text_encoder",
+ "attn_mode": "torch"
+ },
+ "steps": 30000,
+ "cooldown_start": 25000,
+ "cooldown_steps": 5000,
+ "seed": 42,
+ "reseed_on_resume": true,
+ "windows_per_rank": 32,
+ "grad_accumulation": 1,
+ "num_workers": 8,
+ "prefetch_factor": 2,
+ "decoder": "ffmpeg",
+ "shard_size": 4,
+ "param_dtype": "float32",
+ "compute_dtype": "bfloat16",
+ "reduce_dtype": "float32",
+ "activation_checkpointing": true,
+ "reshard_after_forward": true,
+ "betas": [0.9, 0.99],
+ "eps": 1e-08,
+ "weight_decay": 0.05,
+ "fused_optimizer": true,
+ "ema_sigma_rels": [0.1, 0.05],
+ "checkpoint_every": 1000,
+ "log_every": 10,
+ "resume": "auto"
+}
diff --git a/flux-umi/configs/games/train.json b/flux-umi/configs/games/train.json
new file mode 100644
index 0000000000000000000000000000000000000000..25e80a88c7c286b4b26dba42590e05ac12389b9f
--- /dev/null
+++ b/flux-umi/configs/games/train.json
@@ -0,0 +1,59 @@
+{
+ "dataset": "examples.games.dataset:build",
+ "source_root": "grunt=/grunt_v2,vector=/vector_v2",
+ "index_dir": "unused",
+ "output_dir": "/games",
+ "policy": {
+ "trunk_weights": "/droid-init-v2b724-ema.safetensors",
+ "video_vae_id": "/kinovae.safetensors",
+ "text_encoder_id": "/qwen3-vl-4b-instruct",
+ "attn_mode": "torch",
+ "action_modality": "game",
+ "action_dim": 4,
+ "camera_layout": "single",
+ "camera_keys": ["images.game"],
+ "canvas_hw": [512, 512],
+ "chunk_size": 32,
+ "n_action_steps": 8,
+ "fps": 15.0,
+ "action_scale": 2.0,
+ "gripper_flip_dims": [],
+ "caption_dropout": 0.0,
+ "augment": false,
+ "optimizer_lr": 5e-5,
+ "optimizer_lr_heads_multiplier": 5.0,
+ "sampler": "cosmos_unipc",
+ "num_inference_steps": 1,
+ "single_frame_encode": true,
+ "guidance_scale": 1.0,
+ "sampler_shift": 5.0
+ },
+ "steps": 3000,
+ "frozen_steps": 200,
+ "trunk_warmup_steps": 600,
+ "heads_warmup_steps": 200,
+ "cooldown_start": 2600,
+ "cooldown_steps": 400,
+ "seed": 42,
+ "reseed_on_resume": true,
+ "windows_per_rank": 4,
+ "grad_accumulation": 1,
+ "num_workers": 6,
+ "prefetch_factor": 2,
+ "shard_size": 8,
+ "param_dtype": "float32",
+ "compute_dtype": "bfloat16",
+ "reduce_dtype": "float32",
+ "activation_checkpointing": true,
+ "reshard_after_forward": true,
+ "betas": [0.9, 0.99],
+ "eps": 1e-08,
+ "weight_decay": 0.05,
+ "fused_optimizer": true,
+ "ema_sigma_rels": [0.1, 0.05],
+ "checkpoint_every": 250,
+ "keep_checkpoints": 4,
+ "keep_every": 500,
+ "log_every": 10,
+ "resume": "auto"
+}
diff --git a/flux-umi/configs/so101/community_corpus.json b/flux-umi/configs/so101/community_corpus.json
new file mode 100644
index 0000000000000000000000000000000000000000..e7a42ab354c5a826cfd0ecd039d5ab2bb02a89e7
--- /dev/null
+++ b/flux-umi/configs/so101/community_corpus.json
@@ -0,0 +1,1104 @@
+{
+ "format_version": 1,
+ "corpus": "molmoact_corpus_tiled",
+ "description": "SO-100/SO-101 community teleoperation datasets from the Hugging Face Hub, converted to 50-frame tiled (scene | wrist) clips with per-dataset normalized joint-delta actions and states; the training set of the SO-101 community full finetune (docs/so101-lora.md#optional-full-fine-tuning).",
+ "sources": {
+ "molmoact": {
+ "repo_id": "allenai/MolmoAct2-SO100_101-Dataset",
+ "repo_type": "dataset",
+ "role": "manifest: repo_list.json names 1220 `lerobot:/` community datasets and language_annotations///tasks_annotated.parquet holds per-episode instructions; the episodes were read from the listed / dataset repos",
+ "revision": null,
+ "downloaded": "2026-08-10/11",
+ "parts": 709
+ },
+ "community_dataset_v3": {
+ "repo_id": "lerobot/community_dataset_v3",
+ "repo_type": "dataset",
+ "role": "aggregate repo; every dataset is a / subtree (LeRobot v2.1, 30 Hz)",
+ "revision": "716f9acdde8f6a01c41b681f3e72b46abee88a5c",
+ "parts": 312
+ }
+ },
+ "selection": [
+ "30 fps datasets only (20 fps repos dropped); moss robots dropped",
+ "scene camera chosen per dataset by a VLM gate over frame strips (top-down or high-angle views kept; side, wrist-only, unusable and pervasive-human repos dropped); camera names in the datasets are unreliable, several are swapped",
+ "action audit per dataset: teleport and jerk checks, NaN and static episodes dropped",
+ "windows whose actions are dead for more than 60% of frames stripped (--strip-dead-windows 0.6)",
+ "merge share cap 5% of training windows per part (no part reached it)",
+ "parts whose action dimension is not 6 contribute no windows"
+ ],
+ "builder": {
+ "fps": 30,
+ "clip_frames": 50,
+ "window_stride": 25,
+ "max_windows_per_episode": 35,
+ "strip_dead_windows": 0.6,
+ "camera_tile_hw": [
+ 256,
+ 256
+ ],
+ "canvas_hw": [
+ 256,
+ 512
+ ],
+ "tile_order": [
+ "scene (left)",
+ "wrist (right)"
+ ],
+ "missing_wrist_tile": "flat gray (128, 128, 128)",
+ "wrist_dropout": 0.2,
+ "wrist_dropout_rule": "deterministic per (episode_index, window start); dual-view windows only",
+ "action_mode": "joint_delta",
+ "action_definition": "a[t] - a[t-1] on the five joints, computed within the episode; gripper absolute",
+ "normalization": "x_norm = clip(2 * (x - q01) / (q99 - q01) - 1, -6, 6) with the part's own q01/q99",
+ "degenerate_channels": "a channel with q99 - q01 <= 1e-6 (e.g. a gripper that never moved) uses span 1.0: x_norm = x - q01 - 1",
+ "state": "measured joint state at every frame, same normalization with the part's state q01/q99",
+ "units": "as stored by LeRobot (degrees for the joints, gripper opening as recorded)",
+ "channel_names": "as declared by the source dataset (delta channels prefixed d_); a few datasets declare one group label instead of six names, their bounds still have six entries",
+ "prompts": "MolmoAct annotated instruction per episode when present, else the LeRobot task string",
+ "val_split": "the ten largest datasets hold out episodes; at most four windows per held-out episode"
+ },
+ "counts": {
+ "parts_built": 1021,
+ "parts_in_train": 1016,
+ "parts_in_val": 10,
+ "train_windows": 631391,
+ "val_windows": 119,
+ "built_clips": 638507
+ },
+ "val_parts": [
+ "Chojins__chess_game_001_blue_stereo",
+ "Chojins__chess_game_001_red_stereo",
+ "Cornito__so101_chess17",
+ "Loki0929__so100_duck",
+ "Loki0929__so100_lan",
+ "VoicAndrei__so100_kitchen",
+ "kaiserbuffle__hanoiv2",
+ "kaiserbuffle__hanoiv5",
+ "kaiserbuffle__hanoiv6",
+ "samanthalhy__so100_herding_1"
+ ],
+ "parts": [
+ {"part":"00ri__so100_battery","origin":"molmoact","dataset":"00ri/so100_battery","scene_camera":"observation.images.phone","fps":30.0,"built_clips":770,"train_windows":770,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.460938,-1.879102,-0.966797,-1.318359,-0.090334],"action_q99":[1.318359,2.285156,2.460938,0.878906,1.669922,22.854563],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.910156,51.679688,43.29668,37.705078,-62.929688,0.298285],"state_q99":[39.902344,189.580078,167.607422,85.287305,75.004102,22.893364]},
+ {"part":"00ri__so100_battery_bin_center","origin":"molmoact","dataset":"00ri/so100_battery_bin_center","scene_camera":"observation.images.phone","fps":30.0,"built_clips":604,"train_windows":604,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.624414,-2.184961,-1.054688,-2.109375,0.0],"action_q99":[1.40625,2.636719,2.988281,1.230469,2.373047,30.037313],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.783203,56.689453,48.088477,37.190039,-75.849609,0.350877],"state_q99":[60.368555,185.976562,169.716797,76.904297,74.53125,29.736841]},
+ {"part":"00ri__so100_test","origin":"molmoact","dataset":"00ri/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":38,"train_windows":38,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-2.636719,-1.845703,-0.966797,-0.807715,-0.090334],"action_q99":[1.054688,1.933594,1.318359,1.318359,0.966797,19.077687],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.849609,53.613281,60.996094,26.438379,-57.128906,0.298285],"state_q99":[10.986328,189.755859,168.662109,83.847656,1.820215,18.955258]},
+ {"part":"356c__so100_duck_reposition_1","origin":"molmoact","dataset":"356c/so100_duck_reposition_1","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1747,"train_windows":1747,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.724609,-2.460938,-2.109375,-1.318359,-0.240385],"action_q99":[1.757812,2.636719,3.076172,1.845703,1.669922,35.096153],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.511719,66.796875,73.652344,6.328125,-107.666016,2.30608],"state_q99":[49.570312,195.292969,180.703125,88.769531,-39.375,34.171909]},
+ {"part":"356c__so100_nut_sort_1","origin":"molmoact","dataset":"356c/so100_nut_sort_1","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1549,"train_windows":1549,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.636719,-2.197266,-1.582031,-1.230469,6.971154],"action_q99":[1.933594,2.8125,2.460938,1.494141,1.142578,61.658653],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.464844,63.896484,78.471387,27.246094,-101.425781,26.415094],"state_q99":[31.904297,195.205078,180.966797,75.322266,-33.310547,61.215935]},
+ {"part":"356c__so100_nut_test_1","origin":"molmoact","dataset":"356c/so100_nut_test_1","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1122,"train_windows":1122,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.460938,-2.021484,-1.669922,-0.878906,0.0],"action_q99":[1.494141,2.460938,2.021484,1.757812,1.318359,69.71154],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.628906,59.677734,68.466797,5.976562,-57.041016,26.20545],"state_q99":[32.167969,195.205078,182.197266,75.234375,15.46875,68.972748]},
+ {"part":"356c__so100_nut_test_11","origin":"molmoact","dataset":"356c/so100_nut_test_11","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1379,"train_windows":1379,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.460938,-2.109375,-1.669922,-2.460938,0.120192],"action_q99":[1.40625,2.548828,2.285156,1.582031,2.548828,69.11058],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.804688,51.152344,57.744141,-20.917969,-107.138672,5.849057],"state_q99":[32.080078,195.205078,181.669922,79.461914,2.557617,68.343819]},
+ {"part":"356c__so100_rope_reposition_1","origin":"molmoact","dataset":"356c/so100_rope_reposition_1","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1714,"train_windows":1714,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.8125,-2.197266,-1.757812,-3.691406,-0.120192],"action_q99":[1.933594,2.8125,2.021484,2.021484,3.868066,68.629807],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.882812,67.675781,86.922949,6.503906,-124.101562,2.30608],"state_q99":[41.132812,195.205078,180.878906,70.400391,66.181641,67.714882]},
+ {"part":"AMRUBARD__so100_make_coffeetest6","origin":"molmoact","dataset":"AMRUBARD/so100_make_coffeetest6","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1036,"train_windows":1036,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.285156,-1.933594,-3.427734,-2.460938,-0.550964],"action_q99":[1.669922,2.373047,2.109375,3.603516,1.845703,72.015151],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.068359,54.404297,91.757812,-110.478516,-96.328125,0.0],"state_q99":[45.907031,187.03125,176.923828,81.035156,43.59375,68.779639]},
+ {"part":"Aadhavan__so101_bio_test1","origin":"molmoact","dataset":"Aadhavan/so101_bio_test1","scene_camera":"observation.images.top","fps":30.0,"built_clips":25,"train_windows":25,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.589258,-7.511133,-6.808008,-5.475586,-6.292969,-0.487409],"action_q99":[2.988281,10.260352,12.218555,5.530078,5.969531,27.007311],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.353516,12.65625,-2.325586,27.070312,6.416016,-0.615595],"state_q99":[28.125,181.582031,168.398438,92.197266,114.785156,26.77565]},
+ {"part":"Aaron757__so100_test6","origin":"molmoact","dataset":"Aaron757/so100_test6","scene_camera":"observation.images.phone","fps":30.0,"built_clips":13,"train_windows":13,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.826367,-2.8125,-3.603516,-2.65166,-3.0375,0.0],"action_q99":[1.79209,2.968945,2.65166,2.915332,2.285156,38.984848],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-1.054688,80.209863,107.578125,8.304785,-76.621289,0.330579],"state_q99":[35.454199,187.734375,179.121094,57.926074,-2.197266,37.631406]},
+ {"part":"Aaron757__so100_test7","origin":"molmoact","dataset":"Aaron757/so100_test7","scene_camera":"observation.images.phone","fps":30.0,"built_clips":304,"train_windows":304,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.339844,-3.867188,-2.285156,-3.164062,0.0],"action_q99":[1.933594,3.164062,3.339844,2.724609,2.636719,41.477272],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.6875,36.868359,27.773438,29.794922,-94.130859,0.247934],"state_q99":[41.748047,187.822266,179.296875,91.276172,1.494141,40.57851]},
+ {"part":"AndrejOrsula__lerobot_double_ball_stacking","origin":"molmoact","dataset":"AndrejOrsula/lerobot_double_ball_stacking","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":463,"train_windows":463,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.779297,-4.042969,-1.582031,-1.230469,-0.096805],"action_q99":[2.285156,4.570312,4.482422,2.460938,1.142578,62.826717],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.419922,77.058105,92.900391,43.330078,-93.076172,0.139958],"state_q99":[6.152344,191.425781,173.408203,82.792969,-65.566406,63.051086]},
+ {"part":"AndrejOrsula__lerobot_double_ball_stacking_random","origin":"molmoact","dataset":"AndrejOrsula/lerobot_double_ball_stacking_random","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":514,"train_windows":514,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-4.042969,-4.968457,-1.804395,-1.318359,-0.193611],"action_q99":[2.548828,3.691406,4.21875,2.460938,1.318359,84.123909],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.337598,20.654297,-2.109375,44.033203,-131.003613,0.0],"state_q99":[73.212891,191.337891,173.496094,106.259766,-44.472656,84.184746]},
+ {"part":"AndrejOrsula__lerobot_triple_ball_stacking","origin":"molmoact","dataset":"AndrejOrsula/lerobot_triple_ball_stacking","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":1798,"train_windows":1798,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.427734,-3.251953,-2.109375,-1.40625,-0.096805],"action_q99":[1.40625,4.21875,5.009766,2.460938,1.40625,71.636009],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.859375,66.005859,60.46875,31.904297,-105.117188,0.139958],"state_q99":[32.607422,191.425781,174.638672,100.634766,-56.425781,71.448563]},
+ {"part":"Angry-Lasagna__so101_dice_circle_v1","origin":"molmoact","dataset":"Angry-Lasagna/so101_dice_circle_v1","scene_camera":"observation.images.top","fps":30.0,"built_clips":111,"train_windows":111,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-5.273438,-3.810059,-1.933594,-2.57959,-0.338696],"action_q99":[2.109375,3.867188,3.897949,1.845703,1.40625,36.409821],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.214844,16.435547,6.855469,36.474609,-78.75,0.275482],"state_q99":[54.228516,196.787109,181.582031,98.876953,5.185547,36.019283]},
+ {"part":"Angry-Lasagna__so101_test","origin":"molmoact","dataset":"Angry-Lasagna/so101_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":26,"train_windows":26,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.076172,-1.933594,-1.494141,-1.400098,-0.254022],"action_q99":[1.494141,2.548828,2.373047,1.224316,1.494141,35.393734],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.591797,66.708984,97.470703,38.232422,-43.575293,0.344353],"state_q99":[38.289551,191.746582,181.40625,79.628906,0.439453,35.743801]},
+ {"part":"Arouraas__so101_test","origin":"molmoact","dataset":"Arouraas/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.087598,-2.724609,-1.40625,-0.527344,-0.163132],"action_q99":[1.845703,2.736035,2.021484,1.857129,0.966797,23.083199],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.755859,91.933594,75.265137,46.142578,67.5,0.217549],"state_q99":[67.412109,192.216797,174.375,103.920996,89.659863,22.697607]},
+ {"part":"AshBastian9__so101_init_5episodes","origin":"molmoact","dataset":"AshBastian9/so101_init_5episodes","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":175,"train_windows":175,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.285156,-2.361621,-1.582031,-2.109375,0.392773],"action_q99":[3.240527,1.582031,1.494141,1.845703,1.494141,63.943439],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-66.005859,56.337891,35.859375,21.005859,-102.65625,1.208054],"state_q99":[67.137012,201.445312,179.560547,100.019531,5.185547,63.624161]},
+ {"part":"Ashton3__lerobot-aloha","origin":"molmoact","dataset":"Ashton3/lerobot-aloha","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":358,"train_windows":358,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-4.921875,-3.251953,-5.273438,-3.867188,-0.26738],"action_q99":[0.878906,4.482422,3.251953,4.570312,2.548828,77.272728],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-11.953125,36.298828,77.607422,-65.917969,-95.888672,0.461894],"state_q99":[19.511719,189.755859,180.615234,63.896484,28.212891,76.113166]},
+ {"part":"Ayush-Sharan-1__c-4g_tC-T_fC-T_d-250525_v-1","origin":"molmoact","dataset":"Ayush-Sharan-1/c-4g_tC-T_fC-T_d-250525_v-1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":567,"train_windows":567,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.076172,-3.076172,-2.285156,-3.515625,-0.176678],"action_q99":[2.109375,2.548828,2.900391,1.582031,2.636719,49.381626],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.998047,54.140625,61.435547,26.342578,-148.623047,-0.139762],"state_q99":[54.140625,189.316406,179.912109,98.085938,5.712891,49.266247]},
+ {"part":"Ayush-Sharan-1__c-4g_tC-T_fC-T_d-280525_v-1","origin":"molmoact","dataset":"Ayush-Sharan-1/c-4g_tC-T_fC-T_d-280525_v-1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":148,"train_windows":148,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.251953,-3.076172,-2.762402,-3.867188,-0.265018],"action_q99":[2.109375,2.724609,2.988281,1.971387,2.938184,56.007069],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.888672,58.359375,74.003906,12.304688,-148.886719,0.0],"state_q99":[55.107422,189.316406,179.648438,97.056738,10.484473,55.555557]},
+ {"part":"Ayush-Sharan-1__c-4g_tC-T_fC-T_d-290525_v-1","origin":"molmoact","dataset":"Ayush-Sharan-1/c-4g_tC-T_fC-T_d-290525_v-1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":612,"train_windows":612,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.8125,-3.138574,-2.548828,-4.482422,-0.176678],"action_q99":[2.021484,2.8125,2.900391,2.460938,2.724609,49.823322],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.42373,43.857422,49.570312,0.175781,-164.003906,-0.069881],"state_q99":[69.697266,189.580078,179.824219,99.228516,8.4375,49.545773]},
+ {"part":"Ayush-Sharan-1__config-4grid_topCam-T_frontCam-T_d-160525_v-1","origin":"molmoact","dataset":"Ayush-Sharan-1/config-4grid_topCam-T_frontCam-T_d-160525_v-1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":854,"train_windows":854,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.109375,-2.285156,-1.933594,-2.900391,-0.265018],"action_q99":[1.582031,1.933594,2.109375,1.845703,1.845703,42.844521],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.658203,54.808594,63.861328,15.732422,-147.128906,-0.069881],"state_q99":[55.986328,189.316406,179.912109,91.582031,-0.439453,42.557652]},
+ {"part":"Ayush-Sharan-1__so100_pickupOrangeCyl","origin":"molmoact","dataset":"Ayush-Sharan-1/so100_pickupOrangeCyl","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":283,"train_windows":283,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.373047,-2.460938,-1.757812,-1.933594,-0.262009],"action_q99":[1.582031,2.109375,2.021484,1.582031,1.318359,29.868996],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.826172,75.498047,69.960938,42.111035,-102.732715,0.413508],"state_q99":[55.095996,186.240234,176.308594,103.007812,-1.40625,29.772572]},
+ {"part":"Ayush-Sharan-1__so100_ticTacToe","origin":"molmoact","dataset":"Ayush-Sharan-1/so100_ticTacToe","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":104,"train_windows":104,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.164062,-2.918848,-2.109375,-2.127832,-0.262009],"action_q99":[1.230469,2.830957,2.724609,1.77627,1.688379,25.414848],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-11.777344,40.253906,36.474609,44.824219,-77.255859,0.137836],"state_q99":[42.011719,185.976562,176.132812,98.701172,-2.460938,25.223982]},
+ {"part":"Bapt120__so101_cup1","origin":"molmoact","dataset":"Bapt120/so101_cup1","scene_camera":"observation.images.arm","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.676953,-1.494141,-1.318359,-0.351562,-0.210231],"action_q99":[0.791016,1.933594,1.40625,2.116406,0.263672,67.428173],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-1.142578,62.050781,114.609375,-36.826172,-7.382812,0.584795],"state_q99":[33.222656,198.105469,176.220703,63.031641,-3.867188,67.713448]},
+ {"part":"Bapt120__so101_cup3","origin":"molmoact","dataset":"Bapt120/so101_cup3","scene_camera":"observation.images.arm","fps":30.0,"built_clips":34,"train_windows":34,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.673437,-2.552344,-1.589062,-0.355078,3.349685],"action_q99":[1.054688,3.258984,2.988281,4.130859,0.179297,75.122635],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[9.667969,23.818359,53.701172,-106.03125,-7.207031,5.190058],"state_q99":[33.574219,141.416016,172.473047,93.339844,-1.142578,74.707603]},
+ {"part":"Bapt120__so101_cup4","origin":"molmoact","dataset":"Bapt120/so101_cup4","scene_camera":"observation.images.arm","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.204297,-1.845703,-1.582031,-0.351562,0.630694],"action_q99":[0.966797,3.515625,3.251953,1.494141,0.087891,79.817802],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.052734,36.386719,13.710938,31.816406,-34.013672,0.584795],"state_q99":[30.417187,198.632812,175.253906,103.974609,-7.119141,79.166672]},
+ {"part":"Bapt120__so101_cup5","origin":"molmoact","dataset":"Bapt120/so101_cup5","scene_camera":"observation.images.arm","fps":30.0,"built_clips":48,"train_windows":48,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-1.757812,-2.021484,-2.292187,-0.087891,-1.331465],"action_q99":[0.966797,3.339844,3.962109,2.555859,0.182812,41.351088],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[0.703125,41.923828,30.410156,43.681641,-17.841797,0.0],"state_q99":[28.037109,198.28125,141.35625,103.974609,-9.316406,40.935673]},
+ {"part":"Bapt120__so101_cup7","origin":"molmoact","dataset":"Bapt120/so101_cup7","scene_camera":"observation.images.arm","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.376562,-2.373047,-1.845703,-0.175781,-1.401542],"action_q99":[1.318359,3.164062,3.434766,1.669922,0.534375,46.040646],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.515234,35.683594,30.234375,44.736328,-10.019531,-0.146199],"state_q99":[30.058594,196.962891,141.064453,86.333203,1.494141,45.540936]},
+ {"part":"Bapt120__so101_cup8","origin":"molmoact","dataset":"Bapt120/so101_cup8","scene_camera":"observation.images.arm","fps":30.0,"built_clips":441,"train_windows":441,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.164062,-3.076172,-2.197266,-0.351562,-1.751927],"action_q99":[1.757812,5.009766,4.833984,2.8125,0.439453,41.62579],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.974609,29.807227,14.238281,27.755859,-15.46875,-0.365497],"state_q99":[37.617188,199.335938,140.449219,104.150391,9.84375,41.154972]},
+ {"part":"Bartm3__dice3","origin":"molmoact","dataset":"Bartm3/dice3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":31,"train_windows":31,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-3.339844,-2.636719,-1.582031,-1.757812,-4.5677],"action_q99":[0.878906,2.285156,1.494141,1.238379,1.40625,23.668841],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.912109,81.210938,94.482422,8.525391,-92.73252,-3.501401],"state_q99":[13.287305,190.898438,178.242188,81.929883,13.526367,23.280813]},
+ {"part":"Bartm3__dice4","origin":"molmoact","dataset":"Bartm3/dice4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":2044,"train_windows":2044,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-3.076172,-2.460938,-1.69856,-3.339844,-4.5677],"action_q99":[1.318359,2.900391,2.8125,1.933594,2.8125,33.115826],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.800781,14.238281,14.043164,-9.501855,-103.095703,-3.571429],"state_q99":[48.076172,190.810547,178.59375,95.097656,3.867188,32.913166]},
+ {"part":"Bartm3__tape_to_bin","origin":"molmoact","dataset":"Bartm3/tape_to_bin","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":648,"train_windows":648,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-4.570312,-3.164062,-2.109375,-0.966797,-8.438409],"action_q99":[3.515625,3.691406,4.482422,2.548828,0.703125,28.03104],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.529297,56.777344,36.73125,35.149219,-4.130859,-3.253182],"state_q99":[59.414062,193.974609,167.871094,100.898438,25.664062,26.237625]},
+ {"part":"Bartm3__tape_to_bin2","origin":"molmoact","dataset":"Bartm3/tape_to_bin2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1428,"train_windows":1428,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-4.042969,-3.779297,-1.757812,-0.703125,-8.438409],"action_q99":[2.373047,3.251953,4.394531,1.757812,0.703125,23.494665],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-16.875,34.453125,19.599609,51.855469,-6.767578,-3.960396],"state_q99":[60.46875,194.150391,169.453125,101.777344,16.611328,22.630835]},
+ {"part":"Beegbrain__pick_lemon_and_drop_in_bowl","origin":"molmoact","dataset":"Beegbrain/pick_lemon_and_drop_in_bowl","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":553,"train_windows":553,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.076172,-3.251953,-1.669922,-1.669922,0.0],"action_q99":[1.40625,3.164062,4.130859,1.757812,1.757812,63.517307],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.507812,36.035156,29.619141,43.902246,-90.791016,0.940439],"state_q99":[49.304883,189.140625,181.318359,100.458984,46.843945,62.225704]},
+ {"part":"Beegbrain__sweep_tissue_cube","origin":"molmoact","dataset":"Beegbrain/sweep_tissue_cube","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":596,"train_windows":596,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-3.427734,-3.603516,-2.988281,-2.548828,-0.093545],"action_q99":[2.197266,3.339844,3.779297,2.900391,2.460938,0.093545],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.197461,32.167969,36.089648,15.138281,-91.694531,0.626959],"state_q99":[59.853516,189.140625,182.109375,86.484375,33.925781,1.097179]},
+ {"part":"BobBobbson__so100_First_Gripper_Test","origin":"molmoact","dataset":"BobBobbson/so100_First_Gripper_Test","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":989,"train_windows":989,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.248198,-1.022732,-1.745281,-0.816692,0.0,59.7285],"action_q99":[1.890644,0.640816,1.173901,1.305195,0.0,111.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.646484,67.587891,30.849609,33.046875,-41.835938,67.812065],"state_q99":[76.025391,141.767578,143.613281,99.316406,-41.748047,109.467041]},
+ {"part":"BobBobbson__so100_test_FIRST_DATA","origin":"molmoact","dataset":"BobBobbson/so100_test_FIRST_DATA","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1147,"train_windows":1147,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.890797,-1.744069,-2.446805,-1.513717,0.0,-3.0],"action_q99":[1.626833,1.411455,2.211886,2.100188,0.0,38.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.326172,33.925781,30.322266,-8.964844,-90.351562,-2.59467],"state_q99":[95.449219,146.763281,157.412109,99.755859,-90.087891,38.148666]},
+ {"part":"BranoSandy__so100_test","origin":"molmoact","dataset":"BranoSandy/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":256,"train_windows":256,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-3.603516,-2.373047,-3.603516,-0.791016,0.0],"action_q99":[1.845703,2.988281,2.460938,3.867188,0.878906,34.439461],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.693359,28.916016,37.740234,-110.126953,-116.367188,0.277393],"state_q99":[29.794922,188.525391,176.835938,32.414062,-91.582031,34.604717]},
+ {"part":"BranoSandy__so100_test_1","origin":"molmoact","dataset":"BranoSandy/so100_test_1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":53,"train_windows":53,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.285156,-1.757812,-3.779297,-0.263672,0.0],"action_q99":[2.021484,3.164062,1.681348,4.230176,0.187207,30.582958],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.056348,80.947266,113.027344,-110.126953,-106.083984,0.416089],"state_q99":[14.414062,188.613281,176.835938,29.52334,-96.328125,30.72122]},
+ {"part":"BranoSandy__so100_test_cap2","origin":"molmoact","dataset":"BranoSandy/so100_test_cap2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.683105,-2.460938,-1.946777,-3.968262,-0.804199,0.089686],"action_q99":[2.197266,3.616699,2.460938,4.359375,1.142578,24.049327],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.220703,86.835938,106.611328,-110.126953,-105.380859,0.277393],"state_q99":[18.821777,188.173828,176.835938,23.291016,-81.922852,24.410542]},
+ {"part":"BranoSandy__so100_test_cap_20","origin":"molmoact","dataset":"BranoSandy/so100_test_cap_20","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":483,"train_windows":483,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.285156,-1.845703,-2.724609,-0.351562,0.0],"action_q99":[1.142578,2.900391,2.373047,3.339844,0.407812,27.501345],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.421875,58.359375,81.035156,-109.599609,-104.150391,0.346741],"state_q99":[17.666016,188.613281,176.748047,25.927734,-77.783203,27.323162]},
+ {"part":"Chojins__chess_game_001_blue_stereo","origin":"molmoact","dataset":"Chojins/chess_game_001_blue_stereo","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":8404,"train_windows":8404,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.285156,-2.197266,-1.669922,-2.460938,-0.094518],"action_q99":[1.230469,2.285156,1.933594,2.724609,2.460938,16.162571],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.289062,57.392578,79.453125,22.587891,-167.167969,0.151172],"state_q99":[41.923828,181.40625,164.267578,99.492188,-32.871094,15.570673]},
+ {"part":"Chojins__chess_game_001_blue_stereo_flip","origin":"molmoact","dataset":"Chojins/chess_game_001_blue_stereo_flip","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":3893,"train_windows":3893,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.373047,-2.285156,-1.845703,-2.636719,-0.094518],"action_q99":[1.318359,2.373047,2.021484,2.900391,2.548828,17.013233],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.421875,58.095703,81.298828,21.621094,-165.761719,0.151172],"state_q99":[42.363281,180.966797,164.179688,99.580078,-29.003906,16.17536]},
+ {"part":"Chojins__chess_game_001_red_stereo","origin":"molmoact","dataset":"Chojins/chess_game_001_red_stereo","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":8210,"train_windows":8210,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.460938,-2.109375,-1.669922,-2.460938,-0.094518],"action_q99":[1.230469,2.460938,1.845703,2.548828,2.197266,14.272211],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.552734,53.4375,78.134766,25.136719,-180.087891,0.29304],"state_q99":[46.142578,181.494141,163.740234,99.667969,-24.960938,13.626374]},
+ {"part":"Cidoyi__so100_00000","origin":"molmoact","dataset":"Cidoyi/so100_00000","scene_camera":"observation.images.keyboard_camera","fps":30.0,"built_clips":29,"train_windows":29,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-1.669922,-1.794727,-3.64043,-0.527344,96.972481],"action_q99":[1.230469,2.373047,1.582031,1.970508,0.615234,98.073395],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.355273,103.951758,127.177734,-59.709375,168.837891,96.993126],"state_q99":[33.574219,139.343555,160.576172,29.761523,182.988281,97.852234]},
+ {"part":"Cidoyi__so100_20","origin":"molmoact","dataset":"Cidoyi/so100_20","scene_camera":"observation.images.keyboard_camera","fps":30.0,"built_clips":10,"train_windows":10,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.422949,-0.895605,-0.719824,-0.791016,-0.263672,96.880737],"action_q99":[1.054688,1.230469,0.351562,1.51084,0.631934,98.073395],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.463965,118.740234,155.742188,-40.869141,174.375,97.422684],"state_q99":[22.69248,159.785156,161.894531,-2.636719,182.988281,98.281792]},
+ {"part":"Cidoyi__so100_23","origin":"molmoact","dataset":"Cidoyi/so100_23","scene_camera":"observation.images.keyboard_camera","fps":30.0,"built_clips":8,"train_windows":8,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.159277,-0.631934,-0.087891,-1.791211,-0.368262,99.449539],"action_q99":[1.142578,1.669922,0.368262,1.686621,0.263672,99.449539],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.157324,108.984375,159.257812,-60.820312,173.671875,98.936424],"state_q99":[28.037109,160.664062,163.652344,-17.578125,176.748047,99.57045]},
+ {"part":"Congying1112__so100_place_bottle","origin":"molmoact","dataset":"Congying1112/so100_place_bottle","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":39,"train_windows":39,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.900391,-2.91709,-2.565527,-1.318359,-0.433839],"action_q99":[1.318359,3.339844,3.795996,2.548828,1.59873,41.214748],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-0.703125,33.381738,18.193359,-46.879102,-123.310547,0.435098],"state_q99":[37.177734,188.525391,177.1875,101.379199,-78.118066,40.536621]},
+ {"part":"Congying1112__so100_place_bottle_with_two_cameras","origin":"molmoact","dataset":"Congying1112/so100_place_bottle_with_two_cameras","scene_camera":"observation.images.top","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.070508,-2.68418,-2.652539,-3.267773,-1.318359,-0.433839],"action_q99":[0.966797,2.197266,3.691406,3.955078,1.158398,44.221257],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.515625,8.829492,-11.777344,-110.039062,-108.720703,0.507614],"state_q99":[43.60957,189.580078,177.802734,99.156445,-72.038672,43.126904]},
+ {"part":"Congying1112__so100_test","origin":"molmoact","dataset":"Congying1112/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":43,"train_windows":43,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.021484,-2.724609,-2.845898,-1.230469,-0.32538],"action_q99":[1.669922,2.511035,2.758008,3.180762,1.054688,45.501087],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.96875,101.24209,77.507227,13.974609,-103.710938,0.435098],"state_q99":[34.980469,189.755859,177.1875,98.876953,-59.589844,45.894127]},
+ {"part":"Cornito__so101_chess13","origin":"molmoact","dataset":"Cornito/so101_chess13","scene_camera":"observation.images.phone","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.207813,-1.054688,-2.460938,-2.285156,-0.426985],"action_q99":[0.527344,1.279687,1.103906,2.197266,2.021484,14.43211],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.257812,73.300781,97.998047,-103.447266,-8.701172,3.669725],"state_q99":[4.394531,192.128906,180.0,37.705078,106.259766,14.25547]},
+ {"part":"Cornito__so101_chess17","origin":"molmoact","dataset":"Cornito/so101_chess17","scene_camera":"observation.images.phone","fps":30.0,"built_clips":4536,"train_windows":4536,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.548828,-1.933594,-3.076172,-0.878906,-0.426985],"action_q99":[0.878906,2.109375,2.021484,4.042969,0.878906,20.153715],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.079883,48.955078,40.517578,-103.359375,54.84375,2.328864],"state_q99":[37.265625,192.480469,180.0,89.824219,110.126953,19.971771]},
+ {"part":"Cornito__so101_chess3","origin":"molmoact","dataset":"Cornito/so101_chess3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":68,"train_windows":68,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.933594,-1.318359,-3.427734,-1.845703,-0.426985],"action_q99":[0.608203,1.845703,1.582031,2.724609,2.798438,13.321946],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.711719,69.785156,74.794922,-103.447266,-23.783203,-0.141143],"state_q99":[5.185547,192.304688,179.912109,59.765625,105.908203,13.338038]},
+ {"part":"CrawlAiHuggingFace__multiplied_so101_banana","origin":"molmoact","dataset":"CrawlAiHuggingFace/multiplied_so101_banana","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.670312,-2.758008,-1.791211,-0.594141,-0.391543],"action_q99":[1.40625,2.460938,2.385352,2.230664,0.263672,46.51527],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.900586,50.185547,42.451172,22.148438,-11.425781,0.841751],"state_q99":[21.884766,191.689453,177.626953,99.228516,-0.439453,46.21212]},
+ {"part":"CrawlAiHuggingFace__multiplied_so101_first","origin":"molmoact","dataset":"CrawlAiHuggingFace/multiplied_so101_first","scene_camera":"observation.images.topdown","fps":30.0,"built_clips":177,"train_windows":177,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.021484,-1.933594,-1.757812,-1.209375,-0.254669],"action_q99":[1.054688,2.109375,2.264063,2.439844,1.054688,37.60611],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.21875,49.21875,24.366797,-34.804688,76.464844,-0.137836],"state_q99":[56.953125,194.326172,179.384766,98.876953,155.612109,37.973812]},
+ {"part":"DD99to5__so100_blocktest2","origin":"molmoact","dataset":"DD99to5/so100_blocktest2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.8125,-1.591699,-1.943262,-0.966797,-0.184843],"action_q99":[1.40625,2.460938,1.855371,2.470605,0.527344,77.818855],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[0.351562,-14.150391,5.537109,19.160156,80.15625,0.284293],"state_q99":[51.855469,90.966797,69.082031,75.585938,97.822266,78.038376]},
+ {"part":"Dangvi__so100_dataset","origin":"molmoact","dataset":"Dangvi/so100_dataset","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":380,"train_windows":380,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.900391,-3.779297,-1.602246,-4.151074,0.107066],"action_q99":[1.778027,1.054688,0.615234,3.251953,0.703125,28.800856],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.482422,45.087891,28.08457,29.619141,-176.396484,0.425532],"state_q99":[76.221387,189.140625,179.296875,102.744141,2.636719,28.58156]},
+ {"part":"Dangvi__soarm100_data","origin":"molmoact","dataset":"Dangvi/soarm100_data","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":1779,"train_windows":1779,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.691406,-4.130859,-1.669922,-5.712891,-0.107066],"action_q99":[1.933594,2.021484,1.054688,2.988281,2.8125,39.293362],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.152344,45.432422,25.400391,35.507812,-176.308594,0.2772],"state_q99":[74.267578,189.228516,178.945312,103.095703,3.076172,39.148937]},
+ {"part":"Dangvi__soarm100_data2","origin":"molmoact","dataset":"Dangvi/soarm100_data2","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":1031,"train_windows":1031,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-4.042969,-4.482422,-1.669922,-5.185547,-0.103734],"action_q99":[1.669922,2.021484,1.142578,2.900391,2.8125,35.062241],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.306641,38.144531,18.315527,34.13584,-176.308594,0.2079],"state_q99":[69.873047,187.998047,178.066406,100.195312,8.173828,34.996536]},
+ {"part":"DanqingZ__new_tic_tac_toe_4","origin":"molmoact","dataset":"DanqingZ/new_tic_tac_toe_4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":300,"train_windows":300,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-2.126074,-3.164062,-1.669922,-1.142578,0.104932],"action_q99":[2.373047,2.460938,2.653418,2.109375,1.230469,44.386147],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-61.083984,83.056641,81.985254,23.642578,-50.888672,0.417362],"state_q99":[21.989355,190.107422,174.496289,94.41123,30.778418,44.156925]},
+ {"part":"DanqingZ__new_tic_tac_toe_4_06182025","origin":"molmoact","dataset":"DanqingZ/new_tic_tac_toe_4_06182025","scene_camera":"observation.images.top_down","fps":30.0,"built_clips":24,"train_windows":24,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.441797,-2.636719,-3.178125,-1.582031,-0.878906,0.104932],"action_q99":[2.211328,2.900391,3.251953,2.035547,1.332422,46.484787],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.496875,75.761719,76.728516,42.191016,-13.447266,0.33389],"state_q99":[13.183594,189.667969,174.726562,90.653906,23.041406,45.826378]},
+ {"part":"DanqingZ__pick_pink_1","origin":"molmoact","dataset":"DanqingZ/pick_pink_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":479,"train_windows":479,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-3.691406,-4.921875,-2.636719,-1.757812,-8.444444],"action_q99":[2.460938,2.460938,3.251953,3.076172,2.021484,43.195555],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.21875,86.748047,83.320312,32.452734,-63.896484,-6.171875],"state_q99":[16.523438,189.84375,171.5625,97.119141,30.828516,43.046875]},
+ {"part":"DanqingZ__pick_test","origin":"molmoact","dataset":"DanqingZ/pick_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":22,"train_windows":22,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.081445,-2.285156,-3.515625,-2.285156,-1.494141,-8.444444],"action_q99":[3.520898,3.526172,3.608789,2.905664,2.82832,60.555553],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-53.794336,66.09375,65.974219,45.351562,-32.958984,-6.09375],"state_q99":[8.266992,189.84375,169.2,96.783398,18.720703,60.000004]},
+ {"part":"DanqingZ__pick_yellow_1","origin":"molmoact","dataset":"DanqingZ/pick_yellow_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":20,"train_windows":20,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.645508,-3.700195,-4.051758,-1.50293,-1.054688,-8.444444],"action_q99":[2.557617,3.621094,3.427734,1.845703,1.854492,41.111111],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.800781,71.71875,69.1875,51.055664,-24.257812,-6.09375],"state_q99":[-1.230469,189.84375,176.220703,91.854492,26.753906,40.9375]},
+ {"part":"DanqingZ__pick_yellow_3","origin":"molmoact","dataset":"DanqingZ/pick_yellow_3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":513,"train_windows":513,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-3.515625,-4.658203,-2.460938,-1.494141,-8.444444],"action_q99":[2.724609,2.900391,2.8125,2.988281,1.933594,49.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.394531,91.669922,92.109375,32.167969,-36.210938,-6.171875],"state_q99":[17.226562,189.84375,171.914062,91.669922,34.365234,47.8125]},
+ {"part":"DanqingZ__so100_test_3_cameras","origin":"molmoact","dataset":"DanqingZ/so100_test_3_cameras","scene_camera":"observation.images.phone","fps":30.0,"built_clips":20,"train_windows":20,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.383594,-3.691406,-3.779297,-1.933594,-1.241016,-8.444444],"action_q99":[1.845703,3.691406,2.823047,1.40625,1.669922,44.333332],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.033984,92.274609,91.884375,51.1875,-22.774219,-6.09375],"state_q99":[6.866016,189.755859,169.628906,81.759375,19.6875,44.296875]},
+ {"part":"DanqingZ__so100_test_pick_green_1","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_green_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.164062,-3.691406,-2.83623,-0.974707,-8.444444],"action_q99":[1.845703,2.8125,3.179883,3.970898,0.966797,89.222221],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.390625,35.683594,8.869043,11.074219,-4.21875,-5.859375],"state_q99":[35.699414,189.228516,176.140723,84.902344,22.875293,88.678906]},
+ {"part":"DanqingZ__so100_test_pick_green_2","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_green_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":34,"train_windows":34,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.174609,-3.097266,-3.427734,-2.569922,-1.153125,-8.444444],"action_q99":[2.109375,3.603516,3.789844,2.197266,1.065234,62.444443],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.610156,49.658203,52.098047,24.183984,0.351562,-5.625],"state_q99":[55.283203,189.228516,172.033594,92.109375,19.511719,62.674997]},
+ {"part":"DanqingZ__so100_test_pick_green_3","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_green_3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":36,"train_windows":36,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.09375,-3.875977,-4.104492,-2.724609,-0.536133,-8.444444],"action_q99":[2.724609,2.460938,2.8125,2.390625,1.054688,83.333328],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.859375,56.733398,61.347656,35.077148,-4.21875,-5.703125],"state_q99":[69.28418,189.703125,171.166992,99.492188,19.432617,83.671875]},
+ {"part":"DanqingZ__so100_test_pick_green_4","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_green_4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.091992,-3.251953,-3.347754,-2.380957,-0.878906,-8.555555],"action_q99":[2.285156,3.347754,2.900391,4.14668,0.878906,81.555557],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.505957,67.5,78.384375,18.537012,1.582031,-5.703125],"state_q99":[59.421973,189.228516,175.78125,97.741406,16.435547,81.519531]},
+ {"part":"DanqingZ__so100_test_pick_green_5","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_green_5","scene_camera":"observation.images.phone","fps":30.0,"built_clips":861,"train_windows":861,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-4.130859,-5.097656,-2.724609,-1.230469,-8.444444],"action_q99":[2.548828,3.164062,2.821289,3.348633,1.582031,81.233333],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-56.953125,56.680664,66.621094,20.126953,-58.974609,-5.78125],"state_q99":[65.390625,189.580078,173.944336,100.458984,25.839844,80.46875]},
+ {"part":"DanqingZ__so100_test_pick_green_6","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_green_6","scene_camera":"observation.images.phone","fps":30.0,"built_clips":235,"train_windows":235,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-3.779297,-4.986035,-2.636719,-1.582031,-8.444444],"action_q99":[2.285156,3.427734,2.988281,2.988281,1.845703,51.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.572266,53.085938,64.62334,38.695605,-45.087891,-5.859375],"state_q99":[55.019531,189.228516,171.035156,101.25,34.101562,50.78125]},
+ {"part":"DanqingZ__so100_test_pick_grey_2","origin":"molmoact","dataset":"DanqingZ/so100_test_pick_grey_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":23,"train_windows":23,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-4.042969,-5.025586,-1.677832,-1.853613,-8.444444],"action_q99":[1.41416,3.347754,2.460938,2.900391,1.582031,40.817779],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.269531,85.957031,86.326172,35.891895,-42.898535,-6.015625],"state_q99":[34.013672,189.140625,169.101562,98.213379,20.054883,40.46875]},
+ {"part":"DanqingZ__so100_test_yellow_cuboid_1","origin":"molmoact","dataset":"DanqingZ/so100_test_yellow_cuboid_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":29,"train_windows":29,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-4.746094,-3.267773,-2.197266,-1.41416,-8.555555],"action_q99":[1.230469,4.306641,3.523535,2.636719,1.582031,49.242221],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.398438,76.816406,60.644531,52.622754,-57.232617,-5.9375],"state_q99":[27.597656,191.25,173.679785,103.718848,1.230469,48.600781]},
+ {"part":"DanqingZ__so100_test_yellow_cuboid_2","origin":"molmoact","dataset":"DanqingZ/so100_test_yellow_cuboid_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":126,"train_windows":126,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.8125,-3.251953,-2.021484,-1.142578,-8.444444],"action_q99":[1.494141,2.988281,1.757812,2.197266,1.428223,53.555553],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.816406,94.394531,108.457031,21.950684,-27.905273,-6.015625],"state_q99":[43.703613,189.931641,169.804688,87.978516,28.059082,50.703125]},
+ {"part":"DanqingZ__so100_test_yellow_cuboid_3","origin":"molmoact","dataset":"DanqingZ/so100_test_yellow_cuboid_3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":24,"train_windows":24,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.64375,-2.731641,-1.230469,-0.878906,-8.444444],"action_q99":[1.230469,2.819531,2.285156,1.589062,1.2375,32.222221],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.300781,85.078125,87.539062,54.931641,-27.773438,-5.9375],"state_q99":[11.967187,189.667969,172.177734,84.930469,3.955078,31.724998]},
+ {"part":"DanqingZ__so100_test_yellow_cuboid_4","origin":"molmoact","dataset":"DanqingZ/so100_test_yellow_cuboid_4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.779297,-3.955078,-1.494141,-1.318359,-8.444444],"action_q99":[1.40625,2.900391,2.285156,1.669922,2.128711,46.295554],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.947266,86.572266,78.779883,50.07832,-36.738281,-6.09375],"state_q99":[33.134766,189.667969,169.453125,91.669922,24.169922,46.189062]},
+ {"part":"DanqingZ__tic_tac_toe_1_0615_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_1_0615_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":34,"train_windows":34,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.447559,-3.339844,-4.658203,-1.494141,-1.095996,0.0],"action_q99":[1.757812,3.076172,4.260059,2.150684,0.744434,33.78174],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.484375,30.585938,-6.808008,51.37998,-22.412109,0.166945],"state_q99":[21.005859,189.492188,175.253906,97.382812,7.072559,33.045075]},
+ {"part":"DanqingZ__tic_tac_toe_1_0615_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_1_0615_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":130,"train_windows":130,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.109375,-2.724609,-1.494141,-1.230469,-0.104932],"action_q99":[1.845703,3.076172,3.515625,1.845703,1.054688,42.823716],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.099609,41.849121,13.710938,55.745508,-42.141797,-0.166945],"state_q99":[38.232422,189.492188,173.056641,96.855469,2.197266,42.737896]},
+ {"part":"DanqingZ__tic_tac_toe_1_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_1_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":48,"train_windows":48,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.391504,-3.534082,-1.248926,-0.966797,0.104932],"action_q99":[2.109375,3.164062,4.306641,2.109375,0.703125,31.899265],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.486328,63.420117,60.117188,52.734375,-17.878711,0.0],"state_q99":[25.506738,189.580078,175.253906,89.96748,5.643457,31.552589]},
+ {"part":"DanqingZ__tic_tac_toe_1_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_1_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":246,"train_windows":246,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.460938,-3.603516,-2.427539,-0.966797,0.0],"action_q99":[2.285156,3.867188,5.185547,1.812305,0.703125,44.975866],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.892383,42.539062,23.642578,49.746094,-11.074219,0.083472],"state_q99":[26.542969,189.580078,174.023438,97.207031,15.820312,44.626045]},
+ {"part":"DanqingZ__tic_tac_toe_1_raw_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_1_raw_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":211,"train_windows":211,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.405762,-4.130859,-5.185547,-2.636719,-3.076172,-0.104932],"action_q99":[2.460938,4.482422,4.921875,3.14209,2.724609,48.557187],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.220215,36.694336,7.294922,4.943848,-77.827148,-0.250417],"state_q99":[33.376465,189.140625,175.693359,91.845703,2.900391,47.996662]},
+ {"part":"DanqingZ__tic_tac_toe_1_raw_4","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_1_raw_4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":130,"train_windows":130,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.460938,-3.427734,-1.494141,-1.40625,-0.104932],"action_q99":[1.669922,3.691406,4.130859,2.109375,1.669922,41.168939],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.426367,41.806055,15.380859,46.318359,-37.792969,-0.33389],"state_q99":[31.406836,189.404297,175.605469,96.591797,8.701172,40.484138]},
+ {"part":"DanqingZ__tic_tac_toe_2_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_2_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":188,"train_windows":188,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.109375,-2.636719,-1.457227,-1.142578,-0.104932],"action_q99":[1.933594,2.724609,3.691406,1.757812,1.142578,43.983212],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.361523,57.07793,41.923828,48.113086,-35.411133,-0.33389],"state_q99":[33.888867,189.228516,174.814453,96.503906,12.179883,42.237061]},
+ {"part":"DanqingZ__tic_tac_toe_4_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_4_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":191,"train_windows":191,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.482422,-4.042969,-4.921875,-2.285156,-2.373047,-0.104932],"action_q99":[2.988281,4.21875,4.394531,2.900391,2.548828,46.120671],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.822266,57.123633,49.130859,25.229004,-80.244141,0.417362],"state_q99":[49.792676,188.964844,175.517578,97.470703,28.698926,45.826378]},
+ {"part":"DanqingZ__tic_tac_toe_5_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_5_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":26,"train_windows":26,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.339844,-3.327539,-1.669922,-1.142578,0.0],"action_q99":[2.272852,3.164062,3.076172,2.285156,1.054688,42.182583],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.559961,54.943945,34.69043,54.692578,-17.189648,0.500835],"state_q99":[18.896484,189.492188,174.462891,97.382812,17.138672,41.736229]},
+ {"part":"DanqingZ__tic_tac_toe_5_raw_6","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_5_raw_6","scene_camera":"observation.images.phone","fps":30.0,"built_clips":22,"train_windows":22,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.365332,-2.988281,-4.130859,-1.669922,-0.439453,0.104932],"action_q99":[2.486426,4.921875,5.738379,2.551465,0.527344,47.8489],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.873145,83.822168,91.845703,44.257324,-8.964844,0.500835],"state_q99":[19.6875,189.492188,173.056641,71.015625,3.427734,47.32888]},
+ {"part":"DanqingZ__tic_tac_toe_5_raw_7","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_5_raw_7","scene_camera":"observation.images.phone","fps":30.0,"built_clips":23,"train_windows":23,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.663965,-3.427734,-4.921875,-1.933594,-1.257715,0.104932],"action_q99":[2.373047,5.097656,6.091699,3.164062,1.169824,44.910809],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.583984,72.685547,79.277344,40.402441,-23.818359,0.500835],"state_q99":[14.414062,189.667969,171.914062,74.640234,10.986328,44.741234]},
+ {"part":"DanqingZ__tic_tac_toe_6_raw_5","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_6_raw_5","scene_camera":"observation.images.phone","fps":30.0,"built_clips":189,"train_windows":189,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.427734,-4.21875,-2.285156,-1.933594,-0.104932],"action_q99":[2.373047,3.339844,4.130859,2.285156,1.494141,35.257084],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.205664,89.560547,83.935547,43.154297,-61.66582,-0.33389],"state_q99":[36.745312,189.404297,175.517578,94.793555,22.587891,34.97496]},
+ {"part":"DanqingZ__tic_tac_toe_7_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_7_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":257,"train_windows":257,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.197266,-2.724609,-1.230469,-0.966797,-0.104932],"action_q99":[2.285156,2.373047,3.251953,1.933594,0.966797,38.09024],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.029297,65.126953,54.238184,53.349609,-29.091797,-0.33389],"state_q99":[36.5625,189.580078,173.847656,96.943359,7.822266,37.479134]},
+ {"part":"DanqingZ__tic_tac_toe_8_raw_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_8_raw_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":24,"train_windows":24,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-4.887598,-5.097656,-2.262305,-2.18584,0.104932],"action_q99":[3.416309,4.207324,4.646777,2.636719,1.230469,51.864636],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.449219,76.201172,42.576855,47.724609,-14.765625,0.500835],"state_q99":[16.523438,189.140625,175.605469,97.207031,21.445312,52.653588]},
+ {"part":"DanqingZ__tic_tac_toe_8_raw_3","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_8_raw_3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":53,"train_windows":53,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.042969,-4.407715,-4.482422,-1.858887,-1.142578,0.104932],"action_q99":[3.353027,3.691406,3.515625,2.825684,1.770996,48.373558],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.921875,96.679688,102.541992,45.509766,-13.710938,0.500835],"state_q99":[29.091797,189.755859,173.408203,81.04834,29.179688,48.330551]},
+ {"part":"DanqingZ__tic_tac_toe_9_raw_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_9_raw_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":18,"train_windows":18,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.251953,-2.712305,-2.8125,-1.230469,-0.615234,0.104932],"action_q99":[2.724609,3.327539,2.712305,1.933594,0.351562,47.324242],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.695312,108.984375,104.361328,53.398828,-10.986328,0.500835],"state_q99":[23.90625,189.580078,169.892578,75.309961,4.833984,46.911518]},
+ {"part":"DanqingZ__tic_tac_toe_9_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_9_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":25,"train_windows":25,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.955078,-2.511914,-3.541113,-1.494141,-1.318359,0.104932],"action_q99":[2.888965,3.427734,3.10166,2.285156,1.318359,56.873035],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.419922,114.82207,116.931445,46.230469,-10.458984,-0.083472],"state_q99":[19.511719,189.404297,171.826172,71.103516,25.400391,57.262104]},
+ {"part":"DanqingZ__tic_tac_toe_grid_2_raw_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_2_raw_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":178,"train_windows":178,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-3.339844,-4.21875,-2.373047,-2.021484,0.0],"action_q99":[1.757812,3.515625,4.21875,2.636719,2.021484,30.220356],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.046875,54.140625,35.244141,20.598047,-71.982422,-0.166945],"state_q99":[29.763281,189.140625,175.341797,96.328125,1.142578,30.437396]},
+ {"part":"DanqingZ__tic_tac_toe_grid_3","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.507324,-3.076172,-5.273438,-1.494141,-1.770996,0.104932],"action_q99":[1.669922,5.449219,5.800781,2.8125,1.858887,56.977962],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.889648,62.314453,59.071289,38.983887,-36.764648,0.33389],"state_q99":[12.304688,189.580078,173.408203,78.675293,26.920898,56.343906]},
+ {"part":"DanqingZ__tic_tac_toe_grid_4_raw","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_4_raw","scene_camera":"observation.images.phone","fps":30.0,"built_clips":349,"train_windows":349,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-2.460938,-3.691406,-2.8125,-1.054688,0.0],"action_q99":[2.548828,3.427734,4.921875,2.021484,1.054688,42.068204],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.921875,49.833984,33.046875,37.089844,-20.214844,-0.250417],"state_q99":[26.015625,189.580078,175.429688,95.888672,21.421582,41.903172]},
+ {"part":"DanqingZ__tic_tac_toe_grid_4_raw_1","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_4_raw_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":181,"train_windows":181,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.779297,-3.393457,-4.008691,-2.285156,-2.636719,0.0],"action_q99":[2.460938,3.569238,4.096582,2.724609,2.285156,38.259182],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.975488,45.297949,26.71875,-15.370312,-74.091797,-0.166945],"state_q99":[31.606348,189.316406,175.253906,96.64541,-2.460938,37.613523]},
+ {"part":"DanqingZ__tic_tac_toe_grid_6_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_6_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":78,"train_windows":78,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.251953,-5.097656,-7.03125,-2.460938,-1.318359,0.104932],"action_q99":[2.548828,5.185547,5.009766,3.460254,2.054004,48.097586],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.069629,92.548828,86.979199,43.505859,-20.566406,0.250417],"state_q99":[26.695898,189.755859,172.96875,88.186816,24.257812,47.412354]},
+ {"part":"DanqingZ__tic_tac_toe_grid_6_raw_4","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_6_raw_4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":112,"train_windows":112,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-3.462891,-3.867188,-2.021484,-2.548828,0.0],"action_q99":[2.197266,3.023438,2.496094,2.373047,2.373047,46.10703],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.191406,90.878906,98.525391,32.625,-67.306641,0.166945],"state_q99":[31.798828,189.140625,175.341797,74.917969,14.326172,45.575958]},
+ {"part":"DanqingZ__tic_tac_toe_grid_7_raw_2","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_7_raw_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":111,"train_windows":111,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.570312,-3.251953,-4.306641,-2.197266,-3.112207,0.0],"action_q99":[3.251953,3.339844,4.079004,2.900391,2.373047,38.509968],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-62.070996,77.783203,70.430273,29.091797,-67.272363,0.0],"state_q99":[31.325098,189.140625,175.429688,90.547559,8.349609,37.96494]},
+ {"part":"DanqingZ__tic_tac_toe_grid_8","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_8","scene_camera":"observation.images.phone","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.177246,-3.691406,-4.21875,-2.210449,-1.595215,0.104932],"action_q99":[3.339844,3.955078,4.658203,2.649902,2.562012,48.719831],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.976562,92.285156,93.928711,50.523926,-52.998047,0.500835],"state_q99":[15.644531,189.667969,173.408203,81.210938,21.972656,48.414024]},
+ {"part":"DanqingZ__tic_tac_toe_grid_9_raw","origin":"molmoact","dataset":"DanqingZ/tic_tac_toe_grid_9_raw","scene_camera":"observation.images.phone","fps":30.0,"built_clips":380,"train_windows":380,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.109375,-2.900391,-3.339844,-1.230469,0.0],"action_q99":[2.109375,1.757812,3.339844,2.285156,1.142578,38.195171],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.287109,91.582031,84.375,15.310547,-18.175781,-0.33389],"state_q99":[27.755859,189.052734,175.429688,86.748047,23.291016,37.779633]},
+ {"part":"DavidYeh0709__so100_david_0610","origin":"molmoact","dataset":"DavidYeh0709/so100_david_0610","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":57,"train_windows":57,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.548828,-2.934668,-1.40625,-0.978223,17.440758],"action_q99":[0.878906,1.681348,2.483789,3.955078,1.142578,45.50995],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.03877,45.711035,-11.865234,-5.109082,-11.777344,18.518518],"state_q99":[13.886719,135.802441,133.880273,101.777344,40.869141,45.84362]},
+ {"part":"DavidYeh0709__so100_david_0610_2","origin":"molmoact","dataset":"DavidYeh0709/so100_david_0610_2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":96,"train_windows":96,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.17334,-2.66748,-3.955078,-1.933594,-0.878906,16.872038],"action_q99":[0.878906,1.964355,3.427734,3.164062,0.791016,33.270142],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.606934,46.199707,-12.304688,12.88916,-12.51123,18.683128],"state_q99":[15.442383,131.286621,113.818359,101.689453,30.585938,33.390947]},
+ {"part":"DoggyDoggyWhatNow__so101_squirtle","origin":"molmoact","dataset":"DoggyDoggyWhatNow/so101_squirtle","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1162,"train_windows":1162,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.427734,-3.603516,-3.427734,-1.933594,-1.669922,-0.257511],"action_q99":[2.8125,2.8125,2.988281,2.197266,2.109375,84.206009],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.421875,38.144531,16.611328,6.855469,-22.763672,0.136426],"state_q99":[89.472656,190.986328,175.693359,95.625,94.833984,83.21965]},
+ {"part":"DorayakiLin__so100_pick_charger_on_tissue","origin":"molmoact","dataset":"DorayakiLin/so100_pick_charger_on_tissue","scene_camera":"observation.images.phone","fps":30.0,"built_clips":739,"train_windows":739,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-3.076172,-2.460938,-2.021484,-2.373047,-0.100806],"action_q99":[1.40625,3.339844,2.8125,1.757812,2.021484,56.25],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.085938,12.568359,-16.875,33.256055,-114.521484,0.156617],"state_q99":[54.492188,180.263672,153.105469,101.777344,21.466406,55.833984]},
+ {"part":"DorayakiLin__so100_pick_cube_in_box","origin":"molmoact","dataset":"DorayakiLin/so100_pick_cube_in_box","scene_camera":"observation.images.phone","fps":30.0,"built_clips":550,"train_windows":550,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.803711,-2.285156,-2.021484,-1.582031,0.0],"action_q99":[1.318359,3.427734,2.548828,1.669922,1.582031,40.625],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.150391,9.404297,-17.929688,30.770508,-59.589844,0.156617],"state_q99":[39.638672,180.439453,153.193359,90.175781,17.666016,40.172279]},
+ {"part":"DorayakiLin__so100_stack_cube","origin":"molmoact","dataset":"DorayakiLin/so100_stack_cube","scene_camera":"observation.images.phone","fps":30.0,"built_clips":211,"train_windows":211,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.515625,-2.636719,-1.606641,-0.966797,-0.100806],"action_q99":[1.142578,3.076172,2.900391,1.230469,1.40625,42.137096],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.348828,13.359375,-17.929688,40.517578,-72.685547,0.234926],"state_q99":[52.470703,180.263672,153.28125,103.447266,-2.988281,41.738449]},
+ {"part":"DorayakiLin__so100_test","origin":"molmoact","dataset":"DorayakiLin/so100_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":31,"train_windows":31,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.251953,-2.109375,-1.872949,-1.757812,-3.7125,0.227273],"action_q99":[2.8125,2.663965,3.042773,1.521387,1.812305,42.954548],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-64.011621,74.53125,82.705078,38.475,-18.687305,0.98832],"state_q99":[5.185547,188.525391,177.011719,79.216699,33.310547,42.407906]},
+ {"part":"DorayakiLin__so100_test_Lucas2","origin":"molmoact","dataset":"DorayakiLin/so100_test_Lucas2","scene_camera":"observation.images.top","fps":30.0,"built_clips":37,"train_windows":37,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.325586,-4.306641,-4.042969,-2.285156,-2.285156,0.227273],"action_q99":[2.237695,5.442188,5.361328,2.109375,2.285156,39.43182],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.102148,38.408203,32.431641,43.925977,-10.235742,0.628931],"state_q99":[25.305469,187.119141,177.626953,94.475391,45.432422,38.903862]},
+ {"part":"DorayakiLin__yzw_so100_stack_cube_v4","origin":"molmoact","dataset":"DorayakiLin/yzw_so100_stack_cube_v4","scene_camera":"observation.images.top","fps":30.0,"built_clips":3530,"train_windows":3530,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.615234,-2.373047,-2.636719,-1.290234,-0.527344,0.0],"action_q99":[0.791016,2.988281,3.164062,1.494141,0.527344,62.485874],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-11.865234,43.59375,29.794922,48.603516,-15.292969,0.443262],"state_q99":[14.150391,189.931641,179.560547,101.865234,11.601562,61.968082]},
+ {"part":"EGLima__so100_test","origin":"molmoact","dataset":"EGLima/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":48,"train_windows":48,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.335254,-2.598926,-1.845703,-1.104785,0.0],"action_q99":[2.021484,3.076172,3.251953,1.230469,0.439453,74.553993],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.595703,21.922559,-5.04668,50.136328,-30.058594,3.384279],"state_q99":[29.35459,187.558594,174.638672,96.943359,18.28125,74.344978]},
+ {"part":"FAlatyr__so101_test100","origin":"molmoact","dataset":"FAlatyr/so101_test100","scene_camera":"observation.images.camera","fps":30.0,"built_clips":191,"train_windows":191,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-4.130859,-4.202051,-3.251953,-3.076172,-0.988426],"action_q99":[2.532129,3.762598,3.955078,4.130859,3.603516,54.398148],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.466797,0.544043,-27.861328,9.052734,-120.498047,0.747943],"state_q99":[61.611328,180.087891,157.148438,94.130859,11.689453,54.001499]},
+ {"part":"FG007__so100_test","origin":"molmoact","dataset":"FG007/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":55,"train_windows":55,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-4.050879,-3.251953,-1.853613,-1.589941,-0.537057],"action_q99":[1.669922,2.548828,2.724609,2.900391,2.724609,74.221268],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.783203,28.732324,23.378906,8.41377,-74.267578,-0.092507],"state_q99":[58.095703,188.484961,179.033203,86.484375,58.630957,74.745605]},
+ {"part":"Fergusonf__so100_test","origin":"molmoact","dataset":"Fergusonf/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":322,"train_windows":322,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.867188,-8.349609,-4.394531,-0.966797,-0.654618],"action_q99":[2.021484,2.8125,5.19873,3.867188,0.966797,83.614456],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.926758,124.325684,-12.041016,-112.939453,-201.019043,0.346741],"state_q99":[7.998047,191.865234,180.351562,-20.087402,-174.221191,83.217751]},
+ {"part":"GALEOTE__so101_test","origin":"molmoact","dataset":"GALEOTE/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":4,"train_windows":4,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-0.351562,-4.47627,-4.876172,-2.800195,-0.084104],"action_q99":[4.618652,0.263672,3.603516,4.361133,0.378809,0.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[18.984375,122.622363,108.544922,-40.514063,10.316602,0.9839],"state_q99":[138.955078,137.109375,180.351562,78.662109,56.300977,8.192308]},
+ {"part":"Gano007__so100_doliprane","origin":"molmoact","dataset":"Gano007/so100_doliprane","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":643,"train_windows":643,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-4.394531,-3.955078,-2.197266,-3.955078,-0.930626],"action_q99":[1.891406,3.076172,4.21875,2.373047,2.548828,43.529612],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.853516,24.082031,-1.318359,25.3125,-121.728516,0.143266],"state_q99":[37.353516,188.964844,172.441406,105.205078,42.978516,42.406879]},
+ {"part":"Gano007__so100_first","origin":"molmoact","dataset":"Gano007/so100_first","scene_camera":"observation.images.phone","fps":30.0,"built_clips":39,"train_windows":39,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.115527,-1.939746,-0.885059,-1.318359,-0.416667],"action_q99":[1.318359,1.933594,1.669922,0.878906,1.142578,27.416666],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.908203,57.744141,29.970703,61.083984,-46.757812,0.345781],"state_q99":[30.322266,188.964844,122.431641,100.898438,-8.876953,27.178423]},
+ {"part":"Gano007__so100_gano","origin":"molmoact","dataset":"Gano007/so100_gano","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1015,"train_windows":1015,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.285156,-2.021484,-1.494141,-1.669922,-0.41806],"action_q99":[1.318359,2.197266,2.285156,1.40625,1.845703,43.227425],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.140625,42.810645,11.425781,33.398438,-110.654297,0.783699],"state_q99":[32.871094,186.503906,173.751855,103.535156,85.341797,43.495296]},
+ {"part":"Gano007__so100_lolo","origin":"molmoact","dataset":"Gano007/so100_lolo","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":285,"train_windows":285,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-1.845703,-2.752734,-1.757812,-1.318359,-0.253807],"action_q99":[1.230469,2.285156,2.548828,2.1375,1.494141,43.824024],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.816406,32.431641,8.876953,-22.531641,-114.873047,0.2149],"state_q99":[60.496875,185.185547,171.650391,104.941406,-0.966797,43.624641]},
+ {"part":"Gano007__so100_medic","origin":"molmoact","dataset":"Gano007/so100_medic","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":631,"train_windows":631,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.945898,-4.042969,-3.691406,-2.373047,-3.164062,-0.761421],"action_q99":[2.109375,3.251953,4.130859,2.8125,2.197266,38.832489],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-69.358008,29.619141,5.612695,19.211133,-136.230469,0.133238],"state_q99":[60.732422,185.449219,172.177734,105.292969,37.47832,38.610313]},
+ {"part":"Gano007__so100_second","origin":"molmoact","dataset":"Gano007/so100_second","scene_camera":"observation.images.phone","fps":30.0,"built_clips":792,"train_windows":792,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.636719,-2.285156,-1.318359,-2.636719,-0.666667],"action_q99":[1.582031,2.8125,2.8125,1.494141,2.109375,40.166668],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.025391,31.728516,8.261719,50.888672,-159.521484,0.207469],"state_q99":[51.416016,188.964844,128.056641,101.162109,51.328125,39.972336]},
+ {"part":"Gano007__so100_test","origin":"molmoact","dataset":"Gano007/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":52,"train_windows":52,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.669922,-1.757812,-1.40625,-1.054688,-0.424448],"action_q99":[0.966797,1.40625,1.845703,1.851855,0.878906,52.122242],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.146484,76.025391,52.809961,-6.064453,-97.207031,0.554529],"state_q99":[34.980469,188.4375,179.648438,85.078125,-61.699219,51.663582]},
+ {"part":"Gano007__so100_testfull","origin":"molmoact","dataset":"Gano007/so100_testfull","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1158,"train_windows":1158,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-3.603516,-3.339844,-2.197266,-2.373047,-0.509338],"action_q99":[1.494141,2.548828,3.427734,2.285156,1.845703,70.458405],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-58.183594,28.300781,12.216797,-1.230469,-116.060449,0.462107],"state_q99":[39.199219,193.183594,179.296875,93.251953,60.205078,71.07209]},
+ {"part":"Haribot099__so101_60","origin":"molmoact","dataset":"Haribot099/so101_60","scene_camera":"observation.images.phone","fps":30.0,"built_clips":977,"train_windows":977,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.164062,-2.636719,-2.197266,-3.515625,-0.081967],"action_q99":[1.669922,2.636719,2.988281,2.109375,3.164062,39.672131],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.231152,26.279297,29.443359,9.580078,-11.513672,0.276243],"state_q99":[34.541016,196.435547,185.097656,101.953125,156.445312,39.767263]},
+ {"part":"Haribot099__so101_test","origin":"molmoact","dataset":"Haribot099/so101_test","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":37,"train_windows":37,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.404688,-2.300977,-3.443555,-1.582031,2.216749],"action_q99":[1.40625,2.636719,4.426172,3.723047,2.420508,55.665024],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.556641,33.662109,32.695312,5.354297,-22.148438,5.782313],"state_q99":[39.287109,193.535156,181.40625,95.625,60.644531,55.374153]},
+ {"part":"Haribot099__so101_test1","origin":"molmoact","dataset":"Haribot099/so101_test1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":38,"train_windows":38,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.460938,-1.924805,-1.924805,-0.782227,0.081967],"action_q99":[0.791016,2.021484,2.724609,2.285156,0.958008,45.983608],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.349609,46.230469,35.956055,11.425781,-9.404297,0.483425],"state_q99":[46.933594,194.853516,185.361328,88.488281,17.050781,45.787292]},
+ {"part":"HarrisonLee24__so100_test","origin":"molmoact","dataset":"HarrisonLee24/so100_test","scene_camera":"observation.images.global_cam","fps":30.0,"built_clips":2704,"train_windows":2704,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.515625,-3.867188,-2.8125,-3.164062,-0.284091],"action_q99":[1.582031,4.21875,4.833984,2.8125,2.724609,45.549244],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.529297,71.71875,51.495117,38.759766,-81.650391,0.334448],"state_q99":[36.5625,194.501953,181.142578,103.007812,39.726562,44.64883]},
+ {"part":"HarrisonLee24__so100_test-1","origin":"molmoact","dataset":"HarrisonLee24/so100_test-1","scene_camera":"observation.images.action_cam","fps":30.0,"built_clips":69,"train_windows":69,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.988281,-4.570312,-4.306641,-2.988281,-3.955078,-2.436647],"action_q99":[2.724609,4.306641,3.164062,3.164062,2.548828,45.02924],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-53.701172,46.771875,47.285156,37.880859,-73.740234,-2.304965],"state_q99":[59.714648,188.525391,179.384766,98.876953,73.626855,44.640958]},
+ {"part":"Hennadiy__so100_50","origin":"molmoact","dataset":"Hennadiy/so100_50","scene_camera":"observation.images.phone","fps":30.0,"built_clips":727,"train_windows":727,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.900391,-2.724609,-1.582031,-1.757812,-0.124844],"action_q99":[0.966797,3.779297,3.515625,1.494141,1.494141,55.805241],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[18.017578,36.826172,26.361914,46.313086,43.588477,0.840336],"state_q99":[55.810547,182.285156,165.849609,93.339844,182.724609,54.453785]},
+ {"part":"HuoYixiao__so101_test","origin":"molmoact","dataset":"HuoYixiao/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":997,"train_windows":997,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-2.724609,-2.373047,-1.494141,-0.878906,-0.407498],"action_q99":[2.109375,2.900391,3.076172,1.494141,0.791016,59.087204],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-103.007812,39.550781,26.103516,43.945312,-49.306641,0.527704],"state_q99":[36.914062,193.535156,179.824219,96.943359,22.148438,58.751099]},
+ {"part":"InfiH__so100_test","origin":"molmoact","dataset":"InfiH/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.006543,-1.742871,-1.757812,-1.582031,-1.56709,-0.25729],"action_q99":[1.303418,1.669922,1.669922,1.918652,2.636719,33.190395],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[16.523438,89.824219,-172.089844,10.722656,-98.4375,1.232539],"state_q99":[86.396484,186.855469,-74.591016,81.826172,-0.175781,32.621201]},
+ {"part":"JackLiuX__so100_test_candy","origin":"molmoact","dataset":"JackLiuX/so100_test_candy","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":708,"train_windows":708,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.021484,-1.933594,-1.142578,-1.494141,-8.959044],"action_q99":[1.230469,1.845703,2.021484,1.318359,1.230469,38.651878],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.539062,45.527344,45.878906,33.662109,-46.757812,-7.933399],"state_q99":[35.332031,194.414062,182.8125,81.650391,72.158203,38.39373]},
+ {"part":"JackLiuX__so100_test_candy_new","origin":"molmoact","dataset":"JackLiuX/so100_test_candy_new","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1898,"train_windows":1898,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.582031,-1.318359,-0.878906,-1.318359,-1.320132],"action_q99":[0.966797,1.582031,1.494141,0.791016,1.230469,40.594059],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.357422,63.984375,70.664062,27.949219,-68.90625,-0.990099],"state_q99":[65.126953,194.501953,178.505859,74.970703,16.083984,40.264027]},
+ {"part":"Jeevesh2009__so101_gray_block_lowvar_test","origin":"molmoact","dataset":"Jeevesh2009/so101_gray_block_lowvar_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":1336,"train_windows":1336,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-3.339844,-2.197266,-1.582031,-1.230469,0.082508],"action_q99":[2.724609,3.076172,2.548828,1.582031,0.966797,34.983498],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.773438,72.421875,70.224609,47.8125,-8.876953,0.766017],"state_q99":[6.943359,189.580078,175.517578,93.955078,36.650391,34.88858]},
+ {"part":"Jeevesh2009__so101_gray_block_midvar_test","origin":"molmoact","dataset":"Jeevesh2009/so101_gray_block_midvar_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":1329,"train_windows":1329,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.8125,-1.933594,-1.669922,-1.318359,0.0],"action_q99":[2.8125,2.988281,2.460938,1.669922,0.966797,30.528053],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.992188,74.824805,74.297461,46.142578,-34.277344,0.696379],"state_q99":[5.595117,189.755859,174.814453,93.251953,45.527344,30.013927]},
+ {"part":"Jeevesh2009__so101_gray_block_pickup_test","origin":"molmoact","dataset":"Jeevesh2009/so101_gray_block_pickup_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":662,"train_windows":662,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-5.449219,-3.515625,-2.373047,-1.230469,0.082508],"action_q99":[3.515625,4.746094,3.427734,2.460938,1.142578,38.448845],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.71875,63.984375,81.914062,43.471582,-22.006934,0.766017],"state_q99":[7.119141,187.822266,178.417969,94.042969,20.566406,37.883007]},
+ {"part":"Jeevesh2009__so101_new_test","origin":"molmoact","dataset":"Jeevesh2009/so101_new_test","scene_camera":"observation.images.realsense2","fps":30.0,"built_clips":1195,"train_windows":1195,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.900391,-2.548828,-1.845703,-1.669922,0.0],"action_q99":[1.757812,2.460938,2.8125,1.582031,1.318359,43.755104],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.306641,34.101562,13.710938,35.618555,-98.701172,0.075643],"state_q99":[71.982422,194.501953,177.539062,105.644531,53.789062,42.965202]},
+ {"part":"Jeevesh2009__so101_test","origin":"molmoact","dataset":"Jeevesh2009/so101_test","scene_camera":"observation.images.realsense2","fps":30.0,"built_clips":1195,"train_windows":1195,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.900391,-2.548828,-1.845703,-1.669922,0.0],"action_q99":[1.757812,2.460938,2.8125,1.582031,1.318359,43.755104],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.306641,34.101562,13.710938,35.618555,-98.701172,0.075643],"state_q99":[71.982422,194.501953,177.539062,105.644531,53.789062,42.965202]},
+ {"part":"Jiangeng__so100_413","origin":"molmoact","dataset":"Jiangeng/so100_413","scene_camera":"observation.images.wrist_left","fps":30.0,"built_clips":637,"train_windows":637,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-1.142578,-2.548828,-2.373047,-1.40625,-1.582031,-0.101523],"action_q99":[1.142578,2.197266,2.021484,1.494141,1.494141,47.817261],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-48.164062,49.394531,42.451172,35.81543,-59.458008,0.149477],"state_q99":[51.899414,187.998047,176.132812,93.339844,53.525391,47.570999]},
+ {"part":"JimmyPeng02__so100_test_2","origin":"molmoact","dataset":"JimmyPeng02/so100_test_2","scene_camera":"observation.images.realsense2","fps":30.0,"built_clips":60,"train_windows":60,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.373047,-2.285156,-1.235742,-1.318359,0.426985],"action_q99":[1.230469,2.109375,2.548828,1.230469,0.966797,52.860802],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.776367,42.539062,47.944336,64.511719,-90.74707,1.322418],"state_q99":[41.791992,173.144531,176.000977,103.710938,-26.674805,52.51889]},
+ {"part":"JimmyPeng02__so100_test_6","origin":"molmoact","dataset":"JimmyPeng02/so100_test_6","scene_camera":"observation.images.realsense1","fps":30.0,"built_clips":1021,"train_windows":1021,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.285156,-2.197266,-1.757812,-2.8125,0.085397],"action_q99":[1.318359,2.109375,2.460938,1.845703,2.900391,33.561058],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-57.348633,45.703125,37.133789,14.765625,-53.305664,0.881612],"state_q99":[41.44043,193.183594,181.450195,93.691406,183.735352,33.123425]},
+ {"part":"Jinheng0130__Catch","origin":"molmoact","dataset":"Jinheng0130/Catch","scene_camera":"observation.images.flower","fps":30.0,"built_clips":807,"train_windows":807,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.40625,-1.757812,-1.054688,-0.439453,2.440828],"action_q99":[0.703125,1.318359,1.757812,1.054688,0.439453,57.840237],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.96875,27.949219,52.382812,-87.978516,-104.0625,3.216156],"state_q99":[2.109375,122.431641,177.890625,-29.619141,-81.738281,57.842932]},
+ {"part":"Jinheng0130__Lay","origin":"molmoact","dataset":"Jinheng0130/Lay","scene_camera":"observation.images.flower","fps":30.0,"built_clips":697,"train_windows":697,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-1.669922,-1.933594,-0.791016,-0.527344,3.402367],"action_q99":[1.142578,2.021484,2.021484,0.966797,0.439453,64.775888],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-7.098926,33.574219,69.805371,-86.572266,-94.570312,7.479432],"state_q99":[56.513672,130.693359,178.154297,-42.099609,-80.771484,64.622292]},
+ {"part":"Jinheng0130__Look","origin":"molmoact","dataset":"Jinheng0130/Look","scene_camera":"observation.images.flower","fps":30.0,"built_clips":252,"train_windows":252,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.251953,-5.097656,-5.712891,-7.382812,-7.910156,-0.147929],"action_q99":[4.394531,1.142578,3.779297,6.152344,8.173828,15.162722],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-88.066406,76.574707,51.503906,-49.042969,-97.492676,0.52356],"state_q99":[2.900391,191.953125,179.912109,86.923828,25.576172,15.25804]},
+ {"part":"KeisukeSato1024__so101_pp_green_box_2cam","origin":"molmoact","dataset":"KeisukeSato1024/so101_pp_green_box_2cam","scene_camera":"observation.images.sideview","fps":30.0,"built_clips":72,"train_windows":72,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.460938,-2.285156,-2.109375,-2.197266,0.0757],"action_q99":[1.494141,2.724609,2.285156,2.197266,2.460938,50.946255],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.059863,49.536914,54.84375,29.569043,-129.023438,0.484429],"state_q99":[71.609766,195.908203,179.296875,99.052734,62.138672,50.65744]},
+ {"part":"LT1212__dataset_catch_the_pen","origin":"molmoact","dataset":"LT1212/dataset_catch_the_pen","scene_camera":"observation.images.Logic_camera","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.714941,-2.460938,-1.230469,-1.484473,-0.213904],"action_q99":[0.878906,1.845703,2.197266,1.494141,1.40625,44.884491],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.976562,68.203125,85.703027,28.329785,-100.810547,0.524934],"state_q99":[34.101562,189.492188,179.208984,88.505859,-41.572266,44.415575]},
+ {"part":"LT1212__dataset_catch_the_pene","origin":"molmoact","dataset":"LT1212/dataset_catch_the_pene","scene_camera":"observation.images.Logic_camera","fps":30.0,"built_clips":348,"train_windows":348,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.548828,-2.460938,-1.757812,-0.834082,-0.213904],"action_q99":[0.966797,2.197266,2.373047,2.021484,0.703125,48.394652],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-12.962988,41.001855,40.166016,0.087891,-116.71875,0.524934],"state_q99":[32.607422,189.580078,179.208984,86.572266,-51.152344,47.506561]},
+ {"part":"LeRobot-worldwide-hackathon__191-Dum-E-so100-fries","origin":"molmoact","dataset":"LeRobot-worldwide-hackathon/191-Dum-E-so100-fries","scene_camera":"observation.images.front","fps":30.0,"built_clips":736,"train_windows":736,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.548828,-2.285156,-1.054688,-2.109375,0.400802],"action_q99":[1.230469,2.285156,2.197266,1.669922,2.021484,34.669338],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.365234,45.0,33.837891,43.681641,-147.65625,0.660793],"state_q99":[25.281738,188.789062,175.78125,96.767578,-19.863281,34.188692]},
+ {"part":"LeRobot-worldwide-hackathon__246-Golf","origin":"molmoact","dataset":"LeRobot-worldwide-hackathon/246-Golf","scene_camera":"observation.images.phone","fps":30.0,"built_clips":744,"train_windows":744,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.548828,-2.285156,-1.669922,-1.230469,0.0],"action_q99":[1.230469,3.076172,3.515625,1.845703,1.142578,62.222225],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-74.882812,41.044922,10.634766,34.101562,50.097656,0.97166],"state_q99":[44.384766,191.865234,178.857422,95.097656,132.363281,59.028339]},
+ {"part":"Loki0929__so100_duck","origin":"molmoact","dataset":"Loki0929/so100_duck","scene_camera":"observation.images.third","fps":30.0,"built_clips":4634,"train_windows":4634,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.658203,-4.833984,-5.712891,-5.361328,-3.603516,0.0],"action_q99":[4.130859,5.273438,7.207031,7.382812,4.042969,50.090416],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.957031,42.451172,21.972656,-11.689453,-104.765625,0.332779],"state_q99":[43.59375,189.667969,178.330078,95.625,-28.844824,49.500832]},
+ {"part":"Loki0929__so100_lan","origin":"molmoact","dataset":"Loki0929/so100_lan","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":7886,"train_windows":7886,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.130859,-4.394531,-5.185547,-3.867188,-2.197266,0.0],"action_q99":[3.515625,5.273438,6.152344,4.306641,2.548828,49.638336],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-70.274707,33.574219,24.082031,-39.287109,-109.6875,0.499168],"state_q99":[102.216797,190.634766,178.681641,97.558594,-23.027344,49.500832]},
+ {"part":"Louisnbt__so100_test7","origin":"molmoact","dataset":"Louisnbt/so100_test7","scene_camera":"observation.images.phone","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.512598,-1.952051,-1.845703,-1.669922,-0.439453,-0.156863],"action_q99":[1.40625,1.933594,2.285156,1.318359,0.527344,34.901962],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.644531,111.70459,96.837012,35.928809,-15.205078,0.377929],"state_q99":[1.952051,204.960938,180.966797,77.958984,0.0,34.542706]},
+ {"part":"M3thRocks__so101_test12","origin":"molmoact","dataset":"M3thRocks/so101_test12","scene_camera":"observation.images.phone","fps":30.0,"built_clips":34,"train_windows":34,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.268262,-3.465527,-2.8125,-1.318359,-1.080176,0.085397],"action_q99":[1.40625,3.729199,3.603516,1.230469,1.444043,35.439796],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.719336,31.201172,6.064453,57.05332,-44.384766,0.530303],"state_q99":[56.162109,198.105469,182.021484,101.162109,-15.205078,35.378788]},
+ {"part":"M3thRocks__so101_test13","origin":"molmoact","dataset":"M3thRocks/so101_test13","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1074,"train_windows":1074,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.373047,-1.933594,-0.703125,-0.439453,0.0],"action_q99":[0.703125,2.021484,1.845703,0.703125,0.527344,38.599487],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.943359,47.373047,23.554688,61.611328,-20.830078,0.454545],"state_q99":[52.646484,198.105469,181.845703,101.25,16.875,38.560604]},
+ {"part":"M3thRocks__so101_test2","origin":"molmoact","dataset":"M3thRocks/so101_test2","scene_camera":"observation.images.top","fps":30.0,"built_clips":1082,"train_windows":1082,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.285156,-1.933594,-0.791016,-0.615234,0.0],"action_q99":[1.054688,1.845703,1.582031,0.878906,0.527344,69.19502],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.800781,46.582031,47.197266,62.753906,-37.880859,0.462107],"state_q99":[52.822266,190.810547,169.716797,105.644531,-0.615234,69.112755]},
+ {"part":"M3thRocks__so101_test_test","origin":"molmoact","dataset":"M3thRocks/so101_test_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.109375,-2.197266,-2.021484,-0.878906,0.0],"action_q99":[1.40625,3.076172,2.295703,1.40625,0.878906,41.337759],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.876953,59.589844,46.757812,41.653125,-28.617188,0.369686],"state_q99":[56.074219,190.898438,171.210938,105.380859,6.426562,41.519408]},
+ {"part":"MaChengyang__so100_test","origin":"molmoact","dataset":"MaChengyang/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":690,"train_windows":690,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.427734,-2.8125,-1.669922,-1.494141,-0.243309],"action_q99":[1.494141,3.427734,3.339844,1.582031,1.318359,52.47364],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.5625,24.000293,19.335938,38.232422,-22.587891,0.535988],"state_q99":[27.861328,189.316406,178.857422,90.439453,25.927734,51.837673]},
+ {"part":"MarkoBrie__so101_banana","origin":"molmoact","dataset":"MarkoBrie/so101_banana","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.670312,-2.758008,-1.791211,-0.594141,-0.391543],"action_q99":[1.40625,2.460938,2.385352,2.230664,0.263672,46.51527],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.900586,50.185547,42.451172,22.148438,-11.425781,0.841751],"state_q99":[21.884766,191.689453,177.626953,99.228516,-0.439453,46.21212]},
+ {"part":"Maski211123__so100_test0","origin":"molmoact","dataset":"Maski211123/so100_test0","scene_camera":"observation.images.top","fps":30.0,"built_clips":33,"train_windows":33,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.285156,-2.568164,-1.757812,-1.972266,0.0],"action_q99":[1.494141,4.57998,4.238086,1.40625,2.206934,28.024193],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.969922,48.251953,30.146484,53.847949,-43.700098,0.087489],"state_q99":[10.47832,185.449219,169.365234,95.136328,-9.052734,27.131234]},
+ {"part":"Mazytomo__so101_test","origin":"molmoact","dataset":"Mazytomo/so101_test","scene_camera":"observation.images.head","fps":30.0,"built_clips":162,"train_windows":162,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.164062,-3.515625,-1.757812,-1.230469,-0.264084],"action_q99":[2.197266,3.691406,4.042969,2.021484,1.40625,31.073942],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-69.873047,17.226562,-8.135156,32.241797,-3.779297,0.13708],"state_q99":[8.613281,196.787109,176.220703,100.986328,64.996875,31.185743]},
+ {"part":"Metabolik__so101_test","origin":"molmoact","dataset":"Metabolik/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":37,"train_windows":37,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.439453,-2.988281,-2.021484,-2.030273,-0.615234,-0.253593],"action_q99":[0.439453,2.197266,3.076172,2.302734,0.615234,52.620457],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[2.285156,-13.271484,-6.855469,1.494141,-12.568359,0.0],"state_q99":[10.546875,188.789062,175.693359,86.844727,7.734375,52.412372]},
+ {"part":"Mohamedal__put_banana","origin":"molmoact","dataset":"Mohamedal/put_banana","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":636,"train_windows":636,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.933594,-2.109375,-1.142578,-1.142578,-0.275482],"action_q99":[0.966797,2.109375,2.636719,1.230469,1.318359,45.270889],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.375,26.455078,15.380859,18.272461,-77.374512,0.420168],"state_q99":[53.789062,190.019531,176.220703,91.757812,49.482422,44.887955]},
+ {"part":"Mohamedal__put_banana_bowl_dis","origin":"molmoact","dataset":"Mohamedal/put_banana_bowl_dis","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":878,"train_windows":878,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.021484,-2.197266,-1.230469,-1.669922,-0.367309],"action_q99":[1.054688,2.197266,2.636719,1.230469,1.494141,42.883381],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.552734,29.707031,14.400879,48.867188,-101.777344,0.630252],"state_q99":[64.160156,190.019531,180.263672,104.414062,38.320312,42.296917]},
+ {"part":"Mohamedal__put_banana_bowl_last_test","origin":"molmoact","dataset":"Mohamedal/put_banana_bowl_last_test","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":762,"train_windows":762,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.021484,-2.548828,-3.076172,-1.054688,0.09542],"action_q99":[1.845703,2.109375,3.427734,2.373047,1.054688,71.660301],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.603516,39.375,14.589844,8.701172,-15.732422,0.189466],"state_q99":[37.441406,188.349609,177.978516,107.841797,46.757812,62.372112]},
+ {"part":"Mohamedal__put_banana_bowl_new_data","origin":"molmoact","dataset":"Mohamedal/put_banana_bowl_new_data","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":747,"train_windows":747,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.373047,-2.900391,-2.460938,-1.494141,0.091743],"action_q99":[2.285156,2.724609,3.427734,1.933594,1.494141,77.522934],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-65.214844,21.269531,6.767578,33.487207,-29.882812,0.354862],"state_q99":[33.662109,184.570312,178.417969,103.535156,74.619141,77.50177]},
+ {"part":"Mohamedal__put_cube_bowl","origin":"molmoact","dataset":"Mohamedal/put_cube_bowl","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":825,"train_windows":825,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.845703,-2.197266,-2.109375,-0.791016,0.09542],"action_q99":[1.582031,2.109375,3.076172,1.757812,0.878906,66.984734],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.78125,37.089844,8.386523,16.523438,-13.974609,0.189466],"state_q99":[34.804688,188.261719,177.626953,107.314453,37.880859,61.652142]},
+ {"part":"Mohamedal__put_lemon_bowl_data","origin":"molmoact","dataset":"Mohamedal/put_lemon_bowl_data","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":810,"train_windows":810,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.285156,-2.724609,-2.8125,-1.933594,0.183486],"action_q99":[2.373047,2.8125,3.339844,1.933594,1.40625,73.30275],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.554688,21.796875,8.465625,33.75,-30.146484,0.567779],"state_q99":[33.106641,184.482422,178.417969,103.535156,76.201172,72.746628]},
+ {"part":"Mohamedal__put_peach_bowl_dis","origin":"molmoact","dataset":"Mohamedal/put_peach_bowl_dis","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":678,"train_windows":678,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-1.933594,-2.285156,-1.757812,-1.582031,-0.367309],"action_q99":[1.054688,2.460938,2.724609,1.40625,1.757812,52.617081],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.585938,34.010156,17.226562,48.955078,-103.623047,0.630252],"state_q99":[68.642578,189.931641,180.175781,104.589844,35.595703,51.960785]},
+ {"part":"Mohamedal__put_plum_bowl_dis","origin":"molmoact","dataset":"Mohamedal/put_plum_bowl_dis","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":654,"train_windows":654,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.021484,-2.285156,-2.021484,-1.142578,-0.367309],"action_q99":[0.966797,2.373047,2.900391,1.582031,1.318359,51.331497],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.486328,39.726562,17.929688,45.351562,-66.269531,0.630252],"state_q99":[68.642578,189.931641,180.351562,104.326172,8.251172,50.980392]},
+ {"part":"Mohamedal__so100_put_bananda_bowl_newda","origin":"molmoact","dataset":"Mohamedal/so100_put_bananda_bowl_newda","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":737,"train_windows":737,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.977344,-2.197266,-2.636719,-2.548828,-1.054688,0.192123],"action_q99":[1.845703,2.373047,3.427734,2.109375,0.966797,74.639771],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.923828,31.992188,17.666016,27.059766,-18.720703,1.185771],"state_q99":[37.529297,188.085938,179.384766,103.183594,42.890625,74.31779]},
+ {"part":"Mohamedal__so100_put_plum_bowl_new_data","origin":"molmoact","dataset":"Mohamedal/so100_put_plum_bowl_new_data","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":727,"train_windows":727,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.724609,-3.339844,-2.900391,-2.021484,0.183486],"action_q99":[2.460938,3.164062,4.042969,2.373047,1.757812,76.055046],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.027344,13.710938,-6.927539,28.843945,-32.783203,0.496806],"state_q99":[29.970703,184.570312,178.59375,103.535156,85.150195,75.230659]},
+ {"part":"Mohamedal__so100_test_peach_ddata","origin":"molmoact","dataset":"Mohamedal/so100_test_peach_ddata","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":771,"train_windows":771,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.636719,-3.515625,-2.460938,-2.197266,0.183486],"action_q99":[2.548828,3.251953,3.955078,2.373047,1.669922,75.596329],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.90625,24.697266,11.601562,33.398438,-33.662109,0.496806],"state_q99":[31.552734,184.570312,178.505859,103.535156,79.453125,75.230659]},
+ {"part":"MrAnton__so101_test","origin":"molmoact","dataset":"MrAnton/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":84,"train_windows":84,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.8125,-2.285156,-1.933594,-3.450586,-0.172712],"action_q99":[2.109375,2.548828,2.285156,2.132227,2.636719,30.569946],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.98457,56.162109,69.345703,12.128906,-195.820312,0.278746],"state_q99":[61.809961,191.953125,170.244141,68.818359,-80.683594,30.452961]},
+ {"part":"Mwuqiu__Pick_up_the_Yellow_Duck_Careless","origin":"molmoact","dataset":"Mwuqiu/Pick_up_the_Yellow_Duck_Careless","scene_camera":"observation.images.topview","fps":30.0,"built_clips":423,"train_windows":423,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.724609,-2.460938,-1.669922,-1.142578,-1.806084],"action_q99":[1.494141,2.8125,3.251953,1.582031,1.054688,45.152092],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.439453,38.583984,25.664062,24.873047,-41.923828,-0.802855],"state_q99":[24.257812,184.921875,173.583984,64.863281,10.986328,44.781448]},
+ {"part":"Mwuqiu__Pick_up_the_Yellow_Duck_Precise","origin":"molmoact","dataset":"Mwuqiu/Pick_up_the_Yellow_Duck_Precise","scene_camera":"observation.images.topview","fps":30.0,"built_clips":413,"train_windows":413,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.109375,-1.845703,-1.582031,-0.527344,-1.806084],"action_q99":[1.142578,2.109375,2.636719,1.142578,0.703125,36.026615],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.636719,35.244141,27.597656,35.507812,-28.366699,-0.713648],"state_q99":[17.138672,185.009766,173.759766,64.775391,5.009766,35.59322]},
+ {"part":"Mwuqiu__So100_Four_Tasks","origin":"molmoact","dataset":"Mwuqiu/So100_Four_Tasks","scene_camera":"observation.images.topview","fps":30.0,"built_clips":1523,"train_windows":1523,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.724609,-2.548828,-2.197266,-1.054688,-1.901141],"action_q99":[2.197266,2.988281,3.515625,1.933594,1.142578,46.482891],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.382812,39.287109,25.3125,25.400391,-49.48418,-0.802855],"state_q99":[23.116992,185.097656,173.671875,64.599609,9.580078,46.030331]},
+ {"part":"Mwuqiu__pickup_ducks","origin":"molmoact","dataset":"Mwuqiu/pickup_ducks","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":870,"train_windows":870,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-2.988281,-2.8125,-2.021484,-0.703125,-1.174168],"action_q99":[1.669922,2.988281,3.515625,1.583789,0.703125,41.291584],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-81.035156,27.597656,2.988281,35.507812,-25.751953,-0.673401],"state_q99":[42.626953,186.767578,179.296875,88.769531,0.966797,40.994951]},
+ {"part":"Mwuqiu__so100_0408","origin":"molmoact","dataset":"Mwuqiu/so100_0408","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":339,"train_windows":339,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.636719,-2.197266,-1.142578,-0.791016,-0.782779],"action_q99":[0.966797,2.724609,2.8125,1.318359,0.527344,28.669275],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.146484,59.414062,37.880859,33.837891,-56.221875,-0.167224],"state_q99":[7.294922,187.03125,175.517578,92.460938,-1.054688,28.344482]},
+ {"part":"Mwuqiu__so100_0408_muti","origin":"molmoact","dataset":"Mwuqiu/so100_0408_muti","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":997,"train_windows":997,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.373047,-2.460938,-1.230469,-0.966797,-0.880626],"action_q99":[1.054688,2.548828,3.164062,1.230469,0.703125,31.898239],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-53.349609,50.097656,28.300781,45.966797,-36.826172,-0.334448],"state_q99":[21.926074,186.943359,176.835938,93.251953,-4.306641,31.856188]},
+ {"part":"Mwuqiu__so100_point_first_0422","origin":"molmoact","dataset":"Mwuqiu/so100_point_first_0422","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":261,"train_windows":261,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.285156,-2.548828,-1.494141,-0.351562,-1.174168],"action_q99":[1.318359,2.285156,2.900391,1.40625,0.351562,-0.097847],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.275391,67.324219,62.138672,38.671875,-10.722656,1.254181],"state_q99":[0.826172,186.767578,177.802734,91.792969,2.988281,1.337793]},
+ {"part":"Mwuqiu__so100_point_first_ns","origin":"molmoact","dataset":"Mwuqiu/so100_point_first_ns","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":337,"train_windows":337,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.164062,-2.988281,-0.878906,-0.527344,-1.174168],"action_q99":[0.263672,0.263672,0.703125,1.054688,0.703125,-0.097847],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-55.810547,46.879102,37.617188,28.564453,-10.634766,1.086957],"state_q99":[2.724609,186.503906,177.890625,72.124805,4.921875,1.254181]},
+ {"part":"Mwuqiu__so100_pointit_0422","origin":"molmoact","dataset":"Mwuqiu/so100_pointit_0422","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":677,"train_windows":677,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.724609,-2.900391,-1.582031,-0.439453,-1.272016],"action_q99":[1.230469,2.8125,3.076172,1.582031,0.527344,0.684932],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-56.25,30.84082,4.21875,26.279297,-15.996094,1.254181],"state_q99":[7.294922,186.767578,177.890625,85.449023,7.646484,1.588629]},
+ {"part":"Mwuqiu__so100_test","origin":"molmoact","dataset":"Mwuqiu/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.6875,-3.269531,-3.779297,-2.478516,-0.544922,-3.804247],"action_q99":[1.757812,2.742188,3.955078,2.373047,0.615234,29.639889],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.644531,39.199219,32.607422,64.599609,-13.464844,-1.923077],"state_q99":[8.525391,191.25,171.914062,95.273438,-3.427734,29.264214]},
+ {"part":"Mwuqiu__so100_test_0","origin":"molmoact","dataset":"Mwuqiu/so100_test_0","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":36,"train_windows":36,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.719141,-3.121875,-2.8125,-2.109375,-0.355078,-3.416436],"action_q99":[1.318359,2.682422,4.833984,1.891406,0.263672,31.996306],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.265625,51.679688,42.539062,54.667969,-10.019531,-1.839465],"state_q99":[10.898438,167.783203,166.376953,95.273438,-1.054688,31.772575]},
+ {"part":"Odog16__so100_cube_drop_pick_v1","origin":"molmoact","dataset":"Odog16/so100_cube_drop_pick_v1","scene_camera":"observation.images.workspace","fps":30.0,"built_clips":326,"train_windows":326,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-4.582617,-4.306641,-2.636719,-3.251953,-0.398406],"action_q99":[2.724609,5.712891,3.867188,2.988281,3.251953,34.462151],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.087891,52.558594,56.513672,34.365234,-114.885352,0.350385],"state_q99":[50.712891,189.140625,177.1875,96.152344,-26.191406,33.496849]},
+ {"part":"Odog16__so100_test","origin":"molmoact","dataset":"Odog16/so100_test","scene_camera":"observation.images.workspace","fps":30.0,"built_clips":28,"train_windows":28,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.230469,-1.054688,-0.703125,-1.142578,-0.100301],"action_q99":[1.054688,2.109375,2.460938,0.878906,0.527344,29.928786],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-1.001074,84.726562,99.404297,47.548828,-117.49043,0.21097],"state_q99":[48.164062,190.898438,180.966797,77.255859,-62.631738,29.184246]},
+ {"part":"Odog16__so100_test_2","origin":"molmoact","dataset":"Odog16/so100_test_2","scene_camera":"observation.images.workspace","fps":30.0,"built_clips":319,"train_windows":319,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.339844,-3.427734,-3.164062,-3.867188,-4.130859,-0.100301],"action_q99":[3.455859,3.515625,3.251953,3.603516,3.339844,42.828484],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.035937,44.005078,40.461328,2.903906,-159.454688,0.21097],"state_q99":[86.424609,191.425781,180.878906,88.709766,2.664844,41.772152]},
+ {"part":"Odog16__so100_test_2.1","origin":"molmoact","dataset":"Odog16/so100_test_2.1","scene_camera":"observation.images.workspace","fps":30.0,"built_clips":422,"train_windows":422,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.955078,-3.779297,-3.515625,-4.306641,-4.394531,-0.498008],"action_q99":[4.21875,4.130859,4.042969,4.042969,3.780176,44.023903],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.673828,40.429688,37.265625,-12.658008,-157.587891,0.352609],"state_q99":[85.605469,188.525391,177.539062,101.601562,-5.888672,42.242596]},
+ {"part":"OlivierBautista__so100_capsules","origin":"molmoact","dataset":"OlivierBautista/so100_capsules","scene_camera":"observation.images.12heure","fps":30.0,"built_clips":64,"train_windows":64,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-3.526172,-4.21875,-2.710547,-1.51875,-0.723327],"action_q99":[3.076172,3.100781,4.658203,2.988281,1.543359,41.500904],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.087891,17.226562,-2.724609,54.580078,-77.958984,0.988003],"state_q99":[43.066406,189.228516,179.033203,105.205078,-34.277344,40.790401]},
+ {"part":"PPYH__so100_test","origin":"molmoact","dataset":"PPYH/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":17,"train_windows":17,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-5.443945,-3.513867,-2.45918,-2.19375,0.0],"action_q99":[2.54707,5.976562,5.621484,2.986523,2.102344,35.342807],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.662109,67.236328,72.773438,56.696484,-80.681836,0.502934],"state_q99":[38.408203,194.589844,179.384766,81.295313,-42.363281,34.700754]},
+ {"part":"PearlWhite__so101_boll","origin":"molmoact","dataset":"PearlWhite/so101_boll","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.449316,-3.469043,-3.691406,-3.251953,-2.328223,-0.499168],"action_q99":[1.494141,1.582031,1.845703,4.78916,2.152441,69.71714],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-56.337891,52.646484,41.132812,7.606934,-129.814453,6.339468],"state_q99":[-1.363184,174.285352,170.023535,93.427734,-10.283203,68.91343]},
+ {"part":"RASPIAUDIO__so100_test","origin":"molmoact","dataset":"RASPIAUDIO/so100_test","scene_camera":"observation.images.CRANE","fps":30.0,"built_clips":53,"train_windows":53,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.603516,-3.076172,-2.021484,-4.833984,-0.34662],"action_q99":[1.45459,2.900391,4.275879,2.988281,6.728027,85.61525],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.814453,34.562988,-20.302734,-109.177734,-227.94873,0.0],"state_q99":[37.089844,197.753906,177.1875,100.898438,77.080078,85.762482]},
+ {"part":"RASPIAUDIO__so100_test4","origin":"molmoact","dataset":"RASPIAUDIO/so100_test4","scene_camera":"observation.images.TOP","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.020605,-2.285156,-1.845703,-2.020605,-0.703125,-0.17331],"action_q99":[1.756934,2.460938,2.900391,1.933594,1.054688,55.454075],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.295996,52.998047,24.960938,28.916016,-110.654297,0.74224],"state_q99":[18.983496,190.986328,175.429688,95.888672,-68.291016,54.646422]},
+ {"part":"RASPIAUDIO__so100_test7","origin":"molmoact","dataset":"RASPIAUDIO/so100_test7","scene_camera":"observation.images.TOP","fps":30.0,"built_clips":271,"train_windows":271,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-4.352344,-4.658203,-3.515625,-3.076172,0.0],"action_q99":[2.373047,3.691406,3.427734,3.867188,2.988281,50.04506],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-73.388672,60.029297,65.872266,-4.306641,-149.150391,0.607287],"state_q99":[68.909766,192.216797,180.966797,97.382812,-14.941406,49.900136]},
+ {"part":"RaulSaya__Bylogic0","origin":"molmoact","dataset":"RaulSaya/Bylogic0","scene_camera":"observation.images.phone","fps":30.0,"built_clips":285,"train_windows":285,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.197266,-1.845703,-2.548828,-0.263672,-0.247117],"action_q99":[1.494141,2.636719,2.021484,2.900391,0.263672,65.156509],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.80957,42.890625,90.351562,-87.099609,81.210938,1.074306],"state_q99":[26.367188,201.09375,184.833984,75.058594,94.658203,64.637421]},
+ {"part":"RaulSaya__so101_pickandplacebylogic","origin":"molmoact","dataset":"RaulSaya/so101_pickandplacebylogic","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1476,"train_windows":1476,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.548828,-2.460938,-2.460938,-0.351562,-0.576606],"action_q99":[1.318359,2.900391,2.900391,2.724609,0.351562,60.62603],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-63.457031,33.398438,27.949219,-74.53125,79.628906,0.895255],"state_q99":[42.275391,201.269531,185.009766,75.673828,114.082031,60.429722]},
+ {"part":"RaulSaya__so101_test1","origin":"molmoact","dataset":"RaulSaya/so101_test1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":37,"train_windows":37,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.427734,-4.375195,-3.847852,-1.474805,-0.263672,-0.391543],"action_q99":[1.933594,4.199414,2.900391,3.901465,0.615234,27.016445],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.424121,71.279297,107.226562,-35.683594,75.585938,11.478873],"state_q99":[18.017578,193.710938,180.966797,54.84375,90.615234,26.549295]},
+ {"part":"RaulSaya__so101_test3","origin":"molmoact","dataset":"RaulSaya/so101_test3","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":25,"train_windows":25,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.680859,-5.878125,-5.402637,-5.402637,-0.175781,-0.234926],"action_q99":[3.427734,4.688965,6.193652,3.510352,0.863086,46.782303],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.966797,82.353516,77.57666,1.757812,87.802734,10.84507],"state_q99":[34.711523,195.556641,181.054688,76.552734,103.359375,46.549297]},
+ {"part":"RaulSaya__so101_test4","origin":"molmoact","dataset":"RaulSaya/so101_test4","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.339844,-4.130859,-3.662402,-2.285156,-0.517676,-0.156617],"action_q99":[2.802832,3.603516,2.978613,2.988281,0.263672,41.895069],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.582031,87.451172,104.941406,-10.458984,74.355469,10.56338],"state_q99":[28.849219,196.171875,180.791016,49.971094,99.228516,42.253521]},
+ {"part":"RaulSaya__so101_test5","origin":"molmoact","dataset":"RaulSaya/so101_test5","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":36,"train_windows":36,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-3.396094,-2.496973,-1.757812,-0.263672,-0.267032],"action_q99":[2.724609,4.20293,2.584863,1.178613,0.263672,40.250587],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.851367,89.208984,123.925781,-22.587891,89.560547,10.0],"state_q99":[23.998535,195.292969,180.966797,18.346289,90.439453,40.492958]},
+ {"part":"ReubenLim__so101_ball_in_cup","origin":"molmoact","dataset":"ReubenLim/so101_ball_in_cup","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1884,"train_windows":1884,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.615234,-1.318359,-1.142578,-1.142578,-0.703125,0.0],"action_q99":[0.791016,1.40625,1.142578,1.142578,0.703125,55.320877],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-81.5625,62.402344,74.355469,-7.294922,48.955078,0.636492],"state_q99":[19.654102,193.095703,179.208984,85.869141,106.611328,54.950497]},
+ {"part":"ReubenLim__so101_lerobot_hackathon","origin":"molmoact","dataset":"ReubenLim/so101_lerobot_hackathon","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1339,"train_windows":1339,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.021484,-1.494141,-2.021484,-0.175781,-0.087566],"action_q99":[1.669922,2.197266,1.845703,1.582031,0.263672,56.654991],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-51.416016,37.617188,66.884766,-11.601562,73.300781,0.83682],"state_q99":[73.975781,178.769531,177.011719,67.851562,90.439453,56.463041]},
+ {"part":"ReubenLim__so101_tape_in_square","origin":"molmoact","dataset":"ReubenLim/so101_tape_in_square","scene_camera":"observation.images.birdEye","fps":30.0,"built_clips":1829,"train_windows":1829,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-1.757812,-1.318359,-0.966797,-0.351562,-0.081235],"action_q99":[0.527344,1.40625,1.318359,0.966797,0.263672,32.73761],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.880859,22.236328,6.771094,-2.900391,61.875,1.131542],"state_q99":[18.369141,191.689453,179.912109,87.363281,103.886719,32.390381]},
+ {"part":"ReubenLim__so101_test","origin":"molmoact","dataset":"ReubenLim/so101_test","scene_camera":"observation.images.birdEye","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-1.142578,-0.791016,-1.230469,-1.620703,-0.568643],"action_q99":[0.703125,2.558496,2.031152,1.669922,2.22627,-0.243704],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.667969,84.814453,119.267578,-6.416016,-33.788672,1.06082],"state_q99":[-6.855469,190.283203,178.242188,54.931641,18.457031,1.06082]},
+ {"part":"RickRain__so101_test","origin":"molmoact","dataset":"RickRain/so101_test","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":740,"train_windows":740,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.266211,-3.779297,-3.691406,-2.460938,-4.042969,-0.912863],"action_q99":[4.394531,3.076172,3.955078,2.285156,3.867188,29.377594],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.765625,14.981836,1.494141,28.037109,-55.770117,-0.921659],"state_q99":[87.1875,191.777344,177.890625,99.228516,116.103516,29.266361]},
+ {"part":"RickRain__so101_test_single_lego","origin":"molmoact","dataset":"RickRain/so101_test_single_lego","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":785,"train_windows":785,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-5.712891,-4.570312,-2.900391,-3.251953,-0.995851],"action_q99":[2.8125,5.097656,5.625,3.603516,3.076172,34.107883],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-77.581934,17.050781,0.025488,-4.306641,-26.103516,-1.105991],"state_q99":[67.826074,192.392578,178.066406,99.052734,133.040918,33.640553]},
+ {"part":"Rorschach4153__so101_30_1","origin":"molmoact","dataset":"Rorschach4153/so101_30_1","scene_camera":"observation.images.topdown","fps":30.0,"built_clips":4025,"train_windows":4025,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-1.40625,-1.40625,-1.494141,-1.142578,-0.254669],"action_q99":[0.703125,1.494141,1.40625,1.582031,1.142578,33.616299],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.101562,26.630859,28.125,-18.28125,40.429688,-0.137836],"state_q99":[38.408203,194.414062,179.121094,86.044922,152.305664,33.356304]},
+ {"part":"Rorschach4153__so101_30_fold","origin":"molmoact","dataset":"Rorschach4153/so101_30_fold","scene_camera":"observation.images.topdown","fps":30.0,"built_clips":2096,"train_windows":2096,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.757812,-1.757812,-1.933594,-2.109375,-0.254669],"action_q99":[1.318359,2.021484,2.021484,2.460938,1.933594,26.910015],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.589844,25.136719,30.234375,-37.429102,20.478516,-0.482426],"state_q99":[62.402344,194.414062,179.208984,96.855469,154.511719,26.740179]},
+ {"part":"Ruth011__jetson_orin_nano_super_1","origin":"molmoact","dataset":"Ruth011/jetson_orin_nano_super_1","scene_camera":"observation.images.top","fps":30.0,"built_clips":959,"train_windows":959,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.339844,-3.251953,-3.474316,-1.40625,-1.784489],"action_q99":[2.021484,3.076172,4.130859,3.076172,1.318359,50.652027],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-67.722363,39.814453,25.3125,3.164062,-6.064453,-0.555942],"state_q99":[78.222656,193.007812,180.439453,98.173828,142.822266,50.521194]},
+ {"part":"SGQA__so100_test","origin":"molmoact","dataset":"SGQA/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1435,"train_windows":1435,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-1.669922,-1.933594,-1.318359,-2.285156,0.274223],"action_q99":[1.669922,1.933594,1.757812,1.933594,2.109375,66.6362],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.712891,67.939453,74.267578,36.738281,-169.277344,0.829493],"state_q99":[56.953125,185.273438,173.759766,102.216797,34.720313,66.451614]},
+ {"part":"SKLskl0708__so100_test4","origin":"molmoact","dataset":"SKLskl0708/so100_test4","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":21,"train_windows":21,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.955078,-4.542187,-4.573828,-2.197266,-1.318359,-0.195695],"action_q99":[4.717969,4.190625,3.227344,2.08125,1.494141,36.270058],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.835938,95.301563,127.258594,27.949219,50.361328,0.164609],"state_q99":[30.909375,195.029297,187.119141,61.435547,64.135547,35.637863]},
+ {"part":"SahilChande__so100_demo_cap_pick","origin":"molmoact","dataset":"SahilChande/so100_demo_cap_pick","scene_camera":"observation.images.top_camera","fps":30.0,"built_clips":62,"train_windows":62,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.197266,-1.757812,-3.447949,-0.966797,-0.105597],"action_q99":[1.162793,2.8125,2.988281,3.076172,0.987012,50.58078],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.318359,30.058594,18.369141,-108.896484,-8.322363,-0.196657],"state_q99":[34.56123,186.328125,173.583984,90.527344,18.585352,50.245823]},
+ {"part":"SahilChande__so100_pick_carrot","origin":"molmoact","dataset":"SahilChande/so100_pick_carrot","scene_camera":"observation.images.top_camera","fps":30.0,"built_clips":1407,"train_windows":1407,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.636719,-3.164062,-3.691406,-3.164062,-0.105597],"action_q99":[1.669922,3.339844,4.042969,4.306641,4.306641,55.121433],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-12.392578,32.656641,14.150391,-108.896484,-132.802734,0.098328],"state_q99":[38.232422,186.503906,173.759766,86.347266,11.162109,54.867256]},
+ {"part":"Selinaliu1030__egg_0806","origin":"molmoact","dataset":"Selinaliu1030/egg_0806","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1851,"train_windows":1851,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.060156,-3.691406,-3.251953,-3.691406,-0.966797,-0.340136],"action_q99":[1.845703,3.251953,3.515625,4.482422,1.054688,60.952381],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-89.736328,34.980469,72.822656,-50.361328,-110.566406,0.267738],"state_q99":[83.232422,190.195312,177.978516,71.191406,-78.046875,60.374832]},
+ {"part":"Selinaliu1030__test_now","origin":"molmoact","dataset":"Selinaliu1030/test_now","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.724609,-2.285156,-3.251953,-1.582031,-0.340136],"action_q99":[1.845703,3.076172,4.112402,3.603516,1.318359,61.768707],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.236328,78.662109,101.337891,-47.460938,-88.926855,-0.070872],"state_q99":[54.667969,190.458984,179.033203,69.082031,-56.601562,61.516655]},
+ {"part":"SharkDan__so100_test_f1","origin":"molmoact","dataset":"SharkDan/so100_test_f1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":3160,"train_windows":3160,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.460938,-2.021484,-1.40625,-1.582031,11.064189],"action_q99":[1.845703,2.724609,2.548828,1.669922,1.318359,35.895271],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-58.183594,58.974609,57.568359,33.574219,-113.027344,12.866828],"state_q99":[15.556641,182.988281,170.683594,83.759766,-24.082031,35.835354]},
+ {"part":"SharkDan__so100_test_f3c","origin":"molmoact","dataset":"SharkDan/so100_test_f3c","scene_camera":"observation.images.new_camera","fps":30.0,"built_clips":915,"train_windows":915,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.197266,-2.460938,-1.230469,-0.966797,11.317568],"action_q99":[1.519629,1.933594,1.757812,1.142578,0.966797,41.80743],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.492188,38.759766,31.728516,39.023438,-96.416016,14.124293],"state_q99":[57.94541,186.328125,170.683594,88.505859,-14.300684,41.081516]},
+ {"part":"Stevenyu8888__so101_test","origin":"molmoact","dataset":"Stevenyu8888/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":65,"train_windows":65,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.176367,-3.691406,-1.933594,-2.373047,-0.084818],"action_q99":[2.285156,1.40625,1.757812,3.251953,2.724609,43.002544],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.150391,70.400391,71.894531,39.902344,77.431641,0.688231],"state_q99":[15.656836,185.537109,170.244141,97.470703,179.912109,42.670338]},
+ {"part":"Stevenyu8888__so101_test_3d","origin":"molmoact","dataset":"Stevenyu8888/so101_test_3d","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":79,"train_windows":79,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-3.427734,-3.691406,-1.757812,-2.570801,-0.169635],"action_q99":[2.197266,2.043457,2.636719,3.251953,2.724609,56.234097],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.394531,61.435547,40.253906,34.255371,62.600098,0.550585],"state_q99":[15.556641,186.503906,166.552734,98.085938,157.851562,55.815552]},
+ {"part":"Tank-123__so101_test","origin":"molmoact","dataset":"Tank-123/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":628,"train_windows":628,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-5.097656,-4.570312,-3.955078,-3.603516,-0.585774],"action_q99":[2.900391,4.570312,5.537109,4.042969,5.185547,54.142262],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.072266,46.972266,19.279688,34.804688,11.25,0.068306],"state_q99":[56.130469,198.017578,180.175781,101.513672,149.0625,52.254097]},
+ {"part":"Tank-123__so101_testdata_0820","origin":"molmoact","dataset":"Tank-123/so101_testdata_0820","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":327,"train_windows":327,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-4.21875,-2.636719,-3.076172,-4.394531,-0.598291],"action_q99":[3.251953,3.725684,2.988281,2.988281,3.955078,47.094017],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.228711,72.509766,74.794922,36.650391,9.140625,-0.268637],"state_q99":[59.53623,199.511719,179.648438,99.755859,153.984375,46.768972]},
+ {"part":"Trelis__so100_test2","origin":"molmoact","dataset":"Trelis/so100_test2","scene_camera":"observation.images.Context","fps":30.0,"built_clips":716,"train_windows":716,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.427734,-2.724609,-1.933594,-1.582031,-0.077519],"action_q99":[1.933594,3.164062,2.109375,1.933594,1.582031,36.35659],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[53.505176,84.023438,76.201172,31.289062,68.027344,0.285714],"state_q99":[161.191406,187.119141,157.939453,97.03125,159.873047,36.142857]},
+ {"part":"TzuShian__so100_250527","origin":"molmoact","dataset":"TzuShian/so100_250527","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1129,"train_windows":1129,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.636719,-2.021484,-3.427734,-3.779297,-0.182983],"action_q99":[1.230469,2.724609,2.285156,2.285156,3.427734,93.687103],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-63.105469,26.663379,54.085254,-107.018262,-6.855469,0.168919],"state_q99":[65.654297,188.349609,174.726562,55.865918,102.711621,93.581078]},
+ {"part":"TzuShian__so100_chess_test2","origin":"molmoact","dataset":"TzuShian/so100_chess_test2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":532,"train_windows":532,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-2.8125,-3.339844,-2.021484,-1.318359,-0.094877],"action_q99":[1.933594,2.021484,2.724609,1.757812,1.230469,63.946869],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.427734,73.125,46.318359,35.771484,-11.162109,-0.084459],"state_q99":[28.740234,192.216797,176.660156,93.691406,32.958984,63.118244]},
+ {"part":"TzuShian__so100_chess_test3","origin":"molmoact","dataset":"TzuShian/so100_chess_test3","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":599,"train_windows":599,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.339844,-2.636719,-3.779297,-2.548828,-0.189753],"action_q99":[1.318359,2.988281,2.724609,2.8125,3.779297,96.299812],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.648438,30.146484,78.222656,-100.986328,-7.294922,-0.168919],"state_q99":[36.123047,192.128906,177.011719,48.955078,98.261719,95.608109]},
+ {"part":"VoicAndrei__so100_banana_to_plate_only","origin":"molmoact","dataset":"VoicAndrei/so100_banana_to_plate_only","scene_camera":"observation.images.top","fps":30.0,"built_clips":1062,"train_windows":1062,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.515625,-3.603516,-2.373047,-3.076172,-0.2849],"action_q99":[1.669922,2.988281,3.164062,2.548828,2.636719,53.846157],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.850977,36.210938,26.630859,19.981055,-85.517578,0.327065],"state_q99":[49.746094,183.515625,174.638672,94.482422,82.675195,52.956663]},
+ {"part":"VoicAndrei__so100_cubes_noaptea_companiilor","origin":"molmoact","dataset":"VoicAndrei/so100_cubes_noaptea_companiilor","scene_camera":"observation.images.top","fps":30.0,"built_clips":147,"train_windows":147,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.515625,-3.076172,-3.339844,-2.922363,-3.867188,0.095057],"action_q99":[3.955078,3.779297,3.867188,3.361816,2.724609,42.514258],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.816406,37.353516,23.730469,11.931152,-110.961914,0.913777],"state_q99":[40.166016,190.371094,178.945312,92.460938,9.931641,38.987816]},
+ {"part":"VoicAndrei__so100_cubes_noaptea_companiilor_2","origin":"molmoact","dataset":"VoicAndrei/so100_cubes_noaptea_companiilor_2","scene_camera":"observation.images.side","fps":30.0,"built_clips":4170,"train_windows":4170,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-2.8125,-2.988281,-2.8125,-2.636719,0.095057],"action_q99":[3.515625,3.427734,3.427734,2.8125,2.724609,33.650188],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.0,35.419922,18.544922,1.933594,-117.597656,0.937207],"state_q99":[46.757812,190.371094,178.242188,86.923828,5.888672,33.270851]},
+ {"part":"VoicAndrei__so100_green_blocks","origin":"molmoact","dataset":"VoicAndrei/so100_green_blocks","scene_camera":"observation.images.top","fps":30.0,"built_clips":1824,"train_windows":1824,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.746094,-3.955078,-4.746094,-3.515625,-4.482422,-0.191205],"action_q99":[4.658203,4.570312,4.658203,4.482422,4.394531,55.54493],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.847656,24.257812,8.261719,-3.348633,-124.189453,0.459559],"state_q99":[53.789062,182.373047,171.298828,101.865234,20.654297,54.963238]},
+ {"part":"VoicAndrei__so100_kitchen","origin":"molmoact","dataset":"VoicAndrei/so100_kitchen","scene_camera":"observation.images.top","fps":30.0,"built_clips":16366,"train_windows":16366,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.603516,-2.636719,-3.427734,-5.097656,-3.251953,-0.095602],"action_q99":[3.339844,4.130859,4.130859,5.449219,3.164062,54.162678],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-92.021484,84.814453,61.435547,-23.994141,-124.541016,0.459559],"state_q99":[54.140625,184.21875,178.857422,80.595703,60.205078,53.575359]},
+ {"part":"VoicAndrei__so100_test_blocks","origin":"molmoact","dataset":"VoicAndrei/so100_test_blocks","scene_camera":"observation.images.top","fps":30.0,"built_clips":175,"train_windows":175,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-5.537109,-4.21875,-6.591797,-4.21875,-4.746094,-0.191205],"action_q99":[6.152344,5.313867,5.888672,4.921875,4.482422,41.682602],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.630859,23.115234,6.503906,20.891602,-95.712891,0.367647],"state_q99":[54.667969,184.306641,170.899805,101.074219,31.856836,40.533089]},
+ {"part":"Waykzen__raju","origin":"molmoact","dataset":"Waykzen/raju","scene_camera":"observation.images.phone","fps":30.0,"built_clips":569,"train_windows":569,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-1.494141,-2.548828,-1.318359,-2.636719,0.0],"action_q99":[2.636719,1.757812,2.636719,1.845703,1.757812,34.415633],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.849609,72.421875,60.025781,43.417969,-8.966602,0.208478],"state_q99":[101.074219,192.832031,177.451172,97.207031,103.095703,34.1918]},
+ {"part":"Waykzen__raju2","origin":"molmoact","dataset":"Waykzen/raju2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1494,"train_windows":1494,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-1.494141,-2.197266,-1.845703,-2.900391,0.0],"action_q99":[2.724609,2.197266,2.8125,1.757812,2.109375,31.649191],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.748047,33.662109,17.138672,6.328125,-7.470703,1.615169],"state_q99":[100.019531,193.095703,181.933594,97.910156,100.458984,29.77528]},
+ {"part":"Whakamua__so100_mouse","origin":"molmoact","dataset":"Whakamua/so100_mouse","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":10,"train_windows":10,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.640234,-5.449219,-8.094727,-1.583789,-1.142578,-0.086133],"action_q99":[1.669922,2.460938,2.552344,2.460938,0.878906,37.03876],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.492188,23.90625,-14.941406,68.115234,-2.724609,1.028101],"state_q99":[12.658008,189.052734,168.837891,100.810547,6.154102,36.394791]},
+ {"part":"XXRRSSRR__so100_v3_num_episodes_50","origin":"molmoact","dataset":"XXRRSSRR/so100_v3_num_episodes_50","scene_camera":"observation.images.phone","fps":30.0,"built_clips":618,"train_windows":618,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.900391,-4.306641,-6.591797,-7.998047,-2.900391,-0.108342],"action_q99":[3.603516,4.306641,5.185547,7.989258,3.339844,105.958832],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.414062,52.743164,32.783203,-101.689453,6.943359,-0.491159],"state_q99":[22.324219,178.681641,160.751953,87.099609,70.655273,105.304512]},
+ {"part":"Xiewei1211__Grab_panda_2","origin":"molmoact","dataset":"Xiewei1211/Grab_panda_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":745,"train_windows":745,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.988281,-2.548828,-1.845703,-2.900391,-0.456621],"action_q99":[1.494141,3.955078,3.779297,2.636719,2.988281,61.826485],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-17.666016,37.177734,-226.054688,-5.449219,-134.208984,-0.238284],"state_q99":[57.919922,185.097656,-96.152344,72.773438,35.704688,61.477364]},
+ {"part":"Xiewei1211__so100_test","origin":"molmoact","dataset":"Xiewei1211/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":38,"train_windows":38,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.757812,-2.109375,-1.13291,-0.703125,-0.365297],"action_q99":[0.791016,1.933594,1.757812,1.04502,1.669922,44.474884],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[0.458789,55.722656,-211.289062,26.191406,-63.984375,0.158856],"state_q99":[39.990234,185.009766,-100.371094,76.904297,-6.064453,44.320889]},
+ {"part":"Xiewei1211__so100_test1","origin":"molmoact","dataset":"Xiewei1211/so100_test1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":54,"train_windows":54,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.197266,-2.285156,-1.230469,-0.966797,-0.365297],"action_q99":[1.054688,2.109375,2.197266,1.582031,1.582031,67.397263],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.871094,49.746094,-205.927734,-0.791016,-55.810547,0.158856],"state_q99":[40.341797,184.921875,-96.503906,106.699219,-1.845703,67.11676]},
+ {"part":"Yan1205__so100_test","origin":"molmoact","dataset":"Yan1205/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":893,"train_windows":893,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.164062,-2.988281,-1.494141,-3.779297,-0.818331],"action_q99":[1.582031,2.988281,3.779297,1.494141,4.306641,52.291325],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.871094,38.583984,27.773438,12.744141,-22.236328,0.254453],"state_q99":[31.631836,186.943359,180.527344,85.78125,136.40625,51.738762]},
+ {"part":"Yanis7777__so100_duck","origin":"molmoact","dataset":"Yanis7777/so100_duck","scene_camera":"observation.images.overhead_camera","fps":30.0,"built_clips":560,"train_windows":560,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-4.746094,-3.691406,-1.582031,-0.615234,-0.730594],"action_q99":[2.109375,4.570312,4.394531,1.845703,0.703125,40.639271],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-66.269531,27.861328,30.146484,29.179688,-19.775391,0.413508],"state_q99":[10.546875,188.964844,180.0,89.296875,9.667969,40.385941]},
+ {"part":"ZHANGXD90__so100_test","origin":"molmoact","dataset":"ZHANGXD90/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":50,"train_windows":50,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.021484,-2.021484,-0.703125,-1.845703,4.180064],"action_q99":[1.40625,1.230469,1.669922,0.878906,1.230469,28.69775],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.462891,69.169922,70.3125,53.789062,-2.636719,5.505341],"state_q99":[28.828125,192.392578,174.023438,86.923828,48.938379,28.841412]},
+ {"part":"ZHUZHUXIADDD__so100_test112","origin":"molmoact","dataset":"ZHUZHUXIADDD/so100_test112","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":27,"train_windows":27,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.171973,-2.988281,-2.197266,-0.439453,-0.559702],"action_q99":[1.318359,3.883008,3.787207,1.845703,0.703125,84.285443],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.842187,48.683496,57.744141,45.878906,-9.443848,0.731113],"state_q99":[45.974707,189.931641,168.222656,100.019531,7.207031,83.834282]},
+ {"part":"Zak-Y__so100_test","origin":"molmoact","dataset":"Zak-Y/so100_test","scene_camera":"observation.images.Left_follower","fps":30.0,"built_clips":169,"train_windows":169,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-1.933594,-1.669922,-1.40625,-1.054688,-0.213675],"action_q99":[1.142578,2.285156,1.933594,1.835156,0.878906,40.867522],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.867188,52.734375,59.326172,17.078906,-101.162109,0.23622],"state_q99":[67.841016,187.294922,178.857422,76.904297,-46.525781,38.957482]},
+ {"part":"Zufayri__fayri2","origin":"molmoact","dataset":"Zufayri/fayri2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":70,"train_windows":70,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.409766,-2.021484,-1.669922,-1.318359,-2.8125,-0.50505],"action_q99":[1.40625,1.673437,2.025,1.585547,3.164062,79.942284],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.167578,38.320312,36.5625,58.710938,-167.167969,1.516196],"state_q99":[60.556641,191.162109,173.496094,104.501953,88.330078,79.393524]},
+ {"part":"aaronsu11__so100_lego","origin":"molmoact","dataset":"aaronsu11/so100_lego","scene_camera":"observation.images.top_camera","fps":30.0,"built_clips":1730,"train_windows":1730,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-1.933594,-1.669922,-1.230469,-2.373047,0.400802],"action_q99":[0.791016,2.285156,2.373047,1.230469,2.197266,51.302605],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.828125,50.976562,47.211328,29.984766,-129.550781,0.660793],"state_q99":[32.431641,188.964844,169.628906,85.78125,34.013672,51.174744]},
+ {"part":"aaronsu11__so100_pick","origin":"molmoact","dataset":"aaronsu11/so100_pick","scene_camera":"observation.images.front","fps":30.0,"built_clips":614,"train_windows":614,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.8125,-2.373047,-1.757812,-2.373047,0.400802],"action_q99":[1.142578,2.460938,2.285156,2.373047,2.373047,43.486973],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.42666,34.013672,19.6875,21.884766,-157.115918,0.660793],"state_q99":[39.726562,188.876953,175.693359,94.394531,-24.257812,43.318649]},
+ {"part":"aiwhisperer__test2","origin":"molmoact","dataset":"aiwhisperer/test2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.851172,-5.009766,-9.316406,-4.823437,-3.192188,-0.487329],"action_q99":[3.164062,4.608984,6.503906,5.487891,3.944531,42.592594],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[34.189453,19.466016,-2.8125,33.711328,-8.701172,0.182815],"state_q99":[89.940234,179.824219,179.824219,113.818359,74.675391,41.6819]},
+ {"part":"akira-sasaki__akabeko_instruct_v1","origin":"molmoact","dataset":"akira-sasaki/akabeko_instruct_v1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":2922,"train_windows":2922,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-5.273438,-4.042969,-2.724609,-2.285156,-0.812458],"action_q99":[1.318359,3.955078,4.833984,2.548828,2.021484,29.857821],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.369141,42.011719,19.863281,13.271484,-33.222656,-0.417827],"state_q99":[18.720703,192.216797,176.923828,96.240234,42.890625,29.423868]},
+ {"part":"akira-sasaki__akabeko_instruct_v2","origin":"molmoact","dataset":"akira-sasaki/akabeko_instruct_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":3536,"train_windows":3536,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-5.009766,-3.779297,-2.548828,-1.40625,-0.812458],"action_q99":[1.318359,3.603516,4.746094,2.460938,1.582031,28.503725],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.742188,46.845703,24.960938,33.837891,-22.766309,-0.278552],"state_q99":[14.853516,192.744141,178.769531,97.207031,22.502637,28.066155]},
+ {"part":"akira-sasaki__gr00t_red_block","origin":"molmoact","dataset":"akira-sasaki/gr00t_red_block","scene_camera":"observation.images.top","fps":30.0,"built_clips":463,"train_windows":463,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-5.361328,-4.482422,-2.988281,-1.40625,-0.332502],"action_q99":[1.230469,4.921875,4.394531,2.900391,1.318359,50.041561],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.380859,36.210938,12.652734,-5.449219,-36.826172,0.323415],"state_q99":[55.202344,197.138672,186.240234,100.810547,14.283984,49.870632]},
+ {"part":"akira-sasaki__gr00t_red_test","origin":"molmoact","dataset":"akira-sasaki/gr00t_red_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.501172,-4.921875,-4.042969,-2.636719,-1.318359,-0.083333],"action_q99":[1.230469,4.658203,4.485937,2.640234,1.146094,46.25],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.642578,61.25625,35.771484,9.580078,-32.080078,0.328299],"state_q99":[8.4375,181.845703,169.892578,75.322266,1.683984,45.767565]},
+ {"part":"akira-sasaki__gr00t_rtx5090_test","origin":"molmoact","dataset":"akira-sasaki/gr00t_rtx5090_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":586,"train_windows":586,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-4.746094,-3.779297,-2.373047,-1.494141,-0.731261],"action_q99":[1.494141,4.746094,4.570312,2.460938,1.40625,51.510056],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.588672,46.142578,13.665234,14.150391,-17.841797,-0.279135],"state_q99":[4.482422,184.570312,169.013672,97.65,14.0625,51.187719]},
+ {"part":"akira-sasaki__so100_somlvla","origin":"molmoact","dataset":"akira-sasaki/so100_somlvla","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":293,"train_windows":293,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-4.306641,-3.076172,-4.306641,-1.40625,-0.609343],"action_q99":[1.230469,3.867188,3.955078,3.691406,1.40625,35.587002],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.908203,71.542969,75.29502,-2.021484,-21.560449,-0.208914],"state_q99":[19.423828,191.689453,179.587793,87.802734,10.18916,35.445683]},
+ {"part":"alan-123456__so101_test","origin":"molmoact","dataset":"alan-123456/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":50,"train_windows":50,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-3.055078,-2.724609,-3.230859,-3.251953,-1.275255],"action_q99":[1.318359,3.142969,2.724609,3.164062,3.164062,60.982388],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.535156,70.611328,97.207031,-6.834375,-164.003906,-0.761773],"state_q99":[53.289844,169.716797,179.296875,82.508203,92.109375,61.011082]},
+ {"part":"alan-123456__test2","origin":"molmoact","dataset":"alan-123456/test2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":31,"train_windows":31,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.202734,-3.691406,-3.554297,-2.724609,-1.390176],"action_q99":[1.845703,3.779297,4.510547,3.202734,3.494531,37.62743],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.673438,33.370312,51.767578,27.421875,-0.791016,0.0],"state_q99":[19.775391,191.777344,179.472656,87.338672,85.78125,37.811634]},
+ {"part":"alan-123456__test3","origin":"molmoact","dataset":"alan-123456/test3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":238,"train_windows":238,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-5.449219,-5.097656,-2.724609,-2.724609,-1.112141],"action_q99":[2.8125,3.691406,4.921875,3.779297,2.572559,46.061169],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.28125,55.986328,32.816602,23.483496,-95.361328,-0.34626],"state_q99":[89.824219,192.392578,179.033203,96.240234,12.919922,46.260387]},
+ {"part":"alan-123456__test_plus","origin":"molmoact","dataset":"alan-123456/test_plus","scene_camera":"observation.images.phone","fps":30.0,"built_clips":145,"train_windows":145,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.427734,-3.515625,-2.460938,-2.636719,-1.204819],"action_q99":[2.109375,3.955078,4.482422,3.076172,2.8125,52.3633],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.072266,39.287109,41.044922,17.050781,-140.712891,-0.831025],"state_q99":[51.240234,192.216797,178.857422,94.482422,1.757812,52.146816]},
+ {"part":"alan-123456__test_red_final","origin":"molmoact","dataset":"alan-123456/test_red_final","scene_camera":"observation.images.phone","fps":30.0,"built_clips":102,"train_windows":102,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.927832,-3.955078,-1.933594,-2.460938,-1.112141],"action_q99":[1.845703,3.515625,4.658203,2.460938,2.17002,48.656162],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-16.787109,26.806641,16.171875,33.046875,-76.816406,-0.415512],"state_q99":[52.558594,192.480469,177.539062,95.537109,7.910156,48.476456]},
+ {"part":"amrltqt__so100_test","origin":"molmoact","dataset":"amrltqt/so100_test","scene_camera":"observation.images.wide","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-5.374512,-4.750488,-4.223145,-2.021484,-0.807899],"action_q99":[2.289551,4.306641,4.570312,4.574707,1.933594,35.103232],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.033203,48.691406,31.289062,11.333496,-94.394531,0.210822],"state_q99":[5.901855,190.107422,178.945312,99.492188,-25.136719,35.007028]},
+ {"part":"andy309__so100_0311_1152","origin":"molmoact","dataset":"andy309/so100_0311_1152","scene_camera":"observation.images.top","fps":30.0,"built_clips":985,"train_windows":985,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-2.724609,-3.427734,-3.251953,-2.724609,-2.8125,0.0],"action_q99":[4.21875,3.691406,3.515625,2.373047,2.988281,46.333332],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[11.823047,42.011719,24.609375,48.649219,-15.904688,0.227101],"state_q99":[124.101562,173.759766,163.300781,108.896484,179.736328,45.571537]},
+ {"part":"andy309__so100_0313_no_wrist_camera","origin":"molmoact","dataset":"andy309/so100_0313_no_wrist_camera","scene_camera":"observation.images.top","fps":30.0,"built_clips":263,"train_windows":263,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-4.130859,-4.833984,-4.306641,-2.197266,-1.757812,-0.107991],"action_q99":[2.612109,3.779297,4.10625,1.845703,1.318359,37.257019],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[80.883984,51.240234,43.266797,51.591797,84.726562,0.98912],"state_q99":[158.203125,179.912109,163.388672,108.28125,129.476953,36.498516]},
+ {"part":"anichris__so100_test","origin":"molmoact","dataset":"anichris/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":83,"train_windows":83,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-4.042969,-2.8125,-1.582031,-0.572168,-0.105708],"action_q99":[2.109375,5.009766,4.394531,1.669922,0.439453,99.473573],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.056641,37.525781,21.884766,46.974902,17.841797,0.447761],"state_q99":[66.445312,188.173828,171.298828,104.238281,33.134766,79.444027]},
+ {"part":"apayan__so100_ball1","origin":"molmoact","dataset":"apayan/so100_ball1","scene_camera":"observation.images.top","fps":30.0,"built_clips":70,"train_windows":70,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-0.966797,-0.615234,-1.669922,-3.492773,0.0],"action_q99":[1.318359,1.142578,1.142578,1.318359,1.933594,34.456928],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-61.347656,67.939453,122.783203,-21.796875,-92.724609,0.485774],"state_q99":[92.197266,185.361328,177.978516,51.064453,-5.800781,34.142956]},
+ {"part":"apayan__so100_ball2","origin":"molmoact","dataset":"apayan/so100_ball2","scene_camera":"observation.images.top","fps":30.0,"built_clips":140,"train_windows":140,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.114453,-1.054688,-0.703125,-1.290234,-2.900391,-0.093633],"action_q99":[0.878906,1.582031,1.230469,1.318359,1.729688,36.797752],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-73.184766,18.984375,35.15625,-20.186719,-95.449219,0.485774],"state_q99":[89.824219,185.449219,177.978516,51.064453,-0.439453,35.57807]},
+ {"part":"apayan__so100_ball8","origin":"molmoact","dataset":"apayan/so100_ball8","scene_camera":"observation.images.front","fps":30.0,"built_clips":3501,"train_windows":3501,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.054688,-0.791016,-1.40625,-3.164062,0.0],"action_q99":[1.054688,2.373047,1.933594,1.494141,2.548828,37.921349],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-74.869629,32.431641,49.746094,-14.941406,-97.822266,0.346981],"state_q99":[98.701172,185.800781,177.978516,51.591797,0.703125,38.237335]},
+ {"part":"apayan__so100_key3","origin":"molmoact","dataset":"apayan/so100_key3","scene_camera":"observation.images.front","fps":30.0,"built_clips":1725,"train_windows":1725,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-1.40625,-1.230469,-1.230469,-2.724609,0.0],"action_q99":[1.494141,2.197266,2.021484,1.40625,2.724609,28.183519],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-75.410156,41.923828,57.60791,-12.392578,-98.701172,0.485774],"state_q99":[90.703125,186.152344,177.890625,72.333984,6.240234,27.897293]},
+ {"part":"apayan__so100_key4","origin":"molmoact","dataset":"apayan/so100_key4","scene_camera":"observation.images.front","fps":30.0,"built_clips":344,"train_windows":344,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-1.230469,-0.791016,-1.318359,-3.076172,0.0],"action_q99":[0.615234,1.757812,1.494141,1.230469,2.021484,28.745317],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.867188,83.759766,88.71416,-39.420703,-104.238281,0.485774],"state_q99":[59.853516,188.4375,177.978516,60.820312,4.130859,28.383068]},
+ {"part":"apayan__so100_key5","origin":"molmoact","dataset":"apayan/so100_key5","scene_camera":"observation.images.front","fps":30.0,"built_clips":86,"train_windows":86,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.351562,-1.494141,-0.791016,-1.40625,-3.251953,0.0],"action_q99":[0.263672,2.454785,2.09707,1.494141,2.285156,29.11985],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[1.669922,87.633105,85.52373,-32.400879,-99.755859,0.485774],"state_q99":[11.513672,185.449219,177.978516,49.827832,-1.054688,28.730049]},
+ {"part":"apayan__so100_key6","origin":"molmoact","dataset":"apayan/so100_key6","scene_camera":"observation.images.front","fps":30.0,"built_clips":1723,"train_windows":1723,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-1.054688,-0.703125,-1.494141,-3.251953,0.093633],"action_q99":[0.966797,1.494141,1.582031,0.966797,1.933594,44.943821],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.099609,46.142578,69.433594,-9.755859,-98.876953,0.485774],"state_q99":[81.298828,185.449219,177.890625,53.789062,2.548828,44.760582]},
+ {"part":"apayan__so100_last1","origin":"molmoact","dataset":"apayan/so100_last1","scene_camera":"observation.images.front","fps":30.0,"built_clips":40,"train_windows":40,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.933594,-1.054688,-1.255957,-2.285156,0.0],"action_q99":[1.318359,4.042969,2.373047,1.871191,2.662207,28.089888],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.054688,78.925781,104.238281,-1.933594,-98.349609,0.485774],"state_q99":[50.097656,185.712891,177.714844,51.943359,-0.087891,28.174877]},
+ {"part":"arulloomba__so100_test_20250424_212219","origin":"molmoact","dataset":"arulloomba/so100_test_20250424_212219","scene_camera":"observation.images.detatched_arm","fps":30.0,"built_clips":24,"train_windows":24,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.731641,-2.907422,-2.947852,-1.142578,-2.64375,-6.41251],"action_q99":[2.779102,4.002539,1.845703,1.190039,4.441992,18.258663],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.778711,77.871094,106.171875,37.001953,-64.6875,-2.018388],"state_q99":[23.7375,191.04082,181.494141,61.787109,14.853516,18.219236]},
+ {"part":"arulloomba__so100_test_20250424_213858","origin":"molmoact","dataset":"arulloomba/so100_test_20250424_213858","scene_camera":"observation.images.detatched_arm","fps":30.0,"built_clips":17,"train_windows":17,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.518066,-3.581543,-3.700195,-0.224121,-2.614746,-4.480135],"action_q99":[1.40625,3.915527,2.373047,0.615234,1.278809,21.217245],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.975586,78.398438,104.414062,35.244141,-36.5625,-1.980198],"state_q99":[18.632812,191.865234,183.339844,45.703125,16.259766,21.004244]},
+ {"part":"arulloomba__so100_test_20250424_214343","origin":"molmoact","dataset":"arulloomba/so100_test_20250424_214343","scene_camera":"observation.images.detatched_arm","fps":30.0,"built_clips":18,"train_windows":18,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.035742,-2.548828,-1.764844,-1.40625,-5.80727],"action_q99":[1.845703,5.057227,2.332617,0.926367,1.805273,32.206257],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.001953,47.197266,60.644531,37.177734,-51.943359,-2.263083],"state_q99":[25.136719,192.480469,182.900391,72.61875,3.515625,31.650637]},
+ {"part":"arulloomba__so100_test_20250425_151531","origin":"molmoact","dataset":"arulloomba/so100_test_20250425_151531","scene_camera":"observation.images.detatched_arm","fps":30.0,"built_clips":164,"train_windows":164,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-3.076172,-2.636719,-1.255078,-2.109375,-5.240913],"action_q99":[1.757812,3.955078,2.460938,1.167187,2.373047,31.868134],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.816406,68.554688,90.878906,11.805469,-41.748047,-2.475248],"state_q99":[16.108594,192.304688,183.251953,54.492188,18.720703,32.036774]},
+ {"part":"arulloomba__so100_test_5","origin":"molmoact","dataset":"arulloomba/so100_test_5","scene_camera":"observation.images.detatched_arm","fps":30.0,"built_clips":600,"train_windows":600,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.076172,-2.548828,-1.230469,-2.988281,-0.45208],"action_q99":[1.757812,3.691406,2.373047,1.318359,2.636719,33.453888],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.078125,75.410156,82.792969,15.996094,-47.988281,-0.278552],"state_q99":[11.074219,192.216797,182.109375,71.894531,18.457031,33.077995]},
+ {"part":"badwolf256__so100_twin_cam_duck","origin":"molmoact","dataset":"badwolf256/so100_twin_cam_duck","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":386,"train_windows":386,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.109375,-1.933594,-1.757812,-2.021484,-3.46249],"action_q99":[2.197266,2.460938,2.109375,1.845703,1.669922,48.722176],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.597656,89.25293,88.936523,31.025391,-106.259766,-1.75841],"state_q99":[66.603516,193.886719,174.023438,98.499023,2.8125,47.553516]},
+ {"part":"badwolf256__so100_twin_cam_duck_v2","origin":"molmoact","dataset":"badwolf256/so100_twin_cam_duck_v2","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":421,"train_windows":421,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.373047,-2.021484,-1.757812,-1.757812,3.565769],"action_q99":[2.548828,2.285156,2.285156,1.669922,1.669922,48.811409],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-87.099609,72.346289,75.146484,40.78125,-93.515625,3.402778],"state_q99":[75.7125,191.513672,173.935547,103.083398,-0.175781,47.569443]},
+ {"part":"bap13__so101_test","origin":"molmoact","dataset":"bap13/so101_test","scene_camera":"observation.images.context","fps":30.0,"built_clips":1326,"train_windows":1326,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.164062,-2.988281,-2.109375,-2.900391,-3.604359],"action_q99":[1.669922,2.724609,3.164062,2.021484,3.603516,43.587597],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-57.480469,22.675781,8.173828,33.027539,-161.103516,-1.901408],"state_q99":[66.181641,196.611328,180.439453,101.337891,32.255859,43.802814]},
+ {"part":"bap13__so101_test_3","origin":"molmoact","dataset":"bap13/so101_test_3","scene_camera":"observation.images.context","fps":30.0,"built_clips":1147,"train_windows":1147,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.622656,-1.845703,-2.373047,-0.966797,-3.436714],"action_q99":[1.494141,2.724609,1.845703,2.548828,0.966797,64.626991],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-61.875,49.598438,73.476562,-64.058203,76.201172,-2.042253],"state_q99":[60.732422,196.611328,180.703125,86.132812,128.583984,64.273241]},
+ {"part":"baptiste-04__so100_playX","origin":"molmoact","dataset":"baptiste-04/so100_playX","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1584,"train_windows":1584,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.867188,-3.955078,-1.669922,-1.845703,-0.783875],"action_q99":[1.40625,2.548828,2.8125,1.845703,1.933594,54.87122],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.199219,23.378906,5.361328,36.738281,10.648828,-0.411862],"state_q99":[35.244141,188.4375,174.375,101.337891,149.677734,54.448105]},
+ {"part":"baptiste-04__so100_test_v6","origin":"molmoact","dataset":"baptiste-04/so100_test_v6","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":813,"train_windows":813,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.164062,-3.251953,-1.582031,-1.054688,-0.895857],"action_q99":[1.230469,2.197266,2.460938,1.757812,1.054688,43.784992],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.859375,50.009766,48.867188,22.148438,66.708984,-0.329489],"state_q99":[12.480469,187.207031,174.375,98.701172,149.238281,43.410213]},
+ {"part":"batterysnoopy2025__so100_test5","origin":"molmoact","dataset":"batterysnoopy2025/so100_test5","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":66,"train_windows":66,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.439453,-1.142578,-2.064551,-1.845703,-0.263672,4.4905],"action_q99":[0.615234,1.800879,3.119238,1.88877,0.263672,87.392059],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.8125,6.372949,44.912109,-105.861621,175.605469,23.212046],"state_q99":[27.552832,96.328125,176.835938,-32.431641,182.724609,87.076538]},
+ {"part":"bensprenger__TEST_left_arm_lego_brick","origin":"molmoact","dataset":"bensprenger/TEST_left_arm_lego_brick","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":17,"train_windows":17,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.321875,-2.548828,-2.991797,-1.849219,-1.40625,0.0],"action_q99":[1.054688,2.288672,1.669922,1.673437,1.321875,53.03125],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-17.050781,61.699219,63.629297,13.876172,-115.136719,0.288809],"state_q99":[37.705078,187.03125,174.550781,94.932422,-79.365234,52.851986]},
+ {"part":"bensprenger__final_final_right_arm_test_v1","origin":"molmoact","dataset":"bensprenger/final_final_right_arm_test_v1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":9,"train_windows":9,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.875977,-2.109375,-2.645508,-1.234863,-1.582031,-0.097656],"action_q99":[2.988281,2.030273,1.40625,1.50293,1.586426,0.097656],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-91.142578,129.260742,106.523438,47.623535,-108.369141,-0.361011],"state_q99":[79.110352,186.503906,172.792969,80.771484,-74.175293,0.216606]},
+ {"part":"bensprenger__final_right_arm_test_0","origin":"molmoact","dataset":"bensprenger/final_right_arm_test_0","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":23,"train_windows":23,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.285156,-3.621973,-1.77627,-1.073145,-0.097656],"action_q99":[0.966797,2.585742,2.724609,2.197266,1.091602,40.039062],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.123047,28.125,22.587891,50.449219,-90.513281,-0.015162],"state_q99":[1.318359,186.679688,174.726562,100.458984,-71.367188,39.855595]},
+ {"part":"bensprenger__left_arm_yellow_brick_in_box_v0","origin":"molmoact","dataset":"bensprenger/left_arm_yellow_brick_in_box_v0","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1051,"train_windows":1051,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.021484,-2.197266,-1.757812,-1.669922,-0.097656],"action_q99":[0.878906,2.021484,2.197266,1.933594,1.757812,60.058594],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.179688,49.394531,24.760547,7.094531,-161.216016,0.288809],"state_q99":[63.28125,186.855469,172.96875,101.074219,-21.332813,59.844045]},
+ {"part":"bensprenger__left_arm_yellow_brick_in_box_with_purple_noise_v0","origin":"molmoact","dataset":"bensprenger/left_arm_yellow_brick_in_box_with_purple_noise_v0","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1034,"train_windows":1034,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.109375,-2.285156,-2.109375,-1.933594,-0.097656],"action_q99":[1.142578,2.109375,2.197266,2.460938,2.021484,47.949219],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.210938,51.503906,43.066406,-6.591797,-153.017578,0.144404],"state_q99":[63.896484,186.855469,172.96875,100.898438,1.855371,47.653431]},
+ {"part":"bensprenger__purple_test","origin":"molmoact","dataset":"bensprenger/purple_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":75,"train_windows":75,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.107422,-1.933594,-2.689453,-2.25,-2.636719,-0.097656],"action_q99":[0.878906,2.021484,2.074219,2.021484,2.742187,80.371094],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.568359,71.261719,37.388672,17.4375,-108.017578,1.299639],"state_q99":[4.658203,186.503906,172.757812,99.755859,-37.265625,80.158842]},
+ {"part":"bensprenger__purple_test_2","origin":"molmoact","dataset":"bensprenger/purple_test_2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.636719,-3.082324,-2.021484,-2.109375,-0.195312],"action_q99":[1.40625,2.988281,2.900391,2.297461,2.55498,54.296875],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.65293,73.740234,60.292969,29.003906,-121.734668,1.227437],"state_q99":[6.152344,186.503906,172.792969,95.015918,-44.811914,54.007221]},
+ {"part":"bensprenger__so100_test","origin":"molmoact","dataset":"bensprenger/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":85,"train_windows":85,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.757812,-2.300977,-1.40625,-2.021484,2.832031],"action_q99":[1.230469,2.109375,2.373047,1.494141,2.037305,69.353516],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.713086,47.988281,52.718555,32.34375,-110.390625,15.884477],"state_q99":[47.141016,186.767578,172.880859,88.361719,-12.568359,69.169678]},
+ {"part":"bjb7__so101_berm_build_test_1","origin":"molmoact","dataset":"bjb7/so101_berm_build_test_1","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":1431,"train_windows":1431,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-3.603516,-3.515625,-3.515625,-2.724609,0.0],"action_q99":[1.757812,2.724609,3.427734,3.515625,2.197266,0.631579],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.541016,5.273438,5.537109,-4.921875,-46.899316,2.173913],"state_q99":[33.398438,190.458984,181.40625,89.121094,30.058594,2.384292]},
+ {"part":"bjb7__so101_pen_mug","origin":"molmoact","dataset":"bjb7/so101_pen_mug","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":904,"train_windows":904,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-3.691406,-2.988281,-3.164062,-3.955078,-0.350877],"action_q99":[1.318359,2.724609,2.8125,3.427734,4.042969,30.526316],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.486328,32.607422,35.683594,-59.381543,-187.734375,0.420757],"state_q99":[42.539062,193.271484,180.878906,96.438867,170.244141,30.15428]},
+ {"part":"bjb7__so101_pen_mug_10_1","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_1","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":133,"train_windows":133,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.076172,-2.724609,-3.164062,-3.867188,-0.140351],"action_q99":[1.40625,2.288672,2.460938,3.955078,3.427734,30.73965],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.208984,47.197266,53.163281,-62.666016,-82.529297,0.490884],"state_q99":[25.751953,190.458984,180.703125,73.740234,113.818359,30.575033]},
+ {"part":"bjb7__so101_pen_mug_10_10","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_10","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":113,"train_windows":113,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.164062,-2.900391,-4.130859,-4.62832,-0.280702],"action_q99":[1.757812,2.460938,2.548828,4.394531,4.570312,36.421051],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.933594,44.208984,55.634766,-59.0625,-91.40625,0.631136],"state_q99":[51.064453,190.458984,180.966797,90.291797,129.199219,36.115005]},
+ {"part":"bjb7__so101_pen_mug_10_12","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_12","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":137,"train_windows":137,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.900391,-2.285156,-2.8125,-4.688965,-0.210526],"action_q99":[2.285156,2.197266,2.021484,3.164062,4.658203,51.038596],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.013672,57.915527,78.574219,-37.441406,-179.516602,0.981767],"state_q99":[69.728027,190.458984,180.615234,73.125,129.462891,50.476859]},
+ {"part":"bjb7__so101_pen_mug_10_13","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_13","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":117,"train_windows":117,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.724609,-1.911621,-2.790527,-5.163574,-0.210526],"action_q99":[1.494141,2.021484,1.669922,3.251953,4.21875,31.140353],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.859375,82.089844,113.554688,-38.408203,-110.214844,0.490884],"state_q99":[58.007812,190.458984,181.230469,67.412109,111.269531,30.119216]},
+ {"part":"bjb7__so101_pen_mug_10_14","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_14","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":104,"train_windows":104,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.702441,-2.8125,-2.460938,-3.515625,-4.306641,-0.140351],"action_q99":[1.757812,2.373047,2.021484,3.899707,4.306641,29.754385],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.052539,89.63877,106.171875,-54.609082,-113.297168,2.244039],"state_q99":[57.304688,190.458984,180.966797,93.590332,132.890625,29.52314]},
+ {"part":"bjb7__so101_pen_mug_10_15","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_15","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":96,"train_windows":96,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.59873,-3.515625,-2.548828,-3.708105,-4.482422,0.0],"action_q99":[1.40625,2.285156,1.757812,3.955078,4.921875,30.385965],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.925781,82.705078,110.478516,-49.456934,-111.972656,0.771389],"state_q99":[36.035156,190.458984,181.142578,67.236328,87.890625,30.15428]},
+ {"part":"bjb7__so101_pen_mug_10_2","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_2","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":145,"train_windows":145,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.724609,-2.285156,-2.900391,-4.658203,-0.210526],"action_q99":[1.318359,2.373047,2.724609,3.251953,4.925391,32.143157],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.726562,52.294922,44.472656,-35.690625,-108.017578,0.981767],"state_q99":[47.109375,190.458984,181.142578,77.790234,137.548828,31.354837]},
+ {"part":"bjb7__so101_pen_mug_10_3","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_3","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":137,"train_windows":137,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.573242,-2.636719,-2.197266,-2.988281,-4.482422,-0.140351],"action_q99":[1.933594,2.109375,2.109375,3.427734,3.779297,36.631577],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.111328,60.328125,76.640625,-52.558594,-98.173828,0.490884],"state_q99":[49.306641,190.458984,180.878906,82.001953,140.712891,37.019633]},
+ {"part":"bjb7__so101_pen_mug_10_4","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_4","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":127,"train_windows":127,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.988281,-2.548828,-2.636719,-3.955078,0.0],"action_q99":[1.582031,2.109375,2.197266,3.251953,4.130859,29.450525],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.15625,36.503613,39.814453,-38.55498,-112.793555,0.56101],"state_q99":[48.603516,190.458984,181.318359,88.946191,112.412109,29.733521]},
+ {"part":"bjb7__so101_pen_mug_10_5","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_5","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":115,"train_windows":115,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.76416,-2.236816,-2.900391,-4.921875,0.842105],"action_q99":[1.582031,2.460938,2.197266,3.291504,4.21875,30.175438],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.177734,34.980469,42.363281,-31.992188,-103.710938,1.262272],"state_q99":[58.359375,190.458984,180.878906,92.003906,108.720703,29.943899]},
+ {"part":"bjb7__so101_pen_mug_10_6","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_6","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":135,"train_windows":135,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.900391,-2.460938,-3.076172,-4.570312,0.070175],"action_q99":[1.669922,2.285156,2.373047,3.164062,3.867188,36.421051],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.802734,47.900391,59.853516,-29.794922,-109.256836,0.841515],"state_q99":[44.824219,190.458984,180.878906,69.804492,151.875,36.115005]},
+ {"part":"bjb7__so101_pen_mug_10_7","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_7","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":111,"train_windows":111,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.164062,-2.724609,-3.691406,-4.833984,-0.210526],"action_q99":[2.109375,2.636719,2.548828,3.339844,4.21875,32.280701],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.803516,54.492188,67.324219,-40.166016,-119.970703,0.280505],"state_q99":[43.815234,190.458984,181.142578,77.080078,138.164062,32.187939]},
+ {"part":"bjb7__so101_pen_mug_10_8","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_8","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":119,"train_windows":119,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.076172,-2.548828,-3.164062,-4.921875,0.070175],"action_q99":[2.460938,2.373047,1.757812,2.373047,4.306641,29.699648],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.84082,66.781055,84.111328,-9.755859,-115.136719,0.701262],"state_q99":[51.855469,193.623047,181.142578,77.225977,108.808594,29.294531]},
+ {"part":"bjb7__so101_pen_mug_10_9","origin":"molmoact","dataset":"bjb7/so101_pen_mug_10_9","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":104,"train_windows":104,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.515625,-2.900391,-2.900391,-5.636426,-0.350877],"action_q99":[1.757812,2.197266,2.197266,3.251953,4.746094,34.245613],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.011719,50.250586,62.226562,-9.052734,-106.171875,0.350631],"state_q99":[48.989355,190.546875,180.966797,73.839551,108.369141,34.011223]},
+ {"part":"bjb7__so101_pen_test","origin":"molmoact","dataset":"bjb7/so101_pen_test","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":53,"train_windows":53,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.472363,-2.736035,-2.109375,-4.230176,-0.149474],"action_q99":[0.890332,2.285156,2.724609,2.911816,4.493848,25.754387],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.167969,49.646777,67.939453,-55.634766,-92.285156,0.490884],"state_q99":[8.185254,190.546875,180.703125,87.091699,169.892578,25.525946]},
+ {"part":"bjb7__so101_pen_touch_test_1","origin":"molmoact","dataset":"bjb7/so101_pen_touch_test_1","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":678,"train_windows":678,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-4.570312,-3.515625,-1.757812,-0.351562,0.070175],"action_q99":[1.230469,1.054688,0.527344,0.878906,0.351562,0.631579],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.980469,-2.636719,-12.304688,23.115234,-38.759766,0.701262],"state_q99":[44.912109,190.458984,181.142578,81.474609,3.427734,0.701262]},
+ {"part":"bjb7__so101_pen_touch_test_2","origin":"molmoact","dataset":"bjb7/so101_pen_touch_test_2","scene_camera":"observation.images.camera_2","fps":30.0,"built_clips":801,"train_windows":801,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-4.746094,-3.691406,-1.933594,-0.527344,0.070175],"action_q99":[1.40625,1.582031,0.908789,1.318359,0.351562,0.701754],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.229102,37.353516,39.375,16.523438,-18.369141,0.701262],"state_q99":[38.847656,190.458984,180.966797,79.804688,5.625,0.701262]},
+ {"part":"blackfyre-1__so101_test","origin":"molmoact","dataset":"blackfyre-1/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":40,"train_windows":40,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-3.354785,-2.65166,-2.109375,-0.366504,-0.256191],"action_q99":[0.527344,2.548828,3.076172,2.8125,0.615234,28.778822],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.855469,51.328125,28.270898,16.36084,82.441406,-0.564175],"state_q99":[7.03125,193.271484,179.384766,96.240234,99.404297,28.561354]},
+ {"part":"bobdingli__so101_test","origin":"molmoact","dataset":"bobdingli/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":169,"train_windows":169,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-3.891797,-3.339844,-2.021484,-0.351562,0.239044],"action_q99":[0.878906,2.988281,3.339844,2.021484,0.439453,8.631076],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.999219,44.799609,54.228516,28.125,-31.904297,0.57554],"state_q99":[21.846094,194.501953,179.296875,96.440625,2.900391,8.244604]},
+ {"part":"boyangs235__so100-Pick-Place_dataset_Put-square-in-bowl","origin":"molmoact","dataset":"boyangs235/so100-Pick-Place_dataset_Put-square-in-bowl","scene_camera":"observation.images.top","fps":30.0,"built_clips":1383,"train_windows":1383,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.603516,-3.427734,-1.933594,-2.197266,-0.10627],"action_q99":[1.142578,3.955078,4.130859,1.757812,2.373047,36.769394],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[63.017578,41.389453,31.113281,42.451172,-94.306641,0.0],"state_q99":[122.255859,190.986328,178.505859,99.84375,43.330078,36.377247]},
+ {"part":"boyangs235__so100-Put_square_into_area","origin":"molmoact","dataset":"boyangs235/so100-Put_square_into_area","scene_camera":"observation.images.top","fps":30.0,"built_clips":1324,"train_windows":1324,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-3.515625,-3.251953,-1.845703,-2.636719,-0.10627],"action_q99":[1.142578,3.515625,3.427734,1.669922,2.988281,37.938362],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[52.558594,50.976562,49.658203,15.820312,-103.392773,0.0],"state_q99":[122.255859,190.986328,178.59375,94.482422,33.310547,37.5]},
+ {"part":"brus123__so100_test","origin":"molmoact","dataset":"brus123/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":85,"train_windows":85,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-1.997754,-2.197266,-1.997754,-1.558301,-0.115473],"action_q99":[1.582031,2.285156,2.373047,1.669922,1.845703,87.532333],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.679688,65.813379,50.912402,42.714844,-39.902344,1.021898],"state_q99":[71.806641,183.339844,171.210938,100.458984,7.734375,86.675915]},
+ {"part":"budinggou__so100_test","origin":"molmoact","dataset":"budinggou/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":32,"train_windows":32,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.415039,-2.636719,-3.427734,-3.348633,-2.548828,-0.180258],"action_q99":[1.582031,2.460938,3.348633,3.867188,2.021484,62.145924],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-63.28125,-15.205078,-11.162109,-21.269531,-216.140625,0.480439],"state_q99":[-1.40625,95.326172,84.375,98.701172,-145.283203,61.839397]},
+ {"part":"burgalon__so100_test_camera_top","origin":"molmoact","dataset":"burgalon/so100_test_camera_top","scene_camera":"observation.images.phone","fps":30.0,"built_clips":576,"train_windows":576,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-4.482422,-3.603516,-2.636719,-1.845703,-0.285714],"action_q99":[3.691406,3.955078,3.076172,2.373047,1.669922,34.59238],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.659961,38.847656,27.421875,-79.140234,-100.566211,0.326531],"state_q99":[19.531055,192.65625,179.736328,97.734375,-13.095703,33.551018]},
+ {"part":"bursomi__so101_test","origin":"molmoact","dataset":"bursomi/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":152,"train_windows":152,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.955078,-4.570312,-2.197266,-1.933594,-0.171527],"action_q99":[2.107617,3.076172,3.955078,2.460938,2.636719,46.397942],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.131836,62.050781,60.732422,49.921875,-131.220703,0.224048],"state_q99":[32.340234,199.599609,185.888672,94.042969,-74.276367,45.929798]},
+ {"part":"carlosdp__so100_test","origin":"molmoact","dataset":"carlosdp/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":193,"train_windows":193,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.251953,-3.076172,-1.318359,-0.263672,-0.257069],"action_q99":[1.318359,2.900391,2.724609,1.318359,0.263672,29.576693],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.707031,42.423047,32.607422,40.679297,-2.548828,0.631769],"state_q99":[28.212891,187.382812,180.263672,101.074219,5.888672,29.422382]},
+ {"part":"cdv3__1lyz123576__so101_test","origin":"community_dataset_v3","dataset":"1lyz123576/so101_test","scene_camera":"observation.images.image","fps":30.0,"built_clips":2059,"train_windows":2059,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.900391,-3.251953,-1.669922,-0.878906,-0.162734],"action_q99":[1.933594,3.515625,3.164062,1.669922,1.054688,42.88039],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.660156,-105.996094,-28.652344,52.910156,-26.191406,0.775741],"state_q99":[45.791016,30.058594,90.439453,97.207031,2.548828,42.454163]},
+ {"part":"cdv3__1lyz123576__so101_test-1","origin":"community_dataset_v3","dataset":"1lyz123576/so101_test-1","scene_camera":"observation.images.image","fps":30.0,"built_clips":360,"train_windows":360,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-5.009766,-3.779297,-3.339844,-1.669922,-0.81367],"action_q99":[1.582031,4.21875,6.416016,2.636719,2.109375,39.381611],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.129102,-105.908203,-45.878906,47.339648,-42.363281,0.634697],"state_q99":[37.617188,46.054688,91.230469,95.537109,8.876953,38.629055]},
+ {"part":"cdv3__AkibaGeek__so100_test","origin":"community_dataset_v3","dataset":"AkibaGeek/so100_test","scene_camera":"observation.images.image","fps":30.0,"built_clips":284,"train_windows":284,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-4.746094,-3.251953,-1.669922,-1.494141,-0.382409],"action_q99":[1.40625,4.394531,3.955078,1.494141,1.582031,34.799236],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.133691,-102.128906,-36.035156,52.734375,-58.007812,0.2886],"state_q99":[3.339844,37.001953,86.660156,99.84375,24.345703,33.261185]},
+ {"part":"cdv3__AntoineA__so100_green_cube_black_circle","origin":"community_dataset_v3","dataset":"AntoineA/so100_green_cube_black_circle","scene_camera":"observation.images.image","fps":30.0,"built_clips":146,"train_windows":146,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-5.712891,-4.042969,-1.845703,-2.548828,0.176991],"action_q99":[1.494141,3.515625,5.185547,1.970508,2.988281,17.168142],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.659961,-103.886719,-37.829883,49.833984,-83.79668,0.417827],"state_q99":[31.904297,34.050586,88.330078,98.673047,12.832031,17.200556]},
+ {"part":"cdv3__AnttAI__record-test3","origin":"community_dataset_v3","dataset":"AnttAI/record-test3","scene_camera":"observation.images.image","fps":30.0,"built_clips":592,"train_windows":592,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.231804,-4.067799,-3.958614,-3.455734,-1.97544,0.789889],"action_q99":[1.791712,3.81356,3.884313,3.623508,1.975441,44.075829],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.039594,-98.468735,-35.441372,-8.843537,-14.919145,1.219512],"state_q99":[40.99469,42.067207,99.121651,89.795921,84.715698,42.48916]},
+ {"part":"cdv3__Anybalsmith__pickplacelegocube3","origin":"community_dataset_v3","dataset":"Anybalsmith/pickplacelegocube3","scene_camera":"observation.images.image","fps":30.0,"built_clips":695,"train_windows":695,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.321083,-3.204043,-3.519852,-2.19902,-1.411396,0.0],"action_q99":[3.404256,4.300171,4.061372,3.020882,1.934134,31.762794],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-73.051224,-98.810028,-7.838695,10.800704,-3.001058,0.0],"state_q99":[22.345955,12.112197,99.546898,98.240211,68.059227,31.725544]},
+ {"part":"cdv3__Aoxi29__cookie_v2","origin":"community_dataset_v3","dataset":"Aoxi29/cookie_v2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":583,"train_windows":583,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.197266,-2.548828,-1.494141,-0.966797,-0.26455],"action_q99":[1.230469,2.724609,2.724609,1.318359,0.966797,51.410938],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.072266,-99.580078,-39.462891,44.824219,-15.996094,1.070473],"state_q99":[36.99668,43.242188,95.009766,89.731055,22.412109,52.096344]},
+ {"part":"cdv3__Aven9208__train-test","origin":"community_dataset_v3","dataset":"Aven9208/train-test","scene_camera":"observation.images.image2","fps":30.0,"built_clips":161,"train_windows":161,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.256281,-3.495312,-5.502933,-2.904739,-1.043912,0.780031],"action_q99":[1.662479,6.138111,4.600812,2.563011,1.36734,28.549143],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-7.806367,-98.894554,-80.98687,19.739761,-64.547615,1.435407],"state_q99":[29.960751,56.377552,99.728386,98.464165,-32.366131,27.751196]},
+ {"part":"cdv3__Ayush-Sharan-1__c-4g_tC-T_fC-T_d-280525_v-2","origin":"community_dataset_v3","dataset":"Ayush-Sharan-1/c-4g_tC-T_fC-T_d-280525_v-2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":611,"train_windows":611,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.373047,-2.900391,-2.548828,-3.779297,-0.176678],"action_q99":[1.933594,2.8125,2.636719,2.197266,2.988281,46.079506],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-51.503906,-99.316406,-33.398438,-1.845703,-149.150391,0.0],"state_q99":[53.701172,36.650391,89.736328,99.492188,10.458984,45.911949]},
+ {"part":"cdv3__Ayush-Sharan-1__placeCoinOnGrid_v01","origin":"community_dataset_v3","dataset":"Ayush-Sharan-1/placeCoinOnGrid_v01","scene_camera":"observation.images.image2","fps":30.0,"built_clips":203,"train_windows":203,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.262253,-4.291847,-5.57745,-3.569946,-2.735043,0.0],"action_q99":[2.178467,5.23605,5.224566,2.988792,3.223444,38.268398],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-6.398687,-99.825935,-10.127737,34.837917,-0.903541,0.545331],"state_q99":[50.451191,27.502176,99.81752,97.620026,76.507935,37.900478]},
+ {"part":"cdv3__Beegbrain__draw_pixel_art","origin":"community_dataset_v3","dataset":"Beegbrain/draw_pixel_art","scene_camera":"observation.images.image","fps":30.0,"built_clips":1433,"train_windows":1433,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.883978,-2.40757,-2.628002,-0.977039,-0.683762,0.0],"action_q99":[1.178637,2.407566,2.446762,0.928186,0.683758,32.266911],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-32.118118,-98.049194,-42.468667,-29.768009,26.544567,1.197605],"state_q99":[18.495807,39.355385,99.470436,6.178266,58.925518,32.335331]},
+ {"part":"cdv3__BobBobbson__so100_BEP_Tactile_Dataset_Finalllly","origin":"community_dataset_v3","dataset":"BobBobbson/so100_BEP_Tactile_Dataset_Finalllly","scene_camera":"observation.images.image","fps":30.0,"built_clips":3268,"train_windows":3268,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.407612,-0.886861,-1.265808,-0.567247,0.0,26.299999],"action_q99":[0.843988,0.961771,0.885112,1.016124,0.0,110.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.474609,-62.138672,-58.798828,34.277344,-0.263672,29.812439],"state_q99":[79.365234,31.376953,60.380859,94.042969,0.0,108.193481]},
+ {"part":"cdv3__CalvinChiff__record-flower","origin":"community_dataset_v3","dataset":"CalvinChiff/record-flower","scene_camera":"observation.images.image","fps":30.0,"built_clips":212,"train_windows":212,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.11276,-3.38696,-3.266787,-1.830063,-1.254246,1.170047],"action_q99":[1.261128,3.895004,3.629765,2.204793,0.940683,20.873635],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-45.17691,-98.484848,-69.589906,52.356247,-84.294885,0.881954],"state_q99":[21.191807,54.882156,75.935104,99.394722,47.546879,20.352781]},
+ {"part":"cdv3__Clementppr__dataset_set_up_table_fork","origin":"community_dataset_v3","dataset":"Clementppr/dataset_set_up_table_fork","scene_camera":"observation.images.image","fps":30.0,"built_clips":300,"train_windows":300,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.005025,-3.465763,-3.717133,-2.012074,-1.025641,0.0],"action_q99":[0.86145,3.803886,4.170444,1.69014,1.213675,1.047904],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-6.586254,-95.34314,-90.958412,22.756411,-12.520147,0.958904],"state_q99":[46.381428,65.334964,99.457504,94.71154,72.35409,1.643836]},
+ {"part":"cdv3__Clementppr__dataset_set_up_table_plate","origin":"community_dataset_v3","dataset":"Clementppr/dataset_set_up_table_plate","scene_camera":"observation.images.image","fps":30.0,"built_clips":388,"train_windows":388,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.722899,-2.789518,-3.98912,-2.253521,-2.051282,0.0],"action_q99":[1.7229,2.95858,2.991841,2.253519,1.758242,36.826347],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-47.200729,-96.241829,-56.618444,-1.36218,-20.43956,1.027397],"state_q99":[42.740101,26.013072,99.09584,97.275642,86.490843,36.575344]},
+ {"part":"cdv3__DanqingZ__filtered_pick_pink","origin":"community_dataset_v3","dataset":"DanqingZ/filtered_pick_pink","scene_camera":"observation.images.image","fps":30.0,"built_clips":433,"train_windows":433,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-2.548828,-4.921875,-2.548828,-1.669922,-8.444444],"action_q99":[2.460938,3.691406,3.251953,3.076172,2.021484,42.666668],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.130859,-99.84375,-5.449219,33.180469,-62.841797,-6.171875],"state_q99":[16.523438,0.390234,81.5625,96.503906,30.628125,42.1875]},
+ {"part":"cdv3__DanqingZ__filtered_pick_yellow","origin":"community_dataset_v3","dataset":"DanqingZ/filtered_pick_yellow","scene_camera":"observation.images.image","fps":30.0,"built_clips":458,"train_windows":458,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-2.900391,-4.570312,-2.373047,-1.40625,-8.444444],"action_q99":[2.724609,3.515625,2.724609,2.988281,1.933594,49.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.658203,-99.84375,1.669922,32.581055,-36.70752,-6.171875],"state_q99":[7.646484,-0.527344,81.914062,91.318359,31.376953,48.046875]},
+ {"part":"cdv3__DanqingZ__filtered_pick_yellow_pink","origin":"community_dataset_v3","dataset":"DanqingZ/filtered_pick_yellow_pink","scene_camera":"observation.images.image","fps":30.0,"built_clips":891,"train_windows":891,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-2.724609,-4.746094,-2.460938,-1.582031,-8.444444],"action_q99":[2.548828,3.603516,2.988281,2.988281,1.933594,46.111111],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.394531,-99.84375,-2.8125,32.860547,-52.734375,-6.171875],"state_q99":[16.347656,-0.263672,81.5625,94.394531,30.849609,45.390625]},
+ {"part":"cdv3__DanqingZ__tic_tac_toe_grid_6","origin":"community_dataset_v3","dataset":"DanqingZ/tic_tac_toe_grid_6","scene_camera":"observation.images.image","fps":30.0,"built_clips":864,"train_windows":864,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-3.779297,-4.306641,-2.460938,-1.669922,0.0],"action_q99":[2.197266,3.515625,3.779297,2.548828,1.669922,46.889823],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.773438,-99.667969,-13.007812,36.035156,-56.425781,-0.33389],"state_q99":[33.925781,8.261719,85.429688,91.481836,19.775391,46.24374]},
+ {"part":"cdv3__DanqingZ__tic_tac_toe_grid_combined_2_4_6_7","origin":"community_dataset_v3","dataset":"DanqingZ/tic_tac_toe_grid_combined_2_4_6_7","scene_camera":"observation.images.image","fps":30.0,"built_clips":1558,"train_windows":1558,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.988281,-3.603516,-4.042969,-2.460938,-1.757812,0.0],"action_q99":[2.548828,3.076172,4.394531,2.460938,1.757812,45.330536],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-58.798828,-99.667969,-58.095703,33.75,-62.226562,-0.250417],"state_q99":[31.552734,40.166016,85.429688,95.888672,16.699219,44.741234]},
+ {"part":"cdv3__EGLima__pen_task_v3","origin":"community_dataset_v3","dataset":"EGLima/pen_task_v3","scene_camera":"observation.images.image2","fps":30.0,"built_clips":544,"train_windows":544,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-4.306641,-4.655566,-2.285156,-4.21875,-1.542912],"action_q99":[1.933594,4.833984,4.482422,3.600879,4.21875,68.3703],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.542969,-98.789062,-81.820898,-5.268164,-164.882812,4.214876],"state_q99":[0.615234,63.630176,92.548828,98.701172,54.558984,67.60331]},
+ {"part":"cdv3__EGLima__pen_task_v5","origin":"community_dataset_v3","dataset":"EGLima/pen_task_v5","scene_camera":"observation.images.image2","fps":30.0,"built_clips":2638,"train_windows":2638,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-5.273438,-5.009766,-3.691406,-2.8125,-1.639344],"action_q99":[1.933594,5.273438,5.273438,3.339844,3.867188,47.514949],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.191406,-99.228516,-52.998047,-22.148438,-166.025391,4.380166],"state_q99":[4.921875,64.072266,92.636719,80.859375,15.996094,47.355373]},
+ {"part":"cdv3__EverNorif__so101-pick-pen","origin":"community_dataset_v3","dataset":"EverNorif/so101-pick-pen","scene_camera":"observation.images.image","fps":30.0,"built_clips":1509,"train_windows":1509,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.258065,-5.494503,-5.6134,-6.532017,-3.170413,1.437216],"action_q99":[2.016129,6.08622,5.885017,9.454231,3.136436,31.770046],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-55.901223,-99.407532,-64.909253,-35.887166,-80.594681,1.697128],"state_q99":[19.797382,57.511639,96.662238,95.607239,21.351069,31.723238]},
+ {"part":"cdv3__EverNorif__so101-place-orange","origin":"community_dataset_v3","dataset":"EverNorif/so101-place-orange","scene_camera":"observation.images.image","fps":30.0,"built_clips":1530,"train_windows":1530,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.5,-3.719357,-4.345856,-3.094109,-2.090958,1.891074],"action_q99":[2.5,3.381237,3.893166,3.351955,1.934135,62.556732],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-53.904602,-99.153618,-61.398849,-8.78553,-76.744914,1.89295],"state_q99":[38.556352,53.78756,98.937584,96.726959,0.260824,62.206264]},
+ {"part":"cdv3__EverNorif__so101-table-cleanup","origin":"community_dataset_v3","dataset":"EverNorif/so101-table-cleanup","scene_camera":"observation.images.image","fps":30.0,"built_clips":2855,"train_windows":2855,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.280293,-3.023941,-3.07692,-4.218683,-1.937172,1.714731],"action_q99":[1.180209,2.855942,3.348416,4.555809,1.676403,29.696026],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-56.931873,-99.065422,-53.04039,-36.937717,-91.469444,1.840894],"state_q99":[17.675083,51.656754,99.201065,97.410446,1.430429,29.066404]},
+ {"part":"cdv3__HaloLi0828__record-pick-1","origin":"community_dataset_v3","dataset":"HaloLi0828/record-pick-1","scene_camera":"observation.images.image","fps":30.0,"built_clips":1043,"train_windows":1043,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.759531,-2.455063,-2.902495,-1.577564,-1.466991,0.422654],"action_q99":[1.75953,2.893471,2.993198,1.752853,1.466993,33.260356],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-36.341164,-99.322037,-53.18182,26.384649,-17.102995,0.491228],"state_q99":[58.714462,51.779659,93.272728,85.521149,63.528114,32.701756]},
+ {"part":"cdv3__Haresh55__record-test-5","origin":"community_dataset_v3","dataset":"Haresh55/record-test-5","scene_camera":"observation.images.image","fps":30.0,"built_clips":100,"train_windows":100,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.896343,-3.579037,-1.99393,-1.895379,-1.043316,2.267574],"action_q99":[3.161584,3.04559,2.774168,2.179598,1.059521,54.270596],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-99.528671,-97.238838,19.675091,-19.113083,-18.730158,2.4788],"state_q99":[11.861744,22.319374,100.0,45.6745,-2.137241,53.881279]},
+ {"part":"cdv3__Haribot099__Shape_Place","origin":"community_dataset_v3","dataset":"Haribot099/Shape_Place","scene_camera":"observation.images.image2","fps":30.0,"built_clips":223,"train_windows":223,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.5625,-2.51046,-2.364209,-1.382889,-1.098324,0.631413],"action_q99":[1.367188,2.51046,2.158272,2.074333,1.113494,24.151539],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-56.12722,-99.742271,-24.820145,-28.216796,-59.126366,0.849673],"state_q99":[7.109448,39.003437,98.741005,85.004288,-21.320852,23.986929]},
+ {"part":"cdv3__Jinheng0130__Push","origin":"community_dataset_v3","dataset":"Jinheng0130/Push","scene_camera":"observation.images.image2","fps":30.0,"built_clips":72,"train_windows":72,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.175781,-3.164062,-3.779297,-1.582031,-0.175781,2.292899],"action_q99":[0.175781,2.460938,4.394531,1.452832,0.175781,12.02145],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.537109,0.0,-36.702246,-38.583984,-92.8125,8.526552],"state_q99":[0.527344,57.361816,39.375,-8.432227,-86.923828,11.931937]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__141-Electrify-battery_placing","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/141-Electrify-battery_placing","scene_camera":"observation.images.image2","fps":30.0,"built_clips":761,"train_windows":761,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.86819,-4.264397,-2.995594,-1.748253,-1.408451,0.0],"action_q99":[1.971977,3.667375,2.731277,1.923077,1.199791,32.917706],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-54.519932,-99.235992,-15.69873,30.663221,-37.548588,0.0],"state_q99":[34.755756,30.006791,99.727768,81.998276,55.636177,33.127148]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__141-Electrify-open_alligator","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/141-Electrify-open_alligator","scene_camera":"observation.images.image2","fps":30.0,"built_clips":595,"train_windows":595,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.32206,-3.65802,-3.508774,-1.718948,-1.094035,0.780031],"action_q99":[1.739527,4.168438,2.190762,1.890846,1.198229,41.575665],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-58.678612,-98.82402,-21.901377,33.848133,-39.157406,0.742741],"state_q99":[25.419933,37.62085,98.844955,81.169589,11.966916,41.728561]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__159-LeBabybot-peg_in_hole","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/159-LeBabybot-peg_in_hole","scene_camera":"observation.images.image2","fps":30.0,"built_clips":4048,"train_windows":4048,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.411591,-2.802547,-1.9678,-1.527946,-0.976801,1.276596],"action_q99":[1.708767,2.802547,1.699463,1.527946,1.221001,92.348934],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-16.277399,-95.847458,-35.71106,42.45359,-26.398046,1.916722],"state_q99":[52.353577,48.389832,56.29797,98.305084,53.162392,92.068741]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__160-LegoBot-lego_pixelart_stage_1_v1","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/160-LegoBot-lego_pixelart_stage_1_v1","scene_camera":"observation.images.image","fps":30.0,"built_clips":644,"train_windows":644,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.579037,-1.899826,-1.634135,-1.060791,-1.709402,0.149589],"action_q99":[3.078203,1.381693,2.269632,1.713585,1.367522,39.416603],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-59.752323,-19.895515,-42.356113,59.39127,-32.258854,1.202405],"state_q99":[80.097305,43.14323,32.733814,98.878654,45.689865,39.17368]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__160-LegoBot-lego_pixelart_stage_1_v2","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/160-LegoBot-lego_pixelart_stage_1_v2","scene_camera":"observation.images.image","fps":30.0,"built_clips":585,"train_windows":585,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.257115,-1.567657,-1.816532,-1.135902,-0.92796,0.0],"action_q99":[2.060844,1.320131,1.634878,1.54158,1.074481,35.154186],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-57.994877,-36.754276,-38.964577,58.009708,-24.297924,0.811908],"state_q99":[49.359676,32.749271,59.086286,98.668287,32.138705,34.709064]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__241-Sushi_Shinkansen_So101-pick_sushi","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/241-Sushi_Shinkansen_So101-pick_sushi","scene_camera":"observation.images.image","fps":30.0,"built_clips":2051,"train_windows":2051,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.37676,-3.566986,-3.246167,-2.377922,-1.150627,2.629544],"action_q99":[2.200704,3.069267,4.697928,2.123138,1.464436,36.968292],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-89.293015,-98.059891,-76.212257,31.756302,-10.972581,2.987013],"state_q99":[26.195341,56.895824,97.255264,98.319328,59.906879,36.688313]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__27-AI_Learners-Shape_Pick_and_Place","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/27-AI_Learners-Shape_Pick_and_Place","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1862,"train_windows":1862,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.5625,-2.259415,-2.60791,-1.210026,-1.150627,0.710339],"action_q99":[1.269531,2.594143,1.978416,1.555748,1.098328,28.413576],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-52.666042,-99.398628,-42.266186,35.13282,-79.511177,1.111111],"state_q99":[25.912067,47.594501,98.92086,96.658096,-0.052002,28.69281]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__29-TEAMCHAP-spoonHandling","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/29-TEAMCHAP-spoonHandling","scene_camera":"observation.images.image","fps":30.0,"built_clips":1664,"train_windows":1664,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.111113,-1.711597,-1.681416,-1.897232,-1.02564,2.37366],"action_q99":[1.037037,1.882751,1.415928,1.739132,0.927961,4.517611],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-30.729927,-99.570633,23.821548,-71.176231,-11.306471,3.153745],"state_q99":[32.992702,13.868613,99.6633,50.381374,29.91453,4.467805]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__292-AlorsCent-cube_and_arc_put_into_respective_shaped_holes","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/292-AlorsCent-cube_and_arc_put_into_respective_shaped_holes","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1508,"train_windows":1508,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.49688,-4.299149,-3.91621,-3.010536,-2.246642,1.086957],"action_q99":[2.87141,4.83654,4.462659,3.010536,2.393162,100.0],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-59.140858,-99.821671,-54.123962,13.482057,-74.847374,10.586319],"state_q99":[18.422577,52.474365,99.414345,99.61203,21.221001,99.511398]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__300-Mad_Robots-remove_orange_object","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/300-Mad_Robots-remove_orange_object","scene_camera":"observation.images.image2","fps":30.0,"built_clips":395,"train_windows":395,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-4.731979,-5.119595,-7.461239,-4.377785,-2.197802,0.0],"action_q99":[5.027727,6.210656,6.492248,5.269558,2.442002,78.932587],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-72.365723,-99.10714,-50.553631,-6.118232,-18.782906,2.109705],"state_q99":[33.333332,43.310713,100.0,83.308495,15.56337,79.18425]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__347-WaterworksCrew-HandymanBot","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/347-WaterworksCrew-HandymanBot","scene_camera":"observation.images.image","fps":30.0,"built_clips":645,"train_windows":645,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.177336,-4.629629,-2.804161,-2.659805,-1.094035,1.034208],"action_q99":[1.692421,3.703705,5.065582,2.145004,1.198228,25.457438],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-33.43055,-99.152542,-38.37838,35.588863,-17.216118,0.966495],"state_q99":[33.43055,26.232204,98.828827,86.532761,34.689622,25.193298]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__356-DuctTapeEngineers-MarkTableWhileUnmarked","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/356-DuctTapeEngineers-MarkTableWhileUnmarked","scene_camera":"observation.images.image","fps":30.0,"built_clips":132,"train_windows":132,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.618279,-3.829278,-6.017063,-6.702084,-2.490843,0.0],"action_q99":[2.109473,4.228158,3.322857,5.884756,2.148962,45.468872],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-11.139428,-93.070999,-98.075241,-78.947533,-2.905983,1.535509],"state_q99":[42.936287,92.301109,98.162727,88.041978,55.31917,45.456174]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__364-ET_HOME_SERVICE-cleaning_sat_data","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/364-ET_HOME_SERVICE-cleaning_sat_data","scene_camera":"observation.images.image","fps":30.0,"built_clips":538,"train_windows":538,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-7.78342,-7.032589,-6.134968,-3.85878,-2.051283,0.0],"action_q99":[5.245346,5.317324,6.984426,4.351395,1.611722,56.689537],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-43.72945,-98.09771,-99.549141,32.422359,-9.010989,0.58309],"state_q99":[63.363083,92.217896,99.008118,99.00621,40.561661,56.70554]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__364-ET_HOME_SERVICE-grab_can_sat","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/364-ET_HOME_SERVICE-grab_can_sat","scene_camera":"observation.images.image","fps":30.0,"built_clips":446,"train_windows":446,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.030457,-4.030872,-3.397827,-5.500821,-0.43956,0.085763],"action_q99":[2.538071,4.45969,3.775364,4.187192,0.4884,83.876503],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-36.589947,-97.233032,-21.172227,-69.026917,-3.296703,0.655977],"state_q99":[26.989196,53.826199,99.278633,48.405796,7.008547,84.18367]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__364-ET_HOME_SERVICE-mobile_kitchen_sat","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/364-ET_HOME_SERVICE-mobile_kitchen_sat","scene_camera":"observation.images.image","fps":30.0,"built_clips":752,"train_windows":752,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.876481,-4.116638,-5.191128,-3.441705,-1.367521,0.0],"action_q99":[2.876481,4.030876,4.239734,4.269295,1.269842,43.739281],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-42.602161,-97.060097,-43.642921,-14.534162,-21.701588,0.510204],"state_q99":[40.441521,43.363598,99.278633,85.09317,38.51038,43.586006]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__380-horseinbox-HorseInBox","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/380-horseinbox-HorseInBox","scene_camera":"observation.images.image","fps":30.0,"built_clips":900,"train_windows":900,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.428572,-4.601772,-3.914429,-2.740864,-1.514042,0.0],"action_q99":[1.5,3.805313,4.369595,2.823919,1.514041,47.706421],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-33.905899,-99.829788,-60.070717,-21.541157,-9.705959,0.278358],"state_q99":[23.002241,52.967661,99.728012,99.474609,72.105125,47.459988]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__386-boxbusters-clean_workspace","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/386-boxbusters-clean_workspace","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1047,"train_windows":1047,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.264151,-2.529518,-3.063058,-2.697999,-0.782475,1.035857],"action_q99":[2.803234,3.119728,2.612617,3.655353,0.782475,51.633465],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-9.024612,-98.406044,-90.486513,-39.319149,-61.083614,1.282051],"state_q99":[80.401093,52.852348,98.669962,81.361702,-39.775982,51.474358]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__91-AM-PM-pouring-liquid","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/91-AM-PM-pouring-liquid","scene_camera":"observation.images.image","fps":30.0,"built_clips":1095,"train_windows":1095,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.83682,-4.778156,-2.813065,-5.732814,-2.204145,0.41806],"action_q99":[0.83682,4.180889,3.266788,5.620407,2.046707,25.334448],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-11.564626,-98.972603,-2.239533,-74.529541,-59.717129,0.776288],"state_q99":[3.099017,38.296234,99.902626,75.667397,-6.286014,25.476358]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__Test","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/Test","scene_camera":"observation.images.image","fps":30.0,"built_clips":114,"train_windows":114,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.024649,-3.484031,-2.434624,-1.78344,-1.307531,2.629544],"action_q99":[1.929577,2.564909,4.057709,2.286198,1.778244,35.028614],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-72.531265,-97.891182,-32.387924,42.184875,-11.321262,3.311688],"state_q99":[16.946466,34.029522,96.614822,96.386551,60.165546,35.064934]},
+ {"part":"cdv3__LeRobot-worldwide-hackathon__lego_pixelart_stage_1_v3","origin":"community_dataset_v3","dataset":"LeRobot-worldwide-hackathon/lego_pixelart_stage_1_v3","scene_camera":"observation.images.image","fps":30.0,"built_clips":802,"train_windows":802,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.264229,-2.757432,-3.082504,-2.448975,-2.051285,0.149589],"action_q99":[3.881782,2.843601,3.173164,2.448975,1.953602,42.333584],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-56.231308,-98.882683,-17.042381,41.63987,-28.279854,0.952381],"state_q99":[91.326019,29.093252,98.917946,98.633438,50.964592,42.2449]},
+ {"part":"cdv3__MarkusWuenstel__clean-pens","origin":"community_dataset_v3","dataset":"MarkusWuenstel/clean-pens","scene_camera":"observation.images.image3","fps":30.0,"built_clips":1409,"train_windows":1409,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.69808,-1.579384,-1.536377,-1.887602,-0.731644,1.857585],"action_q99":[0.69808,1.66251,1.355625,2.144997,0.779827,51.070335],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-31.354515,-98.583923,7.850342,-70.155525,-79.497696,2.57732],"state_q99":[27.173914,21.550646,99.458969,75.872215,-14.249103,50.837627]},
+ {"part":"cdv3__MarkusWuenstel__distinguish-pens","origin":"community_dataset_v3","dataset":"MarkusWuenstel/distinguish-pens","scene_camera":"observation.images.image","fps":30.0,"built_clips":205,"train_windows":205,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.872601,-1.911888,-1.830389,-2.659802,-0.571873,2.06422],"action_q99":[1.13438,2.508729,1.55828,3.260403,0.67585,54.740063],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-31.391586,-97.920998,11.05097,-75.041878,-62.785862,2.913279],"state_q99":[24.433657,19.530977,99.188095,74.120605,-44.490646,53.997292]},
+ {"part":"cdv3__MarkusWuenstel__tape-two-cameras","origin":"community_dataset_v3","dataset":"MarkusWuenstel/tape-two-cameras","scene_camera":"observation.images.image","fps":30.0,"built_clips":156,"train_windows":156,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.991884,-2.407639,-2.169006,-1.861742,-0.574863,1.934985],"action_q99":[1.262398,2.407639,2.168999,2.544529,0.627125,29.791021],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-37.774101,-98.334724,7.179946,13.054394,-63.542206,2.946708],"state_q99":[10.21928,20.395504,98.65712,74.97908,-51.683067,29.028214]},
+ {"part":"cdv3__Matlef__cube_tower_circle","origin":"community_dataset_v3","dataset":"Matlef/cube_tower_circle","scene_camera":"observation.images.image3","fps":30.0,"built_clips":7346,"train_windows":7346,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.109375,-3.164062,-1.669922,-2.460938,-6.235012],"action_q99":[2.021484,2.460938,2.548828,2.021484,2.548828,54.676258],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-65.830078,-99.755859,-68.730469,48.603516,-88.681641,-2.960222],"state_q99":[78.574219,58.798828,89.472656,99.84375,64.599609,54.486584]},
+ {"part":"cdv3__Mohamedal__eval_act_so100_model100k","origin":"community_dataset_v3","dataset":"Mohamedal/eval_act_so100_model100k","scene_camera":"observation.images.image","fps":30.0,"built_clips":277,"train_windows":277,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.396595,-4.989888,-6.059506,-3.333119,-2.183531,-0.535576],"action_q99":[3.24522,5.91352,4.139286,3.952323,2.221471,54.668652],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.580469,-98.996484,-45.527344,1.638281,-52.207031,0.630252],"state_q99":[49.426172,46.40625,90.175781,95.800781,16.259766,54.201679]},
+ {"part":"cdv3__Mohamedal__put_banana_bowl_dis_test2","origin":"community_dataset_v3","dataset":"Mohamedal/put_banana_bowl_dis_test2","scene_camera":"observation.images.image","fps":30.0,"built_clips":398,"train_windows":398,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-4.030664,-4.130859,-2.460938,-2.285156,0.107759],"action_q99":[3.076172,3.691406,5.273438,2.636719,2.988281,54.633621],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.015625,-99.755859,-76.025391,50.097656,-42.802734,0.464684],"state_q99":[31.376953,58.447266,88.59375,104.765625,91.757812,53.996281]},
+ {"part":"cdv3__Mohamedal__put_peach_bowl_dis_test2","origin":"community_dataset_v3","dataset":"Mohamedal/put_peach_bowl_dis_test2","scene_camera":"observation.images.image","fps":30.0,"built_clips":401,"train_windows":401,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-4.130859,-4.746094,-2.460938,-2.285156,0.0],"action_q99":[3.427734,3.955078,5.185547,2.900391,2.373047,59.532711],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-67.060547,-93.251953,-81.474609,50.888672,-31.904297,0.160643],"state_q99":[33.222656,66.357422,84.462891,102.919922,87.626953,58.634537]},
+ {"part":"cdv3__Mohamedal__put_plum_bowl_dis_test2","origin":"community_dataset_v3","dataset":"Mohamedal/put_plum_bowl_dis_test2","scene_camera":"observation.images.image","fps":30.0,"built_clips":495,"train_windows":495,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.339844,-4.041211,-2.371289,-2.021484,0.093458],"action_q99":[2.988281,3.251953,4.21875,2.548828,1.933594,54.485981],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-65.654297,-93.339844,-87.447656,46.40625,-36.99668,0.481928],"state_q99":[35.15625,71.542969,84.199219,103.007812,87.451172,53.493977]},
+ {"part":"cdv3__Mohamedal__so100_put_cube_bowl_newda","origin":"community_dataset_v3","dataset":"Mohamedal/so100_put_cube_bowl_newda","scene_camera":"observation.images.image","fps":30.0,"built_clips":670,"train_windows":670,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.636719,-2.724609,-2.636719,-1.230469,0.192123],"action_q99":[1.933594,2.197266,3.691406,2.460938,1.142578,69.932762],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.142578,-97.998047,-66.930469,25.136719,-18.105469,1.185771],"state_q99":[37.177734,50.097656,89.472656,103.183594,49.482422,69.16996]},
+ {"part":"cdv3__MostafaOthman__pickplace_sweetsjp","origin":"community_dataset_v3","dataset":"MostafaOthman/pickplace_sweetsjp","scene_camera":"observation.images.image","fps":30.0,"built_clips":93,"train_windows":93,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.25138,-3.280874,-3.03105,-2.397263,-1.426548,1.127214],"action_q99":[1.398602,4.018422,4.383562,2.413529,1.469044,39.533012],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-16.730885,-99.666252,-53.223656,24.061434,-47.56544,2.230971],"state_q99":[37.331333,39.841469,96.798576,98.720139,27.965235,39.238846]},
+ {"part":"cdv3__MostafaOthman__pickplace_sweetsjp_smallcandy","origin":"community_dataset_v3","dataset":"MostafaOthman/pickplace_sweetsjp_smallcandy","scene_camera":"observation.images.image","fps":30.0,"built_clips":129,"train_windows":129,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.883327,-3.348682,-3.28767,-2.825341,-1.731375,1.016908],"action_q99":[0.836952,4.269565,4.508676,2.654106,1.573977,31.803543],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-14.617691,-99.415939,-60.192976,15.955631,-58.179958,2.099738],"state_q99":[26.836582,42.428036,97.687859,98.549484,22.137014,31.889763]},
+ {"part":"cdv3__MostafaOthman__pickplace_sweetsjp_straw","origin":"community_dataset_v3","dataset":"MostafaOthman/pickplace_sweetsjp_straw","scene_camera":"observation.images.image","fps":30.0,"built_clips":69,"train_windows":69,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.532696,-4.321669,-3.67031,-4.174285,-2.285565,1.025237],"action_q99":[1.459219,4.916667,4.255009,4.015377,2.858782,35.410095],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-12.351544,-98.267326,3.423424,-32.951177,-31.081716,2.252252],"state_q99":[42.121933,24.671618,99.459457,93.639729,65.270683,35.190477]},
+ {"part":"cdv3__Ninkofu__sushi_put","origin":"community_dataset_v3","dataset":"Ninkofu/sushi_put","scene_camera":"observation.images.image","fps":30.0,"built_clips":1030,"train_windows":1030,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.112675,-4.258873,-4.667864,-2.310661,-2.779234,1.200961],"action_q99":[3.433098,5.010437,4.847397,2.310654,2.045097,50.680546],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-24.458448,-98.821053,-67.256189,8.573928,-28.961046,2.325581],"state_q99":[57.651043,54.726736,99.009453,98.775154,93.15033,50.764118]},
+ {"part":"cdv3__OmKulkarni__Pick_place_black_boxes","origin":"community_dataset_v3","dataset":"OmKulkarni/Pick_place_black_boxes","scene_camera":"observation.images.image","fps":30.0,"built_clips":631,"train_windows":631,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.464703,-3.555907,-3.368794,-2.782196,-1.947369,0.0],"action_q99":[3.984406,2.765705,3.457447,3.020668,2.0,59.298782],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-86.986618,-91.796555,-62.02383,32.263512,4.029304,1.558442],"state_q99":[44.900784,51.435604,98.587822,98.902023,84.224663,58.376625]},
+ {"part":"cdv3__RoboHP__pick_small_blue_cube_box","origin":"community_dataset_v3","dataset":"RoboHP/pick_small_blue_cube_box","scene_camera":"observation.images.image2","fps":30.0,"built_clips":360,"train_windows":360,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.548101,-2.704987,-3.438913,-1.954117,-0.936768,0.659522],"action_q99":[1.548103,3.043114,3.710407,1.784203,0.624512,29.018961],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-67.050849,-98.815063,-83.710403,42.099788,-7.028165,1.211305],"state_q99":[59.837879,52.348709,99.185524,99.317696,27.401947,29.004038]},
+ {"part":"cdv3__Ryosei2__0617_green30","origin":"community_dataset_v3","dataset":"Ryosei2/0617_green30","scene_camera":"observation.images.image","fps":30.0,"built_clips":973,"train_windows":973,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.427734,-3.691406,-4.042969,-2.988281,-2.109375,-2.446809],"action_q99":[3.867188,3.691406,4.746094,2.548828,2.021484,39.468086],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.693359,-96.152344,-77.167969,18.984375,-42.820312,-1.249024],"state_q99":[41.660156,54.84375,85.078125,95.185547,64.423828,39.266197]},
+ {"part":"cdv3__Ryosei2__0617_white30","origin":"community_dataset_v3","dataset":"Ryosei2/0617_white30","scene_camera":"observation.images.image","fps":30.0,"built_clips":856,"train_windows":856,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.867188,-4.130859,-4.394531,-3.427734,-2.197266,-2.446809],"action_q99":[3.603516,4.21875,4.833984,3.251953,2.548828,39.042553],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.429688,-96.328125,-73.404492,15.732422,-45.0,-1.327088],"state_q99":[40.605469,51.591797,82.96875,95.273438,45.620508,38.568305]},
+ {"part":"cdv3__Ryosei2__0619_green50","origin":"community_dataset_v3","dataset":"Ryosei2/0619_green50","scene_camera":"observation.images.image","fps":30.0,"built_clips":1376,"train_windows":1376,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.130859,-4.394531,-4.042969,-4.21875,-2.197266,-2.553191],"action_q99":[3.691406,3.339844,5.800781,3.603516,2.636719,41.170212],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.693359,-96.152344,-72.246094,11.425781,-52.03125,-1.405152],"state_q99":[40.801465,50.712891,84.199219,95.361328,62.226562,39.968773]},
+ {"part":"cdv3__Ryosei2__0619_white50","origin":"community_dataset_v3","dataset":"Ryosei2/0619_white50","scene_camera":"observation.images.image","fps":30.0,"built_clips":1337,"train_windows":1337,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.130859,-4.306641,-3.955078,-3.427734,-2.636719,-2.446809],"action_q99":[4.042969,3.164062,4.833984,3.691406,2.988281,39.574467],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.748047,-96.240234,-72.949219,16.435547,-55.283203,-1.405152],"state_q99":[40.517578,48.251953,83.496094,95.361328,70.136719,38.641685]},
+ {"part":"cdv3__Ryosei2__0704_bontan1","origin":"community_dataset_v3","dataset":"Ryosei2/0704_bontan1","scene_camera":"observation.images.image","fps":30.0,"built_clips":90,"train_windows":90,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-5.537109,-4.042969,-2.900391,-1.845703,-0.106952],"action_q99":[1.669922,4.394531,6.416016,1.669922,1.757812,45.454548],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.132812,-100.722656,-59.699707,53.173828,-55.876465,-0.069589],"state_q99":[6.70166,43.439941,85.957031,96.987305,9.404297,44.745998]},
+ {"part":"cdv3__Ryosei2__0704_bontan2","origin":"community_dataset_v3","dataset":"Ryosei2/0704_bontan2","scene_camera":"observation.images.image","fps":30.0,"built_clips":109,"train_windows":109,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-6.461719,-4.573828,-4.042969,-5.189063,-0.106952],"action_q99":[1.757812,4.570312,7.998047,2.8125,3.076172,46.631016],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.746094,-100.722656,-87.075,38.935547,-10.019531,-0.139179],"state_q99":[44.472656,64.342969,86.660156,97.470703,85.826953,46.521919]},
+ {"part":"cdv3__Ryosei2__0704_bontan3","origin":"community_dataset_v3","dataset":"Ryosei2/0704_bontan3","scene_camera":"observation.images.image","fps":30.0,"built_clips":116,"train_windows":116,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-5.537109,-5.185547,-3.94541,-2.197266,-0.106952],"action_q99":[1.318359,4.648535,8.349609,2.373047,4.21875,46.524063],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.716797,-100.722656,-94.306641,37.294629,-71.806641,-0.069589],"state_q99":[7.461035,71.269629,86.660156,97.382812,10.61543,46.029925]},
+ {"part":"cdv3__Ryosei2__0704_bontan4","origin":"community_dataset_v3","dataset":"Ryosei2/0704_bontan4","scene_camera":"observation.images.image","fps":30.0,"built_clips":116,"train_windows":116,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-6.152344,-5.225977,-3.995508,-2.636719,-0.106952],"action_q99":[1.054688,5.097656,7.774805,3.164062,2.109375,43.957218],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.591797,-100.722656,-85.862109,29.842383,-12.744141,-0.139179],"state_q99":[34.365234,64.160156,86.572266,97.910156,69.433594,43.209465]},
+ {"part":"cdv3__Ryosei2__0704_bontan5","origin":"community_dataset_v3","dataset":"Ryosei2/0704_bontan5","scene_camera":"observation.images.image","fps":30.0,"built_clips":112,"train_windows":112,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-5.185547,-5.828906,-3.016406,-2.109375,-0.106952],"action_q99":[1.669922,4.658203,5.741016,2.548828,2.197266,53.155083],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.935547,-100.722656,-77.695312,55.546875,-26.015625,-0.139179],"state_q99":[7.998047,56.689453,85.957031,97.294922,38.084766,53.00209]},
+ {"part":"cdv3__Ryosei2__0704_bontan6","origin":"community_dataset_v3","dataset":"Ryosei2/0704_bontan6","scene_camera":"observation.images.image","fps":30.0,"built_clips":108,"train_windows":108,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-5.563477,-5.185547,-3.981445,-1.230469,-0.106952],"action_q99":[1.757812,4.130859,6.855469,2.724609,1.494141,55.721928],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.941406,-100.722656,-82.230469,44.560547,-36.0,-0.139179],"state_q99":[41.950195,56.71582,86.572266,97.294922,5.888672,55.462772]},
+ {"part":"cdv3__Ryosei2__0704_donut1","origin":"community_dataset_v3","dataset":"Ryosei2/0704_donut1","scene_camera":"observation.images.image","fps":30.0,"built_clips":94,"train_windows":94,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-7.118262,-7.119141,-3.954199,-2.548828,-0.106952],"action_q99":[2.372168,5.272559,6.767578,3.339844,3.076172,61.496256],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-55.898438,-100.722656,-72.592383,27.597656,-14.060742,0.0],"state_q99":[3.076172,55.810547,86.660156,97.207031,61.255371,61.58594]},
+ {"part":"cdv3__Ryosei2__0704_donut2","origin":"community_dataset_v3","dataset":"Ryosei2/0704_donut2","scene_camera":"observation.images.image","fps":30.0,"built_clips":99,"train_windows":99,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-5.502832,-5.678613,-3.305566,-1.757812,-0.106952],"action_q99":[2.636719,4.272363,5.976562,3.041895,1.669922,58.460963],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.021484,-100.810547,-85.957031,49.638867,-49.413867,-0.139179],"state_q99":[56.953125,63.017578,86.572266,97.119141,10.634766,58.455116]},
+ {"part":"cdv3__Ryosei2__0707_SingleCube","origin":"community_dataset_v3","dataset":"Ryosei2/0707_SingleCube","scene_camera":"observation.images.image","fps":30.0,"built_clips":536,"train_windows":536,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.988281,-4.130859,-4.658203,-2.548828,-1.669922,-0.102459],"action_q99":[2.373047,5.009766,4.921875,2.285156,1.757812,34.323769],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.671875,-94.482422,-85.535156,25.998047,-39.919922,0.0],"state_q99":[40.166016,66.287109,87.539062,97.03125,51.767578,33.147243]},
+ {"part":"cdv3__Ryosei2__0709_SingleCube_SamePos","origin":"community_dataset_v3","dataset":"Ryosei2/0709_SingleCube_SamePos","scene_camera":"observation.images.image","fps":30.0,"built_clips":141,"train_windows":141,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.54375,-3.251953,-1.494141,-0.703125,-0.102459],"action_q99":[2.109375,4.042969,4.130859,1.494141,1.142578,36.372952],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.044922,-94.306641,-60.117188,43.066406,-19.6875,0.0],"state_q99":[27.861328,48.164062,87.714844,97.03125,17.694141,35.729237]},
+ {"part":"cdv3__Ryosei2__greenblock0613_0-50","origin":"community_dataset_v3","dataset":"Ryosei2/greenblock0613_0-50","scene_camera":"observation.images.image","fps":30.0,"built_clips":574,"train_windows":574,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.339844,-6.152344,-6.939844,-3.164062,-2.197266,-0.2079],"action_q99":[3.339844,5.976562,6.764062,3.076172,2.460938,35.962578],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.308594,-93.955078,-108.105469,51.679688,-55.722656,-0.312256],"state_q99":[30.585938,76.988672,82.353516,106.435547,39.810937,35.125685]},
+ {"part":"cdv3__Ryosei2__greenblock0617test","origin":"community_dataset_v3","dataset":"Ryosei2/greenblock0617test","scene_camera":"observation.images.image","fps":30.0,"built_clips":164,"train_windows":164,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.61582,-3.251953,-3.867188,-2.548828,-2.285156,-2.553191],"action_q99":[4.306641,3.088477,3.867188,2.197266,1.845703,35.531914],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.320312,-96.152344,-65.227148,30.925195,-43.417969,-1.17096],"state_q99":[40.957031,48.967383,85.078125,95.097656,44.53418,35.519127]},
+ {"part":"cdv3__SharkDan__so100_test_3c","origin":"community_dataset_v3","dataset":"SharkDan/so100_test_3c","scene_camera":"observation.images.image3","fps":30.0,"built_clips":765,"train_windows":765,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.460938,-2.900391,-1.318359,-1.168945,8.445946],"action_q99":[0.966797,2.900391,2.575195,1.40625,0.966797,40.87838],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.756836,-92.900391,-37.705078,36.914062,-34.628906,8.668281],"state_q99":[45.439453,33.837891,80.683594,86.396484,50.449219,40.435837]},
+ {"part":"cdv3__SharkDan__so100_test_f2","origin":"community_dataset_v3","dataset":"SharkDan/so100_test_f2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":623,"train_windows":623,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.339844,-1.933594,-1.40625,-1.142578,11.824324],"action_q99":[2.109375,2.460938,3.339844,1.40625,1.054688,32.010136],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.902344,-92.988281,-17.050781,26.894531,-92.021484,15.98063],"state_q99":[20.917969,23.994141,80.683594,72.773438,-40.517578,31.638416]},
+ {"part":"cdv3__Tear4Pixelation__lego2","origin":"community_dataset_v3","dataset":"Tear4Pixelation/lego2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":253,"train_windows":253,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.706232,-4.82642,-4.977379,-1.994797,-1.463669,0.569569],"action_q99":[1.854599,5.419136,4.886879,2.532527,1.881861,43.287224],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-47.255192,-99.320595,-67.492119,55.924007,-74.32805,0.610583],"state_q99":[34.421364,58.811039,96.398018,98.96373,43.852352,42.835822]},
+ {"part":"cdv3__Tear4Pixelation__yellow-brick","origin":"community_dataset_v3","dataset":"Tear4Pixelation/yellow-brick","scene_camera":"observation.images.image2","fps":30.0,"built_clips":100,"train_windows":100,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.302137,-3.100128,-3.976501,-1.816612,-1.355577,1.186709],"action_q99":[1.252764,3.770424,3.976502,1.730103,1.338373,29.830696],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-12.987099,-98.39595,-59.963932,52.232497,-7.74883,1.241019],"state_q99":[30.777737,55.508652,94.770065,98.530685,55.469059,28.827564]},
+ {"part":"cdv3__Tear4Pixelation__yellow-brick2","origin":"community_dataset_v3","dataset":"Tear4Pixelation/yellow-brick2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":235,"train_windows":235,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.957996,-3.076665,-4.157253,-1.730103,-1.303441,1.265823],"action_q99":[1.084746,4.333472,3.680072,1.816605,1.340979,29.113924],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-16.328787,-98.39595,-61.857529,51.166809,-24.440977,1.175702],"state_q99":[27.828972,55.738286,93.507668,98.703545,68.420178,28.935337]},
+ {"part":"cdv3__Thorns07__so100_stacking1","origin":"community_dataset_v3","dataset":"Thorns07/so100_stacking1","scene_camera":"observation.images.image","fps":30.0,"built_clips":984,"train_windows":984,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.059804,-3.175964,-3.177486,-1.386063,-0.976799,0.101317],"action_q99":[1.059803,3.090134,2.905128,1.793724,1.025642,45.086121],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-36.403507,-97.830803,-40.713963,45.099632,-71.330894,1.43481],"state_q99":[23.318714,36.312363,99.096252,98.698662,-0.31746,44.603867]},
+ {"part":"cdv3__Thorns07__so100stacking","origin":"community_dataset_v3","dataset":"Thorns07/so100stacking","scene_camera":"observation.images.image","fps":30.0,"built_clips":1315,"train_windows":1315,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.764708,-3.43938,-3.63636,-1.960785,-0.927959,0.0],"action_q99":[1.764706,3.525368,3.636364,2.614376,1.025642,41.997963],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-42.621723,-98.000908,-68.50679,32.173912,-61.855923,0.787919],"state_q99":[19.77528,56.507951,100.0,97.549408,-13.308913,41.718318]},
+ {"part":"cdv3__VoicAndrei__so100_cubes_three_cameras","origin":"community_dataset_v3","dataset":"VoicAndrei/so100_cubes_three_cameras","scene_camera":"observation.images.image","fps":30.0,"built_clips":4744,"train_windows":4744,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.603516,-3.515625,-2.8125,-2.900391,-4.394531,-0.191205],"action_q99":[3.955078,2.8125,2.988281,3.076172,3.603516,46.367111],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.796875,-85.693359,-64.775391,0.966797,-118.916016,0.459559],"state_q99":[59.501953,56.865234,75.234375,90.527344,23.642578,44.393383]},
+ {"part":"cdv3__akira-sasaki__gr00t_2cam_blue_dish","origin":"community_dataset_v3","dataset":"akira-sasaki/gr00t_2cam_blue_dish","scene_camera":"observation.images.image","fps":30.0,"built_clips":480,"train_windows":480,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-4.570312,-3.750293,-2.724609,-1.318359,0.0],"action_q99":[1.494141,4.746094,4.482422,2.285156,1.142578,49.268738],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.904297,-98.261719,-92.285156,27.245215,-26.982422,0.348918],"state_q99":[4.980762,59.033496,86.484375,105.46875,4.394531,49.197487]},
+ {"part":"cdv3__akira-sasaki__gr00t_2cam_red_dish","origin":"community_dataset_v3","dataset":"akira-sasaki/gr00t_2cam_red_dish","scene_camera":"observation.images.image","fps":30.0,"built_clips":530,"train_windows":530,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-4.746094,-3.779297,-2.900391,-1.40625,0.0],"action_q99":[0.966797,5.009766,4.482422,2.636719,1.142578,48.080441],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.664062,-98.173828,-68.797266,19.934473,-23.994141,0.418702],"state_q99":[10.212012,38.87666,87.890625,104.589844,10.212012,47.732029]},
+ {"part":"cdv3__akira-sasaki__smolvla_base","origin":"community_dataset_v3","dataset":"akira-sasaki/smolvla_base","scene_camera":"observation.images.image","fps":30.0,"built_clips":984,"train_windows":984,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.867188,-3.603516,-3.867188,-1.845703,-0.677048],"action_q99":[1.494141,5.009766,4.306641,3.164062,1.757812,34.190929],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.457031,-101.865234,-55.019531,-1.142578,-30.849609,-0.208914],"state_q99":[24.698145,33.486328,87.275391,96.416016,9.755859,33.913647]},
+ {"part":"cdv3__andlyu__newiii_many_y_3d","origin":"community_dataset_v3","dataset":"andlyu/newiii_many_y_3d","scene_camera":"observation.images.image3","fps":30.0,"built_clips":2555,"train_windows":2555,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-0.878906,-0.615234,-1.054688,-1.230469,9.031657],"action_q99":[0.527344,1.054688,0.791016,0.878906,0.439453,21.60149],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.333984,-101.689453,-6.943359,-43.417969,-131.572266,9.437751],"state_q99":[39.814453,41.081836,72.861328,101.513672,-9.667969,21.586346]},
+ {"part":"cdv3__andlyu__newiii_salad_cc","origin":"community_dataset_v3","dataset":"andlyu/newiii_salad_cc","scene_camera":"observation.images.image3","fps":30.0,"built_clips":710,"train_windows":710,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.175781,-0.615234,-0.439453,-0.615234,-0.351562,7.914339],"action_q99":[0.175781,0.615234,0.615234,0.527344,0.351562,21.973928],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-1.40625,-79.716797,-5.800781,-33.784277,-105.644531,8.394579],"state_q99":[23.940527,34.628906,52.207031,65.176172,-68.378906,22.088354]},
+ {"part":"cdv3__andlyu__newiii_salad_val","origin":"community_dataset_v3","dataset":"andlyu/newiii_salad_val","scene_camera":"observation.images.image3","fps":30.0,"built_clips":88,"train_windows":88,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.175781,-0.527344,-0.351562,-0.351562,-0.175781,9.869646],"action_q99":[0.175781,0.439453,0.263672,0.351562,0.263672,20.577282],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.636719,-9.680273,-6.976758,-37.265625,-102.392578,10.742972],"state_q99":[17.490234,35.595703,56.823047,-2.394141,-83.847656,20.381527]},
+ {"part":"cdv3__arminfg__norm_cam_changeracks","origin":"community_dataset_v3","dataset":"arminfg/norm_cam_changeracks","scene_camera":"observation.images.image","fps":30.0,"built_clips":210,"train_windows":210,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.334568,-4.342162,-3.994553,-4.148577,-1.046024,0.375657],"action_q99":[3.33457,3.039513,5.356331,5.209841,0.889122,38.76484],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-45.891962,-98.983047,-21.311476,-6.067437,36.721146,0.78637],"state_q99":[14.097497,20.423729,99.812645,89.788055,53.575077,37.942333]},
+ {"part":"cdv3__cerealkiller2527__so101_rayban_quality_assessment_001","origin":"community_dataset_v3","dataset":"cerealkiller2527/so101_rayban_quality_assessment_001","scene_camera":"observation.images.image","fps":30.0,"built_clips":174,"train_windows":174,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.029114,-2.63349,-3.184713,-1.471226,-3.38983,0.0],"action_q99":[1.940891,2.783636,2.729755,2.250114,2.750239,100.0],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-73.706444,-97.983192,-86.287773,15.361828,-99.022606,16.666666],"state_q99":[70.538544,65.630249,99.368515,97.799408,54.489922,88.738739]},
+ {"part":"cdv3__chirag1701__battery","origin":"community_dataset_v3","dataset":"chirag1701/battery","scene_camera":"observation.images.image2","fps":30.0,"built_clips":864,"train_windows":864,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.641178,-2.373886,-2.080505,-1.475693,-0.781454,1.668057],"action_q99":[1.56658,2.37389,2.261421,1.649306,0.885647,37.531277],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-53.352985,-99.660156,-3.63718,32.437122,-4.224664,1.850583],"state_q99":[24.981577,17.417162,98.708577,74.76149,29.23077,37.491432]},
+ {"part":"cdv3__chirag1701__can","origin":"community_dataset_v3","dataset":"chirag1701/can","scene_camera":"observation.images.image2","fps":30.0,"built_clips":785,"train_windows":785,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.543461,-2.795425,-2.44344,-1.647877,-1.615423,0.907591],"action_q99":[1.787166,2.456589,2.986423,2.081528,1.563314,53.135315],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-31.04213,-99.23922,-40.888485,40.397923,-13.797314,1.133333],"state_q99":[49.076126,30.76923,98.18676,83.996536,41.196583,52.866665]},
+ {"part":"cdv3__chirag1701__new0_green_block","origin":"community_dataset_v3","dataset":"chirag1701/new0_green_block","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1004,"train_windows":1004,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.939575,-2.373886,-2.261417,-1.302086,-0.468872,1.668057],"action_q99":[1.864976,2.543449,2.442333,1.649307,0.468872,43.119267],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-51.510685,-99.575188,-14.144589,33.651344,-12.918193,1.850583],"state_q99":[55.637436,31.860662,97.934441,75.021683,14.08254,42.837559]},
+ {"part":"cdv3__chirag1701__new0_green_block_more","origin":"community_dataset_v3","dataset":"chirag1701/new0_green_block_more","scene_camera":"observation.images.image2","fps":30.0,"built_clips":686,"train_windows":686,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.948527,-2.204324,-1.809135,-1.302086,-0.729357,1.668057],"action_q99":[1.715775,2.289108,2.170963,1.475693,0.729357,43.536282],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-57.184967,-99.065422,-8.037719,13.443192,-19.80464,1.850583],"state_q99":[42.676491,25.668649,99.64077,72.159584,23.125763,43.248802]},
+ {"part":"cdv3__chirag1701__pick_place_blue_threecams","origin":"community_dataset_v3","dataset":"chirag1701/pick_place_blue_threecams","scene_camera":"observation.images.image3","fps":30.0,"built_clips":1113,"train_windows":1113,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.922367,-2.121338,-2.079566,-1.044388,-0.678497,1.195652],"action_q99":[1.700556,2.121338,2.260393,1.13142,0.730689,37.282608],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-55.021366,-99.238899,-37.511032,25.706942,-29.311188,1.432469],"state_q99":[87.975428,42.448203,98.587822,73.864609,25.842697,37.244202]},
+ {"part":"cdv3__chirag1701__pick_place_blue_threecams_more","origin":"community_dataset_v3","dataset":"chirag1701/pick_place_blue_threecams_more","scene_camera":"observation.images.image3","fps":30.0,"built_clips":725,"train_windows":725,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.218115,-2.291048,-2.169983,-1.305483,-0.782881,1.195652],"action_q99":[1.922367,2.375902,2.531645,1.305481,0.730689,34.903261],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-93.803421,-99.323463,-59.860547,6.940874,-32.291157,1.432469],"state_q99":[91.880341,57.80127,98.499557,81.233932,12.945774,34.856754]},
+ {"part":"cdv3__chirag1701__record-test_green","origin":"community_dataset_v3","dataset":"chirag1701/record-test_green","scene_camera":"observation.images.image","fps":30.0,"built_clips":888,"train_windows":888,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.218115,-2.291046,-1.989151,-1.479553,-0.678497,1.195652],"action_q99":[1.922365,2.291046,2.260399,1.914711,0.678497,44.891304],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-56.837608,-99.238899,-25.242718,18.166239,-17.977528,1.364257],"state_q99":[85.335472,30.147991,98.146515,80.526136,21.055202,44.542973]},
+ {"part":"cdv3__chirag1701__record-test_red","origin":"community_dataset_v3","dataset":"chirag1701/record-test_red","scene_camera":"observation.images.image","fps":30.0,"built_clips":1033,"train_windows":1033,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.922366,-2.121342,-1.989151,-1.566582,-0.73069,1.195652],"action_q99":[1.774492,2.3759,2.622063,1.827675,0.782881,42.282608],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-57.051281,-99.323463,-29.744041,27.708655,-14.899854,1.364257],"state_q99":[87.072647,35.475689,97.793472,85.089973,24.078164,42.22374]},
+ {"part":"cdv3__chirag1701__record-test_yellow","origin":"community_dataset_v3","dataset":"chirag1701/record-test_yellow","scene_camera":"observation.images.image","fps":30.0,"built_clips":949,"train_windows":949,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.292051,-2.121338,-2.260398,-1.218452,-0.939458,1.195652],"action_q99":[2.144176,2.3759,2.350815,1.305485,0.835073,53.586956],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-55.876068,-99.238899,-29.126213,26.135389,-36.932095,1.432469],"state_q99":[72.863251,34.545456,98.411301,79.177376,19.345383,53.683491]},
+ {"part":"cdv3__chirag1701__sandwich","origin":"community_dataset_v3","dataset":"chirag1701/sandwich","scene_camera":"observation.images.image2","fps":30.0,"built_clips":891,"train_windows":891,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.56658,-2.289108,-2.170963,-1.215279,-0.989841,1.668057],"action_q99":[1.49198,2.119543,2.623249,1.388885,0.83355,56.880733],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-55.858513,-99.150383,-23.484509,25.672159,-28.058609,1.850583],"state_q99":[24.238762,20.305862,99.461159,83.347786,22.393162,56.545578]},
+ {"part":"cdv3__danaaubakirova__svla_so100_task4_v3_clean","origin":"community_dataset_v3","dataset":"danaaubakirova/svla_so100_task4_v3_clean","scene_camera":"observation.images.image","fps":30.0,"built_clips":774,"train_windows":774,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.900391,-2.373047,-1.054688,-1.318359,0.0],"action_q99":[0.966797,2.8125,2.636719,1.40625,0.966797,28.115017],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.902344,-86.835938,-51.943359,34.980469,53.876953,0.207182],"state_q99":[38.583984,46.933594,74.970703,87.011719,119.443359,28.038675]},
+ {"part":"cdv3__danaaubakirova__svla_so100_task4_v3_multiple","origin":"community_dataset_v3","dataset":"danaaubakirova/svla_so100_task4_v3_multiple","scene_camera":"observation.images.image","fps":30.0,"built_clips":1397,"train_windows":1397,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-3.076172,-2.670996,-1.054688,-1.40625,0.0],"action_q99":[1.054688,3.603516,2.548828,1.582031,1.054688,25.133121],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.048828,-86.835938,-32.607422,34.453125,65.654297,0.207182],"state_q99":[21.533203,36.5625,75.058594,76.762793,107.314453,24.861877]},
+ {"part":"cdv3__danielkorth__bike-light","origin":"community_dataset_v3","dataset":"danielkorth/bike-light","scene_camera":"observation.images.image2","fps":30.0,"built_clips":442,"train_windows":442,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.459237,-5.477179,-3.863434,-3.703705,-1.048768,1.972686],"action_q99":[1.795064,4.315353,4.58221,4.306633,0.996329,53.945374],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-42.678898,-98.498749,-57.849831,-1.40605,-25.518925,2.54902],"state_q99":[34.018349,42.03503,98.890785,95.952282,14.969475,53.92157]},
+ {"part":"cdv3__danielkorth__bike-light4am","origin":"community_dataset_v3","dataset":"danielkorth/bike-light4am","scene_camera":"observation.images.image2","fps":30.0,"built_clips":968,"train_windows":968,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.739716,-3.568466,-3.683739,-3.789834,-1.520714,1.972686],"action_q99":[2.243828,3.485477,4.043125,3.445305,1.468275,37.481033],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-20.092579,-99.003738,-60.256289,0.386432,-16.288157,2.559055],"state_q99":[54.846436,58.821087,98.191826,98.969513,39.194138,37.335957]},
+ {"part":"cdv3__danielkorth__bike-light4am-part2","origin":"community_dataset_v3","dataset":"danielkorth/bike-light4am-part2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":986,"train_windows":986,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.590128,-3.568466,-3.504044,-3.359173,-1.573151,2.048558],"action_q99":[2.019447,3.420748,3.773582,3.531441,1.520713,47.209407],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-46.436443,-99.003738,-43.474842,3.80249,-27.368987,2.624672],"state_q99":[55.033066,42.963886,98.191826,98.626022,55.409035,47.0105]},
+ {"part":"cdv3__danielkorth__green-marker","origin":"community_dataset_v3","dataset":"danielkorth/green-marker","scene_camera":"observation.images.image2","fps":30.0,"built_clips":331,"train_windows":331,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.931186,-2.489626,-2.336029,-1.981052,-0.786575,1.972686],"action_q99":[1.421093,2.406641,3.054805,2.239449,0.786576,76.176025],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-9.404849,-99.003738,-65.644653,1.861743,-28.498169,2.559055],"state_q99":[50.404114,53.922791,98.506287,99.141266,43.873991,76.115486]},
+ {"part":"cdv3__danielkorth__green-marker-part2","origin":"community_dataset_v3","dataset":"danielkorth/green-marker-part2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1054,"train_windows":1054,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.81451,-3.900414,-3.054807,-2.756244,-1.363398,2.048558],"action_q99":[2.169035,3.236514,4.043127,3.445312,1.310959,34.218513],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-35.782513,-99.003738,-22.484276,4.09532,-47.448109,2.559055],"state_q99":[52.534901,21.793276,98.034592,98.540146,48.18071,34.251968]},
+ {"part":"cdv3__danielkorth__green-marker2","origin":"community_dataset_v3","dataset":"danielkorth/green-marker2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1266,"train_windows":1266,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.33508,-2.489624,-2.246181,-2.153316,-0.891453,1.972686],"action_q99":[1.795063,2.240664,2.875111,2.583981,0.839015,39.984825],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-37.105068,-98.837692,-75.393082,2.962645,-47.448109,2.559055],"state_q99":[52.241001,67.639687,98.34906,98.797768,40.26862,40.091862]},
+ {"part":"cdv3__danielkorth__green-marker4am","origin":"community_dataset_v3","dataset":"danielkorth/green-marker4am","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1441,"train_windows":1441,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.842186,-2.406639,-2.425876,-2.325581,-1.101207,1.972686],"action_q99":[1.869858,2.406639,2.785265,2.583977,1.206082,37.101669],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.038942,-98.837692,-61.296384,9.059682,-47.448109,2.559055],"state_q99":[54.886112,63.470318,98.270439,99.055389,48.165568,37.07349]},
+ {"part":"cdv3__danielkorth__usb-C-cable","origin":"community_dataset_v3","dataset":"danielkorth/usb-C-cable","scene_camera":"observation.images.image2","fps":30.0,"built_clips":2095,"train_windows":2095,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.44054,-3.319502,-3.144653,-3.703701,-1.153644,2.124431],"action_q99":[2.019447,2.987553,3.414192,3.359169,1.048768,47.192715],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.773695,-98.920715,-60.696539,-9.91842,-19.023199,2.624672],"state_q99":[55.033066,54.254879,98.270439,98.711891,26.935287,46.850395]},
+ {"part":"cdv3__danielkorth__usb-stick","origin":"community_dataset_v3","dataset":"danielkorth/usb-stick","scene_camera":"observation.images.image2","fps":30.0,"built_clips":410,"train_windows":410,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.440539,-6.224066,-3.619949,-3.445305,-2.202412,1.896813],"action_q99":[2.415109,4.232365,6.135673,2.928513,2.322496,34.749622],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-48.477066,-98.498749,-78.071671,-0.213038,-43.589745,2.54902],"state_q99":[37.437065,92.243538,98.805458,98.551346,45.006104,34.901962]},
+ {"part":"cdv3__danielkorth__usbc-cable-2","origin":"community_dataset_v3","dataset":"danielkorth/usbc-cable-2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":210,"train_windows":210,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-4.409872,-5.062241,-3.234502,-3.83118,-1.678028,1.972686],"action_q99":[2.728496,4.106224,4.1761,3.100777,1.283692,44.157814],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-50.018349,-98.498749,-20.221844,18.789944,-43.052502,1.895425],"state_q99":[41.504585,36.947456,98.890785,92.841927,5.299145,44.117645]},
+ {"part":"cdv3__danielkorth__whiteboard-marker","origin":"community_dataset_v3","dataset":"danielkorth/whiteboard-marker","scene_camera":"observation.images.image2","fps":30.0,"built_clips":189,"train_windows":189,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.216156,-11.78423,-4.851753,-3.617569,-2.517044,1.820941],"action_q99":[2.807779,5.145229,13.753819,3.875969,2.388044,42.640366],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-48.895412,-98.33194,-69.283279,34.849596,-43.443222,2.54902],"state_q99":[33.550092,59.96664,98.549484,98.551346,40.122101,42.745098]},
+ {"part":"cdv3__davidgoss__record-test2","origin":"community_dataset_v3","dataset":"davidgoss/record-test2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":236,"train_windows":236,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-5.470249,-5.237461,-7.137004,-4.923927,-1.172161,0.0],"action_q99":[3.550863,6.213936,5.553028,4.426003,1.465202,60.271114],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-41.475574,-98.784721,-35.72744,43.474178,34.945053,0.768156],"state_q99":[66.041872,40.364582,99.723755,99.81221,58.632477,60.684357]},
+ {"part":"cdv3__davidgoss__record-test4","origin":"community_dataset_v3","dataset":"davidgoss/record-test4","scene_camera":"observation.images.image2","fps":30.0,"built_clips":366,"train_windows":366,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-6.81382,-6.391479,-8.492493,-5.71692,-1.479365,0.0],"action_q99":[4.03071,7.63427,7.555758,4.979256,1.758241,44.660061],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-40.578266,-98.871529,-31.583794,39.94554,36.752136,0.768156],"state_q99":[67.896309,40.017361,100.0,99.81221,72.844933,44.413406]},
+ {"part":"cdv3__dongseon__so100_062801","origin":"community_dataset_v3","dataset":"dongseon/so100_062801","scene_camera":"observation.images.image2","fps":30.0,"built_clips":388,"train_windows":388,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.001366,-2.543451,-3.119806,-1.157503,-0.879125,5.508072],"action_q99":[1.365498,2.373886,2.801933,1.65358,0.927959,13.675214],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-58.382748,-89.954338,-39.945464,50.178501,-90.427353,6.396588],"state_q99":[8.571428,50.711417,99.374161,94.254663,-36.019535,13.219616]},
+ {"part":"cdv3__dongseon__so100_062802","origin":"community_dataset_v3","dataset":"dongseon/so100_062802","scene_camera":"observation.images.image2","fps":30.0,"built_clips":338,"train_windows":338,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.456533,-2.797796,-3.188408,-1.157501,-1.269842,5.698006],"action_q99":[1.274466,2.628235,3.188406,1.736255,0.87912,15.194682],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-17.735849,-90.045662,-31.157801,51.05117,-55.08669,6.112296],"state_q99":[52.129379,42.19178,99.46357,98.016663,-1.015873,14.64108]},
+ {"part":"cdv3__dopaul__first_movement_test_v4","origin":"community_dataset_v3","dataset":"dopaul/first_movement_test_v4","scene_camera":"observation.images.image","fps":30.0,"built_clips":243,"train_windows":243,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.251467,-3.842957,-4.648233,-6.901721,-1.172161,0.182149],"action_q99":[1.4079,3.225806,4.261105,7.043406,1.269841,50.0],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-24.631268,-95.894424,-13.420696,-99.601593,-18.010745,0.981033],"state_q99":[16.465339,21.855886,99.277,90.778487,9.756776,49.431654]},
+ {"part":"cdv3__dopaul__first_movement_test_v6","origin":"community_dataset_v3","dataset":"dopaul/first_movement_test_v6","scene_camera":"observation.images.image","fps":30.0,"built_clips":258,"train_windows":258,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.608917,-4.29287,-4.533092,-7.616709,-1.172161,0.182149],"action_q99":[1.64255,3.225807,4.403446,7.944309,1.269841,41.80328],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.40118,-96.062004,-1.736105,-99.681274,-16.483517,0.915631],"state_q99":[16.455752,13.782991,99.096252,87.171318,8.522589,41.792023]},
+ {"part":"cdv3__dopaul__game_v5","origin":"community_dataset_v3","dataset":"dopaul/game_v5","scene_camera":"observation.images.image","fps":30.0,"built_clips":724,"train_windows":724,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.64255,-3.735138,-3.173164,-5.405403,-1.074481,0.091075],"action_q99":[1.486117,3.140923,3.445152,6.142506,0.927961,22.859745],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-44.718289,-96.062004,-47.220966,-98.326691,-26.465445,0.850229],"state_q99":[42.477875,43.391706,98.734749,97.29084,12.711112,22.759974]},
+ {"part":"cdv3__dopaul__game_v6","origin":"community_dataset_v3","dataset":"dopaul/game_v6","scene_camera":"observation.images.image","fps":30.0,"built_clips":1833,"train_windows":1833,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.720767,-3.650253,-3.263824,-6.142506,-1.074481,0.091075],"action_q99":[1.720767,3.140917,3.445148,7.125307,1.025641,29.052824],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-46.681416,-96.062004,-47.853592,-98.88446,-26.886446,0.915631],"state_q99":[38.790562,45.538334,98.734749,96.465341,7.203907,28.622629]},
+ {"part":"cdv3__dopaul__game_v7","origin":"community_dataset_v3","dataset":"dopaul/game_v7","scene_camera":"observation.images.image","fps":30.0,"built_clips":2205,"train_windows":2205,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.4079,-3.650253,-3.173164,-5.978706,-0.879121,0.182149],"action_q99":[1.4079,3.140915,3.535805,7.125305,0.879121,30.418943],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-49.041298,-96.062004,-41.88884,-98.88446,-19.316238,0.915631],"state_q99":[41.657081,42.857143,98.825127,90.109164,7.496947,30.150425]},
+ {"part":"cdv3__doujiangwang__task7_20epi_100000step","origin":"community_dataset_v3","dataset":"doujiangwang/task7_20epi_100000step","scene_camera":"observation.images.image","fps":30.0,"built_clips":317,"train_windows":317,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.8125,-2.724609,-1.669922,-0.527344,-0.182648],"action_q99":[1.230469,2.8125,3.867188,1.669922,0.615234,34.375341],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.740234,-99.667969,-52.119141,51.152344,-16.347656,0.526316],"state_q99":[34.297559,32.958984,84.287109,102.692285,5.800781,34.298248]},
+ {"part":"cdv3__duthvik__sputnik_100_47_custom_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_47_custom_tasks","scene_camera":"observation.images.image","fps":30.0,"built_clips":213,"train_windows":213,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.708984,-2.636719,-2.285156,-3.076172,-0.103093],"action_q99":[1.845703,4.130859,3.164062,2.742188,2.285156,26.907217],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.337891,-100.458984,-12.568359,6.855469,-77.167969,0.659824],"state_q99":[7.910156,8.876953,87.451172,91.423828,0.878906,25.234603]},
+ {"part":"cdv3__duthvik__sputnik_100_64_kitchen_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_64_kitchen_tasks","scene_camera":"observation.images.image","fps":30.0,"built_clips":214,"train_windows":214,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-5.712891,-6.240234,-2.636719,-4.043848,-0.103734],"action_q99":[1.669922,6.416016,7.294922,2.636719,3.427734,53.215767],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.149316,-98.701172,-101.425781,51.152344,-82.880859,0.806452],"state_q99":[14.150391,75.234375,85.341797,102.304688,15.646289,51.979469]},
+ {"part":"cdv3__duthvik__sputnik_100_65_kitchen_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_65_kitchen_tasks","scene_camera":"observation.images.image","fps":30.0,"built_clips":207,"train_windows":207,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-5.537109,-6.767578,-2.636719,-2.8125,-0.103734],"action_q99":[2.373047,6.694629,7.470703,2.285156,2.021484,43.775932],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.448535,-98.789062,-99.755859,60.732422,-61.435547,0.733138],"state_q99":[12.65625,69.433594,84.023438,102.128906,0.966797,40.615837]},
+ {"part":"cdv3__duthvik__sputnik_100_66_kitchen_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_66_kitchen_tasks","scene_camera":"observation.images.image","fps":30.0,"built_clips":200,"train_windows":200,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-5.273438,-6.152344,-2.109375,-2.610352,-0.103093],"action_q99":[2.636719,6.125977,6.679688,2.021484,2.197266,37.628864],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.015625,-100.019531,-99.755859,56.601562,-50.800781,0.879765],"state_q99":[21.533203,70.3125,86.308594,101.865234,3.515625,37.074781]},
+ {"part":"cdv3__duthvik__sputnik_100_67_kitchen_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_67_kitchen_tasks","scene_camera":"observation.images.image","fps":30.0,"built_clips":209,"train_windows":209,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-5.185547,-5.185547,-2.285156,-2.988281,-0.103093],"action_q99":[2.988281,5.643457,6.08291,2.479395,2.636719,33.195877],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.792969,-100.810547,-100.195312,35.452441,-62.138672,0.806452],"state_q99":[20.478516,67.324219,89.384766,101.865234,16.190332,31.115837]},
+ {"part":"cdv3__duthvik__sputnik_100_69_creative_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_69_creative_tasks","scene_camera":"observation.images.image3","fps":30.0,"built_clips":248,"train_windows":248,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.805957,-5.112598,-2.548828,-5.712891,-3.076172,-0.103093],"action_q99":[0.703125,6.152344,1.494141,5.625,3.164062,0.515464],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-17.402344,-100.634766,13.535156,-105.380859,-85.693359,0.879765],"state_q99":[3.603516,44.121094,89.736328,74.707031,2.724609,3.445748]},
+ {"part":"cdv3__duthvik__sputnik_100_70_creative_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_70_creative_tasks","scene_camera":"observation.images.image3","fps":30.0,"built_clips":230,"train_windows":230,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-4.21875,-2.724609,-6.591797,-3.427734,-0.206186],"action_q99":[0.703125,7.382812,1.845703,5.185547,3.691406,0.103093],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.511719,-100.546875,32.501953,-86.132812,-84.726562,3.29912],"state_q99":[5.185547,44.472656,89.824219,71.279297,1.142578,3.372434]},
+ {"part":"cdv3__duthvik__sputnik_100_71_creative_tasks","origin":"community_dataset_v3","dataset":"duthvik/sputnik_100_71_creative_tasks","scene_camera":"observation.images.image3","fps":30.0,"built_clips":276,"train_windows":276,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-4.042969,-2.988281,-6.855469,-3.603516,-0.103093],"action_q99":[0.721582,7.294922,2.548828,4.746094,3.515625,0.103093],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-16.171875,-99.931641,26.894531,-73.037109,-83.320312,3.152493],"state_q99":[4.130859,38.232422,90.351562,70.400391,0.527344,3.29912]},
+ {"part":"cdv3__erlingling__so101_623","origin":"community_dataset_v3","dataset":"erlingling/so101_623","scene_camera":"observation.images.image","fps":30.0,"built_clips":239,"train_windows":239,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-4.306641,-3.515625,-2.548828,-1.318359,-0.645161],"action_q99":[3.427734,4.482422,5.888672,2.460938,1.318359,17.338709],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-73.455469,-89.033203,-82.490625,47.724609,-8.701172,0.0],"state_q99":[55.898438,65.390625,86.044922,88.417969,43.660547,17.452829]},
+ {"part":"cdv3__frk2__pickyellowdropblue4","origin":"community_dataset_v3","dataset":"frk2/pickyellowdropblue4","scene_camera":"observation.images.image","fps":30.0,"built_clips":400,"train_windows":400,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.286449,-3.344173,-3.363637,-1.816681,-0.53724,0.090992],"action_q99":[1.286449,4.087319,3.909092,1.7341,0.537241,26.842585],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-19.305019,-94.272514,-53.519131,52.572708,-8.090842,1.490515],"state_q99":[28.339767,52.609699,96.697215,99.105148,18.192919,26.422764]},
+ {"part":"cdv3__frk2__smallactionspace","origin":"community_dataset_v3","dataset":"frk2/smallactionspace","scene_camera":"observation.images.image","fps":30.0,"built_clips":400,"train_windows":400,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.715266,-3.529961,-3.545456,-2.153594,-0.927961,0.090992],"action_q99":[1.629501,3.901535,3.363636,1.899261,0.976801,38.307552],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-3.415409,-95.20639,-11.230461,56.448765,4.761905,1.506024],"state_q99":[40.270054,17.177097,94.689377,97.886927,29.91453,37.959841]},
+ {"part":"cdv3__gerotropic__so101_pnp","origin":"community_dataset_v3","dataset":"gerotropic/so101_pnp","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1701,"train_windows":1701,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.373047,-2.636719,-1.757812,-2.021484,-0.190476],"action_q99":[0.791016,2.548828,2.285156,1.757812,1.845703,64.952377],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.613281,-102.216797,-48.603516,32.695312,-110.214844,-0.485437],"state_q99":[72.158203,41.132812,87.275391,96.152344,12.919922,64.077667]},
+ {"part":"cdv3__gxy1111__so100_close_drawer","origin":"community_dataset_v3","dataset":"gxy1111/so100_close_drawer","scene_camera":"observation.images.image2","fps":30.0,"built_clips":138,"train_windows":138,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.460938,-2.988281,-1.494141,-1.318359,0.0],"action_q99":[0.878906,2.636719,2.636719,1.582031,0.878906,0.088889],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.955078,-102.041016,-7.243945,17.666016,-30.234375,0.207469],"state_q99":[36.386719,13.659961,83.056641,75.146484,2.146289,0.760719]},
+ {"part":"cdv3__gxy1111__so100_pick_place_easy","origin":"community_dataset_v3","dataset":"gxy1111/so100_pick_place_easy","scene_camera":"observation.images.image2","fps":30.0,"built_clips":229,"train_windows":229,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.373047,-2.724609,-1.318359,-1.054688,0.088889],"action_q99":[1.933594,1.845703,2.460938,1.669922,0.878906,18.133333],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.808594,-62.402344,-54.639844,54.228516,-45.664453,0.622407],"state_q99":[20.390625,39.863672,40.616016,97.382812,-11.074219,17.773169]},
+ {"part":"cdv3__gxy1111__so100_soft2","origin":"community_dataset_v3","dataset":"gxy1111/so100_soft2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":289,"train_windows":289,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-1.669922,-3.164062,-2.373047,-1.933594,0.0],"action_q99":[2.373047,4.394531,1.669922,1.669922,3.691406,24.68],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.486328,-102.480469,-0.439453,6.095215,-101.803711,0.760719],"state_q99":[45.966797,15.789551,87.714844,75.933105,19.744629,24.294606]},
+ {"part":"cdv3__jackyckhsu98__so100_test51","origin":"community_dataset_v3","dataset":"jackyckhsu98/so100_test51","scene_camera":"observation.images.image2","fps":30.0,"built_clips":293,"train_windows":293,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.164062,-2.900391,-1.757812,-0.878906,-0.465983],"action_q99":[1.933594,2.021484,4.695117,1.757812,1.054688,41.379311],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.048828,-45.878906,-103.447266,33.837891,167.871094,0.175593],"state_q99":[34.892578,59.538867,33.134766,105.908203,183.251953,40.561897]},
+ {"part":"cdv3__jccj__shape_matching_u","origin":"community_dataset_v3","dataset":"jccj/shape_matching_u","scene_camera":"observation.images.image2","fps":30.0,"built_clips":798,"train_windows":798,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.49688,-4.299149,-3.825137,-3.311589,-2.637363,0.905797],"action_q99":[2.746567,4.746977,4.826958,3.512291,2.979241,100.0],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-59.84016,-99.821671,-57.833088,2.618817,-76.019539,10.586319],"state_q99":[16.183817,52.831028,99.121521,99.61203,23.321123,99.674271]},
+ {"part":"cdv3__jlesein__TestCube1","origin":"community_dataset_v3","dataset":"jlesein/TestCube1","scene_camera":"observation.images.image","fps":30.0,"built_clips":727,"train_windows":727,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-4.746094,-6.039844,-2.875781,-1.933594,0.0],"action_q99":[2.724609,6.503906,4.570312,3.164062,1.582031,41.792549],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.053516,-100.546875,-102.65625,28.300781,-69.296484,-0.070373],"state_q99":[59.414062,91.40625,88.681641,103.271484,57.919922,41.801548]},
+ {"part":"cdv3__jmrog__record-sweet3","origin":"community_dataset_v3","dataset":"jmrog/record-sweet3","scene_camera":"observation.images.image","fps":30.0,"built_clips":1286,"train_windows":1286,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.379812,-3.012051,-2.497768,-1.774193,-1.367521,0.0],"action_q99":[1.452433,2.667812,3.925068,1.774193,1.416363,41.122215],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-14.549483,-98.728432,-87.449577,27.331163,-89.206352,0.964852],"state_q99":[51.403248,89.191643,99.103539,99.023598,74.798538,40.110268]},
+ {"part":"cdv3__jmrog__record_group","origin":"community_dataset_v3","dataset":"jmrog/record_group","scene_camera":"observation.images.image","fps":30.0,"built_clips":342,"train_windows":342,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.30719,-2.581751,-1.873325,-1.451614,-1.221001,0.461184],"action_q99":[1.452433,2.151465,2.943802,1.370972,0.976801,42.793235],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-12.967503,-95.277023,-47.108921,18.743694,-46.959705,3.514817],"state_q99":[48.153618,66.394188,98.744957,98.454025,35.286934,41.365955]},
+ {"part":"cdv3__jonyshaik__so101_pp_block","origin":"community_dataset_v3","dataset":"jonyshaik/so101_pp_block","scene_camera":"observation.images.image","fps":30.0,"built_clips":1784,"train_windows":1784,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-3.515625,-3.955078,-2.636719,-3.427734,-0.749376],"action_q99":[1.142578,3.515625,4.042969,2.8125,2.900391,47.543713],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.935547,-103.359375,-78.222656,4.306641,-108.075586,-0.471328],"state_q99":[18.193359,61.962891,91.582031,86.923828,69.873047,46.425766]},
+ {"part":"cdv3__juni3227__so100_test_cap_merge","origin":"community_dataset_v3","dataset":"juni3227/so100_test_cap_merge","scene_camera":"observation.images.image","fps":30.0,"built_clips":1394,"train_windows":1394,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.042969,-3.867188,-4.394531,-3.691406,-1.845703,0.0],"action_q99":[4.394531,4.130859,4.130859,3.515625,1.845703,61.010098],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-77.167969,-103.623047,-61.523438,5.225098,-121.776855,0.386997],"state_q99":[87.626953,52.734375,93.867188,104.677734,0.439453,60.351318]},
+ {"part":"cdv3__k1000dai__standup_petbottle","origin":"community_dataset_v3","dataset":"k1000dai/standup_petbottle","scene_camera":"observation.images.image","fps":30.0,"built_clips":1168,"train_windows":1168,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.25926,-2.351952,-3.078316,-3.261803,-1.942799,1.024429],"action_q99":[1.185185,2.855942,2.71616,4.806866,1.836788,47.675335],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-42.921181,-99.494949,-97.108002,-98.045876,-56.887486,1.532312],"state_q99":[25.737766,68.099324,99.186623,95.497025,69.190323,47.501667]},
+ {"part":"cdv3__kaiserbuffle__hanoi","origin":"community_dataset_v3","dataset":"kaiserbuffle/hanoi","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1260,"train_windows":1260,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.669922,-2.109375,-1.40625,-1.669922,-0.257954],"action_q99":[0.966797,1.318359,2.109375,1.757812,1.933594,47.119518],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.3125,-102.392578,-71.367188,-2.197266,-9.492188,0.243902],"state_q99":[31.640625,52.998047,91.933594,100.283203,128.144531,47.154472]},
+ {"part":"cdv3__kaiserbuffle__hanoi_dc","origin":"community_dataset_v3","dataset":"kaiserbuffle/hanoi_dc","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1225,"train_windows":1225,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.219977,-3.794914,-4.452522,-5.261028,-1.470589,0.0],"action_q99":[1.342282,2.58377,4.361652,6.720648,2.197803,47.749336],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.389702,-99.409035,-13.83812,-70.625999,-99.412918,0.559441],"state_q99":[41.486248,28.324188,99.483871,98.245613,100.0,47.662247]},
+ {"part":"cdv3__kaiserbuffle__hanoi_the_good_one","origin":"community_dataset_v3","dataset":"kaiserbuffle/hanoi_the_good_one","scene_camera":"observation.images.image","fps":30.0,"built_clips":176,"train_windows":176,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.086502,-2.800909,-4.18182,-4.532578,-1.672241,0.175439],"action_q99":[1.253657,1.968206,4.090909,6.313232,1.839462,52.192982],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-21.734642,-89.055153,-15.341156,-84.067253,-99.131943,0.633357],"state_q99":[33.402168,38.178707,99.652328,97.998398,99.479164,52.850105]},
+ {"part":"cdv3__kaiserbuffle__hanoi_the_good_two","origin":"community_dataset_v3","dataset":"kaiserbuffle/hanoi_the_good_two","scene_camera":"observation.images.image2","fps":30.0,"built_clips":282,"train_windows":282,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.43816,-3.71417,-4.818183,-5.182186,-1.014366,0.0],"action_q99":[1.629913,2.583771,4.454548,6.396761,1.183434,46.012268],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.911058,-99.240189,-13.058876,-70.334541,-91.546761,0.634697],"state_q99":[44.528965,28.746307,99.557327,99.193871,100.0,45.980255]},
+ {"part":"cdv3__kevin510__so-100-draw-smiley","origin":"community_dataset_v3","dataset":"kevin510/so-100-draw-smiley","scene_camera":"observation.images.image2","fps":30.0,"built_clips":908,"train_windows":908,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.899888,-4.338579,-3.574615,-2.413651,-0.830281,12.288513],"action_q99":[1.12486,4.083374,3.485252,3.828547,1.074481,51.38023],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.783807,-98.234772,-32.029118,2.828197,-14.871795,100.0],"state_q99":[12.186978,43.248013,99.909012,94.681297,22.246643,100.0]},
+ {"part":"cdv3__kirdo__Pick_all_blocks","origin":"community_dataset_v3","dataset":"kirdo/Pick_all_blocks","scene_camera":"observation.images.image","fps":30.0,"built_clips":1442,"train_windows":1442,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-4.130859,-3.779297,-1.757812,-2.285156,-8.306365],"action_q99":[1.318359,4.042969,3.603516,2.460938,2.285156,32.404529],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.326172,-99.84375,-98.701172,19.072266,-155.302734,-4.678771],"state_q99":[41.044922,70.400391,92.021484,97.558594,-54.809473,31.843576]},
+ {"part":"cdv3__kivod__so100_cam2","origin":"community_dataset_v3","dataset":"kivod/so100_cam2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":822,"train_windows":822,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.900391,-2.988281,-1.757812,-2.197266,-0.284495],"action_q99":[1.230469,3.603516,2.724609,1.757812,1.757812,62.660027],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.115234,-103.447266,-63.017578,23.642578,-168.087305,0.270088],"state_q99":[45.263672,48.779297,88.857422,97.646484,80.507812,61.408508]},
+ {"part":"cdv3__kkurzweil__so100_wrist_01","origin":"community_dataset_v3","dataset":"kkurzweil/so100_wrist_01","scene_camera":"observation.images.image","fps":30.0,"built_clips":805,"train_windows":805,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-5.712891,-6.943359,-5.537109,-5.712891,-4.921875,-0.181653],"action_q99":[5.800781,5.361328,6.064453,6.416016,4.306641,40.599457],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-51.855469,-103.535156,-47.988281,-36.416602,-109.775391,0.349895],"state_q99":[85.869141,49.951758,90.878906,88.535742,-12.568359,38.768368]},
+ {"part":"cdv3__kkurzweil__so100_wrist_02","origin":"community_dataset_v3","dataset":"kkurzweil/so100_wrist_02","scene_camera":"observation.images.image","fps":30.0,"built_clips":964,"train_windows":964,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-5.185547,-3.251953,-3.339844,-2.366016,-2.548828,-0.181653],"action_q99":[4.658203,4.482422,3.076172,3.076172,3.251953,29.336966],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.001953,-103.271484,-21.533203,17.578125,-119.53125,2.09937],"state_q99":[87.978516,27.326953,91.054688,92.988281,-6.247266,29.041288]},
+ {"part":"cdv3__kristaqp__so101-pick-place","origin":"community_dataset_v3","dataset":"kristaqp/so101-pick-place","scene_camera":"observation.images.image2","fps":30.0,"built_clips":616,"train_windows":616,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.633259,-3.061226,-2.358276,-2.884613,-1.094604,0.58382],"action_q99":[1.855976,3.656464,2.086174,2.70979,0.886112,36.613846],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-30.289532,-99.913757,32.850364,-7.652174,-62.601189,1.151762],"state_q99":[27.765404,8.667529,99.452553,76.0,-37.236912,36.382114]},
+ {"part":"cdv3__kyomangold__so100_ttt_A2","origin":"community_dataset_v3","dataset":"kyomangold/so100_ttt_A2","scene_camera":"observation.images.image","fps":30.0,"built_clips":220,"train_windows":220,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.248926,-2.197266,-2.021484,-0.791016,-0.966797,1.711712],"action_q99":[1.318359,1.933594,2.373047,0.966797,1.40625,64.954956],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.264355,-98.613281,-88.242188,62.647559,-66.09375,15.653496],"state_q99":[71.982422,73.037109,63.424512,99.84375,4.889355,64.51368]},
+ {"part":"cdv3__kyomangold__so100_ttt_A3","origin":"community_dataset_v3","dataset":"kyomangold/so100_ttt_A3","scene_camera":"observation.images.image","fps":30.0,"built_clips":212,"train_windows":212,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-2.021484,-2.021484,-1.142578,-1.230469,-0.810811],"action_q99":[2.8125,2.373047,2.197266,1.230469,1.142578,58.198196],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-95.888672,-100.634766,-76.113281,46.054688,-56.953125,-0.075988],"state_q99":[90.0,64.969629,77.537988,99.492188,21.708984,57.750763]},
+ {"part":"cdv3__kyomangold__so100_ttt_B2","origin":"community_dataset_v3","dataset":"kyomangold/so100_ttt_B2","scene_camera":"observation.images.image","fps":30.0,"built_clips":218,"train_windows":218,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.460938,-2.373047,-1.142578,-0.527344,-0.540541],"action_q99":[2.460938,2.548828,2.109375,0.986133,0.439453,40.360363],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-108.28125,-100.634766,-83.144531,52.382812,-23.241797,0.0],"state_q99":[91.669922,68.554688,78.925781,99.316406,27.949219,40.045593]},
+ {"part":"cdv3__kyomangold__so100_ttt_B3","origin":"community_dataset_v3","dataset":"kyomangold/so100_ttt_B3","scene_camera":"observation.images.image","fps":30.0,"built_clips":209,"train_windows":209,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.918848,-2.8125,-1.40625,-0.878906,-0.990991],"action_q99":[2.109375,3.358301,2.988281,1.494141,0.615234,61.621624],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.025391,-100.722656,-81.474609,37.959961,-36.298828,-0.303951],"state_q99":[73.037109,69.521484,84.199219,99.667969,10.602246,61.322189]},
+ {"part":"cdv3__lerobot__svla_so100_sorting","origin":"community_dataset_v3","dataset":"lerobot/svla_so100_sorting","scene_camera":"observation.images.image","fps":30.0,"built_clips":1327,"train_windows":1327,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.285156,-1.757812,-1.318359,-1.40625,0.0],"action_q99":[2.460938,2.724609,1.757812,1.669922,1.230469,24.600639],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.728516,-86.748047,-28.545117,28.564453,55.722656,0.069061],"state_q99":[70.927734,37.597852,75.058594,92.900391,127.509961,24.309393]},
+ {"part":"cdv3__lerobot__svla_so100_stacking","origin":"community_dataset_v3","dataset":"lerobot/svla_so100_stacking","scene_camera":"observation.images.image","fps":30.0,"built_clips":787,"train_windows":787,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.900391,-2.373047,-1.054688,-1.318359,0.0],"action_q99":[0.966797,2.8125,2.636719,1.40625,0.966797,28.115017],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.814453,-86.835938,-51.873047,35.050781,53.876953,0.207182],"state_q99":[38.496094,46.933594,74.970703,86.853516,119.443359,27.914365]},
+ {"part":"cdv3__lt-s__so100_train_move_blue_block_tray_to_blue_dish","origin":"community_dataset_v3","dataset":"lt-s/so100_train_move_blue_block_tray_to_blue_dish","scene_camera":"observation.images.image","fps":30.0,"built_clips":190,"train_windows":190,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-6.500391,-4.833984,-3.691406,-7.119141,-0.615655],"action_q99":[1.582031,4.921875,6.4125,3.955078,6.4125,35.883907],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.302734,-99.316406,-36.386719,23.122266,-151.959375,-0.410846],"state_q99":[31.992188,40.338281,83.232422,98.082422,16.875,35.414955]},
+ {"part":"cdv3__lt-s__so100_train_move_blue_block_tray_to_blue_dish_flip","origin":"community_dataset_v3","dataset":"lt-s/so100_train_move_blue_block_tray_to_blue_dish_flip","scene_camera":"observation.images.image","fps":30.0,"built_clips":161,"train_windows":161,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-5.273438,-4.570312,-4.306641,-6.767578,-0.527704],"action_q99":[1.757812,5.097656,5.185547,4.306641,6.679688,34.193492],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.818359,-99.316406,-23.183789,-0.786621,-140.219824,-0.082169],"state_q99":[27.158203,28.652344,83.232422,95.429883,20.917969,33.360722]},
+ {"part":"cdv3__lt-s__so100_train_move_red_block_tray_to_red_dish","origin":"community_dataset_v3","dataset":"lt-s/so100_train_move_red_block_tray_to_red_dish","scene_camera":"observation.images.image","fps":30.0,"built_clips":166,"train_windows":166,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-5.449219,-5.866699,-3.339844,-6.328125,-0.527704],"action_q99":[1.669922,5.097656,5.515137,4.21875,5.537109,41.864555],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-16.259766,-99.404297,-32.409668,13.886719,-134.121094,-0.082169],"state_q99":[21.884766,37.001953,83.232422,93.317871,29.091797,40.571077]},
+ {"part":"cdv3__lt-s__so100_train_move_red_block_tray_to_red_dish_flip","origin":"community_dataset_v3","dataset":"lt-s/so100_train_move_red_block_tray_to_red_dish_flip","scene_camera":"observation.images.image","fps":30.0,"built_clips":165,"train_windows":165,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-5.537109,-5.233887,-4.042969,-7.294922,-0.527704],"action_q99":[1.40625,5.009766,6.152344,3.867188,5.976562,33.597187],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.126953,-99.316406,-45.681152,12.168457,-137.636719,-0.082169],"state_q99":[21.621094,40.605469,83.232422,93.779297,14.414062,31.972061]},
+ {"part":"cdv3__lt-s__so100_train_move_two_blocks_tray_to_matching_dishes","origin":"community_dataset_v3","dataset":"lt-s/so100_train_move_two_blocks_tray_to_matching_dishes","scene_camera":"observation.images.image","fps":30.0,"built_clips":165,"train_windows":165,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-6.15498,-5.451855,-5.012402,-6.679688,-0.527704],"action_q99":[2.285156,6.064453,6.240234,5.361328,7.47334,30.255058],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.46875,-99.404297,-28.388672,2.191992,-153.017578,-0.082169],"state_q99":[30.761719,30.410156,83.320312,92.815137,13.183594,28.266228]},
+ {"part":"cdv3__lt-s__so100_train_move_two_blocks_tray_to_matching_dishes_flip","origin":"community_dataset_v3","dataset":"lt-s/so100_train_move_two_blocks_tray_to_matching_dishes_flip","scene_camera":"observation.images.image","fps":30.0,"built_clips":166,"train_windows":166,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-6.691113,-5.625,-5.636426,-7.833691,-0.439754],"action_q99":[2.021484,5.460645,6.855469,6.25166,8.173828,27.80387],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-11.777344,-99.404297,-21.708984,5.216309,-155.402051,-0.082169],"state_q99":[31.212598,25.664062,83.583984,98.085938,7.998047,26.14051]},
+ {"part":"cdv3__masato-ka__so100_nlact_block_instruct_v3","origin":"community_dataset_v3","dataset":"masato-ka/so100_nlact_block_instruct_v3","scene_camera":"observation.images.image","fps":30.0,"built_clips":1618,"train_windows":1618,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.197266,-2.8125,-1.845703,-4.042969,-0.289017],"action_q99":[1.757812,2.988281,2.460938,1.845703,2.988281,55.186898],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-61.259766,-98.876953,-43.681641,15.556641,-29.53125,0.352734],"state_q99":[60.454687,38.847656,90.351562,88.59375,154.599609,54.585541]},
+ {"part":"cdv3__masato-ka__so100_separate_blue_green_blocks_v2","origin":"community_dataset_v3","dataset":"masato-ka/so100_separate_blue_green_blocks_v2","scene_camera":"observation.images.image","fps":30.0,"built_clips":951,"train_windows":951,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.900391,-2.900391,-2.109375,-3.603516,-0.385356],"action_q99":[2.197266,2.900391,3.164062,2.021484,2.460938,41.907513],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.060156,-97.910156,-56.865234,29.443359,-30.9375,0.440917],"state_q99":[30.410156,45.791016,90.263672,93.955078,94.921875,41.358025]},
+ {"part":"cdv3__masato-ka__so100_separate_blue_grenn_blocks","origin":"community_dataset_v3","dataset":"masato-ka/so100_separate_blue_grenn_blocks","scene_camera":"observation.images.image","fps":30.0,"built_clips":332,"train_windows":332,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.373047,-2.373047,-1.933594,-3.515625,-0.289017],"action_q99":[1.669922,2.636719,2.8125,2.021484,2.021484,40.605974],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.021582,-99.667969,-52.205273,22.851562,-25.3125,0.176367],"state_q99":[29.222754,42.275391,90.263672,94.394531,113.466797,40.211639]},
+ {"part":"cdv3__meetrais__cube_in_the_box4","origin":"community_dataset_v3","dataset":"meetrais/cube_in_the_box4","scene_camera":"observation.images.image2","fps":30.0,"built_clips":837,"train_windows":837,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.988281,-2.988281,-1.845703,-0.703125,-0.202634],"action_q99":[1.054688,3.691406,3.427734,1.51875,0.791016,34.751774],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.117188,-97.646484,-97.910156,2.021484,157.890234,0.0],"state_q99":[49.042969,65.591016,92.724609,72.333984,200.654297,34.372734]},
+ {"part":"cdv3__near0248__woogoo_20250615_011444","origin":"community_dataset_v3","dataset":"near0248/woogoo_20250615_011444","scene_camera":"observation.images.image","fps":30.0,"built_clips":979,"train_windows":979,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.548828,-2.900391,-1.845703,-2.988281,0.258176],"action_q99":[2.197266,3.076172,2.548828,2.373047,2.373047,48.709122],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.150391,-104.238281,-51.240234,25.400391,-21.357422,5.145414],"state_q99":[61.875,48.786328,89.296875,96.240234,102.216797,48.620434]},
+ {"part":"cdv3__near0248__woogoo_20250615_043007","origin":"community_dataset_v3","dataset":"near0248/woogoo_20250615_043007","scene_camera":"observation.images.image","fps":30.0,"built_clips":300,"train_windows":300,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-3.603516,-4.042969,-2.285156,-2.72373,-0.086059],"action_q99":[3.163184,3.955078,4.306641,2.8125,2.109375,51.031843],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.524512,-99.052734,-67.060547,30.058594,18.021094,7.01044],"state_q99":[63.457031,58.183594,87.539062,96.416016,94.833984,50.708424]},
+ {"part":"cdv3__ppankti81__record-blue","origin":"community_dataset_v3","dataset":"ppankti81/record-blue","scene_camera":"observation.images.image2","fps":30.0,"built_clips":113,"train_windows":113,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.812251,-2.835701,-2.772805,-1.944893,-0.537241,1.755917],"action_q99":[1.812252,3.252709,3.041145,1.620747,0.537241,38.33284],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-44.737881,-95.76339,-88.632236,30.745533,-12.576313,2.616089],"state_q99":[31.336224,37.250198,99.465714,98.173882,11.295726,37.67168]},
+ {"part":"cdv3__pranavsaroha__so100_medicine_0611","origin":"community_dataset_v3","dataset":"pranavsaroha/so100_medicine_0611","scene_camera":"observation.images.image","fps":30.0,"built_clips":1470,"train_windows":1470,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.086956,-3.307888,-2.54893,-1.637329,-0.879121,0.0],"action_q99":[1.177536,2.374893,3.379156,1.964798,0.830281,38.46154],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-31.328728,-99.575729,-34.997433,28.571428,-8.131868,0.481431],"state_q99":[29.067499,25.126904,99.144569,82.380951,29.523809,37.25222]},
+ {"part":"cdv3__psg777__blacktape10","origin":"community_dataset_v3","dataset":"psg777/blacktape10","scene_camera":"observation.images.image","fps":30.0,"built_clips":260,"train_windows":260,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.638006,-3.595318,-3.234497,-2.39274,-0.35041,0.408998],"action_q99":[1.758671,2.958194,4.706199,2.475246,0.35041,25.357874],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-11.429985,-98.645218,-80.482513,13.6289,77.295494,1.788269],"state_q99":[93.963387,70.533447,99.103142,95.6913,99.74958,24.320457]},
+ {"part":"cdv3__psg777__blacktape5","origin":"community_dataset_v3","dataset":"psg777/blacktape5","scene_camera":"observation.images.image","fps":30.0,"built_clips":115,"train_windows":115,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.501221,-2.892977,-2.60557,-1.947195,-0.26281,0.681663],"action_q99":[2.638008,2.809361,3.234501,2.145214,0.26281,23.312883],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-83.275604,-98.391197,-24.394619,22.906404,94.323875,1.788269],"state_q99":[57.149925,33.784927,99.103142,75.779968,98.330551,22.103004]},
+ {"part":"cdv3__psg777__blacktape8","origin":"community_dataset_v3","dataset":"psg777/blacktape8","scene_camera":"observation.images.image","fps":30.0,"built_clips":185,"train_windows":185,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.540303,-3.846153,-4.043126,-2.475248,-0.297855,0.477164],"action_q99":[2.833415,3.344482,4.672058,2.805283,0.262817,25.494205],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-57.74369,-98.729889,-72.914795,25.205254,77.796326,1.8598],"state_q99":[64.967834,45.385265,99.103142,94.581284,99.415695,24.320457]},
+ {"part":"cdv3__psg777__combinedtape","origin":"community_dataset_v3","dataset":"psg777/combinedtape","scene_camera":"observation.images.image","fps":30.0,"built_clips":2701,"train_windows":2701,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.247192,-3.093645,-3.144654,-2.145214,-0.525627,0.340832],"action_q99":[2.540302,3.157189,3.504042,2.475248,0.52562,25.630539],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-51.608116,-98.729889,-71.569504,9.277504,57.51252,1.716738],"state_q99":[84.364174,53.090603,99.103142,90.558289,99.74958,24.320457]},
+ {"part":"cdv3__psg777__greencube","origin":"community_dataset_v3","dataset":"psg777/greencube","scene_camera":"observation.images.image","fps":30.0,"built_clips":297,"train_windows":297,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.755726,-2.173912,-2.244164,-1.712189,-0.781441,1.227831],"action_q99":[1.450381,2.257523,2.782764,1.875252,0.83028,31.377899],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-40.348381,-98.078529,-63.847874,19.900703,-26.593407,1.984942],"state_q99":[64.877357,64.9883,99.194633,91.688045,19.56044,29.295004]},
+ {"part":"cdv3__psg777__greencube1","origin":"community_dataset_v3","dataset":"psg777/greencube1","scene_camera":"observation.images.image","fps":30.0,"built_clips":316,"train_windows":316,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.806106,-2.424751,-2.064632,-1.875252,-0.781441,1.091405],"action_q99":[1.221375,2.090302,2.662477,1.956787,0.813674,39.358799],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-36.722359,-98.245613,-55.167786,21.224659,-35.921856,4.03833],"state_q99":[45.751865,54.190475,99.284119,79.56144,18.876678,37.440109]},
+ {"part":"cdv3__psg777__greencube2","origin":"community_dataset_v3","dataset":"psg777/greencube2","scene_camera":"observation.images.image","fps":30.0,"built_clips":339,"train_windows":339,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.526718,-2.173913,-2.154404,-1.630657,-0.537241,0.95498],"action_q99":[1.29771,2.257523,2.423698,1.941297,0.586081,36.221008],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-32.10096,-98.412697,-48.724831,10.964005,-22.393162,1.574264],"state_q99":[67.365799,51.378445,99.284119,83.864296,8.669108,33.333332]},
+ {"part":"cdv3__psg777__greencube3","origin":"community_dataset_v3","dataset":"psg777/greencube3","scene_camera":"observation.images.image","fps":30.0,"built_clips":349,"train_windows":349,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.67939,-2.257526,-2.064636,-1.712189,-0.83028,1.091405],"action_q99":[1.526717,2.090301,2.513466,1.630657,0.879121,34.31105],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-55.27906,-98.078529,-59.731544,13.860157,-18.778999,4.106776],"state_q99":[44.614292,57.396824,99.284119,87.091438,23.663004,31.416838]},
+ {"part":"cdv3__psg777__newone2","origin":"community_dataset_v3","dataset":"psg777/newone2","scene_camera":"observation.images.image","fps":30.0,"built_clips":174,"train_windows":174,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.878613,-2.507313,-2.439024,-1.730534,-0.621734,0.410678],"action_q99":[1.66185,2.340157,2.98103,1.648127,0.537241,35.386723],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-44.025604,-98.501869,-63.563114,28.683451,-15.213675,1.643836],"state_q99":[44.310101,60.715771,99.641899,93.479156,20.341881,32.945206]},
+ {"part":"cdv3__psg777__newone3","origin":"community_dataset_v3","dataset":"psg777/newone3","scene_camera":"observation.images.image","fps":30.0,"built_clips":367,"train_windows":367,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.445087,-2.423737,-2.529358,-1.483315,-0.781441,0.410678],"action_q99":[1.372831,2.507309,2.529358,1.950556,0.732601,36.071182],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-15.291608,-98.41864,-79.23008,17.512175,-24.346764,0.890411],"state_q99":[64.935989,68.53933,99.731422,79.034256,3.736264,33.28767]},
+ {"part":"cdv3__psg777__newone4","origin":"community_dataset_v3","dataset":"psg777/newone4","scene_camera":"observation.images.image","fps":30.0,"built_clips":289,"train_windows":289,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.445086,-2.507313,-2.077686,-1.73053,-0.43956,0.479124],"action_q99":[1.445087,2.089428,3.071363,1.730534,0.29304,39.835728],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.384069,-98.501869,-58.191586,-26.454807,-19.218559,0.958904],"state_q99":[43.883358,72.367874,99.731422,78.382171,6.031746,37.19178]},
+ {"part":"cdv3__psg777__redtape1","origin":"community_dataset_v3","dataset":"psg777/redtape1","scene_camera":"observation.images.image","fps":30.0,"built_clips":427,"train_windows":427,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.954079,-2.675583,-2.425874,-1.89769,-0.26281,0.408998],"action_q99":[2.344894,2.341137,3.234502,2.19307,0.26281,32.651669],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-84.858978,-98.814568,-96.322868,21.100164,69.716192,1.716738],"state_q99":[92.08313,77.730736,99.103142,96.059113,99.74958,31.330473]},
+ {"part":"cdv3__psg777__redtape2","origin":"community_dataset_v3","dataset":"psg777/redtape2","scene_camera":"observation.images.image","fps":30.0,"built_clips":450,"train_windows":450,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.442599,-3.428097,-3.324348,-2.39274,-0.262817,0.340832],"action_q99":[2.540302,3.344482,3.953279,2.722771,0.262817,25.283572],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-32.60762,-98.729889,-62.062778,17.980295,77.879799,1.716738],"state_q99":[97.031174,49.026249,99.103142,86.289001,99.74958,24.658799]},
+ {"part":"cdv3__psg777__redtapepickup","origin":"community_dataset_v3","dataset":"psg777/redtapepickup","scene_camera":"observation.images.image","fps":30.0,"built_clips":142,"train_windows":142,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.758671,-2.842809,-2.875113,-2.145214,-0.293478,0.340832],"action_q99":[2.051785,3.093647,2.54717,2.392738,0.26281,17.382414],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.855022,-98.729889,-31.121077,22.413794,78.63105,1.573677],"state_q99":[64.077187,40.81287,99.192825,87.602631,98.831383,16.165951]},
+ {"part":"cdv3__psg777__redtapepickup1","origin":"community_dataset_v3","dataset":"psg777/redtapepickup1","scene_camera":"observation.images.image","fps":30.0,"built_clips":219,"train_windows":219,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.73571,-3.260866,-4.132977,-2.062706,-0.350418,0.477164],"action_q99":[3.615046,4.347826,3.05481,2.557755,0.350418,22.63122],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-7.273627,-95.935646,-30.313902,24.683088,65.108513,1.573677],"state_q99":[62.790699,39.034718,99.192825,86.535301,94.948247,21.387697]},
+ {"part":"cdv3__psg777__redtapepickup2","origin":"community_dataset_v3","dataset":"psg777/redtapepickup2","scene_camera":"observation.images.image","fps":30.0,"built_clips":187,"train_windows":187,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.540302,-3.093647,-3.593887,-2.062706,-0.26281,0.477164],"action_q99":[3.266244,3.762543,3.362983,3.052803,0.26281,29.31152],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-5.39337,-96.105845,-37.847534,25.697865,83.639397,1.716738],"state_q99":[71.895103,43.099068,99.192825,86.535301,92.988312,28.111588]},
+ {"part":"cdv3__rfruit__so100_building_house_1","origin":"community_dataset_v3","dataset":"rfruit/so100_building_house_1","scene_camera":"observation.images.image","fps":30.0,"built_clips":161,"train_windows":161,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-1.669922,-1.714746,-1.451074,-2.197266,-0.41841],"action_q99":[1.142578,1.582031,1.714746,1.538965,2.021484,38.828449],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.667969,-100.722656,-46.757812,28.125,-129.990234,0.0],"state_q99":[51.767578,37.839551,90.703125,101.689453,7.558594,38.499588]},
+ {"part":"cdv3__rfruit__so100_building_house_2","origin":"community_dataset_v3","dataset":"rfruit/so100_building_house_2","scene_camera":"observation.images.image","fps":30.0,"built_clips":165,"train_windows":165,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.142578,-1.845703,-1.669922,-2.548828,-5.857741],"action_q99":[1.142578,1.757812,1.142578,1.842188,1.40625,50.038496],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.742188,-100.722656,-24.521484,2.373047,-128.935547,-3.215169],"state_q99":[57.392578,27.063281,90.527344,102.392578,-0.551953,49.876339]},
+ {"part":"cdv3__rfruit__so100_building_house_3","origin":"community_dataset_v3","dataset":"rfruit/so100_building_house_3","scene_camera":"observation.images.image","fps":30.0,"built_clips":155,"train_windows":155,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.115332,-1.757812,-1.40625,-2.460938,-0.394011],"action_q99":[1.054688,1.845703,1.054688,1.757812,1.494141,43.97163],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.808594,-100.546875,-51.564551,21.005859,-128.056641,0.247321],"state_q99":[51.328125,37.705078,90.351562,100.722656,-1.142578,43.610882]},
+ {"part":"cdv3__rfruit__so100_building_house_4","origin":"community_dataset_v3","dataset":"rfruit/so100_building_house_4","scene_camera":"observation.images.image","fps":30.0,"built_clips":164,"train_windows":164,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-1.230469,-1.845703,-1.054688,-1.40625,-0.078802],"action_q99":[1.142578,1.845703,1.318359,1.40625,1.494141,46.020489],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.636719,-100.546875,-29.984766,20.126953,-102.216797,0.494641],"state_q99":[50.185547,42.363281,90.351562,98.261719,33.289453,45.978565]},
+ {"part":"cdv3__rfruit__so100_building_house_5","origin":"community_dataset_v3","dataset":"rfruit/so100_building_house_5","scene_camera":"observation.images.image","fps":30.0,"built_clips":157,"train_windows":157,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-1.142578,-1.757812,-1.318359,-2.197266,0.078802],"action_q99":[0.878906,1.582031,1.318359,1.494141,2.021484,40.860518],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.876953,-100.546875,-30.592969,8.261719,-147.65625,0.329761],"state_q99":[40.964062,39.948047,90.485156,98.4375,71.894531,40.521022]},
+ {"part":"cdv3__ricky0526__so101_pick_toy_to_plate_v1","origin":"community_dataset_v3","dataset":"ricky0526/so101_pick_toy_to_plate_v1","scene_camera":"observation.images.image2","fps":30.0,"built_clips":792,"train_windows":792,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.840233,-3.251354,-3.605227,-2.286198,-1.304802,2.166934],"action_q99":[2.593056,3.751564,4.146011,1.947502,1.565762,43.017658],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-51.31086,-98.834305,-51.724136,21.06374,-44.864864,3.277592],"state_q99":[24.927174,47.214822,99.149742,91.388771,24.581724,41.806019]},
+ {"part":"cdv3__ricky0526__so101_pick_toy_to_plate_v2","origin":"community_dataset_v3","dataset":"ricky0526/so101_pick_toy_to_plate_v2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":711,"train_windows":711,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.840233,-3.418091,-3.785488,-1.947502,-1.461378,2.086677],"action_q99":[2.425762,3.751563,4.146011,1.778152,1.722338,39.807384],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-46.73325,-99.084099,-64.100143,32.038834,-61.853283,3.143813],"state_q99":[19.101124,53.788509,98.771851,91.388771,18.112227,38.595318]},
+ {"part":"cdv3__ricky0526__so101_pick_toy_to_plate_v3","origin":"community_dataset_v3","dataset":"ricky0526/so101_pick_toy_to_plate_v3","scene_camera":"observation.images.image","fps":30.0,"built_clips":719,"train_windows":719,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.593058,-6.002501,-5.810727,-3.979679,-1.746869,2.006421],"action_q99":[2.843998,6.586075,6.399277,3.471631,1.722339,57.383629],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-39.65876,-99.167358,-69.984883,-1.179401,-38.608494,3.344482],"state_q99":[32.956304,55.953373,99.244217,91.895317,26.126125,56.254181]},
+ {"part":"cdv3__ricky0526__so101_pick_toy_to_plate_v4","origin":"community_dataset_v3","dataset":"ricky0526/so101_pick_toy_to_plate_v4","scene_camera":"observation.images.image2","fps":30.0,"built_clips":627,"train_windows":627,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.593058,-5.669026,-5.858497,-3.132938,-1.409186,2.086677],"action_q99":[2.50941,6.669447,5.678236,3.048264,1.805323,44.622791],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-29.720349,-99.250626,-76.587623,20.726046,-24.375805,2.943144],"state_q99":[25.842697,59.416321,99.149742,90.62896,34.856629,44.214046]},
+ {"part":"cdv3__robotchip__squidgame1","origin":"community_dataset_v3","dataset":"robotchip/squidgame1","scene_camera":"observation.images.image","fps":30.0,"built_clips":359,"train_windows":359,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","d_main_gripper","main_shoulder_lift"],"action_q01":[-1.40625,-3.955078,-2.197266,-1.669922,-7.752594,28.476562],"action_q99":[1.142578,5.976562,2.548828,1.494141,8.379883,192.919922],"state_names":["main_shoulder_pan","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper","main_shoulder_lift"],"state_q01":[-21.09375,-86.923828,-35.419922,-49.921875,16.081541,27.861328],"state_q99":[34.189453,72.773438,8.876953,-3.515625,99.886749,192.480469]},
+ {"part":"cdv3__rohanc007__record-remove-debris","origin":"community_dataset_v3","dataset":"rohanc007/record-remove-debris","scene_camera":"observation.images.image","fps":30.0,"built_clips":388,"train_windows":388,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.900585,-2.847571,-4.542692,-1.341721,-0.831169,0.85531],"action_q99":[1.900585,4.339194,1.430489,2.012581,0.883117,51.033501],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-13.388183,-98.570831,-79.24045,33.048676,-23.918114,1.993356],"state_q99":[38.369484,70.744011,99.011238,98.804443,38.575278,50.697674]},
+ {"part":"cdv3__rohanc007__record-test4","origin":"community_dataset_v3","dataset":"rohanc007/record-test4","scene_camera":"observation.images.image2","fps":30.0,"built_clips":168,"train_windows":168,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.150787,-3.323392,-2.810516,-1.795639,-0.927961,0.0],"action_q99":[2.325581,2.568387,3.626472,1.978622,0.879122,29.802776],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-66.56694,-99.159309,-67.19101,35.354397,0.285048,1.129568],"state_q99":[61.705311,54.939049,96.044945,99.402222,41.93107,29.966778]},
+ {"part":"cdv3__ryanpennings__so100_pegcrate_e1","origin":"community_dataset_v3","dataset":"ryanpennings/so100_pegcrate_e1","scene_camera":"observation.images.image","fps":30.0,"built_clips":259,"train_windows":259,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.515625,-3.603516,-4.482422,-5.800781,-2.464789],"action_q99":[2.197266,4.394531,4.130859,4.482422,5.009766,26.173708],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.6875,-100.722656,-29.702637,-51.591797,-116.279297,-0.178731],"state_q99":[32.519531,36.386719,85.693359,80.239746,17.393555,25.915995]},
+ {"part":"cdv3__s20000s__soarm100_data","origin":"community_dataset_v3","dataset":"s20000s/soarm100_data","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1779,"train_windows":1779,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.021484,-4.130859,-1.669922,-5.712891,-0.107066],"action_q99":[1.933594,3.691406,1.054688,2.988281,2.8125,39.293362],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.152344,-99.228516,-64.599609,35.507812,-176.308594,0.2772],"state_q99":[74.267578,44.567578,88.945312,103.095703,3.076172,39.148937]},
+ {"part":"cdv3__s20000s__soarm100_data2","origin":"community_dataset_v3","dataset":"s20000s/soarm100_data2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1031,"train_windows":1031,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.021484,-4.482422,-1.669922,-5.185547,-0.103734],"action_q99":[1.669922,4.042969,1.142578,2.900391,2.8125,35.062241],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.306641,-97.998047,-71.684473,34.13584,-176.308594,0.2079],"state_q99":[69.873047,51.855469,88.066406,100.195312,8.173828,34.996536]},
+ {"part":"cdv3__samanthalhy__eval_so100_herding_1_act","origin":"community_dataset_v3","dataset":"samanthalhy/eval_so100_herding_1_act","scene_camera":"observation.images.image2","fps":30.0,"built_clips":350,"train_windows":350,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.613458,-1.966525,-1.284557,-1.051029,-5.146439,-0.348794],"action_q99":[1.744915,1.242187,2.214043,1.237391,4.772266,15.225038],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.796875,-19.511719,-30.410156,66.181641,-176.396484,-0.223714],"state_q99":[26.279297,34.453125,31.552734,90.878906,4.658203,15.063386]},
+ {"part":"cdv3__samanthalhy__so100_herding_2","origin":"community_dataset_v3","dataset":"samanthalhy/so100_herding_2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":4770,"train_windows":4770,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.109375,-1.40625,-0.878906,-3.427734,-0.448934],"action_q99":[0.966797,1.230469,2.197266,1.054688,2.988281,17.845118],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.621094,-32.255859,-55.019531,59.0625,-184.21875,2.237136],"state_q99":[28.212891,48.427734,37.529297,98.701172,18.896484,17.822521]},
+ {"part":"cdv3__samanthalhy__so100_herding_3","origin":"community_dataset_v3","dataset":"samanthalhy/so100_herding_3","scene_camera":"observation.images.image2","fps":30.0,"built_clips":4783,"train_windows":4783,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.109375,-1.40625,-0.878906,-3.427734,-0.448934],"action_q99":[0.966797,1.230469,2.197266,1.054688,2.988281,17.845118],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.621094,-32.255859,-55.019531,59.0625,-184.21875,2.237136],"state_q99":[28.212891,48.427734,37.529297,98.701172,18.896484,17.822521]},
+ {"part":"cdv3__sandhyavs__lego-pickup-clean","origin":"community_dataset_v3","dataset":"sandhyavs/lego-pickup-clean","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1010,"train_windows":1010,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.050289,-3.439382,-3.830368,-3.082054,-2.246643,0.0],"action_q99":[2.802968,3.181427,3.647971,3.748436,2.344322,50.801132],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-30.374594,-98.388466,-29.127706,12.789281,-42.665688,1.360985],"state_q99":[71.423454,33.248516,99.381355,88.557041,46.959705,50.421257]},
+ {"part":"cdv3__sandhyavs__lego-pickup-clean-100","origin":"community_dataset_v3","dataset":"sandhyavs/lego-pickup-clean-100","scene_camera":"observation.images.image2","fps":30.0,"built_clips":2089,"train_windows":2089,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.050288,-3.353394,-3.556772,-2.665558,-2.100122,0.0],"action_q99":[2.96785,3.00946,3.830372,3.331944,2.148962,48.162109],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-29.560261,-98.388466,-32.302254,14.575721,-38.77216,1.10175],"state_q99":[70.195442,38.846481,99.381355,87.576126,84.224663,47.893715]},
+ {"part":"cdv3__sattgle__clean-test","origin":"community_dataset_v3","dataset":"sattgle/clean-test","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1184,"train_windows":1184,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.878289,-4.459402,-3.518269,-7.247627,0.0,0.587248],"action_q99":[2.713816,4.964241,5.773567,5.090595,0.0,32.36661],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-19.325842,-99.175255,-75.741241,-99.656654,99.581261,1.472651],"state_q99":[53.857677,53.15464,99.550766,33.218884,99.581261,31.97756]},
+ {"part":"cdv3__sattgle__clean2-test","origin":"community_dataset_v3","dataset":"sattgle/clean2-test","scene_camera":"observation.images.image2","fps":30.0,"built_clips":876,"train_windows":876,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.453947,-4.711822,-4.600812,-6.557377,0.0,0.587248],"action_q99":[2.796053,5.21666,6.134418,4.141502,0.0,36.409397],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-43.820225,-99.092781,-69.721474,-99.828323,99.581261,1.402525],"state_q99":[53.932583,57.608246,99.460915,29.957081,99.633606,35.904629]},
+ {"part":"cdv3__sattgle__record-test","origin":"community_dataset_v3","dataset":"sattgle/record-test","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1351,"train_windows":1351,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.809211,-2.60833,-3.157419,-3.68162,0.0,0.587248],"action_q99":[2.384869,2.69247,3.247635,4.314064,0.0,27.852348],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-62.921349,-99.505157,-47.349506,-99.570816,99.476578,0.981767],"state_q99":[52.559552,58.432991,99.460915,68.755363,99.633606,27.769985]},
+ {"part":"cdv3__satvikahuja__ball_bbox_wo_part_new_2","origin":"community_dataset_v3","dataset":"satvikahuja/ball_bbox_wo_part_new_2","scene_camera":"observation.images.image","fps":30.0,"built_clips":161,"train_windows":161,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.991188,-1.931591,-1.908224,-0.985627,-0.399512,0.082305],"action_q99":[0.881057,1.543663,2.362562,1.314167,0.39072,51.358025],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-23.159222,-92.192192,-94.848625,20.672682,-9.40171,0.795756],"state_q99":[66.666664,61.84985,99.277,94.926988,15.946276,50.331566]},
+ {"part":"cdv3__satvikahuja__picknplace_brinjal_pan","origin":"community_dataset_v3","dataset":"satvikahuja/picknplace_brinjal_pan","scene_camera":"observation.images.image3","fps":30.0,"built_clips":744,"train_windows":0,"val_windows":0,"action_dim":7,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","d_gripper","extra_wrist.pos"],"action_q01":[-1.376146,-1.180939,-1.544752,-0.938164,-1.025642,-2.473208,-21.008404],"action_q99":[1.261468,1.180935,1.363017,1.108749,0.847865,1.978565,23.025209],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos","extra_wrist.pos"],"state_q01":[-11.441144,-95.286194,-43.981899,33.871655,-4.322344,0.873069,-20.202021],"state_q99":[81.07811,34.680134,78.190048,99.235016,80.024422,45.289456,21.671259],"excluded":"action_dim 7 != 6; no windows in the merged splits"},
+ {"part":"cdv3__satvikahuja__picknplace_carrot_pan","origin":"community_dataset_v3","dataset":"satvikahuja/picknplace_carrot_pan","scene_camera":"observation.images.image3","fps":30.0,"built_clips":640,"train_windows":0,"val_windows":0,"action_dim":7,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","d_gripper","extra_wrist.pos"],"action_q01":[-1.605505,-1.349641,-1.726487,-0.938171,-0.927961,-2.638087,-22.545377],"action_q99":[1.261468,1.34964,1.63562,1.108742,0.83028,1.896126,15.630252],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos","extra_wrist.pos"],"state_q01":[-8.910892,-95.454544,-57.737556,40.986825,-3.422711,0.873069,-22.157024],"state_q99":[81.91199,41.750843,79.457016,99.320015,70.109894,43.202822,15.151515],"excluded":"action_dim 7 != 6; no windows in the merged splits"},
+ {"part":"cdv3__satvikahuja__picknplace_chilli_pan","origin":"community_dataset_v3","dataset":"satvikahuja/picknplace_chilli_pan","scene_camera":"observation.images.image3","fps":30.0,"built_clips":691,"train_windows":0,"val_windows":0,"action_dim":7,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","d_gripper","extra_wrist.pos"],"action_q01":[-1.490826,-1.349641,-1.726486,-1.023453,-0.976801,-2.390766,-22.268908],"action_q99":[1.261467,1.180939,1.544752,1.02346,0.87912,1.896126,15.966387],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos","extra_wrist.pos"],"state_q01":[-9.570957,-95.707069,-42.171947,36.166595,-3.199023,0.80591,-21.395777],"state_q99":[83.772276,33.501682,77.466064,99.235016,65.616608,42.914707,15.33517],"excluded":"action_dim 7 != 6; no windows in the merged splits"},
+ {"part":"cdv3__sergeytata__hackathon-task10","origin":"community_dataset_v3","dataset":"sergeytata/hackathon-task10","scene_camera":"observation.images.image","fps":30.0,"built_clips":64,"train_windows":64,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.001482,-2.531647,-4.501365,-2.228344,-2.804421,0.568643],"action_q99":[1.260192,4.882458,4.185623,3.149609,2.634353,37.855404],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-39.088551,-99.492386,-39.348732,50.96941,-69.15033,0.547945],"state_q99":[17.302704,25.420474,94.565216,98.707451,9.742222,37.389041]},
+ {"part":"cdv3__shreyasgite__tedrake_test","origin":"community_dataset_v3","dataset":"shreyasgite/tedrake_test","scene_camera":"observation.images.image","fps":30.0,"built_clips":208,"train_windows":208,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.380093,-1.822701,-2.63158,-1.561513,-1.269841,0.0],"action_q99":[1.875225,3.148304,1.99637,2.273651,0.87912,35.165878],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-12.064777,-95.548088,-33.187775,45.160015,-10.682784,1.225806],"state_q99":[74.593521,26.753466,99.12664,97.708412,28.937729,34.967743]},
+ {"part":"cdv3__shuohsuan__grasp_data_000_009","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_000_009","scene_camera":"observation.images.image","fps":30.0,"built_clips":192,"train_windows":192,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.854397,-1.826881,-1.916931,-1.719196,-0.43956,0.186567],"action_q99":[0.854397,1.652893,2.104066,1.964798,0.586079,47.947762],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-14.934823,-99.566536,8.263636,18.596631,44.417583,0.873069],"state_q99":[32.067039,-5.413957,99.63636,82.040898,63.418804,47.750168]},
+ {"part":"cdv3__shuohsuan__grasp_data_010_019","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_010_019","scene_camera":"observation.images.image","fps":30.0,"built_clips":229,"train_windows":229,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.419952,-1.471226,-2.096626,-1.72343,-0.488403,0.095694],"action_q99":[1.41995,1.73085,1.731995,1.231026,0.43956,58.086124],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-15.575348,-100.0,14.20765,35.987003,39.633701,1.674619],"state_q99":[79.631714,-3.522069,99.544624,75.467102,56.274968,57.786613]},
+ {"part":"cdv3__shuohsuan__grasp_data_020_029","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_020_029","scene_camera":"observation.images.image","fps":30.0,"built_clips":241,"train_windows":241,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.922968,-2.163567,-2.552418,-1.641365,-0.448843,0.095694],"action_q99":[0.993965,2.250107,2.278944,1.313087,0.39072,52.36268],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-35.963924,-100.0,-81.056465,22.745735,37.924297,1.590457],"state_q99":[40.022549,67.810966,99.36248,98.294067,56.678875,52.153744]},
+ {"part":"cdv3__shuohsuan__grasp_data_030_039","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_030_039","scene_camera":"observation.images.image","fps":30.0,"built_clips":264,"train_windows":264,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.632942,-1.471224,-1.864175,-1.559292,-0.488403,0.191388],"action_q99":[0.922968,1.298141,2.005467,1.477226,0.559221,47.846889],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-69.409996,-100.0,0.910747,25.264013,38.363857,1.656726],"state_q99":[3.419767,3.562194,99.544624,88.870834,69.106227,47.544733]},
+ {"part":"cdv3__shuohsuan__grasp_data_040_049","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_040_049","scene_camera":"observation.images.image","fps":30.0,"built_clips":240,"train_windows":240,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.993965,-1.730852,-2.096626,-1.805496,-0.39072,0.095694],"action_q99":[0.85197,1.55777,1.823154,1.066887,0.39072,50.526318],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-28.898911,-100.0,-68.214935,29.887896,37.728939,1.590457],"state_q99":[4.772642,62.687473,99.2714,75.467102,52.380951,50.231941]},
+ {"part":"cdv3__shuohsuan__grasp_data_050_059","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_050_059","scene_camera":"observation.images.image","fps":30.0,"built_clips":243,"train_windows":243,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.206957,-1.606232,-2.096626,-1.523181,-0.43956,0.095694],"action_q99":[0.891729,1.471226,2.18779,1.887566,0.39072,51.961723],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-24.281097,-100.0,-0.182149,11.535337,33.870575,1.524188],"state_q99":[32.055618,-7.267053,99.36248,87.24614,55.631747,51.75613]},
+ {"part":"cdv3__shuohsuan__grasp_data_060_069","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_060_069","scene_camera":"observation.images.image","fps":30.0,"built_clips":264,"train_windows":264,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.064962,-1.298138,-2.00547,-1.477224,-0.341881,0.095694],"action_q99":[1.277956,1.420168,1.640839,1.395161,0.293041,57.359809],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.367531,-100.0,8.652095,16.180341,37.953113,1.590457],"state_q99":[80.007515,-6.464556,99.2714,80.422424,54.432236,57.322731]},
+ {"part":"cdv3__shuohsuan__grasp_data_070_079","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_070_079","scene_camera":"observation.images.image","fps":30.0,"built_clips":253,"train_windows":253,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.13596,-1.64431,-2.278942,-1.723431,-0.341881,0.095694],"action_q99":[0.86759,1.64431,1.914311,1.641361,0.293041,48.155024],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.292371,-100.0,-60.422588,5.361495,39.720636,1.457919],"state_q99":[37.918076,62.748105,99.291438,75.304634,51.062271,48.376408]},
+ {"part":"cdv3__shuohsuan__grasp_data_080_089","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_080_089","scene_camera":"observation.images.image","fps":30.0,"built_clips":259,"train_windows":259,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.277954,-1.903938,-2.096626,-1.805496,-0.39072,0.095694],"action_q99":[0.922968,1.817398,1.914314,1.641365,0.341881,41.626793],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.846674,-100.0,-60.564663,-22.872461,38.107936,1.39165],"state_q99":[29.734686,61.925991,99.2714,75.710808,50.32967,41.359841]},
+ {"part":"cdv3__shuohsuan__grasp_data_090_099","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_090_099","scene_camera":"observation.images.image","fps":30.0,"built_clips":275,"train_windows":275,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.490948,-1.732589,-2.096626,-1.641365,-0.43956,0.095694],"action_q99":[1.419952,1.55777,2.278942,1.559292,0.4884,48.614356],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-72.115746,-100.0,-6.193079,15.597075,39.145298,1.39165],"state_q99":[28.449455,-3.432902,99.2714,87.652313,56.484493,48.380384]},
+ {"part":"cdv3__shuohsuan__grasp_data_100_109","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_100_109","scene_camera":"observation.images.image","fps":30.0,"built_clips":249,"train_windows":249,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.064962,-1.471226,-2.096626,-1.395161,-0.4884,0.095694],"action_q99":[1.916935,1.47123,1.914307,1.887563,0.43956,50.717705],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-65.877487,-100.0,9.653916,26.563768,32.991451,1.39165],"state_q99":[2.51785,-19.304502,99.453552,88.464661,55.506714,50.762093]},
+ {"part":"cdv3__shuohsuan__grasp_data_110_119","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_110_119","scene_camera":"observation.images.image","fps":30.0,"built_clips":270,"train_windows":270,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.206958,-1.211594,-1.823154,-1.395159,-0.43956,0.095694],"action_q99":[1.419949,1.384682,1.640839,1.887566,0.537239,48.943541],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-65.125893,-100.0,9.744991,19.740049,42.954823,1.39165],"state_q99":[28.031567,-14.139991,99.36248,87.652313,61.145788,48.738236]},
+ {"part":"cdv3__shuohsuan__grasp_data_120_129","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_120_129","scene_camera":"observation.images.image","fps":30.0,"built_clips":308,"train_windows":308,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.348953,-1.211601,-1.731995,-1.313087,-0.341881,0.095694],"action_q99":[1.41995,1.298134,1.640839,1.477226,0.39072,70.239235],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-61.773019,-100.0,11.293261,18.683996,36.605618,1.365805],"state_q99":[78.65464,-8.78288,99.36248,77.497971,54.969475,69.715042]},
+ {"part":"cdv3__shuohsuan__grasp_data_130_139","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_130_139","scene_camera":"observation.images.image","fps":30.0,"built_clips":299,"train_windows":299,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.278409,-2.079723,-2.098541,-1.393444,-0.39072,0.096432],"action_q99":[1.633524,1.733105,2.098537,1.06557,0.341881,41.755062],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-64.614243,-100.0,-66.184448,34.287987,45.836388,0.34965],"state_q99":[37.017803,62.744247,99.819168,78.91806,59.853481,41.468533]},
+ {"part":"cdv3__shuohsuan__grasp_data_140_149","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_140_149","scene_camera":"observation.images.image","fps":30.0,"built_clips":258,"train_windows":258,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.78125,-2.046792,-1.972625,-1.229507,-0.341881,0.0],"action_q99":[1.535511,1.646446,2.189781,1.065573,0.293041,43.008678],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-64.614243,-100.0,-77.869799,41.527447,43.345543,0.20979],"state_q99":[1.335312,69.050803,99.367088,74.940331,56.923077,42.797203]},
+ {"part":"cdv3__shuohsuan__grasp_data_150_159","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_150_159","scene_camera":"observation.images.image","fps":30.0,"built_clips":280,"train_windows":280,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.704544,-1.299828,-1.642334,-1.065571,-0.39072,0.0],"action_q99":[1.207386,1.299828,1.551094,1.311478,0.341881,56.219864],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-22.403561,-100.0,5.153707,30.78759,37.435898,0.20979],"state_q99":[74.183975,-10.824142,99.367088,75.179001,51.788035,55.704894]},
+ {"part":"cdv3__shuohsuan__grasp_data_160_169","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_160_169","scene_camera":"observation.images.image","fps":30.0,"built_clips":291,"train_windows":291,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.704546,-1.386482,-1.642338,-0.983604,-0.43956,0.0],"action_q99":[0.994316,1.213173,1.733574,1.721313,0.43956,53.230473],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-3.783383,-100.0,11.844484,22.195704,43.003662,0.20979],"state_q99":[73.738869,-14.633087,99.276672,74.940331,66.788765,52.867134]},
+ {"part":"cdv3__shuohsuan__grasp_data_170_179","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_170_179","scene_camera":"observation.images.image","fps":30.0,"built_clips":293,"train_windows":293,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.704546,-1.733102,-1.916061,-0.983608,-0.293041,0.0],"action_q99":[0.852272,1.646446,1.824818,1.47541,0.293037,46.962391],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.818991,-100.0,-74.177219,18.297533,45.445667,0.20979],"state_q99":[73.887238,66.721667,99.367088,75.099442,54.461539,46.573425]},
+ {"part":"cdv3__shuohsuan__grasp_data_180_189","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_180_189","scene_camera":"observation.images.image","fps":30.0,"built_clips":268,"train_windows":268,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.775568,-1.906412,-2.098541,-1.31147,-0.293041,0.0],"action_q99":[1.349432,1.90641,2.007301,1.229507,0.293037,43.866925],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.818991,-100.0,-61.573238,22.21957,45.738705,0.20979],"state_q99":[71.876852,61.094223,99.367088,74.940331,54.862028,43.209789]},
+ {"part":"cdv3__shuohsuan__grasp_data_190_199","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_190_199","scene_camera":"observation.images.image","fps":30.0,"built_clips":269,"train_windows":269,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.633522,-1.473137,-1.733576,-1.199181,-0.293041,0.0],"action_q99":[1.5625,1.386482,1.916061,1.557377,0.39072,43.587273],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-65.207718,-100.0,16.998192,7.109785,46.245179,0.20979],"state_q99":[71.142433,-11.452019,99.367088,74.781227,61.465202,43.076923]},
+ {"part":"cdv3__shuohsuan__grasp_data_200_209","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_200_209","scene_camera":"observation.images.image","fps":30.0,"built_clips":239,"train_windows":239,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.994319,-2.166378,-1.733582,-0.983612,-0.341881,0.0],"action_q99":[1.065341,1.386482,2.919708,1.311478,0.341881,46.094501],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-19.732937,-100.0,-84.267632,27.968178,39.909156,0.20979],"state_q99":[33.261127,53.104645,99.367088,74.940331,51.843712,45.874126]},
+ {"part":"cdv3__shuohsuan__grasp_data_210_219","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_210_219","scene_camera":"observation.images.image","fps":30.0,"built_clips":230,"train_windows":230,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.06534,-2.512999,-2.463504,-1.229507,-0.43956,0.0],"action_q99":[0.852273,1.559792,3.102188,1.885246,0.469354,45.901638],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.670623,-100.0,-78.300179,15.592681,43.101341,0.20979],"state_q99":[33.160236,51.10725,99.367088,74.622116,65.988278,45.594406]},
+ {"part":"cdv3__shuohsuan__grasp_data_220_229","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_220_229","scene_camera":"observation.images.image","fps":30.0,"built_clips":273,"train_windows":273,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.065341,-2.166374,-1.733578,-1.147541,-0.293041,0.0],"action_q99":[1.27841,1.386482,2.737226,1.47541,0.293037,49.566055],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-1.632048,-100.0,-83.336347,11.217184,43.589745,0.20979],"state_q99":[77.225517,55.414676,99.367088,74.781227,51.501831,49.090908]},
+ {"part":"cdv3__shuohsuan__grasp_data_230_239","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_230_239","scene_camera":"observation.images.image","fps":30.0,"built_clips":264,"train_windows":264,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.994319,-1.993066,-1.733577,-1.111476,-0.244202,0.0],"action_q99":[0.923296,1.646446,2.372263,1.557377,0.244198,44.358727],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.706232,-100.0,-64.737793,29.355608,46.590476,0.20979],"state_q99":[32.937687,63.612679,99.367088,74.860779,53.531623,43.916084]},
+ {"part":"cdv3__shuohsuan__grasp_data_240_249","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_240_249","scene_camera":"observation.images.image","fps":30.0,"built_clips":281,"train_windows":281,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.420456,-2.339688,-1.642338,-1.31147,-0.293037,0.0],"action_q99":[1.420455,1.386482,2.919708,1.47541,0.39072,46.962391],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-67.210686,-100.0,-73.880654,13.002386,47.399269,0.20979],"state_q99":[33.234421,51.29136,99.367088,74.860779,60.146519,46.573425]},
+ {"part":"cdv3__shuohsuan__grasp_data_250_259","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_250_259","scene_camera":"observation.images.image","fps":30.0,"built_clips":252,"train_windows":252,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.710228,-2.339687,-1.824821,-1.229507,-0.293041,0.0],"action_q99":[0.78125,1.299828,3.010948,1.721313,0.293041,44.358727],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.597181,-100.0,-58.86076,16.149563,47.203907,0.20979],"state_q99":[0.667656,36.604427,99.367088,74.781227,55.946278,44.405594]},
+ {"part":"cdv3__shuohsuan__grasp_data_260_269","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_260_269","scene_camera":"observation.images.image","fps":30.0,"built_clips":241,"train_windows":241,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.278409,-2.599653,-2.372264,-1.639349,-0.464956,0.0],"action_q99":[1.136364,1.733101,3.558394,2.295082,0.341881,49.951782],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.186943,-100.0,-74.050636,12.569611,46.615873,0.20979],"state_q99":[34.718102,48.894485,99.367088,74.940331,63.663002,49.650349]},
+ {"part":"cdv3__shuohsuan__grasp_data_270_279","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_270_279","scene_camera":"observation.images.image","fps":30.0,"built_clips":294,"train_windows":294,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.5625,-2.25303,-1.824815,-1.229507,-0.293041,0.0],"action_q99":[1.207386,1.299828,2.919708,1.72131,0.293037,51.205399],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.038576,-100.0,-55.605785,15.370724,43.296703,0.20979],"state_q99":[72.774483,35.475468,99.276672,74.940331,53.846153,50.76923]},
+ {"part":"cdv3__shuohsuan__grasp_data_280_289","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_280_289","scene_camera":"observation.images.image","fps":30.0,"built_clips":272,"train_windows":272,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.065341,-2.660311,-2.007301,-1.311474,-0.293041,0.0],"action_q99":[0.973011,1.733101,3.102189,1.639347,0.244202,55.834137],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-23.590504,-100.0,-70.253166,22.824185,46.275948,0.20979],"state_q99":[35.83086,68.389061,99.367088,74.781227,54.969475,55.524475]},
+ {"part":"cdv3__shuohsuan__grasp_data_290_299","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_290_299","scene_camera":"observation.images.image","fps":30.0,"built_clips":272,"train_windows":272,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.207386,-3.206238,-1.642334,-1.383605,-0.293041,0.0],"action_q99":[1.065342,1.213173,3.923358,2.213112,0.43956,49.951782],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-63.204746,-100.0,-40.235081,17.501989,46.428327,0.20979],"state_q99":[1.261128,35.475468,99.367088,74.940331,59.462761,50.48951]},
+ {"part":"cdv3__shuohsuan__grasp_data_300_309","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_300_309","scene_camera":"observation.images.image","fps":30.0,"built_clips":229,"train_windows":229,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.639205,-3.430675,-2.919708,-1.393442,-0.293041,0.0],"action_q99":[1.136364,2.253036,4.197081,1.80328,0.293037,48.216007],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-25.890207,-100.0,-50.0,17.979317,47.789989,0.20979],"state_q99":[5.78635,36.604427,99.367088,74.940331,55.750916,47.972027]},
+ {"part":"cdv3__shuohsuan__grasp_data_310_319","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_310_319","scene_camera":"observation.images.image","fps":30.0,"built_clips":231,"train_windows":231,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.207388,-3.812828,-3.102196,-1.885246,-0.293041,0.0],"action_q99":[1.278409,2.166374,4.197081,1.967213,0.293041,47.637417],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.557863,-100.0,-59.584087,8.750995,46.436141,0.20979],"state_q99":[36.201782,63.848891,99.367088,74.781227,55.360195,47.202797]},
+ {"part":"cdv3__shuohsuan__grasp_data_320_329","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_320_329","scene_camera":"observation.images.image","fps":30.0,"built_clips":222,"train_windows":222,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.065342,-3.899481,-3.235403,-1.922951,-0.341881,0.0],"action_q99":[1.207387,1.993065,4.470802,2.459015,0.315506,46.999035],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-40.801186,-100.0,-31.193491,-11.217184,47.106228,0.20979],"state_q99":[1.106825,30.612246,99.367088,74.940331,57.216118,46.772028]},
+ {"part":"cdv3__shuohsuan__grasp_data_330_339","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_330_339","scene_camera":"observation.images.image","fps":30.0,"built_clips":217,"train_windows":217,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.852273,-3.899483,-3.284668,-1.557377,-0.39072,0.0],"action_q99":[1.349431,1.90641,4.470803,2.049175,0.341881,48.891033],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-27.002968,-100.0,-45.569622,17.972157,47.008549,0.20979],"state_q99":[1.48368,35.301781,99.367088,74.940331,57.704517,48.671329]},
+ {"part":"cdv3__shuohsuan__grasp_data_340_349","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_340_349","scene_camera":"observation.images.image","fps":30.0,"built_clips":211,"train_windows":211,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.207386,-3.986135,-3.832115,-1.803276,-0.341881,0.0],"action_q99":[1.349432,2.253029,4.379561,2.622952,0.341881,51.602701],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.191394,-100.0,-31.735985,8.830549,48.128936,0.20979],"state_q99":[33.086052,31.393835,99.367088,79.236275,57.853967,51.074125]},
+ {"part":"cdv3__shuohsuan__grasp_data_350_359","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_350_359","scene_camera":"observation.images.image","fps":30.0,"built_clips":246,"train_windows":246,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.207386,-4.246098,-3.923362,-1.639343,-0.293041,0.0],"action_q99":[1.349432,2.426346,4.562044,2.459015,0.293041,49.180328],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.106084,-100.0,-29.648282,1.511535,44.664227,0.20979],"state_q99":[47.997032,29.214938,99.638336,80.986473,57.557999,48.881119]},
+ {"part":"cdv3__shuohsuan__grasp_data_360_369","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_360_369","scene_camera":"observation.images.image","fps":30.0,"built_clips":248,"train_windows":248,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.994318,-4.008667,-3.832116,-1.393445,-0.293041,0.0],"action_q99":[1.278408,2.253029,4.470802,2.131149,0.293041,55.666346],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-67.359047,-100.0,-36.437614,5.945903,47.191209,0.20979],"state_q99":[1.11276,32.957012,99.367088,74.781227,58.339439,55.524475]},
+ {"part":"cdv3__shuohsuan__grasp_data_370_379","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_370_379","scene_camera":"observation.images.image","fps":30.0,"built_clips":248,"train_windows":248,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.136364,-4.246101,-3.923355,-1.393448,-0.341881,0.0],"action_q99":[1.420454,2.166374,5.20803,2.540982,0.39072,46.962391],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-66.83976,-100.0,-71.880653,30.708035,47.057388,0.20979],"state_q99":[2.893175,48.588799,99.367088,88.623711,63.373872,46.993008]},
+ {"part":"cdv3__shuohsuan__grasp_data_380_389","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_380_389","scene_camera":"observation.images.image","fps":30.0,"built_clips":257,"train_windows":257,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.420454,-4.419411,-3.649635,-1.393446,-0.39072,0.0],"action_q99":[1.491478,2.166374,4.835766,1.967213,0.341881,50.76567],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.112761,-100.0,-55.786617,35.56086,39.34066,0.20979],"state_q99":[75.890205,41.920972,99.54792,88.4646,53.406593,49.930069]},
+ {"part":"cdv3__shuohsuan__grasp_data_390_399","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_390_399","scene_camera":"observation.images.image","fps":30.0,"built_clips":283,"train_windows":283,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.207386,-4.59272,-4.288322,-1.721312,-0.293041,0.0],"action_q99":[1.491477,2.513,5.109489,2.213118,0.244202,49.02218],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.038576,-100.0,-53.978302,16.811456,43.199024,0.20979],"state_q99":[75.445107,35.562309,99.367088,80.509148,53.537483,48.601398]},
+ {"part":"cdv3__shuohsuan__grasp_data_400_409","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_400_409","scene_camera":"observation.images.image","fps":30.0,"built_clips":225,"train_windows":225,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.710227,-3.812824,-3.467155,-1.803284,-0.341881,0.0],"action_q99":[0.497159,1.993065,4.105843,2.295082,0.244202,47.058823],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-28.33828,-100.0,-60.488247,24.821003,47.594627,0.20979],"state_q99":[3.783383,59.617889,99.367088,74.622116,52.771671,46.783218]},
+ {"part":"cdv3__shuohsuan__grasp_data_410_419","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_410_419","scene_camera":"observation.images.image","fps":30.0,"built_clips":235,"train_windows":235,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.49716,-3.812828,-3.558393,-2.213113,-0.39072,0.0],"action_q99":[0.710227,2.079727,4.014595,2.377048,0.293041,52.459015],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-0.816024,-100.0,-43.604883,8.252188,47.044202,0.20979],"state_q99":[35.237389,54.059921,99.367088,74.701668,54.676434,52.167831]},
+ {"part":"cdv3__shuohsuan__grasp_data_420_429","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_420_429","scene_camera":"observation.images.image","fps":30.0,"built_clips":252,"train_windows":252,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.923295,-3.899479,-3.392338,-1.885246,-0.293041,0.0],"action_q99":[0.639206,1.993065,4.74453,2.213113,0.293041,57.280617],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-41.988129,-100.0,0.090416,14.478918,47.448109,0.27972],"state_q99":[4.525223,12.983066,99.367088,74.701668,56.385838,56.853146]},
+ {"part":"cdv3__shuohsuan__grasp_data_430_439","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_430_439","scene_camera":"observation.images.image","fps":30.0,"built_clips":228,"train_windows":228,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.710228,-3.812824,-3.467155,-2.131146,-0.341881,0.0],"action_q99":[0.49716,1.819756,4.470804,2.213112,0.293041,54.77917],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-33.234421,-100.0,-4.339964,21.638823,46.275948,0.27972],"state_q99":[5.637982,4.385584,99.367088,75.263326,56.733579,54.483916]},
+ {"part":"cdv3__shuohsuan__grasp_data_440_449","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_440_449","scene_camera":"observation.images.image","fps":30.0,"built_clips":210,"train_windows":210,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.497159,-3.812828,-3.923357,-1.557381,-0.341881,0.0],"action_q99":[0.852272,2.133448,4.470802,2.213114,0.244202,47.9865],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[0.148368,-100.0,-4.43038,13.524264,47.838829,0.20979],"state_q99":[31.87092,5.742076,99.367088,79.304694,58.2906,47.316085]},
+ {"part":"cdv3__shuohsuan__grasp_data_450_459","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_450_459","scene_camera":"observation.images.image","fps":30.0,"built_clips":235,"train_windows":235,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.682528,-3.812828,-3.558395,-1.361475,-0.322831,0.0],"action_q99":[0.852273,2.166382,4.197083,2.131149,0.244202,53.599806],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-0.238872,-100.0,5.605787,6.267303,46.813187,0.27972],"state_q99":[48.887241,19.669996,99.367088,78.568813,54.657386,52.812588]},
+ {"part":"cdv3__shuohsuan__grasp_data_460_469","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_460_469","scene_camera":"observation.images.image","fps":30.0,"built_clips":261,"train_windows":261,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.923295,-3.726171,-3.102188,-1.47541,-0.341881,0.0],"action_q99":[0.710228,1.763435,4.470802,1.913935,0.293041,46.480232],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-68.768547,-100.0,-8.679928,17.315036,48.034187,0.20979],"state_q99":[5.192878,5.544941,99.54792,74.622116,58.095238,46.363636]},
+ {"part":"cdv3__shuohsuan__grasp_data_470_479","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_470_479","scene_camera":"observation.images.image","fps":30.0,"built_clips":260,"train_windows":260,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.78125,-3.72617,-3.284676,-1.311477,-0.341881,0.0],"action_q99":[0.78125,1.993065,4.744526,2.049183,0.341881,44.262295],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-72.626114,-100.0,-19.077757,26.828957,47.264468,0.27972],"state_q99":[5.41543,16.067738,99.367088,88.4646,60.83028,43.986015]},
+ {"part":"cdv3__shuohsuan__grasp_data_480_489","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_480_489","scene_camera":"observation.images.image","fps":30.0,"built_clips":269,"train_windows":269,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.994316,-3.119587,-2.554741,-1.229507,-0.341881,0.0],"action_q99":[0.78125,1.571063,3.375912,1.731969,0.244202,53.834136],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.002967,-100.0,-14.737794,19.809069,43.247864,0.20979],"state_q99":[77.225517,10.985671,99.367088,95.465393,53.113552,52.815385]},
+ {"part":"cdv3__shuohsuan__grasp_data_490_499","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_490_499","scene_camera":"observation.images.image","fps":30.0,"built_clips":277,"train_windows":277,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.78125,-3.292892,-3.010948,-1.229507,-0.341881,0.0],"action_q99":[0.710228,1.819756,3.923355,2.049179,0.244198,53.670201],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.357567,-100.0,0.542495,13.365155,43.052502,0.20979],"state_q99":[76.854599,2.648719,99.367088,79.315834,53.504272,53.31049]},
+ {"part":"cdv3__shuohsuan__grasp_data_500_509","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_500_509","scene_camera":"observation.images.image","fps":30.0,"built_clips":259,"train_windows":259,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.633523,-3.466204,-3.193432,-1.557377,-0.39072,0.0],"action_q99":[0.639205,2.079727,4.379562,2.622948,0.244202,60.60463],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-28.635015,-100.0,-51.627487,21.320604,46.568985,0.27972],"state_q99":[33.234421,57.879288,99.367088,74.622116,53.943832,59.890208]},
+ {"part":"cdv3__shuohsuan__grasp_data_510_519","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_510_519","scene_camera":"observation.images.image","fps":30.0,"built_clips":219,"train_windows":219,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.704546,-3.72617,-3.284676,-2.085247,-0.341881,0.0],"action_q99":[0.426136,2.253029,4.744526,2.540985,0.293041,60.173576],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-2.818991,-100.0,-51.717903,25.501989,45.982906,0.20979],"state_q99":[32.566765,36.08337,99.638336,74.781227,54.090355,59.930069]},
+ {"part":"cdv3__shuohsuan__grasp_data_520_529","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_520_529","scene_camera":"observation.images.image","fps":30.0,"built_clips":289,"train_windows":289,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.491477,-3.379551,-3.284676,-2.445081,-0.341881,0.0],"action_q99":[0.852273,1.819763,4.197081,2.622952,0.341881,66.92382],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-46.66172,-100.0,-56.509945,16.070007,46.137728,0.27972],"state_q99":[32.566765,40.165001,99.54792,78.42721,57.069595,66.503494]},
+ {"part":"cdv3__shuohsuan__grasp_data_530_539","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_530_539","scene_camera":"observation.images.image","fps":30.0,"built_clips":249,"train_windows":249,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.420454,-3.639511,-2.919708,-2.513935,-0.341881,0.0],"action_q99":[0.710227,1.819763,4.288322,2.622952,0.341881,59.209259],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-26.112761,-100.0,-57.414104,23.54813,44.761906,0.20979],"state_q99":[33.456974,39.904472,99.367088,79.130471,58.469841,58.811188]},
+ {"part":"cdv3__shuohsuan__grasp_data_tg_10","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_tg_10","scene_camera":"observation.images.image","fps":30.0,"built_clips":140,"train_windows":140,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.844141,-2.900391,-3.164062,-2.492578,-1.230469,0.092251],"action_q99":[3.019922,2.988281,3.427734,2.636719,1.318359,35.332104],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-87.802734,-102.65625,-21.621094,-0.734766,-107.753906,0.522778],"state_q99":[79.277344,28.388672,89.912109,84.902344,-65.032031,34.930545]},
+ {"part":"cdv3__shuohsuan__grasp_data_tg_50","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_tg_50","scene_camera":"observation.images.image","fps":30.0,"built_clips":799,"train_windows":799,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-3.164062,-2.900391,-2.636719,-1.054688,0.092251],"action_q99":[2.373047,2.636719,3.339844,2.109375,0.966797,37.546124],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-85.078125,-102.65625,-70.576172,-11.689453,-111.181641,0.448096],"state_q99":[80.068359,54.755859,89.824219,87.714844,-62.138672,36.893204]},
+ {"part":"cdv3__shuohsuan__grasp_data_tsg_50","origin":"community_dataset_v3","dataset":"shuohsuan/grasp_data_tsg_50","scene_camera":"observation.images.image","fps":30.0,"built_clips":798,"train_windows":798,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-3.164062,-2.988281,-2.373047,-1.271777,0.188324],"action_q99":[2.636719,2.724609,3.867188,2.109375,1.230469,46.892654],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-83.144531,-98.261719,-81.826172,1.669922,-128.935547,0.495751],"state_q99":[87.626953,69.34043,86.660156,92.021484,-42.714844,46.600567]},
+ {"part":"cdv3__siqiLi__so100_test","origin":"community_dataset_v3","dataset":"siqiLi/so100_test","scene_camera":"observation.images.image","fps":30.0,"built_clips":687,"train_windows":687,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.306641,-3.164062,-3.251953,-1.230469,0.0],"action_q99":[1.142578,2.460938,3.44707,4.21875,1.40625,97.001038],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.746094,-100.019531,-5.888672,-76.728516,-98.4375,0.487465],"state_q99":[25.400391,36.386719,89.736328,76.376953,-69.433594,96.100273]},
+ {"part":"cdv3__siqiLi__so100_test15","origin":"community_dataset_v3","dataset":"siqiLi/so100_test15","scene_camera":"observation.images.image","fps":30.0,"built_clips":620,"train_windows":620,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-4.394531,-2.109375,-4.921875,-1.230469,0.0],"action_q99":[1.40625,3.515625,2.109375,4.570312,1.230469,95.449844],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.470703,-101.162109,19.423828,-107.402344,-98.349609,0.557103],"state_q99":[21.445312,51.591797,89.648438,76.816406,-68.642578,94.359329]},
+ {"part":"cdv3__siqiLi__so100_test2","origin":"community_dataset_v3","dataset":"siqiLi/so100_test2","scene_camera":"observation.images.image","fps":30.0,"built_clips":620,"train_windows":620,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-4.394531,-2.109375,-4.921875,-1.230469,0.0],"action_q99":[1.40625,3.515625,2.109375,4.570312,1.230469,95.449844],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.470703,-101.162109,19.423828,-107.402344,-98.349609,0.557103],"state_q99":[21.445312,51.591797,89.648438,76.816406,-68.642578,94.359329]},
+ {"part":"cdv3__sleepingdrew__blue_brick","origin":"community_dataset_v3","dataset":"sleepingdrew/blue_brick","scene_camera":"observation.images.image","fps":30.0,"built_clips":965,"train_windows":965,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.931648,-2.706131,-2.395744,-2.068077,-1.315445,0.64],"action_q99":[1.634472,2.959831,2.661936,1.981903,1.315442,49.004],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-30.848709,-99.49324,-37.237373,28.151075,-77.578949,1.577909],"state_q99":[56.236164,47.12838,99.731781,99.033813,53.668421,48.461538]},
+ {"part":"cdv3__stsqitx__clean","origin":"community_dataset_v3","dataset":"stsqitx/clean","scene_camera":"observation.images.image","fps":30.0,"built_clips":211,"train_windows":211,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.852963,-4.928989,-4.628907,-2.186787,-1.074744,0.990099],"action_q99":[2.340893,5.179611,4.531036,3.826881,0.195408,38.613861],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-43.967937,-99.580711,-27.762804,26.482874,-18.583639,2.464332],"state_q99":[28.416834,35.597485,99.011681,87.552216,9.059829,38.067444]},
+ {"part":"cdv3__stsqitx__clean2","origin":"community_dataset_v3","dataset":"stsqitx/clean2","scene_camera":"observation.images.image","fps":30.0,"built_clips":203,"train_windows":203,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.414045,-4.511276,-4.077927,-1.913441,-0.781632,0.990099],"action_q99":[1.901975,4.093567,3.89669,1.548973,0.345384,35.643566],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-46.773548,-99.664574,-16.621742,28.98914,-19.56044,2.140078],"state_q99":[24.735071,27.966457,98.65229,86.895569,3.980464,35.278858]},
+ {"part":"cdv3__tfoldi__so100_glass_1","origin":"community_dataset_v3","dataset":"tfoldi/so100_glass_1","scene_camera":"observation.images.image","fps":30.0,"built_clips":300,"train_windows":0,"val_windows":0,"action_dim":12,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","d_left_gripper","d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[0.0,0.0,0.0,0.0,0.0,0.0,-2.636719,-1.757812,-2.988281,-3.164062,-2.900391,-0.275229],"action_q99":[0.0,0.0,0.0,0.0,0.0,0.0,3.164062,1.669922,2.900391,4.482422,3.691406,66.8367],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper","right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[15.820312,-100.986328,92.724609,70.576172,-70.488281,17.138103,-63.151172,-63.984375,-37.089844,-13.187109,-59.589844,0.974026],"state_q99":[15.908203,-100.986328,92.724609,70.576172,-70.488281,17.138103,20.917969,15.820312,57.399609,97.382812,39.332813,65.749997],"excluded":"action_dim 12 != 6; no windows in the merged splits"},
+ {"part":"cdv3__tfoldi__so100_glass_4","origin":"community_dataset_v3","dataset":"tfoldi/so100_glass_4","scene_camera":"observation.images.image","fps":30.0,"built_clips":450,"train_windows":450,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-1.669922,-4.658203,-3.955078,-3.427734,-2.109375,-0.825688],"action_q99":[1.582031,3.955078,5.703223,3.867188,2.636719,44.189909],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-44.208984,-98.789062,-95.185547,-2.431934,-55.97666,0.649351],"state_q99":[34.189453,49.746094,72.471094,103.271484,59.326172,42.442369]},
+ {"part":"cdv3__tlf123__act_test","origin":"community_dataset_v3","dataset":"tlf123/act_test","scene_camera":"observation.images.image","fps":30.0,"built_clips":87,"train_windows":87,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.636719,-2.548828,-1.494141,-3.251953,0.192864],"action_q99":[1.494141,3.11748,2.414355,1.359668,3.427734,31.964321],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.818359,-102.65625,-13.007812,24.924902,-164.179688,0.079936],"state_q99":[44.472656,27.551074,87.802734,61.962891,2.941699,31.447642]},
+ {"part":"cdv3__tlf123__act_test1","origin":"community_dataset_v3","dataset":"tlf123/act_test1","scene_camera":"observation.images.image","fps":30.0,"built_clips":270,"train_windows":270,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.8125,-2.285156,-1.318359,-2.994434,0.096432],"action_q99":[1.142578,2.636719,3.164062,1.669922,3.427734,28.929605],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.960938,-102.744141,-24.270117,31.904297,-160.664062,-0.239808],"state_q99":[44.912109,24.697266,88.330078,70.494434,2.724609,28.302957]},
+ {"part":"cdv3__triton7777__cube_to_bowl_so100","origin":"community_dataset_v3","dataset":"triton7777/cube_to_bowl_so100","scene_camera":"observation.images.image","fps":30.0,"built_clips":165,"train_windows":165,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-3.914259,-3.977273,-2.888779,-2.085144,-1.75824,0.0],"action_q99":[3.355079,3.693182,3.273953,2.693306,2.002441,31.073944],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-71.595748,-99.409737,-31.73005,47.975597,-80.317459,0.282486],"state_q99":[33.945843,45.701917,92.512314,99.334442,20.293041,30.702448]},
+ {"part":"cdv3__triton7777__cube_to_yellow_basket_so100_teleop_train","origin":"community_dataset_v3","dataset":"triton7777/cube_to_yellow_basket_so100_teleop_train","scene_camera":"observation.images.image","fps":30.0,"built_clips":816,"train_windows":816,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-4.939422,-3.977273,-5.324028,-5.473501,-3.418804,0.0],"action_q99":[4.566635,4.734848,4.333172,6.342312,2.58852,51.408451],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-76.333657,-99.311363,-33.497536,-29.672768,-79.487183,0.376648],"state_q99":[48.093811,42.576488,92.512314,98.447029,22.47033,50.188324]},
+ {"part":"cdv3__un1c0rnio__so101_eraser_mat1","origin":"community_dataset_v3","dataset":"un1c0rnio/so101_eraser_mat1","scene_camera":"observation.images.image","fps":30.0,"built_clips":624,"train_windows":624,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.463593,-2.16757,-2.341288,-1.622543,-1.464434,1.068702],"action_q99":[1.390413,2.250938,2.701486,1.622543,1.474372,29.312977],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-36.334404,-62.060303,-71.920109,50.169205,-29.252409,1.896665],"state_q99":[35.048233,61.641541,57.271095,98.900169,70.513153,29.038588]},
+ {"part":"cdv3__un1c0rnio__so101_sock_stowing_3pair2","origin":"community_dataset_v3","dataset":"un1c0rnio/so101_sock_stowing_3pair2","scene_camera":"observation.images.image","fps":30.0,"built_clips":602,"train_windows":602,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.574183,-3.079879,-3.065826,-2.476517,-0.686695,1.116427],"action_q99":[1.731602,3.178587,4.238052,2.391121,0.629471,48.484848],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-30.264551,-99.079109,-93.423424,22.203533,-1.934135,1.981506],"state_q99":[64.973541,68.27124,99.279282,98.149704,27.591218,48.336855]},
+ {"part":"cdv3__wannrrr__etnai","origin":"community_dataset_v3","dataset":"wannrrr/etnai","scene_camera":"observation.images.image","fps":30.0,"built_clips":336,"train_windows":336,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-5.287356,-11.515665,-8.159565,-5.45004,-1.904761,0.09311],"action_q99":[6.130268,7.620659,10.281052,4.954582,1.562882,65.363129],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-67.440117,-97.744362,-75.558521,21.43375,-7.448107,0.745257],"state_q99":[68.038925,53.667503,98.664886,92.86347,21.514042,63.197832]},
+ {"part":"cdv3__wannrrr__etnai-record","origin":"community_dataset_v3","dataset":"wannrrr/etnai-record","scene_camera":"observation.images.image2","fps":30.0,"built_clips":350,"train_windows":350,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-4.561543,-10.552977,-8.506788,-4.133942,-2.051282,0.186567],"action_q99":[3.853716,7.260448,10.226245,3.885902,1.709402,52.748134],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-13.86503,-97.612961,-62.102176,35.815048,-4.859585,1.744592],"state_q99":[44.703476,53.623188,98.933807,80.877747,19.853479,52.369853]},
+ {"part":"cdv3__weiye11__so100_423_pick","origin":"community_dataset_v3","dataset":"weiye11/so100_423_pick","scene_camera":"observation.images.image","fps":30.0,"built_clips":1077,"train_windows":1077,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-1.494141,-2.988281,-2.548828,-1.494141,-1.845703,-0.099701],"action_q99":[1.494141,2.724609,2.197266,1.582031,1.933594,52.681951],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-53.261719,-96.767578,-24.873047,43.59375,-60.328125,-0.076336],"state_q99":[52.294922,29.267578,84.550781,89.208984,72.017578,52.473282]},
+ {"part":"cdv3__willnorris__bbox-2","origin":"community_dataset_v3","dataset":"willnorris/bbox-2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":628,"train_windows":628,"val_windows":0,"action_dim":6,"action_names":["motors"],"action_q01":[-29.0,-30.0,-28.0,-18.0,-17.0,2046.0],"action_q99":[36.0,23.0,22.0,17.0,19.0,2867.73],"state_names":["motors"],"state_q01":[1075.0,-2211.0,1942.0,2318.0,1785.27,2048.0],"state_q99":[2461.0,-829.0,2953.0,2933.0,2544.0,2863.73]},
+ {"part":"cdv3__willnorris__cylinder-in-box-hillside-1","origin":"community_dataset_v3","dataset":"willnorris/cylinder-in-box-hillside-1","scene_camera":"observation.images.image","fps":30.0,"built_clips":840,"train_windows":840,"val_windows":0,"action_dim":6,"action_names":["motors"],"action_q01":[-0.878906,-2.724609,-1.845703,-1.582031,-0.878906,-0.527344],"action_q99":[1.054688,2.109375,2.109375,2.021484,0.966797,35.859375],"state_names":["motors"],"state_q01":[-27.685547,-98.261719,-37.529297,-8.513086,-9.04043,-0.087891],"state_q99":[39.375,54.404297,90.527344,78.310547,15.46875,35.771484]},
+ {"part":"cdv3__willnorris__cylinder-in-box-hillside-2","origin":"community_dataset_v3","dataset":"willnorris/cylinder-in-box-hillside-2","scene_camera":"observation.images.image","fps":30.0,"built_clips":1070,"train_windows":1070,"val_windows":0,"action_dim":6,"action_names":["motors"],"action_q01":[-1.054688,-1.757812,-1.318359,-1.40625,-0.527344,-0.527344],"action_q99":[0.966797,1.582031,1.494141,1.318359,0.703125,54.580078],"state_names":["motors"],"state_q01":[-27.158203,-98.261719,-37.617188,-16.699219,-4.306641,-0.175781],"state_q99":[45.703125,59.501953,90.439453,77.783203,18.544922,54.492188]},
+ {"part":"cdv3__woohyunwoo__put_in_black_box","origin":"community_dataset_v3","dataset":"woohyunwoo/put_in_black_box","scene_camera":"observation.images.image","fps":30.0,"built_clips":4741,"train_windows":0,"val_windows":0,"action_dim":12,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","d_left_gripper","d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-1.40625,-5.888672,-6.503906,-3.427734,-2.460938,-2.759891,-1.669922,-4.921875,-5.097656,-3.427734,-6.503906,-0.685602],"action_q99":[1.757812,5.625,6.679688,3.515625,2.900391,2.75989,1.757812,5.449219,5.800781,3.691406,5.800781,35.357494],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper","right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-9.228516,-101.425781,-94.306641,36.298828,-107.314453,0.217077,-46.142578,-102.216797,-77.783203,18.193359,2.988281,-0.198939],"state_q99":[37.001953,60.292969,86.660156,104.150391,-39.550781,23.806078,17.402344,41.396484,88.417969,103.007812,140.625,34.814323],"excluded":"action_dim 12 != 6; no windows in the merged splits"},
+ {"part":"cdv3__xhaka3456__Pick_Place","origin":"community_dataset_v3","dataset":"xhaka3456/Pick_Place","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1738,"train_windows":1738,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.988281,-2.900391,-1.933594,-2.197266,-0.191571],"action_q99":[1.40625,2.988281,3.076172,2.460938,2.373047,46.760563],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.419922,-102.216797,-27.319922,26.982422,-109.483594,0.069541],"state_q99":[34.277344,23.291016,92.724609,99.404297,34.189453,45.897079]},
+ {"part":"cdv3__xhaka3456__so100_test_0510","origin":"community_dataset_v3","dataset":"xhaka3456/so100_test_0510","scene_camera":"observation.images.image2","fps":30.0,"built_clips":1113,"train_windows":1113,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.8125,-2.988281,-2.109375,-2.636719,-0.191571],"action_q99":[1.494141,3.164062,2.900391,2.548828,2.8125,48.356808],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.859375,-102.216797,-26.103516,26.71875,-118.476562,0.069541],"state_q99":[34.101562,19.335938,92.724609,99.404297,10.195312,47.421932]},
+ {"part":"cdv3__yangfengzzz__yellow_block_grasp_vary","origin":"community_dataset_v3","dataset":"yangfengzzz/yellow_block_grasp_vary","scene_camera":"observation.images.image","fps":30.0,"built_clips":971,"train_windows":971,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.599327,-4.067795,-4.367256,-2.79232,-1.521511,1.046699],"action_q99":[1.936027,3.8983,5.517865,3.141357,1.41658,54.991947],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-15.879442,-99.157188,-43.541103,29.035049,-13.576334,0.820793],"state_q99":[46.249213,37.463127,95.121948,99.221115,47.01532,54.582764]},
+ {"part":"cdv3__yeshasdaman__cleanup-table","origin":"community_dataset_v3","dataset":"yeshasdaman/cleanup-table","scene_camera":"observation.images.image","fps":30.0,"built_clips":1649,"train_windows":1649,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.286691,-2.64791,-2.61497,-2.494624,-1.414353,0.462963],"action_q99":[1.206272,2.978901,2.614967,3.526882,1.361971,23.996914],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-44.187752,-97.966103,-57.027599,-27.830776,-88.376068,1.382488],"state_q99":[40.740742,55.696611,99.320595,94.027374,34.27204,24.028967]},
+ {"part":"cdv3__yuk6ra__so101-cube-2","origin":"community_dataset_v3","dataset":"yuk6ra/so101-cube-2","scene_camera":"observation.images.image2","fps":30.0,"built_clips":111,"train_windows":111,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-2.129221,-3.715935,-3.140423,-3.242317,-1.055967,1.809955],"action_q99":[2.790015,4.508671,5.07851,2.389076,1.108765,36.847662],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-28.941735,-98.450279,-54.324326,47.581534,-22.181629,2.621232],"state_q99":[38.850574,37.253551,99.36937,98.559929,16.711899,36.304062]},
+ {"part":"cdv3__yuk6ra__so101-onetape-cleanup","origin":"community_dataset_v3","dataset":"yuk6ra/so101-onetape-cleanup","scene_camera":"observation.images.image","fps":30.0,"built_clips":647,"train_windows":647,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-0.731529,-3.218021,-3.416556,-2.568497,-0.579863,1.111111],"action_q99":[0.731529,3.700729,4.993429,1.969177,0.527148,22.301588],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-12.622088,-98.241943,-56.588448,48.983051,-4.409079,2.410424],"state_q99":[10.217881,43.574718,99.187729,99.067795,7.278894,21.813029]},
+ {"part":"cdv3__yuk6ra__so101-tapes-cleanup","origin":"community_dataset_v3","dataset":"yuk6ra/so101-tapes-cleanup","scene_camera":"observation.images.image","fps":30.0,"built_clips":635,"train_windows":635,"val_windows":0,"action_dim":6,"action_names":["d_shoulder_pan","d_shoulder_lift","d_elbow_flex","d_wrist_flex","d_wrist_roll","gripper.pos"],"action_q01":[-1.024141,-3.21802,-3.153745,-2.739723,-0.685292,1.031746],"action_q99":[1.316752,3.459373,5.168638,1.797943,0.685293,27.301588],"state_names":["shoulder_pan.pos","shoulder_lift.pos","elbow_flex.pos","wrist_flex.pos","wrist_roll.pos","gripper.pos"],"state_q01":[-31.555222,-98.241943,-63.523466,51.864407,-3.730759,2.28013],"state_q99":[26.521412,48.848892,99.187729,99.237289,11.922776,26.76482]},
+ {"part":"cezarsolo__so100_data","origin":"molmoact","dataset":"cezarsolo/so100_data","scene_camera":"observation.images.perspective","fps":30.0,"built_clips":842,"train_windows":842,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-2.8125,-3.076172,-1.845703,-1.669922,0.0],"action_q99":[2.285156,2.109375,2.373047,2.021484,1.582031,30.73436],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.271484,60.996094,78.662109,38.056641,159.697266,1.732502],"state_q99":[90.087891,183.867188,172.96875,90.930762,216.826172,29.313929]},
+ {"part":"cezarsolo__so100_newdata","origin":"molmoact","dataset":"cezarsolo/so100_newdata","scene_camera":"observation.images.perspective","fps":30.0,"built_clips":794,"train_windows":794,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.285156,-2.285156,-1.494141,-0.966797,0.0],"action_q99":[2.109375,1.757812,2.109375,1.669922,1.054688,25.113327],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.720703,63.122168,76.025391,39.726562,156.533203,1.732502],"state_q99":[85.78125,183.955078,173.056641,92.460938,201.252832,23.769924]},
+ {"part":"cezarsolo__so100_test","origin":"molmoact","dataset":"cezarsolo/so100_test","scene_camera":"observation.images.perspective","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-1.845703,-1.40625,-1.669922,-1.054688,0.0],"action_q99":[2.021484,1.582031,1.845703,1.933594,0.791016,22.846783],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.371094,81.123047,126.826172,0.439453,156.181641,1.732502],"state_q99":[85.166016,183.867188,171.5625,77.080078,196.347656,21.55232]},
+ {"part":"charleyong__so100_cubes_put_box","origin":"molmoact","dataset":"charleyong/so100_cubes_put_box","scene_camera":"observation.images.stationary","fps":30.0,"built_clips":884,"train_windows":884,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.373047,-2.197266,-2.900391,-1.318359,-0.189934],"action_q99":[0.878906,3.955078,3.339844,4.306641,0.966797,28.205128],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.841992,52.382812,114.345703,-87.626953,-122.377148,0.138792],"state_q99":[30.443555,189.84375,179.824219,74.619141,-72.91582,27.827898]},
+ {"part":"charleyong__so100_tic_tac_toe_autoend","origin":"molmoact","dataset":"charleyong/so100_tic_tac_toe_autoend","scene_camera":"observation.images.stationary","fps":30.0,"built_clips":2576,"train_windows":2576,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-3.867188,-3.427734,-2.373047,-1.318359,-0.2849],"action_q99":[5.800781,5.009766,4.921875,2.636719,1.494141,26.495726],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.291016,40.517578,42.363281,5.252344,-107.578125,0.069396],"state_q99":[98.370703,193.447266,180.351562,84.132422,-58.623047,26.231783]},
+ {"part":"charleyong__so100_tic_tac_toe_updated","origin":"molmoact","dataset":"charleyong/so100_tic_tac_toe_updated","scene_camera":"observation.images.stationary","fps":30.0,"built_clips":2235,"train_windows":2235,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-3.955078,-3.164062,-3.774902,-1.230469,-0.2849],"action_q99":[2.109375,5.976562,5.976562,3.867188,1.230469,25.641026],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.248047,37.96875,39.111328,-29.707031,-103.535156,0.069396],"state_q99":[59.501953,190.195312,180.263672,79.716797,-62.226562,25.537821]},
+ {"part":"chmadran__so100_home_dataset","origin":"molmoact","dataset":"chmadran/so100_home_dataset","scene_camera":"observation.images.logitech","fps":30.0,"built_clips":634,"train_windows":634,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-4.921875,-4.482422,-2.373047,-2.197266,0.0],"action_q99":[2.285156,4.921875,4.306641,2.636719,2.460938,57.707912],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.044922,55.037109,47.548828,21.621094,-44.244141,0.911002],"state_q99":[80.068359,189.667969,181.142578,93.515625,41.660156,56.061668]},
+ {"part":"cjlqwe__so100_1_20","origin":"molmoact","dataset":"cjlqwe/so100_1_20","scene_camera":"observation.images.phone","fps":30.0,"built_clips":594,"train_windows":594,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-2.548828,-2.552344,-1.230469,-1.230469,-6.106195],"action_q99":[0.791016,2.285156,2.900391,1.494141,1.142578,42.654865],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.685547,24.169922,-5.185547,40.166016,-127.177734,-2.522154],"state_q99":[23.027344,191.953125,178.154297,89.736328,-70.576172,42.336741]},
+ {"part":"cjlqwe__so100_21_50","origin":"molmoact","dataset":"cjlqwe/so100_21_50","scene_camera":"observation.images.phone","fps":30.0,"built_clips":703,"train_windows":703,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.636719,-2.373047,-1.40625,-0.966797,-6.106195],"action_q99":[0.966797,2.8125,3.427734,1.933594,0.966797,41.061947],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.894531,26.894531,2.8125,34.980469,-109.160156,-2.522154],"state_q99":[10.546875,191.953125,178.330078,78.222656,-73.740234,41.240627]},
+ {"part":"cjlqwe__so100_51_70","origin":"molmoact","dataset":"cjlqwe/so100_51_70","scene_camera":"observation.images.phone","fps":30.0,"built_clips":481,"train_windows":481,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.900391,-2.636719,-1.40625,-1.142578,-6.173451],"action_q99":[1.142578,3.164062,3.955078,1.582031,1.054688,50.442474],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.960938,28.476562,-0.066797,25.3125,-127.96875,-2.453988],"state_q99":[11.668359,192.041016,178.417969,78.046875,-83.144531,50.274027]},
+ {"part":"cjlqwe__so100_71_100","origin":"molmoact","dataset":"cjlqwe/so100_71_100","scene_camera":"observation.images.phone","fps":30.0,"built_clips":689,"train_windows":689,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.515625,-3.427734,-1.318359,-1.582031,-6.548673],"action_q99":[1.669922,3.427734,3.867188,1.318359,1.669922,45.752213],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.836621,24.082031,-4.130859,31.113281,-137.8125,-2.522154],"state_q99":[14.677734,192.041016,178.417969,84.023438,-68.027344,45.80777]},
+ {"part":"cjlqwe__so100_test2","origin":"molmoact","dataset":"cjlqwe/so100_test2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":275,"train_windows":275,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.460938,-1.933594,-1.142578,-1.582031,-6.106195],"action_q99":[0.878906,2.021484,1.933594,1.230469,1.40625,47.964603],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.363281,65.742188,62.138672,42.804492,-108.984375,-2.113156],"state_q99":[6.943359,191.953125,178.066406,78.046875,-31.025391,47.85276]},
+ {"part":"crabarca__so101_test5","origin":"molmoact","dataset":"crabarca/so101_test5","scene_camera":"observation.images.phone","fps":30.0,"built_clips":55,"train_windows":55,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.096191,-3.076172,-2.373047,-3.691406,-3.867188,-0.526316],"action_q99":[1.845703,3.427734,2.447754,3.076172,4.016602,57.280701],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.421875,30.849609,101.513672,-99.931641,-111.005859,0.264784],"state_q99":[33.486328,194.941406,179.736328,75.585938,95.537109,56.928509]},
+ {"part":"cruiseliu__so101_test","origin":"molmoact","dataset":"cruiseliu/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":65,"train_windows":65,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.054688,-1.230469,-1.355273,-0.703125,15.347335],"action_q99":[1.142578,1.230469,1.40625,1.40625,0.791016,16.074314],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.595703,13.886719,-5.9625,69.257812,-60.117188,15.448852],"state_q99":[18.632812,64.160156,66.181641,104.414062,-14.941406,16.214334]},
+ {"part":"cwhite098__benchy4","origin":"molmoact","dataset":"cwhite098/benchy4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":285,"train_windows":285,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-4.203809,-1.845703,-4.028027,-4.570312,-0.269784],"action_q99":[1.318359,4.306641,2.900391,3.779297,5.009766,31.294962],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.828125,44.472656,73.315723,-70.282617,-9.052734,0.069109],"state_q99":[27.231152,187.119141,177.802734,65.830078,97.382812,30.82239]},
+ {"part":"cyoung96__so100_tennis_balls","origin":"molmoact","dataset":"cyoung96/so100_tennis_balls","scene_camera":"observation.images.phone","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-5.009766,-4.752246,-1.676074,-2.127832,-7.191781],"action_q99":[3.697559,5.009766,5.631152,1.676074,2.285156,57.648403],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.066406,20.384473,-9.580078,70.011914,-38.320312,-3.536068],"state_q99":[66.708984,188.173828,178.945312,105.205078,42.463477,57.167613]},
+ {"part":"cyoung96__so100_test","origin":"molmoact","dataset":"cyoung96/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1290,"train_windows":1290,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.21875,-5.888672,-6.328125,-2.724609,-3.339844,-0.20284],"action_q99":[4.570312,5.449219,6.328125,3.076172,4.042969,50.709938],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.19248,13.447266,-12.919922,38.056641,-6.362402,0.0],"state_q99":[80.947266,188.964844,178.066406,98.173828,115.083105,50.48399]},
+ {"part":"danaaubakirova__so100_task_2","origin":"molmoact","dataset":"danaaubakirova/so100_task_2","scene_camera":"observation.images.top","fps":30.0,"built_clips":277,"train_windows":277,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.316309,-4.130859,-3.164062,-2.373047,-1.933594,0.0],"action_q99":[3.427734,3.525293,2.636719,3.339844,1.933594,30.24494],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-17.138672,84.990234,95.439551,35.498145,61.32832,0.207182],"state_q99":[75.859277,182.988281,169.541016,98.261719,114.697266,29.972374]},
+ {"part":"danaaubakirova__so100_task_3","origin":"molmoact","dataset":"danaaubakirova/so100_task_3","scene_camera":"observation.images.top","fps":30.0,"built_clips":271,"train_windows":271,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.21875,-4.394531,-3.427734,-2.197266,-2.285156,-0.106496],"action_q99":[3.339844,3.779297,2.900391,3.076172,2.021484,28.0213],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.414062,77.783203,90.351562,48.603516,61.083984,0.207182],"state_q99":[75.410156,182.988281,169.572656,98.4375,116.641406,27.555248]},
+ {"part":"danaaubakirova__so100_v2_task_1","origin":"molmoact","dataset":"danaaubakirova/so100_v2_task_1","scene_camera":"observation.images.top","fps":30.0,"built_clips":295,"train_windows":295,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.485059,-4.658203,-3.691406,-2.636719,-2.900391,-0.106496],"action_q99":[3.515625,3.779297,3.076172,3.164062,2.285156,29.715654],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.597656,48.68877,45.615234,28.037109,51.413379,0.0],"state_q99":[75.498047,182.988281,169.628906,98.4375,125.859375,28.867403]},
+ {"part":"danaaubakirova__so100_v2_task_2","origin":"molmoact","dataset":"danaaubakirova/so100_v2_task_2","scene_camera":"observation.images.top","fps":30.0,"built_clips":530,"train_windows":530,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-3.515625,-2.548828,-1.40625,-1.318359,0.0],"action_q99":[1.494141,2.8125,1.933594,1.757812,1.845703,26.943558],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.376953,61.962891,66.09375,34.101562,33.046875,0.069061],"state_q99":[74.355469,185.097656,169.628906,98.085938,119.619141,26.726521]},
+ {"part":"danaaubakirova__so100_v2_task_3","origin":"molmoact","dataset":"danaaubakirova/so100_v2_task_3","scene_camera":"observation.images.top","fps":30.0,"built_clips":441,"train_windows":441,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-4.09043,-3.339844,-1.40625,-1.669922,-0.106496],"action_q99":[2.109375,2.548828,2.197266,2.021484,2.021484,28.434505],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.849609,28.564453,4.746094,30.849609,31.376953,0.069061],"state_q99":[74.970703,183.387305,169.541016,98.173828,121.728516,28.245857]},
+ {"part":"danielritchie__so101_test2","origin":"molmoact","dataset":"danielritchie/so101_test2","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":16,"train_windows":16,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.078613,-4.715332,-3.779297,-0.791016,-0.263672,-4.458599],"action_q99":[1.696289,2.364258,0.263672,1.40625,1.344727,43.381104],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[58.974609,62.578125,52.294922,52.470703,-3.779297,-1.444623],"state_q99":[106.875,181.757812,177.714844,67.5,16.875,43.499199]},
+ {"part":"dongseon__so100_04261","origin":"molmoact","dataset":"dongseon/so100_04261","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":278,"train_windows":278,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-5.800781,-6.328125,-2.285156,-2.739551,0.0],"action_q99":[2.109375,5.185547,5.46416,3.164062,2.285156,10.536219],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.817676,52.207031,51.416016,29.77998,36.474609,0.226415],"state_q99":[39.023438,187.119141,173.671875,96.855469,95.976562,10.126038]},
+ {"part":"dongseon__so100_0429","origin":"molmoact","dataset":"dongseon/so100_0429","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":175,"train_windows":175,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-5.712891,-7.470703,-1.933594,-1.845703,0.0],"action_q99":[1.757812,4.833984,4.833984,3.779297,2.197266,13.006598],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.935547,30.498047,21.708984,61.347656,49.482422,0.589102],"state_q99":[36.650391,182.988281,166.464844,104.853516,96.503906,12.95729]},
+ {"part":"dongseon__so100_0501","origin":"molmoact","dataset":"dongseon/so100_0501","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":176,"train_windows":176,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-5.277832,-6.591797,-2.724609,-1.669922,0.0],"action_q99":[1.586426,4.570312,4.574707,4.047363,1.845703,17.483568],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.583984,37.529297,38.408203,32.607422,23.466797,0.972447],"state_q99":[43.857422,185.537109,176.835938,96.943359,94.570312,16.450567]},
+ {"part":"dongseon__so100_0503","origin":"molmoact","dataset":"dongseon/so100_0503","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":177,"train_windows":177,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-4.66084,-5.976562,-2.021484,-1.669922,0.0],"action_q99":[1.318359,4.570312,4.394531,2.8125,2.021484,15.809168],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.035156,29.619141,23.642578,36.645117,42.275391,0.626959],"state_q99":[36.123047,183.076172,174.726562,99.580078,97.470703,15.595612]},
+ {"part":"dongseon__so100_0505","origin":"molmoact","dataset":"dongseon/so100_0505","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":187,"train_windows":187,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.570312,-5.273438,-2.17002,-2.460938,0.0],"action_q99":[1.554785,4.21875,3.927832,3.076172,2.900391,17.586529],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.318555,21.357422,10.195312,43.945312,23.14248,0.783699],"state_q99":[40.693359,183.251953,174.375,99.492188,130.496484,17.554859]},
+ {"part":"dongseon__so100_0510","origin":"molmoact","dataset":"dongseon/so100_0510","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":156,"train_windows":156,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-4.833105,-5.624121,-1.845703,-1.582031,0.0],"action_q99":[1.40625,4.394531,3.690527,2.988281,1.757812,16.838167],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.517578,34.277344,29.267578,48.428613,45.263672,0.783699],"state_q99":[35.331152,183.251953,174.638672,99.492188,94.130859,16.692789]},
+ {"part":"dongseon__so100_test11","origin":"molmoact","dataset":"dongseon/so100_test11","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":257,"train_windows":257,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-6.064453,-5.625,-3.033984,-2.8125,0.0],"action_q99":[2.109375,4.21875,4.658203,3.251953,2.021484,13.358419],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.826172,58.623047,-21.269531,52.734375,25.576172,0.150943],"state_q99":[13.007812,187.382812,173.671875,98.789062,73.212891,12.830189]},
+ {"part":"dongseon__so100_test8","origin":"molmoact","dataset":"dongseon/so100_test8","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":92,"train_windows":92,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-5.487891,-4.521094,-3.026953,-1.933594,0.0],"action_q99":[2.548828,4.833984,4.696875,3.779297,2.548828,20.64394],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.365234,60.078516,68.916797,36.210938,57.832031,0.448766],"state_q99":[13.183594,188.085938,180.527344,89.121094,92.285156,20.559461]},
+ {"part":"dongseon__so100_test9","origin":"molmoact","dataset":"dongseon/so100_test9","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":233,"train_windows":233,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-6.739453,-5.772656,-2.988281,-2.197266,0.0],"action_q99":[2.285156,4.921875,5.009766,3.515625,2.109375,13.700758],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.419922,55.019531,58.623047,42.451172,24.489844,0.448766],"state_q99":[10.810547,188.085938,180.527344,92.872266,92.285156,13.364248]},
+ {"part":"drjaisree25__carrot_data","origin":"molmoact","dataset":"drjaisree25/carrot_data","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1111,"train_windows":1111,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-1.845703,-1.757812,-1.40625,-1.142578,1.525262],"action_q99":[1.142578,2.109375,2.988281,1.318359,1.142578,45.757866],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.225684,28.090723,2.285156,41.660156,-57.041016,2.035153],"state_q99":[53.261719,190.371094,174.814453,98.173828,66.09375,45.605923]},
+ {"part":"drjaisree25__carrot_data_0","origin":"molmoact","dataset":"drjaisree25/carrot_data_0","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1162,"train_windows":1162,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-1.933594,-1.933594,-1.582031,-0.703125,1.334604],"action_q99":[1.494141,2.109375,2.900391,1.511719,0.703125,55.500477],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.488281,25.576172,0.966797,32.414062,-30.322266,1.850139],"state_q99":[55.722656,190.546875,175.605469,97.998047,22.148438,55.504162]},
+ {"part":"drjaisree25__onion_data","origin":"molmoact","dataset":"drjaisree25/onion_data","scene_camera":"observation.images.webcam0","fps":30.0,"built_clips":1558,"train_windows":1558,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.197266,-2.021484,-1.669922,-1.582031,1.429933],"action_q99":[1.669922,1.845703,2.548828,1.669922,1.582031,79.122971],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.027344,31.113281,1.142578,20.302734,-79.892578,1.480111],"state_q99":[37.880859,191.953125,171.298828,98.525391,78.826465,78.81591]},
+ {"part":"drjaisree25__so100_test","origin":"molmoact","dataset":"drjaisree25/so100_test","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":336,"train_windows":336,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.460938,-2.285156,-2.285156,-1.669922,2.001907],"action_q99":[1.494141,2.460938,2.900391,2.900391,1.582031,59.485226],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.451172,28.828125,4.394531,17.929688,-35.244141,2.256244],"state_q99":[50.361328,190.019531,175.078125,98.173828,120.322266,59.204441]},
+ {"part":"dsfsg__bring_bottle","origin":"molmoact","dataset":"dsfsg/bring_bottle","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":303,"train_windows":303,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-1.933594,-1.318359,-2.285156,-1.669922,-0.105485],"action_q99":[1.318359,1.582031,1.494141,1.933594,1.757812,68.037971],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.394531,42.539062,84.902344,-96.349219,-108.632812,0.879507],"state_q99":[81.836719,188.701172,174.462891,52.998047,-1.054688,67.106422]},
+ {"part":"dsfsg__grasp_pen_and_bottle","origin":"molmoact","dataset":"dsfsg/grasp_pen_and_bottle","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":523,"train_windows":523,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-1.757812,-1.582031,-2.021484,-1.669922,-0.105485],"action_q99":[1.494141,2.109375,2.285156,2.285156,2.988281,69.620255],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.484375,48.603516,72.246094,-61.962891,-132.099609,0.527704],"state_q99":[60.029297,188.789062,174.375,80.859375,-6.503906,68.689529]},
+ {"part":"dsfsg__grasp_pens","origin":"molmoact","dataset":"dsfsg/grasp_pens","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":700,"train_windows":700,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-1.757812,-2.021484,-2.021484,-1.845703,-0.105485],"action_q99":[1.40625,2.021484,1.933594,3.076172,2.021484,66.983124],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.755859,29.970703,19.072266,-40.605469,-139.658203,0.460862],"state_q99":[31.113281,189.667969,174.550781,92.197266,-6.152344,66.733507]},
+ {"part":"dsfsg__so100_test2","origin":"molmoact","dataset":"dsfsg/so100_test2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1787,"train_windows":1787,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.351562,-1.318359,-1.40625,-1.582031,-1.318359,-0.105485],"action_q99":[0.351562,2.021484,1.582031,1.494141,1.933594,66.033752],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.679688,32.34375,57.832031,-57.832031,-101.865234,0.527704],"state_q99":[25.576172,189.667969,174.462891,77.695312,-6.240234,65.171501]},
+ {"part":"dulics__so100_hellolerobot","origin":"molmoact","dataset":"dulics/so100_hellolerobot","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":55,"train_windows":55,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-5.375391,-4.760156,-2.211328,-0.534375,-0.319489],"action_q99":[1.142578,5.104687,4.855078,2.109375,0.527344,58.067097],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.583203,39.54375,10.458984,59.055469,-9.316406,0.333333],"state_q99":[19.6875,191.25,177.099609,99.84375,16.787109,56.002668]},
+ {"part":"dulics__so100_helloworld","origin":"molmoact","dataset":"dulics/so100_helloworld","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":56,"train_windows":56,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-4.490332,-4.22666,-1.494141,-0.527344,-0.159744],"action_q99":[1.494141,2.285156,2.380957,2.197266,0.791016,44.488819],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.367188,15.029297,-5.185547,59.845605,-6.240234,0.333333],"state_q99":[25.959375,191.162109,176.396484,100.019531,20.126953,44.406001]},
+ {"part":"dulics__so100_strawberry_bear","origin":"molmoact","dataset":"dulics/so100_strawberry_bear","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":557,"train_windows":557,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-4.570312,-4.306641,-2.109375,-0.878906,-0.239617],"action_q99":[1.757812,5.639062,5.449219,2.197266,0.878906,55.830669],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.025391,14.677734,-5.185547,38.320312,-16.699219,0.533333],"state_q99":[45.351562,192.568359,177.539062,100.019531,27.773438,55.533333]},
+ {"part":"dweiQAQ__lerobot_data","origin":"molmoact","dataset":"dweiQAQ/lerobot_data","scene_camera":"observation.images.phone","fps":30.0,"built_clips":66,"train_windows":66,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-2.197266,-2.157715,-1.669922,-0.878906,-0.650759],"action_q99":[2.021484,2.157715,2.421387,2.157715,1.151367,76.355751],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-12.919922,38.496094,35.15625,21.309082,-12.089355,-0.165153],"state_q99":[73.652344,191.425781,174.462891,99.931641,4.21875,76.383156]},
+ {"part":"dweiQAQ__so101_test_1","origin":"molmoact","dataset":"dweiQAQ/so101_test_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":269,"train_windows":269,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-3.164062,-2.197266,-1.494141,-1.669922,-4.446855],"action_q99":[2.724609,2.988281,2.285156,1.757812,1.757812,69.956619],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.826172,59.677734,55.458984,36.826172,-39.05332,-2.394715],"state_q99":[73.300781,195.996094,178.857422,90.263672,5.200488,69.859619]},
+ {"part":"easonjcc__so100_test-02","origin":"molmoact","dataset":"easonjcc/so100_test-02","scene_camera":"observation.images.phone","fps":30.0,"built_clips":473,"train_windows":473,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.251953,-3.691406,-2.204297,-1.054688,-0.220751],"action_q99":[0.966797,3.779297,4.394531,1.933594,1.142578,48.123619],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.885937,22.587891,-3.164062,32.776172,39.111328,0.492611],"state_q99":[13.447266,191.513672,177.275391,102.832031,115.927734,48.11166]},
+ {"part":"easonjcc__so100_test-04","origin":"molmoact","dataset":"easonjcc/so100_test-04","scene_camera":"observation.images.c3","fps":30.0,"built_clips":650,"train_windows":650,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.373047,-2.724609,-1.312207,-0.791016,-0.220751],"action_q99":[1.494141,2.460938,2.900391,1.582031,0.966797,49.337749],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.408203,37.353516,-3.339844,38.496094,48.603516,0.656814],"state_q99":[19.775391,194.414062,178.681641,102.480469,115.400391,49.753696]},
+ {"part":"easonjcc__so100_test-05","origin":"molmoact","dataset":"easonjcc/so100_test-05","scene_camera":"observation.images.eye","fps":30.0,"built_clips":305,"train_windows":305,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.570312,-4.570312,-2.021484,-1.318359,-0.110375],"action_q99":[2.373047,4.306641,4.394531,2.197266,1.318359,50.772625],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.935547,29.707031,-2.109375,37.792969,43.560352,0.492611],"state_q99":[22.763672,195.029297,179.472656,102.919922,96.416016,50.410507]},
+ {"part":"easonjcc__so100_test-1","origin":"molmoact","dataset":"easonjcc/so100_test-1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":783,"train_windows":783,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.691406,-3.779297,-2.197266,-0.878906,-0.107991],"action_q99":[1.582031,3.779297,4.921875,2.109375,0.966797,60.695463],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.706641,5.621484,-17.666016,26.982422,60.904688,1.149425],"state_q99":[42.978516,183.867188,172.001953,105.644531,107.845313,60.591133]},
+ {"part":"edgarkim__so100_test","origin":"molmoact","dataset":"edgarkim/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":31,"train_windows":31,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.991797,-1.757812,-1.054688,-1.494141,-0.108578],"action_q99":[1.582031,3.079687,2.460938,1.318359,0.973828,52.877308],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.532812,58.886719,55.546875,47.281641,93.164062,0.406835],"state_q99":[15.560156,185.888672,175.869141,90.439453,119.446875,52.400326]},
+ {"part":"edgarkim__so100_test_edgar_2","origin":"molmoact","dataset":"edgarkim/so100_test_edgar_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":853,"train_windows":853,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.394531,-4.130859,-1.845703,-2.197266,-0.217155],"action_q99":[2.021484,3.955078,3.427734,2.021484,2.373047,69.598267],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.0,29.179688,13.447266,45.439453,53.062207,0.488202],"state_q99":[23.90625,186.416016,176.132812,92.021484,185.185547,69.324654]},
+ {"part":"edgarkim__so100_test_edgar_block","origin":"molmoact","dataset":"edgarkim/so100_test_edgar_block","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1072,"train_windows":1072,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-4.482422,-4.130859,-1.582031,-1.757812,-0.108578],"action_q99":[1.230469,4.130859,3.603516,1.845703,1.582031,40.825191],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.300781,30.498047,15.556641,52.382812,68.203125,0.569569],"state_q99":[15.029297,186.152344,175.078125,91.757812,180.878906,40.602116]},
+ {"part":"edgarkim__so100_test_edgar_blue_block_1","origin":"molmoact","dataset":"edgarkim/so100_test_edgar_blue_block_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":253,"train_windows":253,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-4.184473,-3.481348,-1.40625,-1.40625,0.0],"action_q99":[1.40625,3.867188,3.164062,1.40625,1.318359,40.825191],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.597656,50.131934,46.933594,47.529492,66.09375,0.244101],"state_q99":[8.173828,186.503906,173.232422,91.142578,116.279297,40.358017]},
+ {"part":"enpeicv__so101_test","origin":"molmoact","dataset":"enpeicv/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":766,"train_windows":766,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.975293,-2.724609,-2.109375,-1.494141,-2.936242],"action_q99":[1.250684,2.8125,4.21875,1.669922,1.494141,59.060402],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.001953,47.8125,14.414062,36.210938,-66.553418,2.791014],"state_q99":[5.273438,196.962891,181.757812,96.679688,1.054688,59.155888]},
+ {"part":"francescocrivelli__so100_test_5","origin":"molmoact","dataset":"francescocrivelli/so100_test_5","scene_camera":"observation.images.workspace","fps":30.0,"built_clips":163,"train_windows":163,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.427734,-2.724609,-2.021484,-1.40625,-2.777778],"action_q99":[1.318359,3.691406,3.691406,1.933594,1.318359,36.190475],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.134766,46.318359,45.188965,34.453125,-26.982422,-1.838529],"state_q99":[26.962207,197.226562,180.878906,84.462891,7.822266,35.731415]},
+ {"part":"ganker5__so100_dataline_20250331","origin":"molmoact","dataset":"ganker5/so100_dataline_20250331","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1143,"train_windows":1143,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.494141,-1.40625,-1.142578,-1.40625,-0.58873],"action_q99":[1.054688,1.494141,1.845703,1.142578,1.142578,37.426411],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.884766,45.351562,34.628906,38.583984,-65.126953,0.230238],"state_q99":[37.404492,190.810547,177.275391,89.472656,21.056836,36.60783]},
+ {"part":"ganker5__so100_test","origin":"molmoact","dataset":"ganker5/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":156,"train_windows":156,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.427734,-2.636719,-1.669922,-1.230469,0.336417],"action_q99":[2.197266,2.875781,3.339844,2.285156,1.318359,40.37006],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.736719,42.539062,21.972656,49.658203,-32.582813,0.437828],"state_q99":[47.875781,189.492188,173.496094,98.701172,-0.615234,39.579685]},
+ {"part":"ganondorofu__so101_3cam","origin":"molmoact","dataset":"ganondorofu/so101_3cam","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":16,"train_windows":16,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.106934,-3.634277,-3.049805,-2.900391,-4.21875,-0.396825],"action_q99":[3.194824,2.8125,3.779297,4.486816,3.498047,40.801588],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.878906,57.744141,49.385742,34.101562,39.344238,1.315789],"state_q99":[44.538574,155.421387,140.888672,105.205078,115.110352,40.413532]},
+ {"part":"ganondorofu__so101_3cam_ml","origin":"molmoact","dataset":"ganondorofu/so101_3cam_ml","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":140,"train_windows":140,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-3.498047,-2.900391,-1.933594,-2.267578,-1.084237],"action_q99":[2.636719,4.042969,2.724609,2.636719,2.197266,40.61718],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.455078,46.757812,41.660156,55.318359,-102.216797,0.626566],"state_q99":[50.097656,192.445313,140.537109,106.962891,4.376953,39.912281]},
+ {"part":"ganondorofu__so101_gpulearntest","origin":"molmoact","dataset":"ganondorofu/so101_gpulearntest","scene_camera":"observation.images.phone","fps":30.0,"built_clips":210,"train_windows":210,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.076172,-2.988281,-2.285156,-2.548828,-0.31746],"action_q99":[2.636719,3.625488,2.285156,3.076172,2.373047,40.238094],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.576172,47.636719,40.341797,51.943359,-120.322266,1.12782],"state_q99":[57.041016,161.455078,128.430176,104.941406,-25.664062,40.2099]},
+ {"part":"gavrelina__pingpong-dunk-lr","origin":"molmoact","dataset":"gavrelina/pingpong-dunk-lr","scene_camera":"observation.images.main","fps":30.0,"built_clips":310,"train_windows":310,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.339844,-2.724609,-2.197266,-3.164062,-1.535974],"action_q99":[1.757812,2.900391,2.8125,2.724609,3.515625,75.101051],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-63.35332,40.517578,16.347656,16.699219,-156.269531,-0.350385],"state_q99":[39.974414,182.988281,172.792969,95.009766,125.595703,65.241768]},
+ {"part":"gxy1111__so100_rotate","origin":"molmoact","dataset":"gxy1111/so100_rotate","scene_camera":"observation.images.eye","fps":30.0,"built_clips":783,"train_windows":783,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.8125,-2.636719,-1.933594,-1.845703,-0.088889],"action_q99":[1.142578,2.988281,2.900391,1.933594,2.724609,27.200001],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.267578,53.525391,51.591797,-21.357422,-89.560547,0.829876],"state_q99":[36.826172,192.568359,177.451172,73.476562,19.511719,26.763487]},
+ {"part":"gxy1111__so100_soft","origin":"molmoact","dataset":"gxy1111/so100_soft","scene_camera":"observation.images.eye","fps":30.0,"built_clips":762,"train_windows":762,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.427734,-2.636719,-1.757812,-1.001953,-0.088889],"action_q99":[1.582031,1.845703,1.669922,1.582031,2.548828,22.311111],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.089844,60.046875,48.533203,-2.285156,-86.34375,0.760719],"state_q99":[42.662109,192.568359,177.363281,73.476562,25.224609,22.060858]},
+ {"part":"gxy1111__so100_tape2","origin":"molmoact","dataset":"gxy1111/so100_tape2","scene_camera":"observation.images.eye","fps":30.0,"built_clips":243,"train_windows":243,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-4.130859,-4.130859,-1.241895,-0.878906,0.0],"action_q99":[1.669922,3.076172,2.285156,2.120801,3.691406,25.789334],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.048828,68.994141,71.806641,61.171875,-85.166016,0.760719],"state_q99":[46.40625,192.480469,177.802734,94.394531,17.753906,25.80429]},
+ {"part":"hawnsoung__so101_test_coff_3","origin":"molmoact","dataset":"hawnsoung/so101_test_coff_3","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":9,"train_windows":9,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-0.175781,-1.257715,-3.015527,-1.872949,-1.619617],"action_q99":[1.669922,3.076172,3.130664,2.312402,0.845508,84.44976],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.148242,84.550781,105.205078,37.353516,9.84375,2.233276],"state_q99":[59.353418,196.083984,180.175781,99.228516,30.234375,83.790741]},
+ {"part":"hawnsoung__so101_test_coff_5","origin":"molmoact","dataset":"hawnsoung/so101_test_coff_5","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":90,"train_windows":90,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-4.833984,-3.603516,-2.636719,-3.691406,-1.275917],"action_q99":[3.073535,2.900391,2.8125,3.339844,5.007129,47.443381],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-51.767578,39.902344,29.970703,27.597656,-65.612109,0.51458],"state_q99":[55.195312,196.611328,182.197266,107.578125,101.425781,47.76758]},
+ {"part":"hkphoooey__so100_test","origin":"molmoact","dataset":"hkphoooey/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":464,"train_windows":464,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-6.152344,-4.921875,-2.548828,-2.926758,-0.091659],"action_q99":[2.460938,5.712891,5.449219,2.724609,3.076172,39.413383],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.322266,15.442383,-0.263672,40.078125,-128.232422,0.56899],"state_q99":[46.318359,192.832031,177.890625,99.931641,13.095703,38.26458]},
+ {"part":"hoon-shin__so100_basketball","origin":"molmoact","dataset":"hoon-shin/so100_basketball","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1163,"train_windows":1163,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.988281,-3.251953,-2.119922,-1.318359,-0.412797],"action_q99":[1.230469,2.8125,2.900391,1.933594,1.142578,74.509804],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.703125,22.851562,2.988281,14.755078,-112.763672,-0.088889],"state_q99":[44.824219,188.4375,179.824219,99.228516,-24.4125,74.232888]},
+ {"part":"howld__so100_test","origin":"molmoact","dataset":"howld/so100_test","scene_camera":"observation.images.RGB","fps":30.0,"built_clips":51,"train_windows":51,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-3.086719,-1.582031,-2.295703,-2.998828,-3.225806],"action_q99":[1.845703,2.548828,1.416797,3.164062,2.460938,30.952381],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.746875,101.689453,149.783203,-56.172656,-100.135547,-1.161202],"state_q99":[11.555859,188.789062,180.0,79.804688,-2.636719,30.806011]},
+ {"part":"hrhraj__so100_dice_red_v1","origin":"molmoact","dataset":"hrhraj/so100_dice_red_v1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":325,"train_windows":325,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-2.548828,-2.021484,-2.636719,-0.878906,-0.955691],"action_q99":[1.494141,2.460938,2.285156,2.8125,1.054688,33.449177],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.927734,56.953125,68.818359,-61.171875,-119.355469,0.077882],"state_q99":[71.367188,191.689453,177.802734,75.55166,-56.777344,33.489098]},
+ {"part":"hrhraj__so100_dice_red_v2","origin":"molmoact","dataset":"hrhraj/so100_dice_red_v2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":431,"train_windows":431,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-2.109375,-1.845703,-2.021484,-1.757812,-1.042572],"action_q99":[1.757812,2.021484,1.845703,2.724609,1.669922,28.49696],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.013672,50.993262,51.240234,-57.65625,-171.123047,-0.233645],"state_q99":[73.388672,191.953125,177.978516,99.84375,-27.333984,28.660437]},
+ {"part":"hrhraj__so100_dice_yellow","origin":"molmoact","dataset":"hrhraj/so100_dice_yellow","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":476,"train_windows":476,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.603516,-3.251953,-2.724609,-3.603516,-4.123711],"action_q99":[2.021484,3.164062,4.306641,3.515625,3.691406,26.710403],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.537109,24.521484,11.337891,-45.791016,-130.341797,-1.881533],"state_q99":[92.373047,189.84375,176.132812,99.667969,33.795703,26.550522]},
+ {"part":"hrhraj__so100_lego_figure_with_boxes","origin":"molmoact","dataset":"hrhraj/so100_lego_figure_with_boxes","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":305,"train_windows":305,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.285156,-1.933594,-2.021484,-1.845703,-1.216334],"action_q99":[1.494141,1.582031,1.582031,2.866113,2.021484,32.927887],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.587891,61.611328,59.501953,-63.28125,-171.123047,-0.233645],"state_q99":[73.476562,191.689453,177.714844,87.82207,-27.685547,32.710281]},
+ {"part":"hrhraj__so100_objects_car_v1","origin":"molmoact","dataset":"hrhraj/so100_objects_car_v1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":321,"train_windows":321,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.109375,-1.757812,-1.582031,-1.669922,-1.042572],"action_q99":[0.966797,1.582031,1.933594,1.845703,1.845703,30.842745],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.984375,52.207031,34.277344,27.861328,-171.5625,0.077882],"state_q99":[66.621094,191.953125,177.802734,99.667969,-29.707031,30.68536]},
+ {"part":"hrhraj__so100_objects_v1","origin":"molmoact","dataset":"hrhraj/so100_objects_v1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":326,"train_windows":326,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.933594,-1.757812,-1.757812,-1.582031,-1.042572],"action_q99":[0.791016,1.494141,1.582031,2.109375,1.582031,29.973936],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.591797,56.25,50.976562,-65.039062,-171.386719,0.077882],"state_q99":[68.203125,191.689453,177.890625,95.888672,-14.677734,29.672897]},
+ {"part":"hrhraj__so100_red_dice_with_boxes","origin":"molmoact","dataset":"hrhraj/so100_red_dice_with_boxes","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":321,"train_windows":321,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.109375,-1.669922,-1.845703,-0.615234,-1.042572],"action_q99":[1.494141,1.669922,1.669922,2.109375,0.439453,29.105127],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.803418,65.249121,59.604785,-65.917969,-106.787109,0.077882],"state_q99":[76.376953,191.689453,177.978516,76.201172,-72.280371,28.738317]},
+ {"part":"hrhraj__so100_test","origin":"molmoact","dataset":"hrhraj/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-3.076172,-2.548828,-2.373047,-1.855371,-3.561387],"action_q99":[1.40625,1.933594,2.558496,2.548828,1.76748,25.585756],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.460938,37.529297,24.433594,9.658301,-79.716797,-1.533101],"state_q99":[53.79873,189.316406,175.869141,92.8125,6.240234,25.435539]},
+ {"part":"hrhraj__so100_toy_red_car_with_boxes","origin":"molmoact","dataset":"hrhraj/so100_toy_red_car_with_boxes","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":319,"train_windows":319,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.197266,-1.845703,-2.021484,-1.933594,-1.042572],"action_q99":[1.318359,1.757812,1.757812,2.285156,2.109375,40.973936],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.742188,45.878906,45.85957,-19.599609,-171.123047,0.077882],"state_q99":[78.574219,191.689453,177.802734,88.681641,-38.144531,40.654205]},
+ {"part":"hrhraj__train_so100_dice_red","origin":"molmoact","dataset":"hrhraj/train_so100_dice_red","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":384,"train_windows":384,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.828125,-2.882812,-2.285156,-1.669922,-2.8125,-1.042572],"action_q99":[2.021484,2.460938,2.8125,2.197266,2.8125,30.234579],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.732422,54.492188,49.042969,-74.970703,-97.382812,0.077882],"state_q99":[66.181641,191.777344,177.011719,90.263672,27.421875,30.140188]},
+ {"part":"huyouare__so100_test","origin":"molmoact","dataset":"huyouare/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.460938,-2.021484,-2.206055,-0.791016,10.510204],"action_q99":[0.791016,3.603516,3.990234,1.230469,2.021484,29.602041],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[6.328125,27.158203,4.025391,58.710938,-73.740234,11.228334],"state_q99":[46.854492,187.294922,171.298828,98.701172,7.822266,28.636021]},
+ {"part":"igaewa__so101_smolvla_50_epochs","origin":"molmoact","dataset":"igaewa/so101_smolvla_50_epochs","scene_camera":"observation.images.phone","fps":30.0,"built_clips":403,"train_windows":403,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-5.009766,-4.306641,-2.548828,-2.8125,-0.102775],"action_q99":[2.636719,5.449219,5.888672,2.724609,2.478516,67.6259],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.455078,43.400391,36.035156,41.308594,-48.779297,0.145349],"state_q99":[28.300781,193.886719,178.330078,88.417969,15.908203,65.741281]},
+ {"part":"ilBiondo06__so100_ball_A1","origin":"molmoact","dataset":"ilBiondo06/so100_ball_A1","scene_camera":"observation.images.side","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.123753,-2.740652,-1.888037,-2.551401,-4.365703,2.142704],"action_q99":[3.774142,2.589927,3.051292,2.656894,4.313541,49.179707],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.736328,80.121094,88.97168,26.103516,0.0,3.22163],"state_q99":[13.68457,170.393555,142.734375,79.804688,79.541016,47.220108]},
+ {"part":"ilBiondo06__so100_ball_A2","origin":"molmoact","dataset":"ilBiondo06/so100_ball_A2","scene_camera":"observation.images.side","fps":30.0,"built_clips":69,"train_windows":69,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.611477,-3.27297,-2.196825,-3.453633,-7.867833,0.898936],"action_q99":[2.317826,3.270651,2.842402,3.278487,6.660793,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.204883,82.617188,90.439453,18.516797,0.0,2.894135],"state_q99":[10.741992,169.804688,141.064453,79.804688,109.653223,48.104342]},
+ {"part":"ilBiondo06__so100_ball_A3","origin":"molmoact","dataset":"ilBiondo06/so100_ball_A3","scene_camera":"observation.images.side","fps":30.0,"built_clips":43,"train_windows":43,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.738913,-2.955697,-2.234004,-3.336792,-5.156959,0.711613],"action_q99":[2.775852,2.826136,3.129854,2.355912,6.576467,46.694688],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.058301,87.714844,86.396484,33.088184,0.087891,2.894135],"state_q99":[13.913086,169.897852,141.064453,79.892578,106.725586,45.356436]},
+ {"part":"ilBiondo06__so100_ball_A4","origin":"molmoact","dataset":"ilBiondo06/so100_ball_A4","scene_camera":"observation.images.side","fps":30.0,"built_clips":68,"train_windows":68,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.21069,-3.62676,-2.298054,-3.641341,-8.173975,0.754178],"action_q99":[2.780733,2.792585,2.473598,2.759644,4.502921,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.320312,75.9375,86.396484,24.795703,0.087891,1.294745],"state_q99":[8.701172,170.595703,141.152344,79.804688,109.951172,49.504951]},
+ {"part":"ilBiondo06__so100_ball_B1","origin":"molmoact","dataset":"ilBiondo06/so100_ball_B1","scene_camera":"observation.images.side","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.188001,-2.559067,-1.899468,-2.142934,-3.746817,0.162743],"action_q99":[3.085785,2.851165,2.714013,2.162066,2.959359,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.857422,97.998047,93.164062,35.507812,0.0,2.741813],"state_q99":[10.498535,170.507812,141.152344,79.804688,58.135254,46.949735]},
+ {"part":"ilBiondo06__so100_ball_B2","origin":"molmoact","dataset":"ilBiondo06/so100_ball_B2","scene_camera":"observation.images.side","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.934476,-2.426594,-2.517895,-3.569201,-3.901117,0.024215],"action_q99":[1.846537,2.066817,2.535484,4.138728,1.557336,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.489063,84.902344,80.479687,0.791016,0.0,0.380807],"state_q99":[13.514063,170.15625,142.470703,79.217578,63.105469,49.885757]},
+ {"part":"ilBiondo06__so100_ball_B3","origin":"molmoact","dataset":"ilBiondo06/so100_ball_B3","scene_camera":"observation.images.side","fps":30.0,"built_clips":69,"train_windows":69,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.747881,-2.451985,-2.164214,-3.425633,-2.970741,0.054852],"action_q99":[1.907436,2.167225,2.072761,3.038619,1.27984,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.340918,85.659082,81.054492,0.791016,0.087891,0.304646],"state_q99":[7.734375,170.244141,140.449219,78.447656,60.342187,49.733437]},
+ {"part":"ilBiondo06__so100_ball_B4","origin":"molmoact","dataset":"ilBiondo06/so100_ball_B4","scene_camera":"observation.images.side","fps":30.0,"built_clips":60,"train_windows":60,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.748543,-1.999682,-2.387943,-4.48666,-2.257573,0.05273],"action_q99":[1.75931,1.799742,2.048251,3.07205,1.659904,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.455273,82.265625,83.232422,0.791016,0.0,0.685453],"state_q99":[7.326563,169.205273,140.800781,79.029492,55.666406,49.733437]},
+ {"part":"ilBiondo06__so100_ball_C1","origin":"molmoact","dataset":"ilBiondo06/so100_ball_C1","scene_camera":"observation.images.side","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.784121,-2.150326,-2.043834,-3.355922,-2.417906,0.054095],"action_q99":[1.844826,2.271989,1.877643,2.665776,1.069623,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.527344,93.603516,97.52168,0.791016,0.0,0.609292],"state_q99":[22.763672,170.507812,140.800781,78.189258,60.066211,49.733437]},
+ {"part":"ilBiondo06__so100_ball_C2","origin":"molmoact","dataset":"ilBiondo06/so100_ball_C2","scene_camera":"observation.images.side","fps":30.0,"built_clips":67,"train_windows":67,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.88594,-2.736343,-2.47876,-4.233685,-3.60168,0.034086],"action_q99":[2.27024,2.912661,2.207443,3.23424,1.160014,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.673633,86.044922,94.130859,0.703125,0.0,0.380807],"state_q99":[25.62627,170.419922,141.152344,79.628906,61.120898,49.733437]},
+ {"part":"ilBiondo06__so100_ball_C3","origin":"molmoact","dataset":"ilBiondo06/so100_ball_C3","scene_camera":"observation.images.side","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.299722,-2.278343,-2.516009,-3.65715,-2.558407,0.008316],"action_q99":[1.929116,1.590977,2.26629,2.870947,0.976786,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.080762,87.275391,80.332031,19.222559,0.087891,0.685453],"state_q99":[21.181641,170.457715,140.800781,79.089258,57.481348,49.733437]},
+ {"part":"ilBiondo06__so100_ball_C4","origin":"molmoact","dataset":"ilBiondo06/so100_ball_C4","scene_camera":"observation.images.side","fps":30.0,"built_clips":64,"train_windows":64,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.057504,-2.184692,-1.398315,-1.567757,-0.872482,0.111437],"action_q99":[1.551352,1.651978,1.758976,1.521843,0.688476,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.417969,88.330078,85.869141,49.394531,0.0,0.913938],"state_q99":[23.291016,169.057617,140.800781,79.628906,17.138672,49.733437]},
+ {"part":"ilBiondo06__so100_ball_D1","origin":"molmoact","dataset":"ilBiondo06/so100_ball_D1","scene_camera":"observation.images.above","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.14057,-4.247672,-2.477223,-2.502108,-3.940787,1.158928],"action_q99":[2.995076,3.956682,2.348573,2.840156,4.53646,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.482031,86.835938,81.817383,32.55293,0.0,3.12262],"state_q99":[15.489844,170.332031,140.537109,79.804688,97.261523,49.809597]},
+ {"part":"ilBiondo06__so100_ball_D2","origin":"molmoact","dataset":"ilBiondo06/so100_ball_D2","scene_camera":"observation.images.above","fps":30.0,"built_clips":39,"train_windows":39,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.832456,-3.506437,-1.674507,-2.027099,-4.22063,1.770782],"action_q99":[1.782641,1.781108,1.09893,1.656364,3.448884,48.938758],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.1875,101.953125,90.903516,40.454297,0.439453,3.351104],"state_q99":[7.207031,170.419922,141.064453,79.804688,71.367188,46.921553]},
+ {"part":"ilBiondo06__so100_ball_D3","origin":"molmoact","dataset":"ilBiondo06/so100_ball_D3","scene_camera":"observation.images.above","fps":30.0,"built_clips":69,"train_windows":69,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.232565,-2.536132,-1.713529,-1.519292,-5.762051,1.232179],"action_q99":[2.184252,2.6232,2.459708,2.181371,2.989999,50.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.669922,102.65625,92.373047,35.419922,-0.087891,3.471439],"state_q99":[9.755859,170.244141,140.537109,79.804688,68.073926,49.482864]},
+ {"part":"ilBiondo06__so100_ball_D4","origin":"molmoact","dataset":"ilBiondo06/so100_ball_D4","scene_camera":"observation.images.above","fps":30.0,"built_clips":69,"train_windows":69,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.808629,-2.838775,-2.016051,-1.80365,-4.257597,1.697528],"action_q99":[2.454005,3.221906,3.430097,2.652451,3.037075,48.998884],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.824219,94.607227,92.580469,24.082031,0.087891,2.697639],"state_q99":[10.546875,170.419922,141.064453,79.804688,69.022266,47.035796]},
+ {"part":"isadev__bougies2","origin":"molmoact","dataset":"isadev/bougies2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":3063,"train_windows":3063,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.373047,-2.109375,-2.460938,-2.460938,0.274474],"action_q99":[1.054688,2.724609,3.076172,2.109375,2.460938,32.570904],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.92998,28.828125,0.116895,-19.775391,-108.457031,4.883081],"state_q99":[41.044922,190.107422,176.220703,85.253906,62.490234,32.255848]},
+ {"part":"isadev__bougies3","origin":"molmoact","dataset":"isadev/bougies3","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":2233,"train_windows":2233,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.076172,-2.724609,-3.164062,-2.285156,0.274474],"action_q99":[1.494141,3.164062,3.515625,2.460938,2.021484,28.179323],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.740234,22.939453,10.458984,-12.832031,-91.230469,4.676754],"state_q99":[33.134766,190.371094,176.220703,89.296875,59.765625,27.166439]},
+ {"part":"jiajun001__eraser00_3","origin":"molmoact","dataset":"jiajun001/eraser00_3","scene_camera":"observation.images.front","fps":30.0,"built_clips":1577,"train_windows":1577,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.460938,-2.197266,-1.142578,-2.373047,-1.7294],"action_q99":[1.582031,2.285156,2.636719,1.230469,2.460938,41.607323],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-11.074219,27.49834,11.689453,59.589844,-47.548828,-0.944206],"state_q99":[72.861328,188.525391,176.132812,99.052734,126.914062,41.888412]},
+ {"part":"jiajun001__eraser20-1","origin":"molmoact","dataset":"jiajun001/eraser20-1","scene_camera":"observation.images.front","fps":30.0,"built_clips":757,"train_windows":757,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.460938,-2.109375,-1.669922,-2.373047,0.0],"action_q99":[1.142578,2.197266,2.373047,1.494141,2.295703,52.411998],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.283203,43.066406,28.300781,59.414062,-49.21875,-2.462796],"state_q99":[38.232422,192.480469,171.826172,100.898438,100.546875,40.556011]},
+ {"part":"jiajun001__put13-2","origin":"molmoact","dataset":"jiajun001/put13-2","scene_camera":"observation.images.front","fps":30.0,"built_clips":1038,"train_windows":1038,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.845703,-1.318359,-1.230469,-1.494141,0.0],"action_q99":[0.615234,1.757812,1.669922,0.966797,1.40625,59.39698],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.4375,67.939453,66.445312,52.382812,70.400391,-2.633745],"state_q99":[45.791016,189.404297,171.474609,86.923828,131.044922,47.343209]},
+ {"part":"jiroh2000__so100_test_01","origin":"molmoact","dataset":"jiroh2000/so100_test_01","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":32,"train_windows":32,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.900391,-2.548828,-1.318359,-1.669922,-0.179533],"action_q99":[0.885059,2.197266,2.460938,2.285156,1.763965,29.35368],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.818359,50.537109,43.154297,58.886719,-180.966797,0.271248],"state_q99":[16.61748,188.261719,180.087891,102.919922,-123.486328,29.113924]},
+ {"part":"jiroh2000__so100_test_02","origin":"molmoact","dataset":"jiroh2000/so100_test_02","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":240,"train_windows":240,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.691406,-2.900391,-1.669922,-2.548828,-0.2693],"action_q99":[1.318359,2.724609,2.724609,2.636719,2.724609,32.944344],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.894531,38.935547,30.585938,54.492188,-182.021484,-0.271248],"state_q99":[25.3125,188.261719,180.615234,103.007812,-117.773438,32.459312]},
+ {"part":"jiroh2000__so100_test_04","origin":"molmoact","dataset":"jiroh2000/so100_test_04","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":216,"train_windows":216,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.867188,-3.251953,-1.757812,-3.427734,-0.2693],"action_q99":[1.622461,2.724609,2.8125,2.8125,3.076172,32.764812],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.882812,37.766602,36.123047,61.699219,-182.021484,-0.180832],"state_q99":[21.526172,188.4375,180.263672,102.919922,-117.003516,32.368896]},
+ {"part":"joaoocruz00__so100_makeitD1","origin":"molmoact","dataset":"joaoocruz00/so100_makeitD1","scene_camera":"observation.images.realsensergb","fps":30.0,"built_clips":1116,"train_windows":1116,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-4.130859,-4.394531,-3.691406,-1.494141,-1.663748],"action_q99":[2.021484,4.482422,4.482422,3.339844,1.757812,26.359894],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-77.34375,8.261719,-2.109375,-77.080078,-164.970703,0.981767],"state_q99":[76.904297,189.931641,180.791016,91.142578,86.220703,25.175316]},
+ {"part":"jonhpark__so101_pick_place","origin":"molmoact","dataset":"jonhpark/so101_pick_place","scene_camera":"observation.images.top","fps":30.0,"built_clips":898,"train_windows":898,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.900391,-3.076172,-4.130859,-2.460938,-2.636719,-1.649957],"action_q99":[2.988281,3.339844,3.779297,3.076172,2.373047,74.157303],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.115234,50.537109,39.375,41.660156,-101.777344,0.078309],"state_q99":[75.498047,191.425781,171.210938,98.701172,8.261719,73.688332]},
+ {"part":"joooonhocho__so100_doll_in_bowl_2","origin":"molmoact","dataset":"joooonhocho/so100_doll_in_bowl_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":968,"train_windows":968,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.076172,-2.373047,-2.021484,-0.791016,-0.722311],"action_q99":[1.669922,2.8125,3.164062,2.636719,0.878906,94.78331],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.640625,16.258887,13.359375,-6.241113,69.520605,0.345722],"state_q99":[66.357422,178.857422,177.363281,102.216797,110.391504,94.20916]},
+ {"part":"joooonhocho__so100_test_2","origin":"molmoact","dataset":"joooonhocho/so100_test_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":95,"train_windows":95,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.988281,-2.900391,-1.669922,-0.615234,-0.401284],"action_q99":[1.230469,3.258105,2.988281,2.109375,1.318359,93.418938],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.353516,48.07002,47.109375,30.585938,-1.845703,0.605013],"state_q99":[42.130371,178.769531,177.363281,101.865234,101.513672,92.999138]},
+ {"part":"jsyoon80__act_so100_test","origin":"molmoact","dataset":"jsyoon80/act_so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":53,"train_windows":53,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-3.609668,-3.433887,-1.757812,-4.042969,-0.458716],"action_q99":[2.291309,2.636719,3.779297,1.582031,3.427734,56.513763],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.273438,59.0625,64.311328,28.024805,2.548828,0.372439],"state_q99":[73.701562,189.404297,180.615234,70.664062,94.306641,56.238358]},
+ {"part":"jsyoon80__act_so100_test1","origin":"molmoact","dataset":"jsyoon80/act_so100_test1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.065625,-3.241406,-2.098828,-5.702344,-0.935512],"action_q99":[2.724609,2.010937,2.109375,2.021484,4.559766,34.135853],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.900391,71.542969,62.314453,21.357422,-6.152344,1.164483],"state_q99":[80.585156,191.074219,181.933594,73.212891,97.03125,33.842796]},
+ {"part":"juni3227__so100_test01","origin":"molmoact","dataset":"juni3227/so100_test01","scene_camera":"observation.images.airial","fps":30.0,"built_clips":52,"train_windows":52,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.139648,-3.172852,-4.139648,-1.845703,-2.654297,0.10101],"action_q99":[5.449219,3.788086,4.666992,2.118164,2.469727,37.313132],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-53.191406,34.97168,21.128906,60.196289,-97.558594,1.400778],"state_q99":[59.449219,189.492188,177.011719,104.0625,-31.631836,37.315175]},
+ {"part":"juni3227__so100_test02","origin":"molmoact","dataset":"juni3227/so100_test02","scene_camera":"observation.images.airial","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.746094,-4.566797,-5.526562,-2.457422,-2.021484,0.10101],"action_q99":[6.240234,5.445703,4.563281,2.988281,2.805469,38.783836],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.087891,26.114062,7.998047,61.259766,-98.60625,1.400778],"state_q99":[64.335938,189.580078,176.835938,104.150391,-32.167969,38.596111]},
+ {"part":"juni3227__so100_test03","origin":"molmoact","dataset":"juni3227/so100_test03","scene_camera":"observation.images.airial","fps":30.0,"built_clips":1881,"train_windows":1881,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.570312,-4.306641,-5.361328,-2.988281,-2.460938,0.10101],"action_q99":[4.921875,4.130859,5.009766,3.867188,2.548828,46.161617],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-80.859375,20.126953,-6.943359,-2.583984,-123.398438,0.622568],"state_q99":[92.460938,189.667969,178.59375,104.326172,-40.078125,45.836578]},
+ {"part":"juni3227__so100_test04","origin":"molmoact","dataset":"juni3227/so100_test04","scene_camera":"observation.images.airial","fps":30.0,"built_clips":14,"train_windows":14,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.05332,-3.779297,-4.658203,-3.328418,-1.811426,0.417172],"action_q99":[2.460938,3.076172,5.063379,2.373047,1.845703,27.575758],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.707031,94.833984,62.666016,26.730176,-89.384766,0.856031],"state_q99":[35.595703,188.876953,177.451172,95.602148,-38.014453,27.237352]},
+ {"part":"juni3227__so100_test05","origin":"molmoact","dataset":"juni3227/so100_test05","scene_camera":"observation.images.airial","fps":30.0,"built_clips":1461,"train_windows":1461,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.21875,-5.712891,-5.625,-3.251953,-2.900391,0.0],"action_q99":[4.570312,5.449219,5.449219,3.603516,2.8125,44.316164],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-69.785156,18.457031,-7.382812,25.3125,-104.414062,0.622568],"state_q99":[86.660156,189.667969,174.462891,104.414062,16.388086,43.891052]},
+ {"part":"juni3227__so100_test06","origin":"molmoact","dataset":"juni3227/so100_test06","scene_camera":"observation.images.airial","fps":30.0,"built_clips":97,"train_windows":97,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-3.661523,-4.21875,-4.042969,-1.991602,0.0],"action_q99":[3.339844,3.573633,4.658203,3.13418,1.669922,94.878789],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-74.53125,54.492188,23.466797,15.560156,-122.225977,0.752823],"state_q99":[92.343164,187.998047,178.681641,104.589844,-49.921875,90.910915]},
+ {"part":"juni3227__so100_test07","origin":"molmoact","dataset":"juni3227/so100_test07","scene_camera":"observation.images.airial","fps":30.0,"built_clips":806,"train_windows":806,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.867188,-3.515625,-3.779297,-3.691406,-1.933594,0.0],"action_q99":[4.011328,3.339844,3.427734,3.515625,1.845703,64.141418],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-78.837891,33.574219,27.773438,-3.100781,-126.650391,0.627353],"state_q99":[89.736328,188.349609,178.681641,104.677734,-64.775391,63.568382]},
+ {"part":"juni3227__so100_test_003","origin":"molmoact","dataset":"juni3227/so100_test_003","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":25,"train_windows":25,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.427734,-4.37168,-3.515625,-5.162695,-1.142578,0.097371],"action_q99":[3.229102,4.394531,5.510742,3.867188,1.448438,29.600779],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.586328,54.755859,59.150391,-9.875391,-96.591797,0.151745],"state_q99":[73.037109,188.613281,179.384766,79.430273,-71.015625,28.907436]},
+ {"part":"juni3227__so100_test_004","origin":"molmoact","dataset":"juni3227/so100_test_004","scene_camera":"observation.images.left","fps":30.0,"built_clips":26,"train_windows":26,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.715332,-4.623047,-5.211914,-3.251953,-1.814941,0.097371],"action_q99":[4.240723,6.00293,4.82959,5.677734,2.25,38.072056],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-11.803711,51.974121,58.535156,-20.416992,-91.494141,0.151745],"state_q99":[72.246094,188.789062,179.472656,79.787109,-58.45166,37.860394]},
+ {"part":"juni3227__so100_test_005_practice","origin":"molmoact","dataset":"juni3227/so100_test_005_practice","scene_camera":"observation.images.left","fps":30.0,"built_clips":579,"train_windows":579,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-5.097656,-5.976562,-2.65957,-1.230469,-0.389484],"action_q99":[2.285156,6.064453,6.943359,2.8125,1.230469,45.472248],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.505273,16.347656,-7.845117,42.275391,-41.507227,-0.151745],"state_q99":[68.841211,188.876953,178.505859,98.4375,6.503906,44.992413]},
+ {"part":"juni3227__so100_test_cap01","origin":"molmoact","dataset":"juni3227/so100_test_cap01","scene_camera":"observation.images.airial","fps":30.0,"built_clips":451,"train_windows":451,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.658203,-5.197852,-5.185547,-4.394531,-2.021484,0.0],"action_q99":[4.921875,5.109961,5.712891,4.130859,2.109375,47.695389],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-67.236328,49.206445,30.13418,-4.582617,-109.863281,0.386997],"state_q99":[85.253906,193.798828,183.867188,100.458984,2.373047,47.254961]},
+ {"part":"juni3227__so100_test_cap02_sideway","origin":"molmoact","dataset":"juni3227/so100_test_cap02_sideway","scene_camera":"observation.images.airial","fps":30.0,"built_clips":1330,"train_windows":1330,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-2.900391,-2.724609,-5.185547,-1.230469,-0.1002],"action_q99":[2.900391,3.691406,3.076172,4.130859,1.318359,64.529053],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-80.332031,31.728516,62.402344,-108.28125,-106.875,0.293902],"state_q99":[92.021484,191.953125,181.494141,98.613281,-75.234375,64.731812]},
+ {"part":"jyang-ca__so101_test_grab_place_v2","origin":"molmoact","dataset":"jyang-ca/so101_test_grab_place_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":796,"train_windows":796,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-4.658203,-4.306641,-3.691406,-1.757812,-2.545156],"action_q99":[1.318359,4.21875,4.306641,3.955078,2.197266,49.609197],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.716797,7.646484,-9.404297,-25.463672,40.408594,-0.942712],"state_q99":[35.15625,190.634766,175.957031,93.603516,132.714844,49.253081]},
+ {"part":"kaiserbuffle__hanoiv2","origin":"molmoact","dataset":"kaiserbuffle/hanoiv2","scene_camera":"observation.images.wrist","fps":30.0,"built_clips":595,"train_windows":595,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.757812,-3.339844,-2.8125,-0.878906,-0.257954],"action_q99":[0.791016,1.933594,2.8125,4.306641,1.054688,48.06535],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.388672,77.080078,57.392578,-62.402344,-4.394531,0.325203],"state_q99":[18.464941,192.304688,181.933594,99.931641,111.533203,48.130081]},
+ {"part":"kaiserbuffle__hanoiv4","origin":"molmoact","dataset":"kaiserbuffle/hanoiv4","scene_camera":"observation.images.base","fps":30.0,"built_clips":421,"train_windows":421,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-2.8125,-3.251953,-3.603516,-0.703125,0.0],"action_q99":[0.791016,3.955078,3.867188,4.833984,0.782227,47.868561],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.324219,49.482422,67.060547,-102.216797,-106.523438,0.113122],"state_q99":[22.587891,191.777344,179.648438,96.495117,-2.373047,48.076923]},
+ {"part":"kaiserbuffle__hanoiv5","origin":"molmoact","dataset":"kaiserbuffle/hanoiv5","scene_camera":"observation.images.base","fps":30.0,"built_clips":525,"train_windows":525,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-2.109375,-3.076172,-3.779297,-0.703125,-3.873874],"action_q99":[0.703125,2.8125,3.779297,4.570312,0.791016,55.765766],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.357422,51.679688,45.263672,-65.752734,-103.710938,-2.042901],"state_q99":[17.050781,195.556641,180.351562,101.953125,3.867188,55.771194]},
+ {"part":"kaiserbuffle__hanoiv6","origin":"molmoact","dataset":"kaiserbuffle/hanoiv6","scene_camera":"observation.images.wrist","fps":30.0,"built_clips":560,"train_windows":560,"val_windows":11,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.373047,-4.042969,-4.921875,-1.054688,-0.088574],"action_q99":[1.40625,3.251953,3.779297,6.416016,1.054688,68.113373],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.585938,45.615234,62.753906,-96.240234,-103.886719,1.034483],"state_q99":[39.550781,190.107422,178.59375,100.195312,3.691406,67.844826]},
+ {"part":"kaiserbuffle__so101_test","origin":"molmoact","dataset":"kaiserbuffle/so101_test","scene_camera":"observation.images.base","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.34209,-2.460938,-2.133105,-1.669922,-2.988281,0.0],"action_q99":[1.142578,2.900391,2.636719,2.285156,3.211523,71.648322],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.955078,57.72041,68.243555,2.358984,-47.900391,0.650406],"state_q99":[17.666016,192.128906,181.933594,85.325098,105.205078,71.676424]},
+ {"part":"kaiserbuffle__so101test","origin":"molmoact","dataset":"kaiserbuffle/so101test","scene_camera":"observation.images.base","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.485547,-2.661328,-1.669922,-1.142578,-0.085985],"action_q99":[0.703125,4.155469,4.570312,1.870312,0.791016,50.655201],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.457031,16.889063,-7.105078,41.980078,-7.959375,0.650406],"state_q99":[28.564453,192.216797,181.845703,99.580078,25.576172,49.186993]},
+ {"part":"kaiserbuffle__t","origin":"molmoact","dataset":"kaiserbuffle/t","scene_camera":"observation.images.base","fps":30.0,"built_clips":68,"train_windows":68,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-4.658203,-3.779297,-1.669922,-0.791016,-0.085985],"action_q99":[1.318359,4.570312,6.463477,1.318359,1.142578,43.508167],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.201172,29.091797,8.261719,45.503613,-11.513672,0.325203],"state_q99":[21.908496,192.304688,182.021484,87.275391,23.514258,43.495934]},
+ {"part":"kami-LightYagami__so100_test","origin":"molmoact","dataset":"kami-LightYagami/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":15,"train_windows":15,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.046094,-1.455469,-2.027637,-2.567285,-2.66748,-3.477444],"action_q99":[2.385352,3.867188,2.636719,2.291309,2.291309,20.87782],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.019824,83.207813,69.723633,43.330078,89.811914,-1.864641],"state_q99":[36.826172,194.414062,179.033203,96.013477,202.763672,20.649172]},
+ {"part":"kami-LightYagami__so100_test_6.13","origin":"molmoact","dataset":"kami-LightYagami/so100_test_6.13","scene_camera":"observation.images.phone","fps":30.0,"built_clips":13,"train_windows":13,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.588184,-3.200977,-2.912695,-1.248926,-2.109375,-3.571429],"action_q99":[0.891211,3.000586,3.176367,1.582031,1.230469,47.744362],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.867188,89.824219,61.511133,62.007715,94.394531,-2.002762],"state_q99":[57.574512,194.677734,175.693359,104.481738,156.796875,47.513813]},
+ {"part":"kantine__flip_A0","origin":"molmoact","dataset":"kantine/flip_A0","scene_camera":"observation.images.phone","fps":30.0,"built_clips":153,"train_windows":153,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.460938,-2.285156,-4.746094,-5.009766,-0.191939],"action_q99":[1.227832,2.285156,1.845703,4.570312,4.833984,21.401152],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.037109,94.130859,98.525391,-110.917969,-169.453125,0.801282],"state_q99":[6.328125,189.931641,179.560547,96.061816,174.638672,21.153847]},
+ {"part":"kantine__flip_A1","origin":"molmoact","dataset":"kantine/flip_A1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":118,"train_windows":118,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.615234,-1.933594,-1.845703,-4.130859,-4.482422,-0.191939],"action_q99":[0.703125,2.460938,1.933594,3.867188,4.482422,11.880998],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.082031,101.513672,109.520508,-110.742188,-185.888672,0.801282],"state_q99":[4.746094,189.140625,179.560547,74.786133,175.429688,11.594551]},
+ {"part":"kantine__flip_A2","origin":"molmoact","dataset":"kantine/flip_A2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":108,"train_windows":108,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.439453,-1.757812,-1.582031,-3.867188,-1.318359,-0.191939],"action_q99":[0.439453,2.021484,1.757812,3.515625,1.142578,92.79271],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.574219,107.578125,111.990234,-110.302734,165.585938,0.801282],"state_q99":[5.361328,188.173828,179.384766,72.421875,174.902344,91.690706]},
+ {"part":"kantine__flip_A3","origin":"molmoact","dataset":"kantine/flip_A3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":113,"train_windows":113,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.439453,-1.669922,-1.494141,-3.955078,-1.222559,-0.191939],"action_q99":[0.439453,1.933594,1.845703,3.515625,1.054688,0.191939],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.800781,93.035742,103.902539,-110.214844,159.713086,0.721154],"state_q99":[12.744141,188.261719,179.296875,77.33584,174.462891,0.874199]},
+ {"part":"kantine__kapla_test","origin":"molmoact","dataset":"kantine/kapla_test","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":70,"train_windows":70,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-2.117285,-2.556738,-1.853613,-3.787207,0.0],"action_q99":[3.171973,2.197266,2.548828,1.933594,3.339844,43.910882],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-98.876953,60.812402,56.953125,57.560449,-103.183594,0.220751],"state_q99":[84.566602,192.744141,179.208984,101.785254,9.675879,43.052979]},
+ {"part":"kantine__kapla_tower_2_expert","origin":"molmoact","dataset":"kantine/kapla_tower_2_expert","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":700,"train_windows":700,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-2.636719,-2.373047,-1.669922,-2.900391,0.0],"action_q99":[2.988281,2.021484,2.373047,1.933594,3.251953,41.932457],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-90.087891,53.4375,47.548828,51.855469,-110.654297,0.220751],"state_q99":[86.835938,192.744141,179.472656,103.710938,5.273438,41.427521]},
+ {"part":"kantine__kapla_tower_3_expert","origin":"molmoact","dataset":"kantine/kapla_tower_3_expert","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":1085,"train_windows":1085,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-1.933594,-2.021484,-1.40625,-2.373047,0.0],"action_q99":[2.8125,2.109375,2.197266,1.845703,2.548828,40.994373],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-92.900391,55.907227,48.076172,51.240234,-114.082031,0.220751],"state_q99":[81.298828,192.744141,179.296875,103.974609,9.580078,40.691685]},
+ {"part":"kantine__piling_glasses","origin":"molmoact","dataset":"kantine/piling_glasses","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":291,"train_windows":291,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-1.845703,-2.109375,-1.582031,-2.285156,0.093809],"action_q99":[2.724609,2.109375,2.373047,1.757812,1.669922,52.251408],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-92.656055,44.296875,39.990234,35.859375,-135.351562,0.220751],"state_q99":[66.005859,192.832031,179.121094,103.535156,-33.310547,52.170715]},
+ {"part":"kantine__soldering_2","origin":"molmoact","dataset":"kantine/soldering_2","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":1218,"train_windows":1218,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-1.318359,-1.669922,-1.494141,-2.460938,0.093809],"action_q99":[2.373047,1.142578,1.582031,1.582031,2.021484,45.590996],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-94.130859,60.679687,38.503125,-14.0625,-149.677734,0.220751],"state_q99":[57.304688,192.832031,179.208984,102.561328,-42.275391,45.106697]},
+ {"part":"kantine__soldering_3","origin":"molmoact","dataset":"kantine/soldering_3","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":488,"train_windows":488,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-1.40625,-1.669922,-1.494141,-2.373047,0.0],"action_q99":[2.285156,1.142578,1.582031,1.494141,1.933594,39.399624],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-95.976562,81.123047,81.21709,4.394531,-151.15957,0.220751],"state_q99":[57.041016,192.919922,179.208984,98.261719,-37.792969,39.214865]},
+ {"part":"kantine__stacking_cups","origin":"molmoact","dataset":"kantine/stacking_cups","scene_camera":"observation.images.logitech_1","fps":30.0,"built_clips":935,"train_windows":935,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-1.40625,-1.730566,-1.054688,-2.109375,0.093809],"action_q99":[2.021484,1.757812,2.109375,1.318359,1.318359,36.679176],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-94.21875,57.128906,41.247949,54.931641,-151.435547,0.220751],"state_q99":[50.625,192.919922,179.384766,104.150391,-36.298828,36.497425]},
+ {"part":"kevin-nd__so100_test_1","origin":"molmoact","dataset":"kevin-nd/so100_test_1","scene_camera":"observation.images.top","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.500293,-1.763965,-0.878906,-0.175781,-6.936867],"action_q99":[0.791016,1.142578,1.230469,0.797168,0.263672,31.098986],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.991113,74.619141,68.90625,63.28125,-2.988281,-1.423729],"state_q99":[21.357422,187.910156,168.75,90.0,9.140625,30.644068]},
+ {"part":"kevin-nd__so100_test_2","origin":"molmoact","dataset":"kevin-nd/so100_test_2","scene_camera":"observation.images.top","fps":30.0,"built_clips":544,"train_windows":544,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.933594,-2.109375,-0.966797,-0.175781,-7.170693],"action_q99":[0.791016,1.318359,1.582031,1.054688,0.175781,36.866718],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.291016,57.217676,43.154297,57.832031,-1.582031,-1.491525],"state_q99":[21.444434,188.173828,170.595703,100.986328,10.810547,36.542374]},
+ {"part":"kivod__so100_test2","origin":"molmoact","dataset":"kivod/so100_test2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":846,"train_windows":846,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-3.339844,-2.900391,-1.494141,-1.845703,-0.213371],"action_q99":[1.230469,3.251953,3.339844,1.582031,1.669922,41.536274],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.281641,13.784766,0.263672,29.179688,-177.451172,0.405132],"state_q99":[55.297266,193.271484,179.121094,99.84375,-13.974609,41.188385]},
+ {"part":"kumarhans__simBoxPushTest","origin":"molmoact","dataset":"kumarhans/simBoxPushTest","scene_camera":"observation.images.ego_cam","fps":30.0,"built_clips":504,"train_windows":504,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.743945,-3.955078,-2.636719,-2.548828,-4.306641,2.434783],"action_q99":[2.480273,3.427734,2.636719,2.109375,2.900391,2.956522],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.210934,59.115265,85.377817,-1.661578,-179.38736,2.267652],"state_q99":[36.124989,179.473297,173.979897,89.614498,-0.435448,3.059595]},
+ {"part":"kumarhans__so100_push_box_real1","origin":"molmoact","dataset":"kumarhans/so100_push_box_real1","scene_camera":"observation.images.wrist_cam","fps":30.0,"built_clips":748,"train_windows":748,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.988281,-2.197266,-1.40625,-2.021484,-0.34662],"action_q99":[0.791016,2.285156,1.757812,1.318359,2.724609,9.792027],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.214844,55.019531,61.611328,18.632812,-184.921875,2.608696],"state_q99":[46.850977,193.007812,179.648438,83.056641,5.009766,10.782608]},
+ {"part":"kyomangold__so100_ttt_A1_single","origin":"molmoact","dataset":"kyomangold/so100_ttt_A1_single","scene_camera":"observation.images.phone","fps":30.0,"built_clips":111,"train_windows":111,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.310645,-2.548828,-2.988281,-2.197266,-1.318359,-0.900901],"action_q99":[3.955078,4.130859,3.892676,1.845703,1.318359,58.558559],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.035156,30.849609,19.749902,39.111328,34.453125,-0.607903],"state_q99":[100.107422,190.546875,174.990234,89.736328,88.179785,58.282673]},
+ {"part":"kyomangold__so100_ttt_A1_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_A1_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1823,"train_windows":1823,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.460938,-2.460938,-1.054688,-0.703125,-0.720721],"action_q99":[1.582031,2.460938,2.460938,1.582031,0.791016,40.99099],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[36.5625,43.945312,49.21875,49.921875,-13.271484,-0.303951],"state_q99":[100.546875,190.195312,175.078125,89.033203,26.368066,40.577507]},
+ {"part":"kyomangold__so100_ttt_A2_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_A2_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":515,"train_windows":515,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.8125,-3.076172,-1.669922,-2.197266,-1.171171],"action_q99":[2.460938,2.285156,2.604199,1.845703,2.285156,70.720718],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-0.878906,45.878906,52.03125,24.609375,1.262988,-0.531915],"state_q99":[98.876953,190.371094,175.078125,89.384766,113.90625,70.308512]},
+ {"part":"kyomangold__so100_ttt_A3_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_A3_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":463,"train_windows":463,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-2.900391,-3.339844,-1.725293,-1.845703,-0.990991],"action_q99":[3.691406,2.724609,2.724609,2.109375,2.373047,97.027031],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.869141,47.900391,53.701172,34.804688,9.140625,-0.455927],"state_q99":[100.371094,190.371094,175.078125,89.384766,90.934277,97.112465]},
+ {"part":"kyomangold__so100_ttt_B1","origin":"molmoact","dataset":"kyomangold/so100_ttt_B1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":215,"train_windows":215,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.548828,-2.481152,-1.40625,-0.615234,3.423423],"action_q99":[1.933594,2.109375,2.285156,1.074902,0.439453,38.738739],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[14.813086,22.743457,5.449219,64.072266,-5.645215,3.647416],"state_q99":[86.484375,190.634766,168.486328,99.492188,23.554688,38.046352]},
+ {"part":"kyomangold__so100_ttt_B1_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_B1_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":466,"train_windows":466,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.636719,-2.900391,-1.933594,-1.054688,-1.171171],"action_q99":[2.988281,3.603516,2.988281,1.933594,1.230469,96.846848],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[19.511719,45.878906,50.625,31.762793,28.037109,-0.607903],"state_q99":[101.162109,190.634766,174.990234,89.912109,97.470703,96.580544]},
+ {"part":"kyomangold__so100_ttt_B2_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_B2_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":414,"train_windows":414,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.8125,-3.164062,-1.845703,-1.230469,-1.171171],"action_q99":[3.867188,3.867188,2.548828,1.933594,1.142578,94.234238],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.625,45.966797,50.712891,33.871289,43.769531,-0.607903],"state_q99":[101.162109,190.722656,175.078125,89.912109,100.810547,94.072952]},
+ {"part":"kyomangold__so100_ttt_B3_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_B3_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":421,"train_windows":421,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.988281,-3.076172,-2.988281,-1.933594,-1.40625,-1.171171],"action_q99":[5.009766,4.570312,2.988281,2.021484,1.40625,81.891891],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-30.410156,46.40625,51.416016,35.859375,41.111719,-0.607903],"state_q99":[100.810547,190.634766,175.078125,89.912109,101.25,81.079033]},
+ {"part":"kyomangold__so100_ttt_C1","origin":"molmoact","dataset":"kyomangold/so100_ttt_C1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":209,"train_windows":209,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.285156,-2.285156,-1.757812,-1.318359,-0.900901],"action_q99":[1.40625,2.109375,2.988281,1.582031,1.142578,80.090088],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[13.535156,23.291016,-9.319922,-43.330078,-93.515625,-0.227964],"state_q99":[82.792969,190.634766,174.550781,99.404297,16.611328,79.86322]},
+ {"part":"kyomangold__so100_ttt_C1_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_C1_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":436,"train_windows":436,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.464258,-2.460938,-2.724609,-2.285156,-1.054688,-1.171171],"action_q99":[2.900391,4.042969,3.955078,1.669922,0.966797,87.025227],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[11.25,18.632812,2.373047,32.988867,47.227148,-0.835866],"state_q99":[99.404297,190.634766,174.902344,90.263672,109.511719,86.524317]},
+ {"part":"kyomangold__so100_ttt_C2","origin":"molmoact","dataset":"kyomangold/so100_ttt_C2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":211,"train_windows":211,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-2.636719,-2.567285,-1.142578,-0.703125,-0.900901],"action_q99":[1.757812,2.109375,2.021484,1.318359,0.439453,56.126125],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.625,26.279297,15.908203,41.748047,-17.490234,-0.303951],"state_q99":[78.486328,190.898438,174.726562,97.910156,22.236328,55.927052]},
+ {"part":"kyomangold__so100_ttt_C2_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_C2_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":429,"train_windows":429,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.636719,-2.724609,-2.109375,-1.230469,-1.081081],"action_q99":[3.515625,4.042969,3.779297,1.757812,1.142578,93.24324],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.118066,25.400391,15.556641,40.869141,46.704199,-0.835866],"state_q99":[100.248926,190.634766,174.814453,89.912109,113.378906,93.009117]},
+ {"part":"kyomangold__so100_ttt_C3","origin":"molmoact","dataset":"kyomangold/so100_ttt_C3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":204,"train_windows":204,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.373047,-2.636719,-1.318359,-0.791016,-0.900901],"action_q99":[2.021484,2.460938,2.373047,1.669922,0.615234,58.288288],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.939453,22.412109,2.988281,38.213965,-13.886719,-0.303951],"state_q99":[76.113281,190.546875,174.638672,98.4375,22.236328,57.766719]},
+ {"part":"kyomangold__so100_ttt_C3_v2","origin":"molmoact","dataset":"kyomangold/so100_ttt_C3_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":446,"train_windows":446,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-2.8125,-2.8125,-1.494141,-1.230469,-1.081081],"action_q99":[4.042969,3.691406,3.339844,1.494141,1.142578,86.396393],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.115234,19.511719,3.867188,44.384766,56.162109,-0.607903],"state_q99":[100.458984,190.634766,174.023438,89.912109,111.796875,86.094223]},
+ {"part":"lalalalalalalalalala__so101_test","origin":"molmoact","dataset":"lalalalalalalalalala/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":39,"train_windows":39,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.603516,-2.8125,-2.109375,-1.386035,-0.613497],"action_q99":[1.582031,3.143848,2.880176,1.561816,1.649707,46.625767],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.173828,31.640625,16.455762,45.703125,-27.421875,-0.506879],"state_q99":[42.451172,190.107422,172.177734,99.404297,11.777344,46.415642]},
+ {"part":"lbxa__tiny","origin":"molmoact","dataset":"lbxa/tiny","scene_camera":"observation.images.top","fps":30.0,"built_clips":263,"train_windows":263,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.548828,-2.636719,-2.170898,-2.548828,-0.995851],"action_q99":[1.907227,2.021484,2.109375,2.548828,2.988281,49.045643],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.806641,66.647461,67.939453,-39.146484,-94.21875,0.0],"state_q99":[72.597656,195.908203,181.142578,95.800781,30.796875,48.796036]},
+ {"part":"lirislab__clear_square","origin":"molmoact","dataset":"lirislab/clear_square","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":690,"train_windows":690,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.867188,-3.691406,-4.130859,-2.373047,-0.182648],"action_q99":[2.373047,3.779297,4.042969,4.042969,2.548828,0.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.429688,32.607422,25.664062,-40.869141,-33.75,0.205058],"state_q99":[39.209766,183.779297,174.814453,88.076953,32.167969,0.546822]},
+ {"part":"lirislab__clear_square_orig","origin":"molmoact","dataset":"lirislab/clear_square_orig","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":690,"train_windows":690,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.867188,-3.691406,-4.130859,-2.373047,-0.182648],"action_q99":[2.373047,3.779297,4.042969,4.042969,2.548828,0.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.429688,32.607422,25.664062,-40.869141,-33.75,0.205058],"state_q99":[39.209766,183.779297,174.814453,88.076953,32.167969,0.546822]},
+ {"part":"lirislab__fold_bottom_right","origin":"molmoact","dataset":"lirislab/fold_bottom_right","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":396,"train_windows":396,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-3.076172,-3.603516,-2.373047,-1.757812,-0.185357],"action_q99":[2.900391,2.8125,3.515625,2.285156,1.582031,69.786842],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.816406,33.662109,24.609375,28.67168,-39.550781,1.045296],"state_q99":[84.541113,190.986328,181.494141,102.128906,31.455176,69.318818]},
+ {"part":"lirislab__lemon_into_bowl","origin":"molmoact","dataset":"lirislab/lemon_into_bowl","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":553,"train_windows":553,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.076172,-3.251953,-1.669922,-1.669922,0.0],"action_q99":[1.40625,3.164062,4.130859,1.757812,1.757812,63.517307],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.507812,36.035156,29.619141,43.902246,-90.791016,0.940439],"state_q99":[49.304883,189.140625,181.318359,100.458984,46.843945,62.225704]},
+ {"part":"lirislab__open_top_drawer_teabox","origin":"molmoact","dataset":"lirislab/open_top_drawer_teabox","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":339,"train_windows":339,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.724609,-4.482422,-1.494141,-2.197266,0.0],"action_q99":[1.054688,2.900391,3.339844,2.109375,1.494141,43.21796],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.265625,62.314453,12.65625,42.890625,-6.416895,1.097179],"state_q99":[1.407129,189.140625,182.285156,100.635645,47.460938,42.241379]},
+ {"part":"lirislab__push_cup_target","origin":"molmoact","dataset":"lirislab/push_cup_target","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":297,"train_windows":297,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.339844,-4.21875,-2.285156,-1.582031,0.0],"action_q99":[2.109375,3.164062,3.603516,2.900391,1.582031,0.093545],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.884473,49.330371,43.353809,27.124805,-37.792969,0.626959],"state_q99":[62.378613,188.876953,182.349316,93.515625,27.158203,1.018809]},
+ {"part":"lirislab__put_banana_bowl","origin":"molmoact","dataset":"lirislab/put_banana_bowl","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":341,"train_windows":341,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.691406,-3.867188,-2.900391,-2.285156,0.0],"action_q99":[2.460938,3.251953,3.955078,2.622656,2.271094,54.443405],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.941406,39.550781,39.462891,-18.369141,-58.798828,1.018809],"state_q99":[53.775,189.052734,182.285156,94.570312,44.208984,53.369907]},
+ {"part":"lirislab__put_caps_into_teabox","origin":"molmoact","dataset":"lirislab/put_caps_into_teabox","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":386,"train_windows":386,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.32207,-2.988281,-3.603516,-2.109375,-1.582031,0.0],"action_q99":[1.757812,3.339844,4.570312,2.109375,1.318359,50.795135],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.464844,35.771484,20.90918,41.835938,-59.501953,1.097179],"state_q99":[59.275195,189.140625,182.373047,100.283203,12.216797,50.470219]},
+ {"part":"lirislab__put_coffee_cap_teabox","origin":"molmoact","dataset":"lirislab/put_coffee_cap_teabox","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":533,"train_windows":533,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-2.724609,-3.427734,-1.845703,-1.318359,0.0],"action_q99":[1.845703,2.548828,3.862793,1.933594,1.318359,56.441151],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.111328,37.177734,26.806641,47.289551,-53.701172,1.132404],"state_q99":[51.240234,190.986328,181.40625,100.810547,12.216797,55.662022]},
+ {"part":"lirislab__sweep_tissue_cube","origin":"molmoact","dataset":"lirislab/sweep_tissue_cube","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":596,"train_windows":596,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-3.427734,-3.603516,-2.988281,-2.548828,-0.093545],"action_q99":[2.197266,3.339844,3.779297,2.900391,2.460938,0.093545],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.197461,32.167969,36.089648,15.138281,-91.694531,0.626959],"state_q99":[59.853516,189.140625,182.109375,86.484375,33.925781,1.097179]},
+ {"part":"lirislab__unfold_bottom_right","origin":"molmoact","dataset":"lirislab/unfold_bottom_right","scene_camera":"observation.images.realsense_side","fps":30.0,"built_clips":334,"train_windows":334,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.8125,-2.988281,-2.285156,-2.373047,-0.093545],"action_q99":[2.460938,2.724609,3.427734,2.484668,1.494141,56.314312],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-61.083984,56.618262,56.337891,-4.02627,-65.654297,1.097179],"state_q99":[68.203125,188.525391,182.285156,95.625,22.172168,55.250782]},
+ {"part":"liustar1989__so100_test4","origin":"molmoact","dataset":"liustar1989/so100_test4","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":29,"train_windows":29,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.672559,-4.045605,-4.924512,-2.375684,-2.026758,-0.601375],"action_q99":[1.933594,4.580859,5.808691,2.112012,2.109375,38.232817],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.280371,54.140625,20.526855,54.228516,-90.175781,0.947119],"state_q99":[21.192187,191.689453,180.0,99.580078,-14.853516,38.169491]},
+ {"part":"liustar1989__so100_test8","origin":"molmoact","dataset":"liustar1989/so100_test8","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":102,"train_windows":102,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-6.679688,-6.329004,-2.988281,-3.691406,-0.171821],"action_q99":[2.285156,6.943359,8.349609,2.460938,2.460938,45.27835],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.996094,34.362598,10.809668,62.928809,-119.180566,1.966102],"state_q99":[26.191406,192.128906,180.0,100.019531,-27.508887,44.952544]},
+ {"part":"liyitenga__so100_pick_dabaitu1","origin":"molmoact","dataset":"liyitenga/so100_pick_dabaitu1","scene_camera":"observation.images.top","fps":30.0,"built_clips":495,"train_windows":495,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.636719,-2.197266,-1.40625,-2.460938,-2.62605],"action_q99":[3.164062,2.8125,3.076172,1.494141,2.548828,27.310925],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-84.023438,63.896484,65.478516,32.34375,-86.719043,-1.05042],"state_q99":[11.953125,180.527344,176.484375,75.322266,37.792969,26.890757]},
+ {"part":"love3165303__so100_pick2","origin":"molmoact","dataset":"love3165303/so100_pick2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":383,"train_windows":383,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-4.833984,-3.164062,-2.548828,-1.494141,-0.197628],"action_q99":[2.548828,4.833984,4.394531,2.197266,1.230469,64.031616],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.943359,71.806641,73.125,22.535156,-23.203125,0.388727],"state_q99":[44.208984,184.482422,166.464844,61.787109,9.667969,62.876583]},
+ {"part":"love3165303__so100_pick3","origin":"molmoact","dataset":"love3165303/so100_pick3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":359,"train_windows":359,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-6.01084,-4.21875,-2.900391,-2.285156,-2.195609],"action_q99":[3.164062,6.679688,6.152344,3.164062,1.845703,58.882236],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-17.578125,51.293848,47.724609,8.789062,-39.814453,-0.482426],"state_q99":[47.319434,184.570312,170.15625,69.082031,8.085938,56.47071]},
+ {"part":"love3165303__so100_pick4","origin":"molmoact","dataset":"love3165303/so100_pick4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":16,"train_windows":16,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-3.875977,-2.95752,-2.95752,-2.15332,-2.195609],"action_q99":[1.854492,4.979004,5.849121,2.197266,3.164062,47.60479],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.013184,73.125,55.107422,21.445312,-24.688477,-1.102688],"state_q99":[21.541992,186.767578,171.123047,68.90625,5.273438,45.758098]},
+ {"part":"love3165303__so100_pick6","origin":"molmoact","dataset":"love3165303/so100_pick6","scene_camera":"observation.images.phone","fps":30.0,"built_clips":538,"train_windows":538,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-4.21875,-2.460938,-3.955078,-1.230469,-2.095809],"action_q99":[1.142578,3.867188,3.691406,3.164062,1.582031,37.94012],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.732422,51.841406,64.511719,-0.791016,-119.355469,-1.309442],"state_q99":[30.146484,186.767578,171.210938,84.199219,-79.804688,37.35355]},
+ {"part":"love3165303__so100_pick_all_lego","origin":"molmoact","dataset":"love3165303/so100_pick_all_lego","scene_camera":"observation.images.top","fps":30.0,"built_clips":643,"train_windows":643,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-4.658203,-3.779297,-2.900391,-4.658203,-1.933594,-0.0998],"action_q99":[5.537109,4.921875,2.900391,3.955078,2.109375,39.720558],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-84.199219,44.560547,39.726562,-0.263672,-113.527441,0.396511],"state_q99":[39.259863,189.580078,175.693359,104.326172,-17.956934,39.413162]},
+ {"part":"love3165303__so100_pick_ball_colors1","origin":"molmoact","dataset":"love3165303/so100_pick_ball_colors1","scene_camera":"observation.images.top","fps":30.0,"built_clips":222,"train_windows":222,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-1.933594,-4.042969,-2.636719,-2.636719,-0.920215,-0.0998],"action_q99":[1.40625,3.381152,3.251953,2.197266,0.791016,41.317364],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-28.037109,52.827539,68.642578,11.513672,-104.589844,0.396511],"state_q99":[28.828125,190.107422,175.78125,78.486328,-81.5625,40.919907]},
+ {"part":"love3165303__so100_pick_ball_colors2","origin":"molmoact","dataset":"love3165303/so100_pick_ball_colors2","scene_camera":"observation.images.top","fps":30.0,"built_clips":1839,"train_windows":1839,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-2.021484,-4.570312,-3.164062,-2.460938,-1.142578,-0.0998],"action_q99":[1.757812,4.21875,4.306641,2.373047,0.791016,44.810379],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-28.652344,38.583984,43.769531,-15.644531,-108.544922,0.396511],"state_q99":[42.099609,189.931641,175.957031,79.101562,-76.904297,44.409199]},
+ {"part":"love3165303__so100_pick_ball_colors3","origin":"molmoact","dataset":"love3165303/so100_pick_ball_colors3","scene_camera":"observation.images.top","fps":30.0,"built_clips":1119,"train_windows":1119,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-2.285156,-4.130859,-2.8125,-3.955078,-1.142578,0.0],"action_q99":[2.285156,4.658203,4.130859,3.164062,1.40625,47.50499],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-24.169922,30.020801,48.691406,-36.650391,-100.898438,0.237906],"state_q99":[40.078125,189.931641,175.957031,78.134766,-71.191406,47.105473]},
+ {"part":"love3165303__so100_pick_multi_tape1","origin":"molmoact","dataset":"love3165303/so100_pick_multi_tape1","scene_camera":"observation.images.top","fps":30.0,"built_clips":617,"train_windows":617,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-3.515625,-4.042969,-3.164062,-2.988281,-1.933594,-0.0998],"action_q99":[4.21875,3.691406,2.8125,1.845703,2.197266,44.111778],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-83.759766,37.353516,29.069824,32.058105,-48.603516,0.396511],"state_q99":[41.484375,190.195312,175.693359,100.371094,34.848633,44.012688]},
+ {"part":"lqzjbs__data_testssss6","origin":"molmoact","dataset":"lqzjbs/data_testssss6","scene_camera":"observation.images.Logic_camera","fps":30.0,"built_clips":382,"train_windows":382,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.251953,-3.867188,-2.021484,-2.285156,-0.320171],"action_q99":[2.285156,4.130859,3.339844,2.537402,1.582031,47.691567],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-53.701172,46.054688,17.138672,18.644238,-105.457324,0.208768],"state_q99":[18.457031,190.634766,180.439453,99.667969,61.611328,44.570633]},
+ {"part":"lsrsir__so100_test","origin":"molmoact","dataset":"lsrsir/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":24,"train_windows":24,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.785059,-4.21875,-5.564355,-2.900391,-1.081934,-0.346021],"action_q99":[1.345605,4.597559,5.003613,3.076172,1.054688,40.138409],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-1.548633,41.781445,13.89375,48.312598,-22.412109,-0.081967],"state_q99":[49.21875,185.537109,173.320312,100.986328,1.724414,39.918034]},
+ {"part":"lsrsir__so100_test1","origin":"molmoact","dataset":"lsrsir/so100_test1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.167578,-4.40332,-6.240234,-3.260742,-1.40625,-0.432526],"action_q99":[1.849219,5.275195,7.386328,2.988281,1.75957,38.235294],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[4.129102,39.7125,10.541602,49.744336,-23.385938,-0.163934],"state_q99":[55.116211,185.712891,173.847656,101.337891,8.615039,37.706557]},
+ {"part":"lsrsir__so100_test2","origin":"molmoact","dataset":"lsrsir/so100_test2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":28,"train_windows":28,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.541797,-4.549219,-6.739453,-3.765234,-1.845703,-0.605536],"action_q99":[2.988281,6.057422,7.551562,3.244922,1.662891,37.370243],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.722656,38.320312,9.499219,40.78125,-19.599609,0.0],"state_q99":[40.693359,185.273438,174.023438,101.25,13.176562,36.885246]},
+ {"part":"lsrsir__so100_test3","origin":"molmoact","dataset":"lsrsir/so100_test3","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.519336,-6.438867,-3.427734,-1.882617,-0.605536],"action_q99":[2.058398,5.712891,7.03125,2.988281,1.567969,38.927334],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.261719,36.738281,6.767578,45.351562,-17.272266,-0.163934],"state_q99":[39.111328,185.273438,172.705078,101.25,14.0625,38.606556]},
+ {"part":"lt-s__so100_train_move_six_blocks_tray_to_matching_dishes","origin":"molmoact","dataset":"lt-s/so100_train_move_six_blocks_tray_to_matching_dishes","scene_camera":"observation.images.center_cam","fps":30.0,"built_clips":443,"train_windows":443,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-4.570312,-5.185547,-4.633594,-5.009766,-0.439754],"action_q99":[2.460938,5.185547,5.009766,5.009766,6.152344,26.976254],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.256641,65.591016,64.887891,34.804688,-114.535547,-0.082169],"state_q99":[32.607422,189.404297,173.232422,94.482422,35.233594,25.860312]},
+ {"part":"lt-s__so100_train_move_six_blocks_tray_to_matching_dishes_flip","origin":"molmoact","dataset":"lt-s/so100_train_move_six_blocks_tray_to_matching_dishes_flip","scene_camera":"observation.images.center_cam","fps":30.0,"built_clips":421,"train_windows":421,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-4.921875,-5.273438,-4.746094,-5.888672,-0.439754],"action_q99":[2.460938,5.449219,5.009766,5.273438,6.855469,26.297274],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-18.065918,68.154785,70.488281,18.751465,-144.237305,-0.082169],"state_q99":[28.612793,189.316406,173.232422,94.26709,18.457031,25.061628]},
+ {"part":"luriss__so100_pick_and_place_box_task_0429_1","origin":"molmoact","dataset":"luriss/so100_pick_and_place_box_task_0429_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":369,"train_windows":369,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.460938,-2.548828,-1.494141,-1.054688,-0.095877],"action_q99":[2.021484,2.724609,2.8125,1.40625,1.054688,28.18792],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.285156,-254.895996,1.045898,38.843262,-91.586426,0.552105],"state_q99":[55.810547,187.207031,175.517578,93.251953,60.829102,28.019323]},
+ {"part":"luriss__so100_pick_and_place_box_task_0430","origin":"molmoact","dataset":"luriss/so100_pick_and_place_box_task_0430","scene_camera":"observation.images.phone","fps":30.0,"built_clips":395,"train_windows":395,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.285156,-2.285156,-1.40625,-0.439453,-0.095877],"action_q99":[1.757812,2.460938,2.724609,1.142578,0.439453,32.341323],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.736328,-173.320312,33.486328,37.214648,-22.763672,0.552105],"state_q99":[35.383008,187.558594,174.726562,93.164062,1.054688,32.298134]},
+ {"part":"luriss__so100_pick_and_place_box_task_0430_1","origin":"molmoact","dataset":"luriss/so100_pick_and_place_box_task_0430_1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":714,"train_windows":714,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.8125,-2.900391,-2.900391,-0.791016,-0.095877],"action_q99":[1.845703,2.988281,3.603516,1.582031,0.966797,37.583893],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-51.679688,-172.265625,25.576172,31.376953,-38.144531,0.552105],"state_q99":[31.552734,187.910156,175.078125,93.427734,14.589844,37.819187]},
+ {"part":"magnusk__so100_blocktest","origin":"molmoact","dataset":"magnusk/so100_blocktest","scene_camera":"observation.images.phone","fps":30.0,"built_clips":48,"train_windows":48,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.867188,-4.130859,-2.021484,-0.527344,-0.184843],"action_q99":[2.011816,4.18623,2.548828,1.669922,0.703125,31.608133],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.085938,-14.238281,5.361328,51.975879,79.892578,0.0],"state_q99":[45.143262,131.363965,132.890625,101.337891,102.480469,31.05899]},
+ {"part":"magnusk__so100_blocktest_50","origin":"molmoact","dataset":"magnusk/so100_blocktest_50","scene_camera":"observation.images.phone","fps":30.0,"built_clips":749,"train_windows":749,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.482422,-4.306641,-2.109375,-1.494141,-0.277264],"action_q99":[1.841309,4.833984,4.658203,2.373047,1.318359,31.700554],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.134766,-14.765625,2.109375,39.375,75.410156,0.0],"state_q99":[50.009766,164.882812,189.931641,101.953125,104.677734,31.268657]},
+ {"part":"maitereo__so100_bag_placement_20250426","origin":"molmoact","dataset":"maitereo/so100_bag_placement_20250426","scene_camera":"observation.images.tabletop","fps":30.0,"built_clips":1559,"train_windows":1559,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.318359,-1.40625,-0.966797,-1.142578,-0.105708],"action_q99":[1.318359,1.318359,1.40625,1.054688,0.966797,93.446091],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-65.654297,44.852344,29.707031,-2.636719,-106.347656,0.226244],"state_q99":[71.542969,189.316406,171.035156,106.347656,15.352734,92.98642]},
+ {"part":"maitereo__so100_test","origin":"molmoact","dataset":"maitereo/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":61,"train_windows":61,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-1.769238,-1.757812,-0.966797,-0.878906,-0.105708],"action_q99":[1.582031,1.757812,1.593457,1.154004,2.109375,67.547569],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-79.101562,67.148438,37.781543,57.610547,-26.103516,0.226244],"state_q99":[70.488281,189.140625,169.453125,101.777344,66.005859,67.081444]},
+ {"part":"manfye__so100_test1","origin":"molmoact","dataset":"manfye/so100_test1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.691406,-3.779297,-1.757812,-1.054688,-0.404449],"action_q99":[1.230469,3.437402,3.427734,1.943262,1.142578,52.578362],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[13.798828,30.136816,-10.986328,55.019531,9.84375,0.08244],"state_q99":[53.447168,181.933594,165.761719,104.853516,58.231934,52.596867]},
+ {"part":"manoj92__so100_marker1","origin":"molmoact","dataset":"manoj92/so100_marker1","scene_camera":"observation.images.scene","fps":30.0,"built_clips":18,"train_windows":18,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.320996,-4.394531,-3.872461,-3.694043,-4.836621,-0.451671],"action_q99":[1.054688,2.815137,2.817773,6.786035,1.84834,35.504064],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[5.537109,74.091797,106.787109,-8.187012,-187.912793,-0.876339],"state_q99":[29.885449,192.392578,178.242188,84.289746,-8.522754,35.540409]},
+ {"part":"masato-ka__so100_cutlery_handling","origin":"molmoact","dataset":"masato-ka/so100_cutlery_handling","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":880,"train_windows":880,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.373047,-2.021484,-2.285156,-3.867188,-0.770713],"action_q99":[1.933594,2.109375,2.109375,2.109375,3.603516,29.961464],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.572266,54.228516,49.130859,-17.753906,-20.214844,0.617284],"state_q99":[46.34209,188.349609,180.878906,86.484375,146.513672,29.541445]},
+ {"part":"masato-ka__so100_cutlery_handling_simple","origin":"molmoact","dataset":"masato-ka/so100_cutlery_handling_simple","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":996,"train_windows":996,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.900391,-2.636719,-1.933594,-3.779297,-0.578035],"action_q99":[2.021484,2.636719,2.900391,1.845703,3.515625,31.502892],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.847656,41.660156,33.662109,17.402344,-32.385938,0.617284],"state_q99":[36.035156,188.349609,180.791016,98.4375,127.001953,31.393299]},
+ {"part":"masato-ka__so100_grasp_lego","origin":"molmoact","dataset":"masato-ka/so100_grasp_lego","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":795,"train_windows":795,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.548828,-2.109375,-1.494141,-4.306641,-0.096993],"action_q99":[0.966797,2.197266,1.669922,1.494141,2.460938,42.014551],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-7.734375,67.851562,70.576172,-7.03125,-10.107422,0.724638],"state_q99":[29.443359,194.501953,181.40625,80.15625,108.208301,41.123188]},
+ {"part":"masato-ka__so100_grasp_snack","origin":"molmoact","dataset":"masato-ka/so100_grasp_snack","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":473,"train_windows":473,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.603516,-3.164062,-2.021484,-4.833984,-0.481696],"action_q99":[2.021484,2.900391,3.076172,1.757812,3.427734,87.382468],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.102246,45.785742,44.645801,21.09375,-53.613281,-0.176367],"state_q99":[33.310547,189.052734,180.263672,98.876953,111.887402,87.127867]},
+ {"part":"masato-ka__so100_lego_sort","origin":"molmoact","dataset":"masato-ka/so100_lego_sort","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1706,"train_windows":1706,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-1.933594,-2.109375,-1.845703,-3.339844,-0.193986],"action_q99":[1.40625,1.845703,1.933594,2.460938,3.339844,51.600391],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-29.882812,62.578125,58.183594,-2.900391,-3.515625,0.724638],"state_q99":[32.871094,194.414062,181.494141,85.341797,153.984375,51.449276]},
+ {"part":"masato-ka__so100_test","origin":"molmoact","dataset":"masato-ka/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":41,"train_windows":41,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.850098,-1.234863,-1.230469,-2.021484,-0.193986],"action_q99":[0.878906,1.669922,1.142578,1.582031,2.553223,39.57808],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.867188,92.188477,118.564453,17.314453,-5.361328,0.634058],"state_q99":[26.635254,194.414062,181.494141,53.525391,92.8125,37.957429]},
+ {"part":"mathieutk__so100_goba","origin":"molmoact","dataset":"mathieutk/so100_goba","scene_camera":"observation.images.red","fps":30.0,"built_clips":65,"train_windows":65,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.961914,-5.695312,-4.280273,-2.636719,-1.054688,-0.092678],"action_q99":[3.665039,4.570312,6.503906,1.933594,0.966797,61.075069],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.522461,46.318359,14.765625,46.87207,-19.863281,0.411862],"state_q99":[23.44043,179.973633,168.574219,92.197266,5.510742,59.052718]},
+ {"part":"mathieutk__so100_gobc","origin":"molmoact","dataset":"mathieutk/so100_gobc","scene_camera":"observation.images.red","fps":30.0,"built_clips":106,"train_windows":106,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.8125,-5.449219,-4.570312,-2.988281,-1.230469,-0.092678],"action_q99":[3.571875,5.097656,6.648047,2.636719,0.966797,53.012047],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.394531,43.945312,12.568359,36.123047,-25.769531,0.494234],"state_q99":[23.786719,179.736328,168.574219,90.696094,8.757422,52.93575]},
+ {"part":"maujim__TraveltoJam4","origin":"molmoact","dataset":"maujim/TraveltoJam4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":555,"train_windows":555,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.779297,-4.21875,-0.351562,-0.175781,-0.45977],"action_q99":[1.074023,0.351562,0.615234,2.548828,0.175781,10.191571],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.388672,26.542969,-1.669922,-10.107422,69.433594,-0.482703],"state_q99":[70.927734,190.898438,183.779297,87.1875,91.757812,10.378118]},
+ {"part":"maujim__place_bagel_on_jig","origin":"molmoact","dataset":"maujim/place_bagel_on_jig","scene_camera":"observation.images.phone","fps":30.0,"built_clips":591,"train_windows":591,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.076172,-2.021484,-2.900391,-4.130859,-0.45977],"action_q99":[1.40625,2.988281,2.285156,2.8125,3.515625,48.045979],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.554688,43.857422,76.271484,-88.934766,-11.337891,-0.160901],"state_q99":[61.259766,190.546875,183.691406,53.701172,92.285156,47.546257]},
+ {"part":"maujim__place_bagel_on_jig3","origin":"molmoact","dataset":"maujim/place_bagel_on_jig3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1061,"train_windows":1061,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.339844,-2.8125,-2.548828,-4.042969,-0.689655],"action_q99":[1.669922,2.636719,2.109375,2.8125,3.339844,57.011497],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.113281,50.625,53.876953,-20.039062,-8.4375,-0.402253],"state_q99":[71.894531,190.634766,183.691406,69.550488,95.537109,56.717617]},
+ {"part":"maujim__so100_bagel_ps4","origin":"molmoact","dataset":"maujim/so100_bagel_ps4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":18,"train_windows":18,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.647266,-1.494141,-2.285156,-3.888281,-0.383142],"action_q99":[0.878906,1.719141,0.791016,1.669922,2.373047,44.922606],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.0625,82.603125,129.097266,-40.253906,93.603516,0.0],"state_q99":[16.171875,188.789062,181.054688,29.619141,169.541016,44.97184]},
+ {"part":"maujim__so100bagelps4","origin":"molmoact","dataset":"maujim/so100bagelps4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":149,"train_windows":149,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.021484,-1.230469,-1.933594,-2.967187,-0.536398],"action_q99":[0.966797,2.373047,1.318359,2.109375,2.548828,48.27586],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.117188,65.432812,108.720703,-53.690625,83.408203,-0.321802],"state_q99":[48.171094,190.810547,181.230469,26.455078,178.857422,48.672565]},
+ {"part":"meetrais__ball_in_the_box","origin":"molmoact","dataset":"meetrais/ball_in_the_box","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":878,"train_windows":878,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.548828,-2.900391,-1.757812,-0.703125,-0.203252],"action_q99":[0.791016,2.548828,3.603516,2.109375,0.703125,50.203251],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-14.765625,27.246094,4.921875,4.21875,169.980469,0.070323],"state_q99":[47.988281,180.175781,180.615234,80.130762,201.445312,49.979606]},
+ {"part":"mercu7__so101_test","origin":"molmoact","dataset":"mercu7/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":29,"train_windows":29,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.495215,-1.616309,-2.636719,-1.176855,-3.125],"action_q99":[1.738477,2.900391,1.738477,0.679395,3.076172,25.342969],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.021484,76.464844,115.141113,-24.609375,1.230469,-0.138504],"state_q99":[41.835938,191.162109,178.59375,43.066406,93.022559,25.623268]},
+ {"part":"mfyu__so101_white_box_3","origin":"molmoact","dataset":"mfyu/so101_white_box_3","scene_camera":"observation.images.phone","fps":30.0,"built_clips":157,"train_windows":157,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-1.845703,-2.197266,-5.232129,-1.669922,-0.084388],"action_q99":[1.054688,2.724609,3.691406,3.210645,1.757812,68.101265],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-92.548828,31.201172,-4.658203,-100.634766,-21.269531,11.784232],"state_q99":[-36.650391,198.105469,181.494141,100.107422,127.880859,68.049789]},
+ {"part":"mfyu__so101_white_box_green_nums_20_0729","origin":"molmoact","dataset":"mfyu/so101_white_box_green_nums_20_0729","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":700,"train_windows":700,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.40625,-1.494141,-3.164062,-1.757812,0.92827],"action_q99":[1.318359,1.845703,1.845703,3.339844,1.494141,67.76371],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.201172,65.039062,61.259766,-100.634766,-124.112109,12.019917],"state_q99":[15.029297,198.808594,181.757812,100.107422,170.15625,67.88382]},
+ {"part":"mfyu__so101_white_box_green_nums_20_0730","origin":"molmoact","dataset":"mfyu/so101_white_box_green_nums_20_0730","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":698,"train_windows":698,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-1.845703,-1.845703,-1.757812,-1.230469,-0.168776],"action_q99":[1.054688,1.933594,1.933594,1.582031,1.318359,58.818565],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-97.382812,31.640625,9.783984,-79.980469,-11.689453,12.946059],"state_q99":[4.394531,198.808594,181.582031,100.107422,170.859375,58.672203]},
+ {"part":"mldev19__so100_brick","origin":"molmoact","dataset":"mldev19/so100_brick","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":465,"train_windows":465,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.04082,-3.867188,-2.988281,-1.757812,-0.878906,-0.089286],"action_q99":[2.548828,2.988281,3.164062,1.494141,1.230469,26.269642],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.361133,70.400391,81.5625,27.246094,-19.248047,0.278164],"state_q99":[22.324219,193.271484,181.054688,72.421875,15.996094,25.938803]},
+ {"part":"mldev19__so100_test_4","origin":"molmoact","dataset":"mldev19/so100_test_4","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":11,"train_windows":11,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.766602,-4.135254,-3.60791,-1.410645,-2.553223,0.0],"action_q99":[3.164062,2.988281,2.636719,1.410645,0.180176,26.763111],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.287109,55.190918,65.390625,34.716797,-68.730469,0.83682],"state_q99":[20.039062,191.513672,183.339844,69.965332,-5.185547,26.569038]},
+ {"part":"mldev19__so100_test_brick_1","origin":"molmoact","dataset":"mldev19/so100_test_brick_1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":15,"train_windows":15,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-0.615234,-0.439453,-2.03291,-0.263672,0.0],"action_q99":[2.197266,3.164062,3.614941,1.066113,1.429102,29.374998],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.849023,28.740234,16.435547,47.724609,-21.269531,0.347705],"state_q99":[17.753906,193.271484,181.054688,102.744141,2.988281,29.554935]},
+ {"part":"nguyen-v__so100_test_white_plug","origin":"molmoact","dataset":"nguyen-v/so100_test_white_plug","scene_camera":"observation.images.phone","fps":30.0,"built_clips":611,"train_windows":611,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-3.515625,-2.988281,-3.251953,-3.076172,-0.366636],"action_q99":[1.757812,3.515625,3.955078,2.636719,2.988281,41.979836],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.574219,34.013672,25.576172,-44.296875,-135.175781,0.556328],"state_q99":[36.298828,186.591797,175.517578,102.919922,19.160156,41.863701]},
+ {"part":"nicholasluschaeffler__dataset50_1","origin":"molmoact","dataset":"nicholasluschaeffler/dataset50_1","scene_camera":"observation.images.front","fps":30.0,"built_clips":781,"train_windows":781,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.955078,-3.691406,-2.548828,-2.636719,-0.182983],"action_q99":[2.021484,3.867188,4.394531,3.076172,4.746094,51.601101],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-76.552734,26.572852,2.960156,-44.499023,-12.392578,0.0],"state_q99":[53.613281,192.919922,185.273438,98.964844,124.247461,51.267449]},
+ {"part":"noorzamri86__so100_test_globe_in_bin1","origin":"molmoact","dataset":"noorzamri86/so100_test_globe_in_bin1","scene_camera":"observation.images.up","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-4.176563,-3.825,-2.41875,-3.033984,-0.352423],"action_q99":[0.791016,2.285156,3.427734,3.121875,3.255469,83.002643],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.236328,10.371094,-12.216797,1.884375,-9.404297,1.001001],"state_q99":[16.0875,186.767578,172.880859,98.613281,161.940234,81.781784]},
+ {"part":"northhycao__grasp_cubes_noleader","origin":"molmoact","dataset":"northhycao/grasp_cubes_noleader","scene_camera":"observation.images.realsense_top","fps":30.0,"built_clips":294,"train_windows":294,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.988281,-2.021484,-1.582031,-1.318359,-0.401284],"action_q99":[1.757812,2.373047,1.494141,1.65498,1.318359,22.552166],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-1.479199,40.169531,27.881543,36.489551,-56.953125,0.13986],"state_q99":[54.404297,194.765625,177.539062,82.938867,6.561914,22.587412]},
+ {"part":"nz-nz__so101_test","origin":"molmoact","dataset":"nz-nz/so101_test","scene_camera":"observation.images.top","fps":30.0,"built_clips":275,"train_windows":275,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.934668,-2.724609,-1.230469,-0.878906,-0.765957],"action_q99":[1.40625,2.758887,2.021484,1.494141,0.878906,36.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.703125,51.416016,59.0625,17.753906,-19.160156,0.213068],"state_q99":[12.216797,195.117188,180.527344,91.054688,37.685742,35.72443]},
+ {"part":"odellus__so100_grasp","origin":"molmoact","dataset":"odellus/so100_grasp","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":603,"train_windows":603,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-2.900391,-2.460938,-2.285156,-0.527344,-0.769823],"action_q99":[2.460938,2.988281,3.779297,1.845703,0.527344,35.55966],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.246094,34.101562,21.533203,24.873047,-9.755859,0.0],"state_q99":[63.017578,192.392578,179.033203,99.309375,10.019531,35.006973]},
+ {"part":"odellus__so100_test","origin":"molmoact","dataset":"odellus/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":18,"train_windows":18,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-3.64043,-2.548828,-2.109375,-0.263672,-0.951501],"action_q99":[2.849414,2.358984,3.575391,1.831641,0.263672,28.483448],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.113281,54.228516,61.083984,48.955078,0.615234,0.488145],"state_q99":[45.175781,191.513672,176.044922,84.411914,1.054688,28.591352]},
+ {"part":"odellus__so100_test_2","origin":"molmoact","dataset":"odellus/so100_test_2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":17,"train_windows":17,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.460938,-2.548828,-2.548828,-1.258594,-0.302344,-0.511162],"action_q99":[2.714062,2.724609,4.081641,1.40625,0.351562,32.30485],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.771484,69.873047,63.632812,47.724609,0.615234,1.046025],"state_q99":[26.894531,191.074219,175.166016,77.431641,0.966797,31.659693]},
+ {"part":"orsoromeo__so101_pick_and_place","origin":"molmoact","dataset":"orsoromeo/so101_pick_and_place","scene_camera":"observation.images.phone","fps":30.0,"built_clips":789,"train_windows":789,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.988281,-2.255273,-1.40625,-1.318359,-0.086356],"action_q99":[1.142578,2.373047,2.8125,1.669922,1.142578,38.860104],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.757812,46.669922,28.476562,44.238867,56.953125,0.081766],"state_q99":[18.105469,194.414062,183.251953,93.22207,126.474609,38.757153]},
+ {"part":"orsoromeo__so101_test22","origin":"molmoact","dataset":"orsoromeo/so101_test22","scene_camera":"observation.images.phone","fps":30.0,"built_clips":769,"train_windows":769,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.988281,-2.021484,-1.474805,-1.318359,0.0],"action_q99":[1.142578,2.373047,2.636719,1.669922,1.142578,34.110535],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.087891,51.416016,33.066211,54.931641,63.28125,0.081766],"state_q99":[9.667969,194.326172,183.164062,93.427734,128.144531,33.932953]},
+ {"part":"ortiztx__so101_test2_1","origin":"molmoact","dataset":"ortiztx/so101_test2_1","scene_camera":"observation.images.base","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-1.142578,-0.527344,-2.285156,-4.130859,6.593407],"action_q99":[1.40625,2.576074,3.164062,2.197266,4.827832,70.82917],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.792969,25.664062,4.482422,63.720703,-29.091797,12.598425],"state_q99":[12.650098,169.453125,174.111328,97.322168,120.585938,63.582676]},
+ {"part":"ortiztx__so101_training30_v1","origin":"molmoact","dataset":"ortiztx/so101_training30_v1","scene_camera":"observation.images.top","fps":30.0,"built_clips":95,"train_windows":95,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.136426,-3.076172,-2.806348,-4.130859,-1.40625,-0.599401],"action_q99":[1.054688,3.427734,3.339844,3.948926,1.757812,65.034966],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.835938,49.746094,65.390625,-92.636719,56.777344,0.0],"state_q99":[11.074219,190.810547,177.890625,84.726562,107.666016,63.976376]},
+ {"part":"paszea__so100_lego","origin":"molmoact","dataset":"paszea/so100_lego","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1301,"train_windows":1301,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.724609,-1.494141,-3.251953,-3.603516,-0.219298],"action_q99":[2.109375,2.460938,2.988281,2.724609,2.109375,100.0],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-69.960938,30.234375,62.929688,-85.078125,-96.152344,-0.257069],"state_q99":[39.726562,189.140625,177.978516,80.859375,5.712891,100.0]},
+ {"part":"paszea__so100_lego_mix","origin":"molmoact","dataset":"paszea/so100_lego_mix","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1750,"train_windows":1750,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-2.724609,-2.460938,-1.933594,-2.197266,-0.848256],"action_q99":[0.615234,1.933594,2.021484,2.021484,2.021484,42.884071],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.828125,-9.580078,-0.439453,-1.40625,-127.705078,-0.165153],"state_q99":[11.953125,129.375,119.707031,79.189453,8.257324,42.113956]},
+ {"part":"paszea__so100_test","origin":"molmoact","dataset":"paszea/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.641113,-3.168457,-1.318359,-0.878906,-0.109649],"action_q99":[1.230469,2.021484,2.460938,1.757812,1.230469,66.354163],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.357422,9.755859,-11.953125,32.664551,-49.130859,1.028278],"state_q99":[54.14502,188.876953,177.011719,80.771484,8.085938,65.809769]},
+ {"part":"paszea__so100_whale_2","origin":"molmoact","dataset":"paszea/so100_whale_2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":938,"train_windows":938,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.548828,-2.373047,-2.021484,-0.439453,0.0],"action_q99":[2.109375,2.109375,1.933594,1.845703,0.703125,82.127197],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-68.115234,50.712891,54.445605,22.148438,-17.009473,1.028278],"state_q99":[31.201172,189.140625,177.099609,80.771484,14.501953,81.748077]},
+ {"part":"paszea__so100_whale_grab","origin":"molmoact","dataset":"paszea/so100_whale_grab","scene_camera":"observation.images.phone","fps":30.0,"built_clips":956,"train_windows":956,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.548828,-2.460938,-1.669922,-0.615234,0.0],"action_q99":[1.40625,2.636719,3.076172,1.494141,0.703125,73.028507],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.388477,16.611328,-11.337891,29.881055,-39.902344,0.771208],"state_q99":[39.814453,189.140625,177.099609,81.123047,15.644531,72.750641]},
+ {"part":"pbvr__so101_test002","origin":"molmoact","dataset":"pbvr/so101_test002","scene_camera":"observation.images.topdown","fps":30.0,"built_clips":1791,"train_windows":1791,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-5.273438,-4.394531,-2.460938,-1.582031,-0.449236],"action_q99":[2.8125,4.570312,4.658203,2.900391,1.582031,45.462711],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.998047,36.474609,-2.197266,41.835938,-23.291016,-0.282287],"state_q99":[59.501953,198.105469,177.539062,99.755859,11.337891,45.37756]},
+ {"part":"pbvr__so101_test003","origin":"molmoact","dataset":"pbvr/so101_test003","scene_camera":"observation.images.topdown","fps":30.0,"built_clips":1235,"train_windows":1235,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.300293,-5.537109,-4.482422,-2.548828,-1.757812,-0.359389],"action_q99":[3.164062,4.921875,5.097656,2.900391,1.582031,43.57592],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-56.737793,37.177734,2.109375,46.40625,-15.820312,-0.282287],"state_q99":[49.570312,198.017578,177.978516,99.755859,9.931641,43.542694]},
+ {"part":"peerlesssa__so100_test","origin":"molmoact","dataset":"peerlesssa/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":29,"train_windows":29,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.976172,-5.11875,-3.339844,-3.185156,-0.724219,-2.946429],"action_q99":[3.515625,4.482422,3.076172,2.724609,0.703125,29.753572],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-10.195312,57.371484,72.158203,27.685547,-17.862891,-2.021661],"state_q99":[74.794922,192.216797,179.208984,99.425391,1.582031,29.025272]},
+ {"part":"peerlesssa__so100_test-1","origin":"molmoact","dataset":"peerlesssa/so100_test-1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":250,"train_windows":250,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.260547,-2.109375,-2.460938,-1.845703,-0.263672,-2.857143],"action_q99":[2.197266,2.021484,2.724609,1.757812,0.263672,40.153571],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-12.480469,52.294922,48.691406,31.464844,-8.525391,-2.093863],"state_q99":[81.689063,192.480469,179.560547,95.800781,-6.943359,39.618772]},
+ {"part":"pierfabre__CowCleanRandom","origin":"molmoact","dataset":"pierfabre/CowCleanRandom","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":418,"train_windows":418,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-2.636719,-2.460938,-2.197266,-2.373047,-3.32681],"action_q99":[3.076172,3.427734,2.900391,2.373047,2.109375,42.563602],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-79.716797,47.109375,15.644531,52.03125,-84.550781,7.97498],"state_q99":[73.659375,190.898438,124.920703,116.630859,72.509766,42.298672]},
+ {"part":"pierfabre__chicken","origin":"molmoact","dataset":"pierfabre/chicken","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":1223,"train_windows":1223,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.746094,-2.373047,-2.724609,-1.933594,-3.691406,-2.054795],"action_q99":[4.570312,2.636719,2.109375,2.548828,4.21875,70.64579],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-101.425781,88.055859,58.271484,68.115234,-112.412109,5.39484],"state_q99":[102.744141,190.986328,147.480469,117.070312,166.025391,70.367477]},
+ {"part":"pierfabre__cow2","origin":"molmoact","dataset":"pierfabre/cow2","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":630,"train_windows":630,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.988281,-3.603516,-3.603516,-3.779297,-2.109375,-2.250489],"action_q99":[3.955078,3.955078,4.394531,2.900391,2.511035,71.526421],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.288379,23.378906,-12.304688,53.613281,-41.220703,7.97498],"state_q99":[61.611328,190.986328,108.193359,116.71875,64.172461,72.009384]},
+ {"part":"pierfabre__pig2","origin":"molmoact","dataset":"pierfabre/pig2","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":822,"train_windows":822,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.779297,-3.251953,-2.636719,-2.900391,-2.109375,-2.250489],"action_q99":[4.042969,4.306641,3.076172,2.460938,2.021484,58.317024],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-70.488281,23.203125,-10.810547,48.515625,-44.384766,8.444097],"state_q99":[76.640625,190.722656,109.266504,114.433594,39.550781,57.8577]},
+ {"part":"pierfabre__pig3","origin":"molmoact","dataset":"pierfabre/pig3","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":875,"train_windows":875,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-2.8125,-2.373047,-2.724609,-2.109375,-2.250489],"action_q99":[3.427734,3.339844,2.460938,2.460938,2.109375,71.917809],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-80.419922,33.310547,8.964844,36.123047,-73.829883,7.271306],"state_q99":[73.654102,190.898438,133.330078,116.542969,100.989844,72.08757]},
+ {"part":"pierfabre__pig_test","origin":"molmoact","dataset":"pierfabre/pig_test","scene_camera":"observation.images.robot","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.616699,-2.474121,-2.061035,-2.8125,-1.067871,-1.8591],"action_q99":[3.867188,2.737793,1.757812,3.102539,1.243652,57.632095],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-69.635742,52.782715,49.746094,14.501953,-11.953125,8.287724],"state_q99":[76.113281,190.546875,123.61377,114.169922,12.480469,57.8577]},
+ {"part":"pierfabre__sheep","origin":"molmoact","dataset":"pierfabre/sheep","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":977,"train_windows":977,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.339844,-2.636719,-2.8125,-2.373047,-4.306641,-2.544031],"action_q99":[3.603516,2.900391,2.197266,2.988281,4.921875,55.185909],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.414062,92.8125,62.816309,60.380859,-166.943848,8.209538],"state_q99":[62.314453,190.986328,137.285156,117.070312,132.099609,54.886631]},
+ {"part":"pingev__so100_test_2025-03-15-2","origin":"molmoact","dataset":"pingev/so100_test_2025-03-15-2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":399,"train_windows":399,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-1.933594,-2.460938,-1.318359,-2.109375,0.0],"action_q99":[3.867188,2.460938,3.603516,2.109375,2.109375,52.645271],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.509766,45.703125,47.260547,65.214844,-65.742188,0.802855],"state_q99":[23.466797,131.835938,128.496094,105.029297,99.316406,51.650311]},
+ {"part":"pranavsaroha__so100_med_cubes_0608","origin":"molmoact","dataset":"pranavsaroha/so100_med_cubes_0608","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1400,"train_windows":1400,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.285156,-2.197266,-2.548828,-2.109375,-0.185874],"action_q99":[1.494141,3.164062,2.285156,3.164062,2.109375,37.081783],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.980469,82.040625,69.032813,-11.865234,-69.394922,-0.097182],"state_q99":[22.236328,182.724609,174.726562,78.310547,14.375391,36.734695]},
+ {"part":"pranavsaroha__so100_med_cubes_0608_test","origin":"molmoact","dataset":"pranavsaroha/so100_med_cubes_0608_test","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.494141,-1.582031,-0.966797,-1.054688,-0.185874],"action_q99":[0.966797,1.845703,1.980176,1.054688,0.615234,42.986059],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.292969,79.453125,46.757812,36.376172,-95.185547,0.097182],"state_q99":[25.136719,183.779297,182.724609,95.449219,-22.324219,42.971816]},
+ {"part":"pranavsaroha__so100_medicine_0602","origin":"molmoact","dataset":"pranavsaroha/so100_medicine_0602","scene_camera":"observation.images.left_wrist","fps":30.0,"built_clips":560,"train_windows":560,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.021484,-2.636719,-2.021484,-1.669922,0.743494],"action_q99":[1.230469,2.460938,2.8125,2.285156,1.582031,34.293682],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.681641,43.945312,0.175781,23.378906,-80.244141,0.680272],"state_q99":[38.320312,179.472656,168.837891,107.314453,33.574219,34.013603]},
+ {"part":"pranavsaroha__so100_medicine_0604_test","origin":"molmoact","dataset":"pranavsaroha/so100_medicine_0604_test","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":35,"train_windows":35,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.724609,-4.348828,-2.460938,-2.197266,0.743494],"action_q99":[1.55918,3.251953,4.042969,3.141211,2.109375,49.531597],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.164648,44.121094,-6.393164,15.823828,-80.859375,0.485909],"state_q99":[35.244141,179.560547,169.013672,107.314453,2.285156,47.762877]},
+ {"part":"pranavsaroha__so100_medicine_0604_test1","origin":"molmoact","dataset":"pranavsaroha/so100_medicine_0604_test1","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":34,"train_windows":34,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.635645,-3.481348,-3.569238,-4.696875,-1.845703,0.836431],"action_q99":[0.844629,3.129785,2.724609,3.603516,4.184473,36.492565],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-9.052734,83.003027,84.287109,-20.692969,-43.154297,1.166181],"state_q99":[9.217969,179.296875,169.243066,82.441406,13.36377,34.83382]},
+ {"part":"pranavsaroha__so100_medicine_0605","origin":"molmoact","dataset":"pranavsaroha/so100_medicine_0605","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1400,"train_windows":1400,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.197266,-2.285156,-2.460938,-2.285156,-0.185874],"action_q99":[1.582031,2.900391,2.460938,2.988281,2.636719,29.182158],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.373047,80.419922,65.578711,-5.976562,-111.520898,-0.097182],"state_q99":[34.101562,183.427734,179.384766,92.460938,10.722656,28.66861]},
+ {"part":"pranavsaroha__so100_medicine_0605_test","origin":"molmoact","dataset":"pranavsaroha/so100_medicine_0605_test","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":20,"train_windows":20,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.300977,-4.042969,-5.201367,-6.591797,-5.800781,1.394052],"action_q99":[1.933594,4.721484,4.586133,5.728711,7.078711,27.853161],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.976562,102.392578,83.953125,10.659375,-106.433789,1.652089],"state_q99":[32.783203,179.296875,169.541016,97.781836,-0.249609,26.839651]},
+ {"part":"psg777__glue3","origin":"molmoact","dataset":"psg777/glue3","scene_camera":"observation.images.bird","fps":30.0,"built_clips":233,"train_windows":233,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.076172,-2.636719,-1.845703,-0.439453,-0.136612],"action_q99":[2.197266,2.373047,2.636719,1.845703,0.527344,31.010929],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-62.490234,29.092676,17.226562,10.546875,-114.433594,1.099656],"state_q99":[88.59375,187.558594,168.222656,105.292969,-87.099609,30.515465]},
+ {"part":"psg777__so100test1","origin":"molmoact","dataset":"psg777/so100test1","scene_camera":"observation.images.bird","fps":30.0,"built_clips":77,"train_windows":77,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.026953,-2.460938,-2.548828,-0.439453,-0.204918],"action_q99":[2.197266,2.939063,4.257422,1.845703,0.439453,33.606556],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.556641,42.011719,19.785937,56.594531,-4.130859,0.4811],"state_q99":[3.515625,188.349609,151.875,105.205078,-2.900391,32.852234]},
+ {"part":"ptizzza__so101_pompom","origin":"molmoact","dataset":"ptizzza/so101_pompom","scene_camera":"observation.images.realsense_RGB","fps":30.0,"built_clips":445,"train_windows":445,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.076172,-2.460938,-1.582031,-0.703125,-0.1001],"action_q99":[1.230469,2.548828,2.373047,1.757812,0.966797,45.545544],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.976562,44.594824,41.958105,45.122168,-36.210938,0.417246],"state_q99":[52.734375,179.296875,165.761719,93.251953,7.787988,45.340748]},
+ {"part":"ptizzza__so101_pompom1","origin":"molmoact","dataset":"ptizzza/so101_pompom1","scene_camera":"observation.images.realsense_RGB","fps":30.0,"built_clips":796,"train_windows":796,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.285156,-2.548828,-1.318359,-0.615234,-0.2002],"action_q99":[0.878906,2.021484,2.285156,1.494141,0.615234,32.532536],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.597656,23.115234,4.482422,38.320312,-16.700098,0.208623],"state_q99":[38.144531,178.681641,167.695312,101.425781,17.490234,32.475658]},
+ {"part":"ptizzza__so101_pompom_orange","origin":"molmoact","dataset":"ptizzza/so101_pompom_orange","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":708,"train_windows":708,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-3.076172,-2.724609,-1.054688,-0.966797,-0.079114],"action_q99":[1.230469,2.548828,2.021484,1.230469,1.318359,27.610762],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.861328,64.423828,56.162109,48.515625,-49.130859,0.773558],"state_q99":[23.994141,191.689453,176.923828,87.978516,-2.021484,27.004922]},
+ {"part":"ptizzza__so101_test2","origin":"molmoact","dataset":"ptizzza/so101_test2","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":100,"train_windows":100,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-3.603516,-2.988281,-1.845703,-1.142578,-0.1001],"action_q99":[1.230469,3.076172,2.373047,1.669922,0.966797,33.244246],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[4.394531,35.410254,36.5625,32.34375,-54.228516,0.417246],"state_q99":[60.732422,179.033203,165.849609,78.769336,4.130859,33.240612]},
+ {"part":"qiujun__so101_test","origin":"molmoact","dataset":"qiujun/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1504,"train_windows":1504,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-8.701172,-7.03125,-2.988281,-2.373047,-0.315706],"action_q99":[2.900391,5.537109,7.03125,3.076172,2.285156,26.519337],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.724609,27.246094,-0.087891,36.035156,-56.162109,0.404585],"state_q99":[15.029297,195.908203,180.175781,98.789062,9.052734,26.095751]},
+ {"part":"redravensama__so100_test","origin":"molmoact","dataset":"redravensama/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":36,"train_windows":36,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.653223,-4.21875,-7.190332,-2.373047,-1.21377,-0.182149],"action_q99":[1.389551,4.394531,5.240039,3.076172,0.703125,42.241347],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-19.901074,27.279492,-13.535156,58.886719,-29.33877,0.345542],"state_q99":[14.045801,182.988281,168.398438,104.238281,-10.85625,42.129924]},
+ {"part":"reedscot__so100_test4","origin":"molmoact","dataset":"reedscot/so100_test4","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1581,"train_windows":1581,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.900391,-2.460938,-2.548828,-2.900391,-3.018269],"action_q99":[2.109375,2.373047,2.988281,2.636719,2.900391,58.699059],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-51.092578,31.552734,1.669922,-34.657031,-94.482422,-1.281139],"state_q99":[53.729297,188.876953,178.330078,104.326172,86.748047,58.220914]},
+ {"part":"roboticshack__team-7-right-arm-grasp-tape","origin":"molmoact","dataset":"roboticshack/team-7-right-arm-grasp-tape","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":2011,"train_windows":2011,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.021484,-2.724609,-1.757812,-1.230469,-0.097656],"action_q99":[0.791016,2.460938,2.285156,1.669922,1.142578,55.761719],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.144531,33.046875,25.224609,18.105469,-110.039062,0.072202],"state_q99":[17.050781,186.679688,172.792969,100.458984,-51.591797,55.74007]},
+ {"part":"roboticshack__team13-three-balls-stacking","origin":"molmoact","dataset":"roboticshack/team13-three-balls-stacking","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":1798,"train_windows":1798,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-3.427734,-3.251953,-2.109375,-1.40625,-0.096805],"action_q99":[1.40625,4.21875,5.009766,2.460938,1.40625,71.636009],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.859375,66.005859,60.46875,31.904297,-105.117188,0.139958],"state_q99":[32.607422,191.425781,174.638672,100.634766,-56.425781,71.448563]},
+ {"part":"roboticshack__team13-two-balls-stacking","origin":"molmoact","dataset":"roboticshack/team13-two-balls-stacking","scene_camera":"observation.images.realsense","fps":30.0,"built_clips":463,"train_windows":463,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.779297,-4.042969,-1.582031,-1.230469,-0.096805],"action_q99":[2.285156,4.570312,4.482422,2.460938,1.142578,62.826717],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.419922,77.058105,92.900391,43.330078,-93.076172,0.139958],"state_q99":[6.152344,191.425781,173.408203,82.792969,-65.566406,63.051086]},
+ {"part":"rocach94__so101_Test","origin":"molmoact","dataset":"rocach94/so101_Test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.703125,-2.900391,-1.749023,-1.318359,-0.518555,-0.329761],"action_q99":[1.142578,1.845703,1.318359,1.230469,0.342773,21.838417],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-8.173828,98.182617,111.990234,39.814453,-6.855469,0.686695],"state_q99":[22.763672,198.017578,177.451172,80.771484,9.474609,21.888412]},
+ {"part":"rocach94__so101_bin_and_wheel_is_changing_dynamically","origin":"molmoact","dataset":"rocach94/so101_bin_and_wheel_is_changing_dynamically","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":790,"train_windows":790,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.988281,-2.109375,-2.460938,-1.669922,-0.989283],"action_q99":[1.318359,2.636719,2.373047,2.8125,1.669922,24.81451],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.726562,38.408203,31.289062,7.822266,-47.724609,0.171674],"state_q99":[47.888086,198.720703,177.966211,86.308594,59.765625,24.46352]},
+ {"part":"rocach94__so101_data1","origin":"molmoact","dataset":"rocach94/so101_data1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":446,"train_windows":446,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-3.251953,-1.933594,-1.582031,-2.109375,-1.896125],"action_q99":[1.230469,1.40625,1.582031,1.318359,2.021484,27.287716],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.169922,53.242383,47.636719,21.387305,-26.474414,-0.600858],"state_q99":[28.583789,198.105469,177.978516,88.769531,74.53125,26.952789]},
+ {"part":"rocach94__so101_data2","origin":"molmoact","dataset":"rocach94/so101_data2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":891,"train_windows":891,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.076172,-2.109375,-1.582031,-2.021484,-1.896125],"action_q99":[1.054688,2.285156,2.285156,1.757812,1.933594,20.197857],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.255859,35.231836,20.654297,32.94668,-63.418359,-0.686695],"state_q99":[34.101562,198.369141,177.890625,88.769531,65.754492,19.914164]},
+ {"part":"rocach94__so101_dataset_v1","origin":"molmoact","dataset":"rocach94/so101_dataset_v1","scene_camera":"observation.images.phone","fps":30.0,"built_clips":801,"train_windows":801,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-2.988281,-2.197266,-1.933594,-2.197266,-0.824402],"action_q99":[0.966797,2.460938,2.8125,2.021484,2.460938,18.301731],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.609375,48.867188,36.386719,32.301562,-23.554688,0.257511],"state_q99":[27.926367,198.457031,177.978516,83.320312,88.505859,18.283262]},
+ {"part":"rocach94__so101_dataset_v2","origin":"molmoact","dataset":"rocach94/so101_dataset_v2","scene_camera":"observation.images.phone","fps":30.0,"built_clips":712,"train_windows":712,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.636719,-2.068066,-2.021484,-2.636719,0.659522],"action_q99":[1.054688,2.724609,2.900391,2.021484,3.427734,18.13685],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-28.786816,54.305859,42.275391,31.066699,-18.808594,1.287554],"state_q99":[36.210938,198.544922,177.802734,98.173828,107.578125,17.76824]},
+ {"part":"rocach94__so101_dataset_v3_with_wall","origin":"molmoact","dataset":"rocach94/so101_dataset_v3_with_wall","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":862,"train_windows":862,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.724609,-1.933594,-1.933594,-1.054688,-1.071723],"action_q99":[1.230469,2.285156,2.373047,2.109375,1.054688,21.18714],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.044922,48.691406,30.761719,18.358594,-26.015625,0.171674],"state_q99":[46.669922,198.720703,177.978516,95.537109,43.07168,20.944206]},
+ {"part":"rshoff__so101_test_2","origin":"molmoact","dataset":"rshoff/so101_test_2","scene_camera":"observation.images.pole","fps":30.0,"built_clips":59,"train_windows":59,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.562891,-3.178125,-2.900391,-2.460938,-1.669922,-0.419111],"action_q99":[3.603516,3.691406,3.719531,2.650781,2.460938,21.13663],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.894531,48.501562,16.846875,45.372656,-76.816406,0.410959],"state_q99":[40.714453,194.150391,179.384766,101.25,10.676953,20.958904]},
+ {"part":"ruanwz__so101_test","origin":"molmoact","dataset":"ruanwz/so101_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":598,"train_windows":598,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.548828,-3.603516,-1.054688,-4.658203,-5.273438,-6.313131],"action_q99":[1.582031,4.658203,1.318359,6.503906,4.921875,33.080807],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-13.535156,63.632812,150.029297,-84.638672,-9.667969,-3.045685],"state_q99":[47.019727,200.126953,181.582031,62.666016,96.064453,32.993231]},
+ {"part":"ryanpennings__so100_pegcrate_c2","origin":"molmoact","dataset":"ryanpennings/so100_pegcrate_c2","scene_camera":"observation.images.topcamera","fps":30.0,"built_clips":527,"train_windows":527,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.339844,-5.079199,-4.570312,-4.746094,-5.097656,-2.445652],"action_q99":[3.251953,4.658203,4.130859,5.694434,4.570312,23.641304],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-78.310547,48.515625,49.870898,-38.440723,-176.660156,0.564061],"state_q99":[79.346777,192.832031,178.857422,95.870215,31.969336,23.287672]},
+ {"part":"ryanpennings__so100_pegcrate_c3","origin":"molmoact","dataset":"ryanpennings/so100_pegcrate_c3","scene_camera":"observation.images.topcamera","fps":30.0,"built_clips":379,"train_windows":379,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-5.273438,-4.746094,-5.185547,-5.185547,-3.07971],"action_q99":[3.166699,3.515625,3.339844,3.078809,4.921875,25.724638],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.691406,57.216797,63.457031,-29.53125,-166.728516,0.644641],"state_q99":[55.195312,192.832031,178.945312,98.176465,5.537109,25.302176]},
+ {"part":"ryanpennings__so100_pegcrate_d1a","origin":"molmoact","dataset":"ryanpennings/so100_pegcrate_d1a","scene_camera":"observation.images.topcamera","fps":30.0,"built_clips":25,"train_windows":25,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.845703,-3.774902,-3.247559,-2.548828,-3.076172,-1.625587],"action_q99":[1.841309,3.862793,4.042969,3.155273,3.946289,23.122066],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-12.392578,47.460938,51.328125,-33.222656,-88.59375,0.268097],"state_q99":[32.695312,190.283203,176.132812,92.724609,5.800781,22.783736]},
+ {"part":"ryanpennings__so100_pegcrate_d1b","origin":"molmoact","dataset":"ryanpennings/so100_pegcrate_d1b","scene_camera":"observation.images.topcamera","fps":30.0,"built_clips":539,"train_windows":539,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.691406,-2.900391,-3.691406,-5.361328,-1.877934],"action_q99":[2.548828,3.515625,2.988281,4.042969,3.955078,23.82629],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-65.970703,56.162109,66.041016,-57.041016,-104.554688,-0.178731],"state_q99":[51.767578,190.195312,175.957031,76.289062,11.865234,22.788204]},
+ {"part":"samanthalhy__so100_herding_1","origin":"molmoact","dataset":"samanthalhy/so100_herding_1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1645,"train_windows":1645,"val_windows":12,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-0.966797,-1.142578,-1.054688,-3.955078,-0.448934],"action_q99":[1.318359,1.582031,1.933594,1.142578,3.691406,15.039282],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.445312,54.755859,58.271484,62.841797,-176.660156,-0.149142],"state_q99":[26.191406,109.951172,123.574219,94.306641,1.582031,15.212528]},
+ {"part":"samsitol__so100_PnP","origin":"molmoact","dataset":"samsitol/so100_PnP","scene_camera":"observation.images.head","fps":30.0,"built_clips":753,"train_windows":753,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-4.21875,-3.779297,-3.779297,-2.021484,-1.845703,-0.111857],"action_q99":[3.164062,3.339844,3.427734,2.460938,2.548828,41.051453],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-62.423437,7.294922,-17.753906,33.686719,115.224609,0.838223],"state_q99":[98.613281,186.855469,172.705078,93.076172,197.092969,40.150879]},
+ {"part":"samsitol__so100_PnP01","origin":"molmoact","dataset":"samsitol/so100_PnP01","scene_camera":"observation.images.head","fps":30.0,"built_clips":397,"train_windows":397,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.867188,-4.306641,-2.285156,-2.021484,-0.111857],"action_q99":[1.933594,3.691406,4.21875,2.548828,1.933594,43.624161],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-71.64668,10.371094,-18.808594,35.771484,121.552734,0.754401],"state_q99":[75.777539,187.207031,172.705078,92.548828,212.167969,43.000839]},
+ {"part":"samsitol__so100_PnPacorn","origin":"molmoact","dataset":"samsitol/so100_PnPacorn","scene_camera":"observation.images.head","fps":30.0,"built_clips":2808,"train_windows":2808,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-2.900391,-2.724609,-2.373047,-1.669922,-0.106838],"action_q99":[2.636719,2.900391,2.8125,2.900391,2.109375,55.876072],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-72.464941,27.994043,5.185547,-22.5,20.917969,0.191205],"state_q99":[95.273438,179.121094,166.728516,105.644531,110.214844,55.782983]},
+ {"part":"samsitol__so100_PnPblock","origin":"molmoact","dataset":"samsitol/so100_PnPblock","scene_camera":"observation.images.head","fps":30.0,"built_clips":1011,"train_windows":1011,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.900391,-3.164062,-2.988281,-2.021484,-1.494141,-0.111857],"action_q99":[2.548828,3.076172,2.8125,2.109375,1.845703,38.702461],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.551563,20.039062,0.710156,20.830078,101.601562,0.838223],"state_q99":[97.119141,187.119141,172.705078,93.164062,192.216797,38.474434]},
+ {"part":"samsitol__so100_PnPfixed","origin":"molmoact","dataset":"samsitol/so100_PnPfixed","scene_camera":"observation.images.head","fps":30.0,"built_clips":387,"train_windows":387,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.867188,-3.603516,-3.691406,-1.933594,-1.582031,-0.111857],"action_q99":[3.164062,3.691406,3.515625,2.460938,2.548828,54.809845],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.62041,16.083984,-6.943359,33.222656,128.320312,0.838223],"state_q99":[99.140625,187.119141,172.617188,92.460938,187.046191,54.596813]},
+ {"part":"samsitol__so100_PnPred","origin":"molmoact","dataset":"samsitol/so100_PnPred","scene_camera":"observation.images.head","fps":30.0,"built_clips":350,"train_windows":350,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.427734,-2.988281,-2.900391,-1.933594,-1.582031,-0.111857],"action_q99":[2.724609,3.251953,2.8125,2.109375,2.109375,41.275169],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.646484,26.71875,5.315625,34.846875,99.931641,1.005868],"state_q99":[96.152344,189.667969,172.617188,93.251953,197.367188,41.15675]},
+ {"part":"samsitol__so100_boarduni","origin":"molmoact","dataset":"samsitol/so100_boarduni","scene_camera":"observation.images.head","fps":30.0,"built_clips":3094,"train_windows":3094,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.285156,-2.373047,-1.757812,-1.054688,-0.106838],"action_q99":[1.054688,2.548828,2.636719,1.669922,1.142578,47.008549],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-77.871094,15.380859,-15.292969,9.667969,15.820312,0.191205],"state_q99":[68.730469,178.857422,166.289062,105.820312,147.480469,46.749523]},
+ {"part":"samsitol__so100_test","origin":"molmoact","dataset":"samsitol/so100_test","scene_camera":"observation.images.head","fps":30.0,"built_clips":76,"train_windows":76,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.039941,-4.519336,-5.204004,-2.743066,-2.197266,-0.111857],"action_q99":[2.636719,4.306641,4.306641,2.724609,2.021484,47.362417],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-64.248047,20.039062,0.439453,27.861328,85.517578,0.754401],"state_q99":[42.802734,186.591797,173.056641,92.373047,189.667969,47.44342]},
+ {"part":"samsitol__so101_test3","origin":"molmoact","dataset":"samsitol/so101_test3","scene_camera":"observation.images.head","fps":30.0,"built_clips":46,"train_windows":46,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.197266,-2.900391,-1.865039,-1.337695,0.120627],"action_q99":[1.337695,2.109375,1.845703,2.285156,1.933594,38.35947],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.299414,64.951172,34.716797,42.969727,-41.679492,1.240876],"state_q99":[23.486133,185.009766,171.210938,98.173828,65.039062,38.029198]},
+ {"part":"samsitol__so101_test5","origin":"molmoact","dataset":"samsitol/so101_test5","scene_camera":"observation.images.head","fps":30.0,"built_clips":154,"train_windows":154,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-4.710938,-4.833984,-2.285156,-2.460938,0.120627],"action_q99":[2.25,4.183594,4.042969,2.8125,2.900391,38.118214],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.291016,17.578125,-19.248047,17.753906,-42.169922,1.167883],"state_q99":[69.169922,185.097656,171.650391,98.173828,87.134766,37.883213]},
+ {"part":"sbyang19__so100_test_apple","origin":"molmoact","dataset":"sbyang19/so100_test_apple","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":78,"train_windows":78,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-3.427734,-4.44375,-2.109375,-1.543359,-0.104384],"action_q99":[0.966797,3.427734,3.251953,2.373047,2.246484,89.039665],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.799219,8.789062,-5.058984,-9.580078,-2.021484,0.334169],"state_q99":[34.980469,192.568359,175.517578,103.095703,107.666016,89.306602]},
+ {"part":"sbyang19__so100_test_cards","origin":"molmoact","dataset":"sbyang19/so100_test_cards","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":86,"train_windows":86,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-2.988281,-2.988281,-1.40625,-1.40625,-0.104384],"action_q99":[1.142578,3.17373,3.076172,1.669922,1.933594,75.574112],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.36123,27.148535,6.152344,51.591797,13.359375,0.417711],"state_q99":[13.095703,191.865234,171.123047,103.095703,112.412109,75.271515]},
+ {"part":"sbyang19__so100_test_marker","origin":"molmoact","dataset":"sbyang19/so100_test_marker","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":89,"train_windows":89,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-3.251953,-2.988281,-1.582031,-1.318359,-0.208768],"action_q99":[1.142578,2.724609,3.059473,1.757812,1.741113,61.06472],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-59.414062,13.710938,-5.888672,48.076172,26.999121,0.417711],"state_q99":[31.975488,191.953125,172.353516,103.095703,119.247363,60.735172]},
+ {"part":"senjougi__so100_test1","origin":"molmoact","dataset":"senjougi/so100_test1","scene_camera":"observation.images.camera","fps":30.0,"built_clips":40,"train_windows":40,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.109375,-1.318359,-1.40625,-1.142578,-0.221729],"action_q99":[0.971191,2.109375,1.933594,0.966797,0.791016,35.25499],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[50.888672,81.28125,95.185547,54.667969,-10.722656,0.0],"state_q99":[98.525391,186.591797,167.958984,96.152344,30.761719,34.933887]},
+ {"part":"senjougi__so100_test3","origin":"molmoact","dataset":"senjougi/so100_test3","scene_camera":"observation.images.camera","fps":30.0,"built_clips":44,"train_windows":44,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-3.691406,-2.731641,-1.318359,-0.703125,-0.443459],"action_q99":[0.703125,2.197266,1.673437,1.409766,0.703125,72.505547],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[51.152344,81.914062,85.253906,66.621094,-16.611328,0.0],"state_q99":[101.337891,186.416016,166.201172,101.513672,40.605469,72.233818]},
+ {"part":"seonixx__so100_test_v3","origin":"molmoact","dataset":"seonixx/so100_test_v3","scene_camera":"observation.images.top","fps":30.0,"built_clips":1360,"train_windows":1360,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-3.603516,-3.603516,-1.845703,-1.494141,-0.26455],"action_q99":[1.230469,3.164062,3.691406,2.109375,1.494141,34.391533],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.580078,35.15625,29.436328,-10.634766,-4.306641,0.420875],"state_q99":[53.964844,193.623047,176.572266,80.595703,83.496094,34.090908]},
+ {"part":"seonixx__so100_test_v3_small_1c","origin":"molmoact","dataset":"seonixx/so100_test_v3_small_1c","scene_camera":"observation.images.top","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-3.353906,-3.339844,-1.582031,-1.596094,-0.26455],"action_q99":[1.054688,3.427734,3.955078,1.933594,1.230469,36.507938],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.400391,29.123438,21.796875,-2.460938,-5.625,0.420875],"state_q99":[13.123828,193.710938,179.560547,73.476562,47.197266,35.983165]},
+ {"part":"sergiov2000__so100_ball_leader_40","origin":"molmoact","dataset":"sergiov2000/so100_ball_leader_40","scene_camera":"observation.images.above","fps":30.0,"built_clips":846,"train_windows":846,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.669922,-1.845703,-0.791016,-0.527344,-0.715746],"action_q99":[1.142578,1.494141,1.494141,0.966797,0.439453,45.320041],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.921875,85.253906,69.873047,27.333984,-9.755859,0.910596],"state_q99":[14.501953,184.130859,182.900391,79.737012,10.634766,45.115894]},
+ {"part":"sergiov2000__so100_dataset3_test","origin":"molmoact","dataset":"sergiov2000/so100_dataset3_test","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-2.655176,-1.933594,-1.494141,-1.073145,-0.817996],"action_q99":[1.688379,2.127832,2.127832,1.161035,0.966797,50.123721],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.27041,64.863281,79.716797,37.792969,-10.829004,-0.557769],"state_q99":[77.52832,186.943359,179.384766,78.046875,20.214844,49.792032]},
+ {"part":"sergiov2000__so100_dataset5","origin":"molmoact","dataset":"sergiov2000/so100_dataset5","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":679,"train_windows":679,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.251953,-3.251953,-3.603516,-1.845703,-1.318359,-0.920245],"action_q99":[2.565527,2.724609,3.251953,1.757812,1.757812,32.125766],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.103516,47.548828,50.097656,37.089844,-33.837891,-0.557769],"state_q99":[74.179688,187.03125,179.648438,96.152344,34.892578,31.872511]},
+ {"part":"sergiov2000__so100_lego_and_ball_40_ball","origin":"molmoact","dataset":"sergiov2000/so100_lego_and_ball_40_ball","scene_camera":"observation.images.above","fps":30.0,"built_clips":892,"train_windows":892,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.582031,-1.669922,-0.791016,-0.439453,-0.715746],"action_q99":[1.142578,1.582031,1.494141,0.791016,0.439453,30.470348],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.449219,74.003906,69.609375,35.507812,-18.914941,-0.496689],"state_q99":[9.316406,183.691406,185.976562,80.683594,6.679688,30.298014]},
+ {"part":"sergiov2000__so100_lego_and_ball_40_lego","origin":"molmoact","dataset":"sergiov2000/so100_lego_and_ball_40_lego","scene_camera":"observation.images.above","fps":30.0,"built_clips":976,"train_windows":976,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.669922,-1.757812,-0.878906,-0.527344,-0.715746],"action_q99":[1.230469,1.845703,1.669922,0.878906,0.527344,28.016359],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-50.449219,64.863281,64.951172,33.75,-21.806543,-0.662252],"state_q99":[10.634766,183.691406,186.064453,79.628906,8.525391,28.228477]},
+ {"part":"sergiov2000__so100_lego_leader_40","origin":"molmoact","dataset":"sergiov2000/so100_lego_leader_40","scene_camera":"observation.images.above","fps":30.0,"built_clips":775,"train_windows":775,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.845703,-2.021484,-0.878906,-0.615234,-0.715746],"action_q99":[1.230469,1.933594,1.933594,0.966797,0.615234,31.697342],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.482422,70.292285,56.865234,31.552734,-21.972656,0.910596],"state_q99":[14.765625,184.482422,182.988281,83.935547,21.09375,31.972681]},
+ {"part":"sergiov2000__so100_movella_stack_ball_test","origin":"molmoact","dataset":"sergiov2000/so100_movella_stack_ball_test","scene_camera":"observation.images.above","fps":30.0,"built_clips":19,"train_windows":19,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.662792,-4.789358,-4.457692,-4.903805,-3.004077,0.971732],"action_q99":[2.898393,4.396821,4.696757,3.981524,3.93762,33.076511],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.818359,84.550781,90.718066,22.324219,-0.263672,2.533532],"state_q99":[3.076172,170.653711,142.646484,78.662109,42.172559,32.935917]},
+ {"part":"sergiov2000__so100_test","origin":"molmoact","dataset":"sergiov2000/so100_test","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":40,"train_windows":40,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.126074,-2.988281,-2.213965,-1.142578,-0.703125,-1.124744],"action_q99":[2.109375,1.845703,1.422949,1.142578,1.054688,25.664621],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.361328,65.126953,79.716797,36.123047,-28.652344,-0.796813],"state_q99":[80.595703,186.679688,179.736328,85.546582,7.734375,25.65737]},
+ {"part":"sergiov2000__so100_test_red_2ep","origin":"molmoact","dataset":"sergiov2000/so100_test_red_2ep","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":45,"train_windows":45,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.878906,-3.164062,-2.996191,-0.966797,-0.791016,-0.920245],"action_q99":[1.230469,1.669922,1.757812,0.703125,1.054688,24.037832],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.396484,60.820312,68.179395,45.966797,-7.998047,-0.413907],"state_q99":[18.017578,186.775488,182.460938,80.787305,17.402344,24.096854]},
+ {"part":"sergiov2000__so100_test_yellow_3ep","origin":"molmoact","dataset":"sergiov2000/so100_test_yellow_3ep","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":47,"train_windows":47,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-2.8125,-3.076172,-1.473926,-1.318359,-0.920245],"action_q99":[1.582031,2.636719,2.968066,1.318359,1.142578,38.273006],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.066406,63.457031,73.037109,42.119824,-33.310547,-0.413907],"state_q99":[2.021484,186.855469,182.460938,84.841699,4.130859,37.138245]},
+ {"part":"sergiov2000__temp_test_red_2ep","origin":"molmoact","dataset":"sergiov2000/temp_test_red_2ep","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":38,"train_windows":38,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-1.866797,-1.582031,-0.966797,-0.636328,-0.817996],"action_q99":[1.318359,2.197266,2.569922,0.703125,0.9,19.120655],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.208984,64.160156,79.804688,46.845703,-6.767578,-0.496689],"state_q99":[24.015234,187.052344,181.933594,82.177734,27.421875,18.874172]},
+ {"part":"sergiov2000__temp_test_yellow_2ep","origin":"molmoact","dataset":"sergiov2000/temp_test_yellow_2ep","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":42,"train_windows":42,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.791016,-1.582031,-1.669922,-0.791016,-0.615234,-0.817996],"action_q99":[1.161914,1.933594,1.95293,0.791016,0.527344,23.642128],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.579883,65.879297,70.927734,45.263672,-23.593359,-0.496689],"state_q99":[1.230469,187.119141,182.460938,90.527344,-1.142578,23.528145]},
+ {"part":"sergiov2000__test_5_rubik_cube","origin":"molmoact","dataset":"sergiov2000/test_5_rubik_cube","scene_camera":"observation.images.side","fps":30.0,"built_clips":101,"train_windows":101,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-1.845703,-2.197266,-1.066992,-1.142578,-0.920245],"action_q99":[0.791016,2.297461,2.460938,1.054688,0.703125,44.274029],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-5.625,66.005859,60.292969,50.097656,-42.099609,0.248344],"state_q99":[27.070312,186.767578,191.162109,93.61582,3.339844,44.039734]},
+ {"part":"sergiov2000__test_green_10_episodes","origin":"molmoact","dataset":"sergiov2000/test_green_10_episodes","scene_camera":"observation.images.above","fps":30.0,"built_clips":148,"train_windows":148,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.460938,-2.652539,-1.494141,-0.966797,-0.920245],"action_q99":[1.494141,2.460938,2.300977,1.40625,0.878906,40.593048],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.531445,61.962891,64.072266,27.829688,-28.476562,-0.57947],"state_q99":[12.216797,186.503906,182.460938,88.681641,6.168164,40.427152]},
+ {"part":"sergiov2000__test_red_50_episodes","origin":"molmoact","dataset":"sergiov2000/test_red_50_episodes","scene_camera":"observation.images.above","fps":30.0,"built_clips":1027,"train_windows":1027,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.109375,-2.109375,-1.142578,-0.703125,-0.920245],"action_q99":[1.40625,2.460938,2.197266,1.054688,0.703125,32.515339],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.779297,53.701172,57.304688,36.914062,-16.435547,-0.57947],"state_q99":[15.183105,186.679688,182.460938,85.341797,13.095703,32.284767]},
+ {"part":"sergiov2000__test_yellow_50_episodes","origin":"molmoact","dataset":"sergiov2000/test_yellow_50_episodes","scene_camera":"observation.images.above","fps":30.0,"built_clips":1019,"train_windows":1019,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.230469,-2.285156,-2.373047,-1.230469,-0.703125,-0.920245],"action_q99":[1.318359,2.285156,2.109375,1.230469,0.791016,33.946831],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.427734,57.304688,59.326172,29.443359,-15.908203,-0.57947],"state_q99":[14.677734,186.679688,182.548828,85.956152,15.205078,34.023178]},
+ {"part":"sergiov2000__yellow_20_episodes","origin":"molmoact","dataset":"sergiov2000/yellow_20_episodes","scene_camera":"observation.images.blackboard","fps":30.0,"built_clips":453,"train_windows":453,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-1.757812,-1.669922,-0.966797,-0.654785,-0.920245],"action_q99":[1.230469,2.197266,1.933594,0.791016,0.615234,25.869122],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.548828,60.732422,69.521484,38.759766,-20.742188,-0.57947],"state_q99":[17.929688,186.767578,183.339844,82.353516,16.699219,25.865066]},
+ {"part":"shawntan72__pick_and_place_pill_bottle_1","origin":"molmoact","dataset":"shawntan72/pick_and_place_pill_bottle_1","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":1036,"train_windows":1036,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.142578,-1.933594,-1.054688,-2.460938,-1.054688,0.0],"action_q99":[0.966797,2.285156,1.318359,2.8125,1.230469,54.682777],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.703125,47.789648,108.632812,-81.123047,153.050098,0.686342],"state_q99":[28.476562,191.865234,174.726562,77.607422,190.986328,54.838711]},
+ {"part":"shawntan72__pick_and_place_pill_bottle_2","origin":"molmoact","dataset":"shawntan72/pick_and_place_pill_bottle_2","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":471,"train_windows":471,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.197266,-1.669922,-3.251953,-1.142578,-0.100705],"action_q99":[1.230469,2.900391,1.669922,3.779297,1.230469,55.186302],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-54.387598,39.58418,73.388672,-86.89043,167.53623,0.82361],"state_q99":[30.585938,191.689453,174.726562,79.189453,200.390625,55.113243]},
+ {"part":"shawntan72__pick_and_place_pill_bottle_3","origin":"molmoact","dataset":"shawntan72/pick_and_place_pill_bottle_3","scene_camera":"observation.images.overhead","fps":30.0,"built_clips":783,"train_windows":783,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.076172,-2.988281,-3.691406,-1.40625,-0.100705],"action_q99":[1.845703,4.394531,2.636719,5.625,1.40625,53.776436],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-64.599609,36.123047,56.214844,-94.482422,159.345703,0.686342],"state_q99":[27.615234,191.601562,174.902344,79.277344,200.953125,53.740562]},
+ {"part":"shylee__so100_cube","origin":"molmoact","dataset":"shylee/so100_cube","scene_camera":"observation.images.WristCam","fps":30.0,"built_clips":2033,"train_windows":2033,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.164062,-3.251953,-0.527344,-1.054688,-0.096246],"action_q99":[1.582031,2.109375,1.40625,1.582031,0.966797,33.686237],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.056641,22.412109,-4.823437,42.363281,-42.802734,0.314218],"state_q99":[54.052734,181.669922,172.617188,103.007812,31.640625,33.454833]},
+ {"part":"shylee__so100_cup","origin":"molmoact","dataset":"shylee/so100_cup","scene_camera":"observation.images.phone","fps":30.0,"built_clips":1378,"train_windows":1378,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.988281,-2.900391,-2.460938,-1.757812,-2.988281,-1.740812],"action_q99":[3.339844,4.394531,4.394531,2.724609,2.021484,37.427467],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-77.871094,-5.185547,6.328125,45.263672,-106.166602,0.139276],"state_q99":[75.498047,151.171875,167.341113,103.007812,39.287109,37.116993]},
+ {"part":"shylee__so100_cup_test","origin":"molmoact","dataset":"shylee/so100_cup_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":11,"train_windows":11,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.527344,-4.433203,-3.730078,-1.835156,-3.933984,-1.934236],"action_q99":[2.285156,4.433203,4.257422,2.5875,0.829687,27.36944],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-4.394531,-4.872656,6.416016,45.752344,-113.027344,-0.487465],"state_q99":[59.677734,155.390625,163.916016,102.568359,-0.049219,27.228413]},
+ {"part":"shylee__so100_gauze","origin":"molmoact","dataset":"shylee/so100_gauze","scene_camera":"observation.images.WristCam","fps":30.0,"built_clips":1408,"train_windows":1408,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-4.21875,-4.306641,-0.878906,-2.285156,-0.096246],"action_q99":[1.933594,2.636719,1.845703,2.373047,1.757812,42.348412],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.341797,13.623047,-11.074219,42.363281,-91.845703,0.392773],"state_q99":[47.636719,181.757812,172.617188,103.271484,50.273438,41.71249]},
+ {"part":"shylee__so100_gauze_test","origin":"molmoact","dataset":"shylee/so100_gauze_test","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":11,"train_windows":11,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.952734,-1.494141,-1.142578,-0.952734,-0.351562,0.0],"action_q99":[0.439453,0.966797,0.527344,1.128516,0.703125,29.162657],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.785156,79.541016,60.292969,55.810547,-11.25,0.549882],"state_q99":[16.787109,181.494141,168.574219,97.910156,27.597656,28.750982]},
+ {"part":"shylee__so100_gauze_test2","origin":"molmoact","dataset":"shylee/so100_gauze_test2","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":10,"train_windows":10,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.641992,-2.243848,-0.878906,-0.573926,0.096246],"action_q99":[0.703125,1.10127,1.10127,1.452832,0.966797,26.564005],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.34375,79.892578,59.238281,59.532715,-15.866895,0.549882],"state_q99":[26.542969,181.494141,167.519531,102.832031,28.828125,26.31579]},
+ {"part":"shylee__so100_pengrip","origin":"molmoact","dataset":"shylee/so100_pengrip","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":1805,"train_windows":1805,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-4.042969,-4.130859,-1.054688,-1.757812,-0.096246],"action_q99":[2.021484,2.8125,1.845703,2.109375,1.582031,36.766121],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.935547,21.005859,-6.767578,42.363281,-92.109375,0.0],"state_q99":[42.099609,181.669922,172.617188,103.095703,44.472656,35.035351]},
+ {"part":"shylee__so100_pengripA","origin":"molmoact","dataset":"shylee/so100_pengripA","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":1879,"train_windows":1879,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.943262,-4.042969,-4.130859,-1.318359,-2.021484,-0.096246],"action_q99":[2.021484,2.8125,2.109375,2.197266,1.757812,36.092396],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-41.132812,21.09375,-7.919824,39.111328,-93.339844,0.0],"state_q99":[47.724609,181.669922,172.617188,103.095703,40.351465,34.406914]},
+ {"part":"shylee__so100_pengripB","origin":"molmoact","dataset":"shylee/so100_pengripB","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":242,"train_windows":242,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-3.515625,-3.61582,-1.142578,-1.757812,-0.189036],"action_q99":[1.845703,2.373047,1.669922,2.021484,1.582031,29.300568],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-43.505859,21.244922,-12.216797,43.417969,-107.161523,0.285103],"state_q99":[68.452734,189.755859,177.890625,104.0625,50.185547,27.898788]},
+ {"part":"shylee__so100_pengripF","origin":"molmoact","dataset":"shylee/so100_pengripF","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":1938,"train_windows":1938,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-4.394531,-3.867188,-1.669922,-2.460938,-0.189036],"action_q99":[2.197266,2.460938,1.669922,2.373047,2.285156,35.160683],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-60.556641,27.861328,-0.966797,34.541016,-117.421875,2.993585],"state_q99":[61.640332,189.667969,177.802734,103.886719,45.351562,34.283676]},
+ {"part":"shylee__so100_pengripG","origin":"molmoact","dataset":"shylee/so100_pengripG","scene_camera":"observation.images.TopCam","fps":30.0,"built_clips":2095,"train_windows":2095,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.955078,-4.21875,-0.878906,-1.40625,0.096061],"action_q99":[2.109375,2.636719,1.582031,2.285156,1.582031,40.441883],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-47.373047,28.388672,12.216797,35.859375,-47.373047,0.628931],"state_q99":[53.407617,190.634766,180.351562,96.855469,45.351562,39.203354]},
+ {"part":"sincostangerines__purple_dice","origin":"molmoact","dataset":"sincostangerines/purple_dice","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":710,"train_windows":710,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.636719,-2.197266,-1.757812,-1.757812,0.087951],"action_q99":[1.318359,2.8125,2.548828,2.021484,1.582031,26.033422],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-26.806641,63.808594,58.673145,16.468945,0.087891,0.675219],"state_q99":[54.140625,182.8125,175.429688,86.132812,82.86416,26.266035]},
+ {"part":"sincostangerines__six_dice","origin":"molmoact","dataset":"sincostangerines/six_dice","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":498,"train_windows":498,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.054688,-3.164062,-2.724609,-1.40625,-1.845703,0.087951],"action_q99":[0.966797,2.988281,2.548828,1.494141,1.669922,30.870712],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-21.181641,65.039062,80.068359,42.451172,-6.943359,0.742741],"state_q99":[30.9375,182.373047,173.847656,84.947168,83.935547,31.127617]},
+ {"part":"sincostangerines__stack_cubes_70","origin":"molmoact","dataset":"sincostangerines/stack_cubes_70","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":611,"train_windows":611,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.021484,-3.339844,-2.988281,-1.669922,-1.494141,-0.088417],"action_q99":[1.845703,2.636719,2.724609,1.845703,1.582031,47.480106],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-25.3125,65.214844,66.796875,57.041016,-55.634766,0.140056],"state_q99":[39.111328,184.746094,164.091797,98.789062,34.447852,47.268906]},
+ {"part":"sincostangerines__stack_cubes_p1","origin":"molmoact","dataset":"sincostangerines/stack_cubes_p1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":632,"train_windows":632,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-1.142578,-1.230469,-0.791016,-0.966797,-0.266904],"action_q99":[1.582031,1.669922,1.142578,0.791016,1.318359,53.113876],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.992188,57.191309,58.86123,84.814453,-33.248145,0.069541],"state_q99":[33.662109,117.773438,99.316406,104.589844,30.234375,53.07997]},
+ {"part":"sincostangerines__stack_cubes_p2","origin":"molmoact","dataset":"sincostangerines/stack_cubes_p2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":486,"train_windows":486,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-3.329297,-2.548828,-0.966797,-1.142578,-0.088968],"action_q99":[1.669922,2.021484,0.263672,1.582031,1.142578,53.380783],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-33.486328,79.980469,85.078125,69.433594,-31.289062,-0.069541],"state_q99":[40.957031,196.259766,173.496094,104.853516,31.816406,53.477051]},
+ {"part":"sincostangerines__stack_cubes_p3","origin":"molmoact","dataset":"sincostangerines/stack_cubes_p3","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":342,"train_windows":342,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-4.482422,-3.164062,-1.669922,-1.494141,-0.177936],"action_q99":[2.285156,3.515625,3.6,1.669922,1.582031,47.153027],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.462891,81.738281,81.298828,65.126953,-22.763672,-0.347705],"state_q99":[20.566406,195.205078,173.496094,104.677734,28.476562,46.870655]},
+ {"part":"sixpigs1__so100_pick_cube_in_box","origin":"molmoact","dataset":"sixpigs1/so100_pick_cube_in_box","scene_camera":"observation.images.above","fps":30.0,"built_clips":948,"train_windows":948,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-3.164062,-3.603516,-2.109375,-2.460938,0.09901],"action_q99":[1.582031,4.21875,4.482422,2.548828,2.197266,33.927722],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.742188,52.060254,43.242188,26.455078,-88.505859,0.073692],"state_q99":[48.486621,190.458984,176.748047,86.484375,7.734375,33.529846]},
+ {"part":"slowturtle99__so100_dataset","origin":"molmoact","dataset":"slowturtle99/so100_dataset","scene_camera":"observation.images.head_camera","fps":30.0,"built_clips":1530,"train_windows":1530,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-2.109375,-1.933594,-1.494141,-1.757812,0.171527],"action_q99":[1.669922,3.251953,3.603516,1.845703,1.494141,36.792454],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.880859,67.939453,70.488281,22.148438,-125.947266,0.534759],"state_q99":[43.066406,191.162109,177.363281,85.869141,-50.185547,36.720142]},
+ {"part":"slowturtle99__so100_dataset_2","origin":"molmoact","dataset":"slowturtle99/so100_dataset_2","scene_camera":"observation.images.head_camera","fps":30.0,"built_clips":1608,"train_windows":1608,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.900391,-3.251953,-2.548828,-2.197266,-2.285156,0.171527],"action_q99":[2.021484,4.482422,4.570312,3.164062,1.845703,37.993137],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.705078,73.476562,84.814453,20.039062,-104.318262,0.534759],"state_q99":[23.90625,191.074219,177.363281,77.958984,-48.611426,37.789661]},
+ {"part":"slowturtle99__so100_pick_place","origin":"molmoact","dataset":"slowturtle99/so100_pick_place","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":1307,"train_windows":1307,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.373047,-2.021484,-1.40625,-1.669922,0.171527],"action_q99":[1.669922,3.515625,3.779297,1.933594,1.494141,33.704975],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.726562,58.447266,64.248047,26.630859,-127.792969,0.623886],"state_q99":[46.176855,190.722656,177.275391,85.693359,-52.03125,33.511585]},
+ {"part":"slowturtle99__so100_pick_place_blocks","origin":"molmoact","dataset":"slowturtle99/so100_pick_place_blocks","scene_camera":"observation.images.top","fps":30.0,"built_clips":1316,"train_windows":1316,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.636719,-2.021484,-2.109375,-1.845703,-2.285156,0.081367],"action_q99":[2.285156,3.164062,3.076172,2.109375,1.933594,24.017088],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-44.648438,62.578125,71.542969,10.180371,-123.325488,0.357654],"state_q99":[39.990234,194.0625,180.439453,80.244141,-37.001953,23.891273]},
+ {"part":"slowturtle99__so100_test","origin":"molmoact","dataset":"slowturtle99/so100_test","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":824,"train_windows":824,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.197266,-1.845703,-1.318359,-1.142578,0.171527],"action_q99":[1.845703,2.548828,2.109375,2.197266,1.494141,33.248712],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-24.697266,68.143359,77.607422,13.826953,-124.365234,0.534759],"state_q99":[48.515625,190.898438,177.539062,87.802734,-3.867188,33.215688]},
+ {"part":"sshh11__so100_orange_50ep_1","origin":"molmoact","dataset":"sshh11/so100_orange_50ep_1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":521,"train_windows":521,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-7.119141,-7.294922,-3.251953,-3.251953,-0.683594],"action_q99":[2.900391,7.03125,7.382812,3.427734,3.076172,55.957031],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-39.287109,14.798145,-11.041699,33.310547,-81.354199,0.470958],"state_q99":[59.853516,192.832031,179.121094,94.394531,48.691406,54.631084]},
+ {"part":"sshh11__so100_orange_50ep_2","origin":"molmoact","dataset":"sshh11/so100_orange_50ep_2","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":498,"train_windows":498,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.339844,-5.888672,-5.800781,-3.515625,-5.273438,-0.585938],"action_q99":[3.164062,5.185547,4.921875,3.779297,5.273438,54.394531],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-49.658203,40.187109,16.959375,12.941016,-116.521875,0.470958],"state_q99":[57.392578,192.919922,180.966797,94.042969,54.407813,53.375198]},
+ {"part":"sshh11__so100_orange_50ep_2cam_2","origin":"molmoact","dataset":"sshh11/so100_orange_50ep_2cam_2","scene_camera":"observation.images.laptop2","fps":30.0,"built_clips":507,"train_windows":507,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.900391,-4.658203,-4.394531,-3.339844,-3.867188,-0.585938],"action_q99":[2.636719,5.009766,4.746094,3.427734,3.779297,40.039062],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-46.230469,24.194531,1.757812,-2.021484,-123.486328,0.549451],"state_q99":[54.348047,193.447266,181.40625,94.21875,35.419922,39.481945]},
+ {"part":"sshh11__so100_test","origin":"molmoact","dataset":"sshh11/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":24,"train_windows":24,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.40625,-2.130469,-2.482031,-1.589062,-1.40625,-0.292969],"action_q99":[1.494141,2.475,2.636719,1.318359,2.64375,21.5],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.684766,74.53125,47.787891,39.814453,-84.255469,0.549451],"state_q99":[34.853906,192.919922,181.318359,93.097266,5.712891,20.753531]},
+ {"part":"sshh11__so100_test_1","origin":"molmoact","dataset":"sshh11/so100_test_1","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.724609,-5.454492,-5.32002,-2.021484,-2.197266,-0.488281],"action_q99":[2.8125,5.542383,5.097656,2.636719,2.636719,53.027344],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.453125,25.736133,8.979785,49.570312,-44.208984,0.549451],"state_q99":[41.138086,193.183594,181.494141,94.394531,5.377148,52.668762]},
+ {"part":"sucrammal__plant_pour_data","origin":"molmoact","dataset":"sucrammal/plant_pour_data","scene_camera":"observation.images.phone","fps":30.0,"built_clips":829,"train_windows":829,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-4.042969,-2.197266,-5.273438,-0.966797,8.443541],"action_q99":[1.669922,2.988281,3.076172,3.339844,1.142578,100.915565],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.541016,33.046875,97.04707,-102.744141,-114.697266,15.02849],"state_q99":[42.890625,140.712891,172.529297,55.634766,-77.167969,100.071228]},
+ {"part":"sucrammal__plant_pour_test","origin":"molmoact","dataset":"sucrammal/plant_pour_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":49,"train_windows":49,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.757812,-2.894238,-2.021484,-4.482422,-1.40625,2.448627],"action_q99":[1.230469,2.373047,2.636719,4.212598,1.142578,80.548324],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-34.365234,28.125,81.650391,-102.919922,-113.812207,2.777778],"state_q99":[39.023438,137.724609,172.441406,34.686035,-73.043262,79.965813]},
+ {"part":"sucrammal__plant_pour_test_again","origin":"molmoact","dataset":"sucrammal/plant_pour_test_again","scene_camera":"observation.images.phone","fps":30.0,"built_clips":33,"train_windows":33,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.109375,-2.021484,-3.244043,-7.279102,16.785351],"action_q99":[1.933594,3.076172,3.164062,2.88457,7.462793,55.34079],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-20.126953,38.408203,108.457031,-103.271484,-152.929688,19.658119],"state_q99":[41.660156,106.435547,172.617188,-59.517773,-74.898633,56.572647]},
+ {"part":"suoxd123__so100_test","origin":"molmoact","dataset":"suoxd123/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":26,"train_windows":26,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.194434,-2.988281,-2.249121,-1.757812,-0.615234,-6.761566],"action_q99":[2.373047,1.545996,1.949414,1.494141,0.175781,43.238434],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.607422,40.517578,42.011719,64.335938,-28.300781,2.800908],"state_q99":[45.930762,186.767578,167.871094,65.039062,-6.767578,42.922028]},
+ {"part":"suoxd123__so100_test_0530_20","origin":"molmoact","dataset":"suoxd123/so100_test_0530_20","scene_camera":"observation.images.phone","fps":30.0,"built_clips":187,"train_windows":187,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.285156,-2.724609,-2.548828,-1.97666,-0.878906,-6.939502],"action_q99":[2.591895,2.460938,2.988281,1.845703,0.966797,47.730428],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-55.019531,17.578125,20.302734,63.632812,-40.78125,-2.422407],"state_q99":[44.07627,187.03125,182.460938,64.775391,4.261816,47.993942]},
+ {"part":"taiobot__so101_test8","origin":"molmoact","dataset":"taiobot/so101_test8","scene_camera":"observation.images.front","fps":30.0,"built_clips":522,"train_windows":522,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.691406,-4.21875,-2.8125,-2.109375,-0.599315],"action_q99":[1.318359,3.515625,3.515625,2.8125,2.285156,62.328766],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-48.339844,4.788281,14.150391,25.70625,-62.226562,0.227445],"state_q99":[70.797656,186.240234,170.595703,96.503906,26.015625,62.171343]},
+ {"part":"taxitain__so100_obj_to_bin_top0_180","origin":"molmoact","dataset":"taxitain/so100_obj_to_bin_top0_180","scene_camera":"observation.images.top0","fps":30.0,"built_clips":1284,"train_windows":1284,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.460938,-2.460938,-1.901953,-1.933594,7.214612],"action_q99":[2.021484,2.988281,3.164062,1.933594,2.373047,72.328766],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-98.613281,12.304688,0.703125,-27.949219,-69.433594,10.243902],"state_q99":[81.411328,189.84375,180.351562,102.65625,115.136719,71.49826]},
+ {"part":"taxitain__so100_obj_to_bin_v2","origin":"molmoact","dataset":"taxitain/so100_obj_to_bin_v2","scene_camera":"observation.images.top0","fps":30.0,"built_clips":1041,"train_windows":1041,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.373047,-3.427734,-3.251953,-2.548828,-2.988281,0.0],"action_q99":[2.460938,4.306641,4.570312,2.373047,2.900391,55.981739],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-92.551465,20.566406,7.116504,-49.759277,-126.545801,1.393728],"state_q99":[79.189453,190.107422,180.351562,97.998047,124.365234,55.74913]},
+ {"part":"tenkau__so101_block_stack","origin":"molmoact","dataset":"tenkau/so101_block_stack","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":155,"train_windows":155,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-1.933594,-1.845703,-2.021484,-1.582031,-1.082431],"action_q99":[2.373047,2.285156,3.515625,1.582031,1.22168,45.129059],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.598633,75.673828,64.696289,32.167969,-42.363281,-0.55905],"state_q99":[33.741211,191.25,177.1875,90.703125,15.1875,44.863731]},
+ {"part":"tenkau__so101_block_stack_kanzenrikai","origin":"molmoact","dataset":"tenkau/so101_block_stack_kanzenrikai","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":282,"train_windows":282,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.669922,-2.724609,-2.373047,-1.845703,-1.494141,-1.332223],"action_q99":[2.197266,2.021484,2.900391,1.757812,1.40625,47.710243],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-35.332031,59.765625,45.439453,30.322266,-45.615234,-0.628931],"state_q99":[35.15625,191.337891,177.539062,90.791016,12.480469,47.379456]},
+ {"part":"tenkau__so101_color_block","origin":"molmoact","dataset":"tenkau/so101_color_block","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1019,"train_windows":1019,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.933594,-2.8125,-2.285156,-2.197266,-2.285156,-1.582015],"action_q99":[1.933594,2.109375,2.988281,2.109375,2.460938,46.378021],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-52.822266,48.779297,34.804688,-27.070312,-117.861328,-0.908456],"state_q99":[60.644531,191.337891,177.626953,90.878906,17.753906,46.261356]},
+ {"part":"tenkau__so101ver4","origin":"molmoact","dataset":"tenkau/so101ver4","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":66,"train_windows":66,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.109375,-2.021484,-1.845703,-1.845703,-1.582031,-1.082431],"action_q99":[2.212207,1.845703,2.387988,1.669922,1.318359,54.204826],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.298828,66.181641,51.767578,35.244141,-48.999902,-0.489168],"state_q99":[44.356641,191.513672,177.1875,90.878906,24.169922,53.87841]},
+ {"part":"tfoldi__glasses_exp_5","origin":"molmoact","dataset":"tfoldi/glasses_exp_5","scene_camera":"observation.images.top","fps":30.0,"built_clips":272,"train_windows":272,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.133789,-4.394531,-4.658203,-3.251953,-2.109375,-0.276753],"action_q99":[0.878906,4.394531,5.088867,2.891602,2.636719,43.450184],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-40.429688,55.371094,28.142578,1.142578,-8.165039,1.385493],"state_q99":[17.393555,186.855469,175.157227,81.914062,86.220703,43.194782]},
+ {"part":"tobdeu__so100_block_to_bin","origin":"molmoact","dataset":"tobdeu/so100_block_to_bin","scene_camera":"observation.images.top_view","fps":30.0,"built_clips":540,"train_windows":540,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.076172,-3.555176,-2.900391,-1.845703,-2.109375,-0.175285],"action_q99":[2.460938,3.779297,3.427734,1.845703,2.197266,45.574059],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-12.480469,72.430664,77.831543,54.316406,-86.484375,0.348189],"state_q99":[70.400391,189.492188,169.980469,89.824219,14.941406,43.137187]},
+ {"part":"tobdeu__so100_test_setup","origin":"molmoact","dataset":"tobdeu/so100_test_setup","scene_camera":"observation.images.top_view","fps":30.0,"built_clips":23,"train_windows":23,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.387305,-3.164062,-2.508398,-1.629492,-1.629492,-0.087642],"action_q99":[2.197266,3.515625,3.387305,1.582031,1.230469,27.824716],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-3.955078,89.824219,102.392578,57.608789,-36.298828,0.348189],"state_q99":[66.005859,189.316406,170.507812,76.816406,14.589844,25.941504]},
+ {"part":"wefio__so101_test","origin":"molmoact","dataset":"wefio/so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":1348,"train_windows":1348,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-2.197266,-2.460938,-1.494141,-1.142578,-0.515907],"action_q99":[1.494141,1.669922,2.285156,1.669922,1.318359,44.282028],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-38.496094,52.734375,41.396484,31.640625,15.901172,0.068729],"state_q99":[69.873047,191.162109,179.121094,101.162109,171.035156,44.536083]},
+ {"part":"weidezhang__so100_test","origin":"molmoact","dataset":"weidezhang/so100_test","scene_camera":"observation.images.phone","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.255078,-1.51875,-2.046094,-1.342969,-0.966797,-0.093809],"action_q99":[1.230469,1.582031,1.845703,1.757812,1.079297,57.624765],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-2.900391,65.917969,49.911328,41.171484,-28.125,0.156986],"state_q99":[41.421094,180.175781,166.816406,92.573437,21.357422,57.243329]},
+ {"part":"weiye11__0603_pi0_onlyright","origin":"molmoact","dataset":"weiye11/0603_pi0_onlyright","scene_camera":"observation.images.front","fps":30.0,"built_clips":270,"train_windows":270,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-0.527344,-2.988281,-3.427734,-1.318359,-1.054688,3.940887],"action_q99":[0.527344,4.306641,4.746094,1.757812,0.966797,34.679802],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-6.767578,48.491895,31.153711,37.353516,-26.303027,4.469697],"state_q99":[8.349609,188.4375,176.220703,80.531543,-10.107422,34.39394]},
+ {"part":"weiye11__0605_pi0","origin":"molmoact","dataset":"weiye11/0605_pi0","scene_camera":"observation.images.front","fps":30.0,"built_clips":227,"train_windows":227,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-0.615234,-3.515625,-4.130859,-1.995996,-1.582031,3.940887],"action_q99":[0.527344,4.658203,5.888672,1.757812,0.966797,39.507389],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-7.294922,45.527344,20.302734,47.636719,-26.341699,4.318182],"state_q99":[10.458984,188.701172,176.396484,96.503906,-4.833984,39.220455]},
+ {"part":"weiye11__0605_pi0_100","origin":"molmoact","dataset":"weiye11/0605_pi0_100","scene_camera":"observation.images.front","fps":30.0,"built_clips":730,"train_windows":730,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-0.615234,-3.427734,-4.042969,-1.845703,-1.582031,4.039409],"action_q99":[0.615234,4.482422,5.625,1.933594,0.878906,36.748772],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-1.845703,47.197266,21.357422,49.21875,-24.521484,4.318182],"state_q99":[12.128906,188.876953,176.396484,96.416016,-5.361328,35.757576]},
+ {"part":"weiye11__so100_410_zwy","origin":"molmoact","dataset":"weiye11/so100_410_zwy","scene_camera":"observation.images.top","fps":30.0,"built_clips":1287,"train_windows":1287,"val_windows":0,"action_dim":6,"action_names":["d_left_shoulder_pan","d_left_shoulder_lift","d_left_elbow_flex","d_left_wrist_flex","d_left_wrist_roll","left_gripper"],"action_q01":[-1.757812,-2.636719,-2.460938,-1.494141,-1.757812,0.0],"action_q99":[1.845703,2.285156,2.109375,1.494141,1.757812,50.152283],"state_names":["left_shoulder_pan","left_shoulder_lift","left_elbow_flex","left_wrist_flex","left_wrist_roll","left_gripper"],"state_q01":[-81.474609,45.175781,42.618164,31.025391,-86.748047,0.597907],"state_q99":[95.585449,188.613281,176.132812,92.460938,30.498047,49.850525]},
+ {"part":"weiye11__so100_421_pick","origin":"molmoact","dataset":"weiye11/so100_421_pick","scene_camera":"observation.images.wrist_left","fps":30.0,"built_clips":863,"train_windows":863,"val_windows":0,"action_dim":6,"action_names":["d_right_shoulder_pan","d_right_shoulder_lift","d_right_elbow_flex","d_right_wrist_flex","d_right_wrist_roll","right_gripper"],"action_q01":[-0.966797,-3.427734,-3.515625,-2.285156,-1.230469,-0.099701],"action_q99":[0.966797,4.21875,4.570312,1.845703,1.582031,52.342968],"state_names":["right_shoulder_pan","right_shoulder_lift","right_elbow_flex","right_wrist_flex","right_wrist_roll","right_gripper"],"state_q01":[-34.628906,21.09375,-5.450977,42.275391,-39.199219,-0.458015],"state_q99":[36.035156,187.470703,174.726562,106.875,48.515625,52.290077]},
+ {"part":"xiaozhudi__so100_test","origin":"molmoact","dataset":"xiaozhudi/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":30,"train_windows":30,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-2.772949,-1.933594,-1.757812,-2.157715,2.380952],"action_q99":[1.054688,1.494141,3.124512,1.582031,2.900391,41.904762],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-15.556641,54.052734,37.96875,63.28125,-101.337891,4.659864],"state_q99":[21.005859,182.891602,151.809082,104.501953,9.228516,41.632652]},
+ {"part":"yadunund__so100_move_black_knight","origin":"molmoact","dataset":"yadunund/so100_move_black_knight","scene_camera":"observation.images.camera","fps":30.0,"built_clips":1427,"train_windows":1427,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.318359,-4.482422,-4.21875,-2.460938,-5.361328,-3.056351],"action_q99":[1.142578,3.427734,3.691406,3.427734,5.361328,26.26552],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-32.607422,48.119238,42.539062,45.263672,-9.667969,-1.451278],"state_q99":[11.25,181.230469,171.386719,99.580078,118.476562,25.846579]},
+ {"part":"ycdamn1988__so100_0420_3","origin":"molmoact","dataset":"ycdamn1988/so100_0420_3","scene_camera":"observation.images.orbbec","fps":30.0,"built_clips":2182,"train_windows":2182,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.197266,-4.306641,-3.955078,-2.285156,-2.109375,-0.094162],"action_q99":[2.636719,5.185547,5.625,2.021484,1.669922,59.227871],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-36.474609,51.679688,42.978516,64.511719,-45.351562,-0.174672],"state_q99":[50.016797,188.085938,172.880859,103.710938,42.539062,58.951969]},
+ {"part":"youjiang97__so100_test","origin":"molmoact","dataset":"youjiang97/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":36,"train_windows":36,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-1.318359,-2.021484,-0.97998,-1.582031,-0.069784],"action_q99":[2.034668,1.582031,1.595215,1.40625,1.318359,19.120726],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-31.552734,110.039062,124.426758,49.042969,-47.021484,1.055195],"state_q99":[35.683594,192.041016,184.921875,88.488281,3.515625,18.831169]},
+ {"part":"youjiang97__so100_tt","origin":"molmoact","dataset":"youjiang97/so100_tt","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":577,"train_windows":577,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-2.373047,-2.021484,-1.582031,-1.582031,-0.069784],"action_q99":[1.845703,1.933594,2.197266,1.494141,1.582031,20.446615],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-27.333984,80.507812,84.023438,52.207031,-108.896484,0.892857],"state_q99":[55.546875,193.623047,185.625,86.748047,-44.384766,20.454546]},
+ {"part":"youliangtan__so100_strawberry_grape","origin":"molmoact","dataset":"youliangtan/so100_strawberry_grape","scene_camera":"observation.images.webcam","fps":30.0,"built_clips":1183,"train_windows":1183,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-3.164062,-4.658203,-5.712891,-4.570312,-4.394531,-2.920962],"action_q99":[3.076172,6.064453,6.503906,6.152344,5.800781,52.405499],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[52.207031,50.449219,45.574805,15.820312,-125.507812,-0.71048],"state_q99":[135.527344,176.572266,168.134766,92.460938,41.916797,51.687389]},
+ {"part":"youliangtan__so101-pen-to-holder","origin":"molmoact","dataset":"youliangtan/so101-pen-to-holder","scene_camera":"observation.images.global","fps":30.0,"built_clips":68,"train_windows":68,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-2.126953,-2.917969,-3.708984,-4.833984,-3.251953,-0.672269],"action_q99":[1.582031,2.302734,3.884766,7.224609,3.867188,31.327732],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-45.878906,18.457031,-15.029297,-55.371094,-0.439453,-0.282486],"state_q99":[28.441406,186.943359,167.519531,98.876953,134.560547,30.508473]},
+ {"part":"zainhub__so100_test","origin":"molmoact","dataset":"zainhub/so100_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":33,"train_windows":33,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.934473,-2.549707,-1.933594,-1.494141,-1.142578,-5.64784],"action_q99":[1.582031,1.933594,2.022363,1.582031,1.40625,37.624584],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-6.064453,71.015625,87.978516,55.458105,-16.699219,-3.994394],"state_q99":[48.779297,171.386719,164.267578,95.976562,-16.171875,37.631397]},
+ {"part":"zheng6677__new_so101_test","origin":"molmoact","dataset":"zheng6677/new_so101_test","scene_camera":"observation.images.laptop","fps":30.0,"built_clips":309,"train_windows":309,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.582031,-4.482422,-3.251953,-1.933594,-1.582031,-0.354925],"action_q99":[1.582031,4.130859,4.21875,2.724609,1.494141,37.355812],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-37.792969,28.388672,11.689453,33.526758,-83.847656,-0.225564],"state_q99":[34.189453,193.623047,180.223242,95.185547,37.617188,37.142857]},
+ {"part":"zheng6677__new_so101_test1","origin":"molmoact","dataset":"zheng6677/new_so101_test1","scene_camera":"observation.images.top","fps":30.0,"built_clips":775,"train_windows":775,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-3.955078,-3.164062,-2.285156,-1.933594,-0.443656],"action_q99":[1.75166,3.867188,3.509473,2.373047,2.109375,53.416149],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-42.275391,35.507812,32.695312,18.896484,-82.617188,-0.601504],"state_q99":[34.277344,194.677734,180.087891,88.154297,47.630566,53.759396]},
+ {"part":"zlj666__so101_test","origin":"molmoact","dataset":"zlj666/so101_test","scene_camera":"observation.images.camera1","fps":30.0,"built_clips":58,"train_windows":58,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-0.966797,-3.603516,-2.296582,-3.966504,-0.703125,-1.001822],"action_q99":[0.878906,2.900391,3.779297,2.548828,0.878906,39.162113],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-23.027344,0.175781,-4.29873,-95.131934,74.882812,0.140154],"state_q99":[21.368848,153.017578,178.154297,-11.777344,87.363281,37.981781]},
+ {"part":"zlj666__so101_test2","origin":"molmoact","dataset":"zlj666/so101_test2","scene_camera":"observation.images.camera1","fps":30.0,"built_clips":338,"train_windows":338,"val_windows":0,"action_dim":6,"action_names":["d_main_shoulder_pan","d_main_shoulder_lift","d_main_elbow_flex","d_main_wrist_flex","d_main_wrist_roll","main_gripper"],"action_q01":[-1.494141,-4.130859,-2.373047,-3.251953,-5.185547,-1.493776],"action_q99":[1.582031,3.076172,2.460938,3.251953,3.779297,46.05809],"state_names":["main_shoulder_pan","main_shoulder_lift","main_elbow_flex","main_wrist_flex","main_wrist_roll","main_gripper"],"state_q01":[-22.324219,34.892578,34.444336,-69.262207,-10.898438,-1.4862],"state_q99":[27.685547,196.875,184.746094,76.992188,99.931641,46.072186]}
+ ]
+}
diff --git a/flux-umi/configs/so101/train.json b/flux-umi/configs/so101/train.json
new file mode 100644
index 0000000000000000000000000000000000000000..a5ebd8f718e5919a09de7b9a15185ce883af1ad4
--- /dev/null
+++ b/flux-umi/configs/so101/train.json
@@ -0,0 +1,73 @@
+{
+ "source_root": "outputs/so101/source",
+ "index_dir": "outputs/so101/index",
+ "output_dir": "outputs/so101/run-seed42",
+ "policy": {
+ "trunk_weights": "outputs/weights/flux-3-action-base.safetensors",
+ "video_vae_id": "outputs/weights/video_vae.safetensors",
+ "text_encoder_id": "outputs/weights/text_encoder",
+ "attn_mode": "torch",
+ "action_dim": 6,
+ "action_modality": "action",
+ "camera_layout": "side_by_side",
+ "camera_keys": ["images.scene", "images.wrist"],
+ "canvas_hw": [256, 512],
+ "inference_profile": "history",
+ "n_obs_steps": 8,
+ "history_snapshots": 2,
+ "condition_on_past_actions": true,
+ "video_position_fps": 24.0,
+ "text_fixed_length": 320,
+ "chunk_size": 42,
+ "n_action_steps": 32,
+ "fps": 30.0,
+ "action_scale": 2.0,
+ "gripper_flip_dims": [],
+ "action_parameterization": "joint_delta",
+ "absolute_action_dims": [5],
+ "normalization_clip": 6.0,
+ "camera_dropout": {"images.wrist": 0.2},
+ "train_timestep_width": 0.75,
+ "train_timestep_shift": 42.0,
+ "separate_timesteps": true,
+ "video_logit_mean": 1.08,
+ "video_logit_std": 1.0,
+ "conditioning_noise_max": 0.2,
+ "loss_reduction": "modalities",
+ "action_channel_weights": [1, 1, 1, 1, 1, 2],
+ "action_loss_weight": 0.5,
+ "video_loss_weight": 1.0,
+ "caption_dropout": 0.1,
+ "augment": false,
+ "optimizer_lr": 0.00013,
+ "optimizer_lr_heads_multiplier": 5.0
+ },
+ "steps": 10000,
+ "cooldown_start": null,
+ "cooldown_steps": 0,
+ "seed": 42,
+ "reseed_on_resume": false,
+ "windows_per_rank": 16,
+ "grad_accumulation": 2,
+ "num_workers": 8,
+ "prefetch_factor": 2,
+ "decoder": "pyav",
+ "frame_hw": [256, 256],
+ "shard_size": 8,
+ "param_dtype": "float32",
+ "compute_dtype": "bfloat16",
+ "reduce_dtype": "float32",
+ "activation_checkpointing": true,
+ "reshard_after_forward": true,
+ "betas": [0.9, 0.99],
+ "eps": 1e-08,
+ "weight_decay": 0.05,
+ "fused_optimizer": true,
+ "max_grad_norm": 1.0,
+ "ema_sigma_rels": [0.1, 0.05],
+ "checkpoint_every": 500,
+ "keep_checkpoints": null,
+ "keep_every": null,
+ "log_every": 10,
+ "resume": "auto"
+}
diff --git a/flux-umi/configs/umi/umi_posttrain_16g.json b/flux-umi/configs/umi/umi_posttrain_16g.json
new file mode 100644
index 0000000000000000000000000000000000000000..793a1ea692e6237fdd1b2f0a6db0f8226f50a8c6
--- /dev/null
+++ b/flux-umi/configs/umi/umi_posttrain_16g.json
@@ -0,0 +1,172 @@
+{
+ "source_root": null,
+ "index_dir": null,
+ "output_dir": "",
+ "dataset": "flux_action.data.umi.all_windows:build",
+ "sampling_contract": "umi-all-windows-pad-v1",
+ "sampling_manifest_sha256": null,
+ "sampling_legal_starts": null,
+ "policy": {
+ "action_dim": 20,
+ "action_modality": "action",
+ "camera_layout": "side_by_side",
+ "camera_keys": [
+ "images.left_ego",
+ "images.right_ego"
+ ],
+ "canvas_hw": [
+ 256,
+ 512
+ ],
+ "chunk_size": 32,
+ "n_action_steps": 32,
+ "fps": 30,
+ "action_scale": 2.0,
+ "gripper_flip_dims": [],
+ "action_parameterization": "absolute",
+ "absolute_action_dims": [],
+ "action_normalization": null,
+ "state_normalization": null,
+ "normalization_clip": 6.0,
+ "camera_dropout": {},
+ "trunk_weights": "outputs/weights/flux-3-action-base.safetensors",
+ "video_vae_id": "outputs/weights/video_vae.safetensors",
+ "text_encoder_id": "outputs/weights/text_encoder",
+ "dit_config": {},
+ "content_streams": [
+ "video",
+ "video_cond"
+ ],
+ "head_init_seed": 42,
+ "torch_dtype": "float32",
+ "quantization": null,
+ "attn_mode": "torch",
+ "compile_model": false,
+ "single_frame_encode": true,
+ "inference_profile": "default",
+ "n_obs_steps": 1,
+ "history_snapshots": 1,
+ "condition_on_past_actions": false,
+ "video_position_fps": 24.0,
+ "text_fixed_length": 320,
+ "sampler": null,
+ "num_inference_steps": null,
+ "guidance_scale": null,
+ "guidance_scale_action": null,
+ "sampler_shift": null,
+ "inference_seed": 0,
+ "train_timestep_width": 0.75,
+ "train_timestep_shift": 42.0,
+ "separate_timesteps": false,
+ "video_logit_mean": 1.08,
+ "video_logit_std": 1.0,
+ "conditioning_noise_max": 0.0,
+ "loss_reduction": "joint_tokens",
+ "action_channel_weights": null,
+ "action_loss_weight": 50.0,
+ "video_loss_weight": 1.0,
+ "caption_dropout": 0.1,
+ "augment": true,
+ "vae_batch_windows": 1,
+ "optimizer_lr": 0.00013576450198781714,
+ "optimizer_lr_heads_multiplier": 5.0,
+ "state_dropout": 0.5,
+ "vae_cute_rmsnorm": true,
+ "vae_cute_rope": true,
+ "vae_natten_no_lse": true,
+ "vae_trim_causal_tail": true,
+ "vae_natten_triton_tokperm": true,
+ "vae_fused_pointwise": true,
+ "vae_cuda_graph": true,
+ "preprocess_batched": true,
+ "prefetch_randomness": true,
+ "dit_swiglu_fused": true,
+ "dit_qknorm_triton": true,
+ "dit_rope_triton": true,
+ "dit_norm_mod_gate_fused": true,
+ "dit_time_embed_dedup": true,
+ "vae_na3d_triton": true,
+ "vae_ln_exact_fast": true,
+ "vae_qk_fused": true,
+ "vae_mlp_residual_fused": true,
+ "dit_mod_rows": true,
+ "dit_qknorm_rope_fused": true,
+ "vae_fused_fc1_glu": true,
+ "vae_na3d_tma": true,
+ "vae_merge_glue_fused": true,
+ "dit_pe_cache": true,
+ "dit_out_stage": true,
+ "pack_cache": true
+ },
+ "steps": 2510,
+ "cooldown_start": 2008,
+ "cooldown_steps": 502,
+ "frozen_steps": 0,
+ "trunk_warmup_steps": 251,
+ "heads_warmup_steps": 251,
+ "seed": 42,
+ "reseed_on_resume": false,
+ "windows_per_rank": 140,
+ "grad_accumulation": 2,
+ "num_workers": 24,
+ "prefetch_factor": 1,
+ "in_process_loader": false,
+ "reuse_epoch_loader": false,
+ "prefetch_next_epoch": false,
+ "decoder": "pyav",
+ "frame_hw": [
+ 256,
+ 256
+ ],
+ "shard_size": 8,
+ "param_dtype": "float32",
+ "compute_dtype": "bfloat16",
+ "reduce_dtype": "float32",
+ "activation_checkpointing": true,
+ "ac_mode": "sac",
+ "ac_save_mlp_blocks": 0,
+ "ac_skip_last": 0,
+ "ac_sac_save": [
+ "out_stage"
+ ],
+ "ac_sac_extra_save": [
+ "sdpa"
+ ],
+ "ac_sac_extra_blocks": 16,
+ "ac_offload": "off",
+ "ac_offload_keep_last": 2,
+ "ac_offload_prefetch": 1,
+ "reshard_after_forward": true,
+ "fsdp_comm_memory_from_pg": false,
+ "manual_gc_every": 5,
+ "async_step_end": true,
+ "betas": [
+ 0.9,
+ 0.99
+ ],
+ "eps": 1e-08,
+ "weight_decay": 0.05,
+ "fused_optimizer": true,
+ "max_grad_norm": null,
+ "visits_per_epoch": 1,
+ "ema_sigma_rels": [
+ 0.1,
+ 0.05
+ ],
+ "frozen_streams": [
+ "image",
+ "image_cond",
+ "audio",
+ "audio_cond"
+ ],
+ "checkpoint_every": 251,
+ "keep_checkpoints": 2,
+ "keep_every": null,
+ "log_every": 1,
+ "resume": "auto",
+ "initialize_from": null,
+ "allow_global_batch_change": false,
+ "allow_seed_change": false,
+ "max_epochs": 10,
+ "prepare_async": false
+}
diff --git a/flux-umi/docs/embodiments.md b/flux-umi/docs/embodiments.md
new file mode 100644
index 0000000000000000000000000000000000000000..04d46b7910761f73acf008bc7ced770b57868958
--- /dev/null
+++ b/flux-umi/docs/embodiments.md
@@ -0,0 +1,31 @@
+# Custom tasks and embodiments
+
+Complete [setup](setup.md), including the base and encoder download.
+The [gaming example](../examples/games/README.md) trains one policy on two browser games.
+
+`flux-action train` reads a DROID or LeRobot index. To train on other data, provide the windows yourself
+and configure the dataset, schedule and action dimensions below. The UMI section of the [README](../README.md)
+describes the shared training, resume and export workflow.
+
+## The window
+
+Each sample is one dict: `images.` `(frames, 3, H, W)` uint8 with `frames = chunk_size + 1` (one
+observed frame, then the frames the actions lead to), `state (D,)` float32, `action (chunk_size, D)` float32,
+`task` (the caption, a string), `window_seed` (int), and optionally `action_mask (D,)`.
+
+## The config
+
+**`dataset = "pkg.module:callable"`.** The callable receives the `TrainConfig` and `seed, epoch, rank, world_size, num_workers, windows_per_rank, skip_batches, grad_accumulation`, and returns an iterable dataset with a `batches_per_rank` attribute that yields the windows above. Derive the sampling from `(seed, epoch, rank, position)` and skip the first `skip_batches`; resume is exact when you do. `index_dir` is ignored. A 60-line reference: `tests/training/test_embodiment_plug.py`.
+
+**`frozen_steps`, `trunk_warmup_steps`, `heads_warmup_steps`.** The defaults (1000 / 2000 / 1000) fit a 30k-step
+run. For 3000 steps use 200 / 600 / 200; with the defaults the trunk never unfreezes.
+
+**`action_mask`,** only if embodiments with different action widths share one head. Zero-pad the narrower action
+to `D` and set the mask per window; the loss averages over unmasked dims. The caption tells them apart.
+
+**`export-checkpoint --dtype bfloat16`.** Export bf16 weights for inference; the default export keeps
+the fp32 master weights. For a policy that conditions on one frame, `PolicyConfig.single_frame_encode`
+encodes that frame alone instead of padding it to the VAE’s 45-frame chunk. This changes the encoded
+latents and is off by default; retain the setting used by your checkpoint.
+
+[`examples/games`](../examples/games/README.md) does all of the above on two browser games.
diff --git a/flux-umi/docs/folding-checkpoint.md b/flux-umi/docs/folding-checkpoint.md
new file mode 100644
index 0000000000000000000000000000000000000000..6133334ae228d9a601d3153c20a9c9414bfbf7a8
--- /dev/null
+++ b/flux-umi/docs/folding-checkpoint.md
@@ -0,0 +1,38 @@
+# Cloth-folding inference checkpoint
+
+The following inventory was provided by the model owner. Weight bytes and the remote manifest/config have not been independently downloaded or validated during this documentation update. Internal job IDs, experiment names, bucket names and training-storage paths are intentionally omitted from this public document.
+
+## Provided export
+
+```text
+checkpoints/flux_fold_clothes_bf16/
+ config.json
+ manifest.json
+ model.safetensors
+```
+
+- Format: already exported inference policy, BF16; **do not export it again merely to run inference**.
+- Selected checkpoint: step 14418, model weights (not asserted to be EMA).
+- Reported weight-file size: 13,894,466,592 bytes.
+- Earlier training checkpoints at steps 4806 and 9612 were reported in training storage; only the final step was reported in the supplied remote export.
+- The 16-GPU training template in this source archive is not evidence of this checkpoint's exact training configuration. The supplied experiment label suggests a different worker/window/epoch setup; obtain the actual train configuration rather than treating that template as the rollout recipe.
+
+## Loading
+
+`flux-action infer` accepts this **export directory**, not a raw training `step-N` directory. `FluxActionPolicy.from_pretrained` reads the policy config and verifies the manifest against config/model bytes. Keep the three files together; if any file is changed, a matching manifest must be generated by the proper export path.
+
+The supplied inventory lists only policy weights/config/manifest. The VAE and text encoder are separate requirements of the policy code. Resolve the locations referenced by `config.json` and verify that they are accessible in the inference environment. A policy-weight export alone does not establish that encoder assets are bundled.
+
+Read sampler, num_inference_steps, guidance_scale, guidance_scale_action and sampler_shift from the actual export config; do not replace them with guessed settings from a training template. The model owner reports this export as ready for inference; the current source still validates those fields at load/inference time.
+
+Once the matching environment, encoder assets and a correctly prepared UMI observation NPZ are available:
+
+```bash
+flux-action infer --checkpoint /path/to/checkpoints/flux_fold_clothes_bf16 --observation /path/to/umi_observation.npz --task "fold the clothes" --output /path/to/new_inference_output --device cuda
+```
+
+The NPZ must use the export's camera keys and 20-D UMI relative state; a raw 16-D pose is not the model state. A UMI robot adapter must restore anchor-relative action chunks and handle robot coordinates/grippers. This command is a documented interface, not a new runtime validation of the remote weights.
+
+## Weight release checks
+
+Before distributing the actual checkpoint, inspect config strings for internal encoder/checkpoint paths. Changing `config.json` to portable locations requires regenerating its manifest hash; silently editing config while retaining the old manifest will fail integrity checks. This documentation update does not modify or redistribute the remote weights.
diff --git a/flux-umi/docs/setup.md b/flux-umi/docs/setup.md
new file mode 100644
index 0000000000000000000000000000000000000000..a7b8468fb87cb9ec8120fb3d0bdf19d3277628e1
--- /dev/null
+++ b/flux-umi/docs/setup.md
@@ -0,0 +1,30 @@
+# Setup
+
+Training requires Linux and an NVIDIA GPU. Data preparation and tests also run on CPU.
+See [training-environment.md](training-environment.md) for the exact stack the optimized kernels were validated on.
+
+## Install
+
+With `uv` installed, from the repository root:
+
+```sh
+uv sync --locked --extra encoders --extra data
+uv pip install --python .venv/bin/python 'natten==0.21.6+torch2100cu128' -f https://whl.natten.org/
+```
+
+- `--extra encoders` installs `transformers` and `huggingface-hub` for the Qwen3-VL-4B text encoder and the Hub.
+- `--extra data` installs `pyarrow` and PyAV for reading LeRobot parquet and video files.
+- NATTEN is not part of `uv.lock` because its wheels are built per torch and CUDA version. Pick the wheel from
+ [whl.natten.org](https://whl.natten.org/) that matches your torch/CUDA (e.g. `torch2100cu130` for CUDA 13.0).
+ Reinstall it after every `uv sync`.
+
+## Download the base weights
+
+```sh
+uv run hf download black-forest-labs/flux-3-action-base \
+ --include 'flux-3-action-base.safetensors' --include 'video_vae.safetensors' \
+ --include 'text_encoder/*' \
+ --local-dir outputs/weights
+```
+
+`configs/umi/umi_posttrain_16g.json` points at these paths. Keep the weights fixed for a run.
diff --git a/flux-umi/docs/training-environment.md b/flux-umi/docs/training-environment.md
new file mode 100644
index 0000000000000000000000000000000000000000..2d9f0000768555b65fc3d0c2a591388eee2bee9d
--- /dev/null
+++ b/flux-umi/docs/training-environment.md
@@ -0,0 +1,53 @@
+# Validated training environment and launch (UMI, v6 optimizations)
+
+The optimized UMI configuration (`configs/umi/umi_posttrain_16g.json`) was validated on exactly one software stack. The
+CuTe / NATTEN adapters pin parts of it (torch build, NATTEN hashes, compute capability) and refuse to run elsewhere when
+`FLUX_ACTION_*_REQUIRE_KERNEL=1` is set (the launcher sets it); the Triton kernels compile for any recent GPU but were
+only verified bitwise on this stack. To run on another stack, set the `policy.vae_*` / `policy.dit_*` performance flags to
+`false` in the config (the reference kernels are then used).
+
+| component | validated version |
+|---|---|
+| GPU | NVIDIA Blackwell (SM103, compute capability 10.3), 8 per node, NVLink |
+| driver / CUDA | 580.105.08 / CUDA 13.0 (`ptxas` cuda_13.0.r13.0) |
+| OS | Ubuntu 24.04.5 LTS |
+| Python | 3.12 |
+| torch / torchvision | 2.10.0+cu130 / 0.25.0+cu130 |
+| cuDNN / cuBLAS | 9.15.1.9 (`nvidia-cudnn-cu13`) / 13.1.0.3 |
+| Triton | 3.6.0 (with `TRITON_PTXAS_PATH` pointing at a CUDA 13.0 `ptxas`) |
+| CuTe DSL (`nvidia-cutlass-dsl`) | 4.8.0 |
+| NATTEN | 0.21.6+torch2100cu130 |
+| transformers / safetensors / numpy / av | 5.16.1 / 0.8.0 / 2.2.6 / 15.1.0 |
+
+Environment variables set by `tools/train_umi.sh`: `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` (required by
+selective activation checkpointing near the memory limit), `FLUX_ACTION_CUTE_RMSNORM_REQUIRE_KERNEL=1`,
+`FLUX_ACTION_CUTE_VAE_ROPE_REQUIRE_KERNEL=1`, `FLUX_ACTION_NATTEN_NO_LSE_REQUIRE_KERNEL=1`,
+`NATTEN_TOKPERM_DEFAULT_IMPL=cutlass`, `OMP_NUM_THREADS=1`. Set `FLUX_PYTHON`, `TRITON_PTXAS_PATH`, `TRITON_CACHE_DIR`,
+`CC` / `CXX` for your toolchain. Nothing else in the environment changes training behaviour.
+
+## Single node
+
+```bash
+FLUX_CONFIG=/data/umi_flux/train_config.json bash tools/train_umi.sh --override 'output_dir="/path/to/run"'
+```
+
+## Several nodes
+
+Run the same script on every node with the rendezvous variables set; the script then replaces `--standalone` by a c10d
+rendezvous so all nodes form one job:
+
+```bash
+FLUX_NNODES=2 FLUX_NODE_RANK= FLUX_MASTER_ADDR= FLUX_MASTER_PORT=29500 \
+FLUX_CONFIG=/data/umi_flux/train_config.json bash tools/train_umi.sh
+```
+
+The all-windows sampler requires `steps == max_epochs * updates_per_epoch` (the dataset builder refuses a mismatch), so
+regenerate `train_config.json` with `tools/prepare_umi_lerobot_v3.py --world-size ` whenever the GPU count changes.
+NCCL transport settings (`NCCL_IB_*`, `NCCL_SOCKET_IFNAME`) are site-specific and not set by the launcher.
+
+## Loader workers and data order
+
+The window order is independent of the worker count: batch `b` of a rank is always the same contiguous slice of the epoch
+order and the loader returns batches in order (`training/data.py`), so `num_workers` changes neither which windows a step
+trains on nor the number of updates per epoch; a resume still requires the same worker count (it is part of the sampling
+contract). The UMI config uses 24 workers, which removed the remaining data waits in our runs.
diff --git a/flux-umi/examples/__init__.py b/flux-umi/examples/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/examples/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/examples/games/README.md b/flux-umi/examples/games/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..7e1633b37485e2f0bd05e12215c1241584abf3eb
--- /dev/null
+++ b/flux-umi/examples/games/README.md
@@ -0,0 +1,86 @@
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+# FLUX Action游戏示例
+
+通过flux-action train与[embodiment配置](../../docs/embodiments.md),让同一checkpoint学习第一人称射击GRUNT和赛车VECTOR。caption选择游戏;这是独立示例,不是DROID训练配方。两个游戏均为确定性模拟,固定seed得到相同episode,脚本bot负责记录数据。
+
+示例展示参数为step3000、seed5001,每帧可显示按键、原始动作与32步计划。GRUNT动作是移动、侧移、转向、开火;VECTOR是转向、油门、氮气,填充到4维。
+
+## 文件与运行
+
+- dataset.py通过TrainConfig.dataset="examples.games.dataset:build"接入训练器。每个游戏使用index.json及每条episode一个.npz;frames为uint8[T,256,256,3],action为float32[T,D],15Hz。每窗33帧、32动作;VECTOR的填充维度不计loss。
+- rotor条目为无人机,其caption取index.json中每条飞行指令(caption=None),数据不在本仓库。
+- test_trainer_games.py使用合成数据测试两游戏混合、填充维度mask、逐episode caption及精确恢复。
+- configs/games/train.json为3000步配置,阶段200/600/200,采样1步,需替换、、。模拟器、bot、记录器和播放器位于各自仓库。
+
+完成[环境准备](../../docs/setup.md)及基础模型/编码器下载后配置数据路径:
+
+```sh
+# 1. record a game with its bot (in the game's repo) -> data//index.json + ep_*.npz
+# 2. train (edit the paths in configs/games/train.json)
+torchrun --nproc_per_node 8 -m flux_action.cli train --config configs/games/train.json
+# 3. export in bf16
+flux-action export-checkpoint --checkpoint /step-3000 --output /export-3000-bf16 --dtype bfloat16
+```
+
+服务端用FluxActionPolicy.from_pretrained(..., device="cuda")加载导出,再调用policy.prepare_inference()。保持config.json中的num_inference_steps=1及single_frame_encode=true;predict_action_chunk输出32步计划。caption选择游戏;VECTOR只取前3个动作维度。
+
+---
+
+
+
+# FLUX Action plays games
+
+This example trains one FLUX Action checkpoint on two browser games, a first-person shooter (GRUNT) and a road
+racer (VECTOR), through `flux-action train` with the [embodiment settings](../../docs/embodiments.md). The
+caption tells the model which game it is playing. It is an example, not part of the DROID recipe.
+
+Both games are deterministic (seed to identical episode) and have a scripted bot that records the training data.
+
+
+
+
+*The same checkpoint on both games, step 3000, seed 5001. Under each frame: the keys the model is pressing, the
+raw action values, and its 32-step plan.*
+
+| Game | Action dimensions |
+|---|---|
+| GRUNT | Move, strafe, turn, fire |
+| VECTOR | Steer, throttle, nitro (padded to four dimensions) |
+
+## Files
+
+- `dataset.py`: the trainer plug (`TrainConfig.dataset = "examples.games.dataset:build"`). Reads each game's
+ recorded episodes, one `index.json` plus one `.npz` per episode with `frames (T, 256, 256, 3)` uint8 and
+ `action (T, D)` float32 at 15 Hz. One window is 33 frames and 32 actions. VECTOR's 3-dim actions are zero-padded
+ to 4 and masked from the loss. A third entry, `rotor`, is a drone whose caption is the episode's own flight
+ instruction (`caption=None`, read from `index.json`); its data is not in this repository.
+- `test_trainer_games.py`: the plug through the real trainer on synthetic data: two games mixed, padded dims
+ masked from the loss, per-episode captions, exact resume.
+- `../../configs/games/train.json`: the DROID recipe at 3000 steps with phases 200 / 600 / 200 and one sampler
+ step. Replace ``, ``, ``.
+
+The games themselves (simulator, bot, recorder, player) are in their own repositories.
+
+## Run
+
+Complete [setup](../../docs/setup.md), including the base and encoder download, then set
+the paths in the game training configuration.
+
+```sh
+# 1. record a game with its bot (in the game's repo) -> data//index.json + ep_*.npz
+# 2. train (edit the paths in configs/games/train.json)
+torchrun --nproc_per_node 8 -m flux_action.cli train --config configs/games/train.json
+# 3. export in bf16
+flux-action export-checkpoint --checkpoint /step-3000 --output /export-3000-bf16 --dtype bfloat16
+```
+
+To serve, load the export with `FluxActionPolicy.from_pretrained(..., device="cuda")`, call
+`policy.prepare_inference()`, and keep `num_inference_steps=1` and `single_frame_encode=true` from its
+`config.json`. Use
+`policy.predict_action_chunk` to return a 32-step plan. The caption selects the game; for VECTOR,
+use the first three of the four action dims.
diff --git a/flux-umi/examples/games/__init__.py b/flux-umi/examples/games/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/examples/games/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/examples/games/dataset.py b/flux-umi/examples/games/dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..d45b81eafb7df978ee10e81453f4b70ee127ad99
--- /dev/null
+++ b/flux-umi/examples/games/dataset.py
@@ -0,0 +1,231 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""GRUNT and VECTOR as one FLUX Action training stream through the trainer.
+
+Each game keeps its own recorded episodes; this module gives them one contract so they train through the same
+heads and the same loop as DROID:
+
+ modality "game", action_dim 4:
+ GRUNT [move, strafe, turn, fire]
+ VECTOR [steer, throttle, nitro, 0] 4th dim padded, masked from the loss
+ caption: the game's own line, the only thing that says which game a window is from.
+ state: the last executed action, same padding.
+
+Wired in with ``TrainConfig.dataset = "examples.games.dataset:build"`` (the trainer imports and calls
+``build``). ``source_root`` is "grunt=/path,vector=/path"; ``index_dir`` is unused.
+
+Sampling follows the DROID loader: one window per episode visit, episodes in a seeded epoch order, sliced by
+rank then worker, fixed ``windows_per_rank`` per batch, exact-position resume via ``skip_batches``. The epoch
+order shuffles the union of episodes, so the game mix is proportional to episode counts (800 / 800: half each).
+"""
+
+from __future__ import annotations
+
+import json
+from io import BytesIO
+from pathlib import Path
+from random import Random
+from typing import Any
+
+import numpy as np
+import torch
+from PIL import Image
+from torch.utils.data import IterableDataset, get_worker_info
+
+CAMERA = "images.game"
+MODALITY = "game"
+ACTION_DIM = 4
+WINDOW = 33
+CHUNK = 32
+
+GAMES: dict[str, dict[str, Any]] = {
+ "grunt": dict(dim=4, caption="play the shooter: hunt the grunts, dodge the plasma, stay alive"),
+ "vector": dict(
+ dim=3,
+ caption="drive the racer: read the road, brake before the bends, pass the traffic, take the fuel",
+ ),
+ # rotor (indoor drone, [fwd, lat, up, yaw]): the caption is per episode, the flight instruction the pilot
+ # followed ("take off, fly under the table, and land behind the bookcase"). index.json carries it as
+ # episodes[i].task; caption=None means read it from the episode.
+ "rotor": dict(dim=4, caption=None, prefix="fly the drone: "),
+}
+
+
+def parse_roots(source_root: str) -> dict[str, list[Path]]:
+ """``grunt=/a,vector=/b+/c`` -> {game: [roots]}; ``+`` joins several datasets of one game (e.g. two
+ recording sessions). Episodes of all roots are pooled with equal weight per episode."""
+ roots: dict[str, list[Path]] = {}
+ for part in str(source_root).split(","):
+ game, _, path = part.partition("=")
+ if not _ or game not in GAMES:
+ raise ValueError(
+ f"source_root parts must be =[+...] with game in {list(GAMES)}, got {part!r}"
+ )
+ roots[game] = [Path(p) for p in path.split("+") if p]
+ return roots
+
+
+def load_episodes(roots: dict[str, list[Path]]) -> list[dict[str, Any]]:
+ """The union of every game's episodes, in a fixed order (game order of ``roots``, root order, then index order)."""
+ episodes = []
+ for game, game_roots in roots.items():
+ for root in game_roots:
+ index = json.loads((root / "index.json").read_text())
+ if int(index.get("action_dim", GAMES[game]["dim"])) != GAMES[game]["dim"]:
+ raise ValueError(
+ f"{game}: dataset action_dim {index.get('action_dim')} != {GAMES[game]['dim']}"
+ )
+ length = int(index["length"])
+ if length < WINDOW:
+ raise ValueError(f"{game}: episodes have {length} frames, need >= {WINDOW}")
+ for e in index["episodes"]:
+ ep = {"game": game, "file": str(root / e["file"]), "length": length}
+ if GAMES[game]["caption"] is None:
+ if not e.get("task"):
+ raise ValueError(
+ f"{game}: per-episode captions required but episodes[].task missing in {root / 'index.json'}"
+ )
+ ep["caption"] = GAMES[game].get("prefix", "") + str(e["task"])
+ episodes.append(ep)
+ return episodes
+
+
+def caption_of(e: dict[str, Any]) -> str:
+ """The game's fixed line, or the episode's own instruction when the game has per-episode captions."""
+ fixed = GAMES[e["game"]]["caption"]
+ return fixed if fixed is not None else e["caption"]
+
+
+def pad4(a: np.ndarray) -> np.ndarray:
+ if a.shape[-1] == ACTION_DIM:
+ return a
+ out = np.zeros(a.shape[:-1] + (ACTION_DIM,), dtype=a.dtype)
+ out[..., : a.shape[-1]] = a
+ return out
+
+
+def epoch_order(n: int, seed: int, epoch: int) -> list[int]:
+ order = list(range(n))
+ Random(f"{seed}:{epoch}").shuffle(order)
+ return order
+
+
+class GameWindowDataset(IterableDataset):
+ """Same slicing contract as ``training.data.DroidWindowDataset`` (see that class for the topology math)."""
+
+ def __init__(
+ self,
+ episodes: list[dict[str, Any]],
+ *,
+ seed: int,
+ epoch: int = 0,
+ rank: int = 0,
+ world_size: int = 1,
+ num_workers: int = 1,
+ windows_per_rank: int = 1,
+ skip_batches: int = 0,
+ grad_accumulation: int = 1,
+ ):
+ if not 0 <= rank < world_size:
+ raise ValueError("rank must lie in [0, world_size)")
+ self.episodes = episodes
+ self.seed, self.epoch = seed, epoch
+ self.rank, self.world_size = rank, world_size
+ self.num_workers, self.windows_per_rank = num_workers, windows_per_rank
+ self.skip_batches = skip_batches
+ per_worker = len(episodes) // (world_size * num_workers * windows_per_rank)
+ updates = per_worker * num_workers // grad_accumulation
+ self.batches_per_rank = updates * grad_accumulation
+ if self.batches_per_rank == 0:
+ raise ValueError(
+ f"{len(episodes)} episodes cannot fill one update on {world_size} ranks x {num_workers} workers x "
+ f"{windows_per_rank} windows x {grad_accumulation} accumulation steps"
+ )
+ if skip_batches > self.batches_per_rank:
+ raise ValueError(
+ f"skip_batches {skip_batches} exceeds the {self.batches_per_rank} batches of an epoch"
+ )
+ self._cache: dict[str, dict[str, np.ndarray]] = {}
+
+ def rank_order(self) -> list[int]:
+ return epoch_order(len(self.episodes), self.seed, self.epoch)[self.rank :: self.world_size]
+
+ def worker_batches(self, worker_id: int) -> int:
+ remaining = self.batches_per_rank - worker_id
+ return -(-remaining // self.num_workers) if remaining > 0 else 0
+
+ def worker_positions(self, worker_id: int) -> list[int]:
+ mine = self.rank_order()[worker_id :: self.num_workers]
+ produced = 0
+ if self.skip_batches > worker_id:
+ produced = -(-(self.skip_batches - worker_id) // self.num_workers)
+ return mine[produced * self.windows_per_rank : self.worker_batches(worker_id) * self.windows_per_rank]
+
+ def logical_worker(self, physical_worker: int) -> int:
+ return (physical_worker + self.skip_batches) % self.num_workers
+
+ def __iter__(self):
+ info = get_worker_info()
+ worker_id, workers = (info.id, info.num_workers) if info is not None else (0, 1)
+ if workers != self.num_workers:
+ raise RuntimeError(f"dataset built for {self.num_workers} workers but the loader runs {workers}")
+ for position in self.worker_positions(self.logical_worker(worker_id)):
+ yield self.window(position)
+
+ def _episode(self, path: str) -> dict[str, np.ndarray]:
+ ep = self._cache.get(path)
+ if ep is None:
+ if len(self._cache) > 32:
+ self._cache.clear()
+ with np.load(path) as z:
+ if "frames_png" in z.files: # one PNG per frame, lossless, about 2.6x smaller than raw uint8
+ buf, off = z["frames_png"].tobytes(), z["frames_off"]
+ frames = np.stack(
+ [
+ np.asarray(Image.open(BytesIO(buf[off[i] : off[i + 1]])).convert("RGB"))
+ for i in range(len(off) - 1)
+ ]
+ )
+ else:
+ frames = z["frames"]
+ ep = {"frames": frames, "action": pad4(z["action"])}
+ self._cache[path] = ep
+ return ep
+
+ def window(self, position: int) -> dict[str, Any]:
+ e = self.episodes[position]
+ rng = Random(f"{self.seed}:{self.epoch}:{position}")
+ s = rng.randrange(0, e["length"] - WINDOW + 1)
+ window_seed = rng.getrandbits(63)
+ ep = self._episode(e["file"])
+ act = ep["action"]
+ frames = torch.from_numpy(np.ascontiguousarray(ep["frames"][s : s + WINDOW])).permute(0, 3, 1, 2)
+ state = torch.from_numpy(act[s - 1].astype(np.float32)) if s > 0 else torch.zeros(ACTION_DIM)
+ mask = torch.zeros(ACTION_DIM)
+ mask[: GAMES[e["game"]]["dim"]] = 1.0
+ return {
+ CAMERA: frames, # (33, 3, H, W) uint8
+ "state": state,
+ "action": torch.from_numpy(act[s : s + CHUNK].astype(np.float32)),
+ "action_mask": mask,
+ "task": caption_of(e),
+ "episode_index": position,
+ "start": s,
+ "window_seed": window_seed,
+ }
+
+
+def build(config, **kwargs) -> GameWindowDataset:
+ """The trainer's dataset hook: ``config`` is the TrainConfig, ``kwargs`` the topology/position arguments."""
+ return GameWindowDataset(load_episodes(parse_roots(config.source_root)), **kwargs)
diff --git a/flux-umi/examples/games/test_trainer_games.py b/flux-umi/examples/games/test_trainer_games.py
new file mode 100644
index 0000000000000000000000000000000000000000..94865dd71ac43c13281f543da816250d71456d32
--- /dev/null
+++ b/flux-umi/examples/games/test_trainer_games.py
@@ -0,0 +1,180 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""The official trainer on the games dataset: a tiny policy, fake episodes for every game, six updates,
+checkpoint + export, the mask keeps padded channels out of the loss, exact resume."""
+
+import json
+import sys
+from pathlib import Path
+
+import numpy as np
+import pytest
+import torch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # repo root, so `examples.games.dataset` imports
+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tests"))
+from conftest import TINY_DIT, FakeVideoVAE # noqa: E402
+
+from examples.games.dataset import ( # noqa: E402
+ ACTION_DIM,
+ GAMES,
+ GameWindowDataset,
+ load_episodes,
+ parse_roots,
+)
+from flux_action.models.text_encoder import MockTextEncoder # noqa: E402
+from flux_action.policy import FluxActionPolicy # noqa: E402
+from flux_action.processing import packing # noqa: E402
+from flux_action.training.trainer import TrainConfig, Trainer # noqa: E402
+
+
+def fake_game(root: Path, game: str, n: int, length: int = 40, hw: int = 32):
+ root.mkdir(parents=True)
+ dim = GAMES[game]["dim"]
+ eps = []
+ rng = np.random.default_rng(hash(game) % 1000)
+ for i in range(n):
+ f = f"ep_{i:04d}.npz"
+ np.savez(
+ root / f,
+ frames=rng.integers(0, 255, (length, hw, hw, 3), dtype=np.uint8),
+ action=rng.uniform(-1, 1, (length, dim)).astype(np.float32),
+ )
+ e = {"file": f}
+ if GAMES[game]["caption"] is None:
+ e["task"] = f"take off, fly to place {i}, and land" # per-episode instruction (ROTOR)
+ eps.append(e)
+ (root / "index.json").write_text(json.dumps({"episodes": eps, "length": length, "action_dim": dim}))
+
+
+@pytest.fixture(scope="module")
+def roots(tmp_path_factory):
+ root = tmp_path_factory.mktemp("games")
+ for g in GAMES:
+ fake_game(root / g, g, 8)
+ return ",".join(f"{g}={root / g}" for g in GAMES)
+
+
+def tiny_policy(config):
+ return FluxActionPolicy(config, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+def make_config(roots, output, **overrides):
+ values = dict(
+ source_root=roots,
+ index_dir="unused",
+ output_dir=str(output),
+ dataset="examples.games.dataset:build",
+ policy=dict(
+ camera_layout="single",
+ camera_keys=["images.game"],
+ canvas_hw=[64, 64],
+ action_dim=ACTION_DIM,
+ action_modality="game",
+ dit_config=TINY_DIT,
+ augment=False,
+ caption_dropout=0.0,
+ gripper_flip_dims=[],
+ ),
+ steps=6,
+ frozen_steps=1,
+ trunk_warmup_steps=3,
+ heads_warmup_steps=2,
+ cooldown_start=4,
+ cooldown_steps=2,
+ windows_per_rank=2,
+ num_workers=1,
+ in_process_loader=True,
+ param_dtype="float32",
+ compute_dtype="float32",
+ checkpoint_every=3,
+ log_every=1,
+ ema_sigma_rels=(0.10,),
+ )
+ values.update(overrides)
+ return TrainConfig(**values)
+
+
+def test_dataset_mixes_games_and_masks_padding(roots):
+ eps = load_episodes(parse_roots(roots))
+ assert len(eps) == 8 * len(GAMES) and {e["game"] for e in eps} == set(GAMES)
+ ds = GameWindowDataset(eps, seed=1, windows_per_rank=2)
+ items = list(ds)
+ assert len(items) == 8 * len(GAMES)
+ fixed = {GAMES[g]["caption"]: g for g in GAMES if GAMES[g]["caption"] is not None}
+
+ def game_of(task: str) -> str:
+ if task in fixed:
+ return fixed[task]
+ assert task.startswith("fly the drone: take off, fly to place ") # ROTOR: per-episode instruction
+ return "rotor"
+
+ seen = {game_of(it["task"]) for it in items}
+ assert seen == set(GAMES)
+ assert (
+ len({it["task"] for it in items if game_of(it["task"]) == "rotor"}) == 8
+ ) # every rotor episode has its own caption
+ for it in items:
+ g = game_of(it["task"])
+ assert it["action"].shape == (32, ACTION_DIM) and it["state"].shape == (ACTION_DIM,)
+ assert it["action_mask"].tolist() == [1.0] * GAMES[g]["dim"] + [0.0] * (ACTION_DIM - GAMES[g]["dim"])
+ if g == "vector":
+ assert float(it["action"][:, 3].abs().max()) == 0.0 and float(it["state"][3]) == 0.0
+ # rank/worker slicing partitions the epoch like the DROID loader
+ a = [
+ it["episode_index"] for it in GameWindowDataset(eps, seed=1, rank=0, world_size=2, windows_per_rank=2)
+ ]
+ b = [
+ it["episode_index"] for it in GameWindowDataset(eps, seed=1, rank=1, world_size=2, windows_per_rank=2)
+ ]
+ assert not set(a) & set(b) and len(a) + len(b) == 8 * len(GAMES)
+
+
+def test_masked_flow_loss_ignores_padded_channel():
+ B, K, D, Nv = 2, 32, 4, 10
+ tgt = {"x_video": torch.zeros(B, Nv, 8), "x_game": torch.zeros(B, K, D)}
+ pred = {"x_video": torch.zeros(B, Nv, 8), "x_game": torch.zeros(B, K, D)}
+ pred["x_game"][1, :, 3] = 100.0 # garbage in the padded channel of a vector window
+ mask = torch.tensor([[1, 1, 1, 1], [1, 1, 1, 0]], dtype=torch.float32)
+ assert float(packing.flow_loss(pred, tgt, "game", 50.0, 1.0, action_mask=mask)["loss"]) == 0.0
+ assert float(packing.flow_loss(pred, tgt, "game", 50.0, 1.0)["loss"]) > 0.0
+ # the (n, D) mask applies unchanged to the packed per-token layout the trainer uses (window-major tokens)
+ flat = packing.flatten_windows(tgt)
+ flat_pred = packing.flatten_windows(pred)
+ assert float(packing.flow_loss(flat_pred, flat, "game", 50.0, 1.0, action_mask=mask)["loss"]) == 0.0
+ pred["x_game"][0, :, 3] = 1.0 # a REAL channel (grunt window) must count
+ assert float(packing.flow_loss(pred, tgt, "game", 50.0, 1.0, action_mask=mask)["loss"]) > 0.0
+
+
+def test_trainer_runs_games_end_to_end_and_resumes(roots, tmp_path):
+ output = tmp_path / "run"
+ Trainer(make_config(roots, output), policy_factory=tiny_policy).run()
+ lines = [json.loads(line) for line in (output / "metrics.jsonl").read_text().splitlines()]
+ steps = [r for r in lines if "loss" in r]
+ assert [r["step"] for r in steps] == [1, 2, 3, 4, 5, 6]
+ assert all(np.isfinite(r["loss"]) for r in steps)
+ # our schedule knobs took: trunk frozen at step 1, warming after
+ assert steps[0]["lr_trunk"] == 0.0 and steps[2]["lr_trunk"] > 0.0
+ assert (output / "step-6" / "state.json").is_file()
+ # exact resume: 3 steps, then 3 more, equals the 6-step run
+ part = tmp_path / "part"
+ Trainer(make_config(roots, part, steps=3), policy_factory=tiny_policy).run()
+ Trainer(make_config(roots, part, steps=6, reseed_on_resume=False), policy_factory=tiny_policy).run()
+ full = [r["loss"] for r in steps]
+ resumed = [
+ json.loads(line)["loss"]
+ for line in (part / "metrics.jsonl").read_text().splitlines()
+ if "loss" in line
+ ]
+ assert resumed[3:] == pytest.approx(full[3:], rel=1e-5, abs=1e-6)
diff --git a/flux-umi/pyproject.toml b/flux-umi/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..00a5e65a0229e81245c15741366be4c47e72c7ff
--- /dev/null
+++ b/flux-umi/pyproject.toml
@@ -0,0 +1,47 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[project]
+name = "flux-action"
+version = "0.1.0.dev0"
+description = "Standalone FLUX Action model and DROID workflow"
+requires-python = ">=3.12,<3.13"
+dependencies = ["torch>=2.11.0; sys_platform == 'darwin'", "torchvision>=0.26.0; sys_platform == 'darwin'", "torch>=2.10.0; sys_platform != 'darwin'", "torchvision>=0.25.0; sys_platform != 'darwin'", "numpy>=2.0,<2.3", "einops==0.8.1", "safetensors>=0.4.3,<1"]
+
+[project.optional-dependencies]
+encoders = ["transformers==5.16.1", "huggingface-hub>=0.34,<2"]
+data = [
+ "av>=14,<16",
+ "pyarrow>=19,<22",
+]
+serve = [
+ "msgpack>=1.0,<2",
+ "websockets>=13,<16",
+]
+[dependency-groups]
+dev = ["pytest>=8,<10", "ruff==0.14.3"]
+
+[project.scripts]
+flux-action = "flux_action.cli:main"
+
+# PyPI's aarch64 torch wheels are CPU-only; the PyTorch index has CUDA 12.8 builds for both x86-64 and
+# aarch64 (GB200, GH200). The marker keeps macOS on PyPI.
+[[tool.uv.index]]
+name = "pytorch-cu128"
+url = "https://download.pytorch.org/whl/cu128"
+explicit = true
+
+[tool.uv.sources]
+torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
+torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
+
+[tool.ruff]
+line-length = 110
+target-version = "py312"
+
+[tool.ruff.lint]
+select = ["E4", "E7", "E9", "F", "I"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
diff --git a/flux-umi/src/flux_action/__init__.py b/flux-umi/src/flux_action/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/checkpoints/__init__.py b/flux-umi/src/flux_action/checkpoints/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/checkpoints/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/checkpoints/artifacts.py b/flux-umi/src/flux_action/checkpoints/artifacts.py
new file mode 100644
index 0000000000000000000000000000000000000000..6636b01aea7580a3c62d7c787629a4535d0941c1
--- /dev/null
+++ b/flux-umi/src/flux_action/checkpoints/artifacts.py
@@ -0,0 +1,25 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Artifact integrity helpers shared by data and policy exports."""
+
+import hashlib
+from pathlib import Path
+
+
+def sha256(path):
+ digest = hashlib.sha256()
+ with Path(path).open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ digest.update(block)
+ return digest.hexdigest()
diff --git a/flux-umi/src/flux_action/cli.py b/flux-umi/src/flux_action/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..33abc5b4ea25840ee629fee15d7a8ee861739aa4
--- /dev/null
+++ b/flux-umi/src/flux_action/cli.py
@@ -0,0 +1,395 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Commands for data preparation and indexing, training, checkpoint export and offline inference."""
+
+import argparse
+import json
+
+from .data.droid.episodes import prepare_episode, validate_episode
+
+
+def _parse_settings(items: list[str]) -> dict:
+ """``KEY=VALUE`` overrides, VALUE as JSON when it parses and as a plain string otherwise.
+
+ The fallback is what lets ``--setting sampler=euler`` work alongside ``--setting guidance_scale=3.0``;
+ ``TrainConfig.from_file`` reads ``--override`` the same way.
+ """
+ settings = {}
+ for item in items:
+ key, sep, raw = item.partition("=")
+ if not sep:
+ raise ValueError(f"--setting {item!r} is not KEY=VALUE")
+ try:
+ settings[key] = json.loads(raw)
+ except json.JSONDecodeError:
+ settings[key] = raw
+ return settings
+
+
+def _add_checkpoint_arguments(parser) -> None:
+ parser.add_argument("--checkpoint", required=True, help="local policy directory or Hugging Face repo ID")
+ parser.add_argument("--revision", help="Hugging Face commit, tag or branch")
+ parser.add_argument("--subfolder", help="policy package within the repository, e.g. variants/gd-fp8r")
+
+
+def _add_precision_arguments(parser, *, compile_default: bool) -> None:
+ """Serve-time precision knobs shared by ``infer`` and ``serve-robolab`` (see inference/precision.py)."""
+ parser.add_argument(
+ "--compile-dit",
+ action=argparse.BooleanOptionalAction,
+ default=compile_default,
+ help="torch.compile prepared DiT inference; the first call includes compilation",
+ )
+ parser.add_argument(
+ "--offload-text-encoder",
+ action="store_true",
+ help="keep the text encoder on the CPU between new captions (frees about 9 GB of GPU memory)",
+ )
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="FLUX Action: DROID preparation, checkpoint export and offline inference"
+ )
+ commands = parser.add_subparsers(dest="command", required=True)
+ prepare = commands.add_parser("prepare", help="validate/package decoded arrays and supplied valid ranges")
+ prepare.add_argument("--metadata", required=True)
+ prepare.add_argument("--arrays", required=True)
+ prepare.add_argument("--output", required=True)
+ validate = commands.add_parser("validate-data", help="verify an intermediate episode")
+ validate.add_argument("directory")
+ cosmos = commands.add_parser("prepare-droid", help="convert a pinned local Cosmos3-DROID episode")
+ cosmos.add_argument("--source-root", required=True)
+ cosmos.add_argument("--lock", required=True)
+ cosmos.add_argument("--episode-index", required=True, type=int)
+ cosmos.add_argument("--output", required=True)
+ infer = commands.add_parser("infer", help="record offline inference from a policy package")
+ _add_checkpoint_arguments(infer)
+ infer.add_argument("--observation", required=True)
+ infer.add_argument("--task", required=True)
+ infer.add_argument("--output", required=True)
+ infer.add_argument("--device", default="cuda")
+ infer.add_argument(
+ "--setting",
+ action="append",
+ default=[],
+ metavar="KEY=VALUE",
+ help="inference override for exports without saved sampling settings, e.g. sampler=euler; "
+ "VALUE is JSON when it parses, otherwise a plain string",
+ )
+ _add_precision_arguments(infer, compile_default=False)
+ index = commands.add_parser("index-droid", help="build the whole-dataset manifest and rows array")
+ index.add_argument(
+ "--source-root", required=True, help="directory holding success/ of nvidia/Cosmos3-DROID"
+ )
+ index.add_argument("--filter", required=True, help="keep_ranges json from KarlP/droid")
+ index.add_argument("--output-dir", required=True)
+ index.add_argument("--revision", default=None, help="dataset commit hash to record")
+ index.add_argument("--only-available", action="store_true", help="keep only episodes whose files exist")
+ index.add_argument("--hash-files", action="store_true", help="record SHA-256 of every referenced file")
+ lerobot = commands.add_parser(
+ "index-lerobot",
+ help="index a LeRobot dataset (v2.1 or v3.0) for training: manifest, rows array, normalization statistics",
+ )
+ lerobot.add_argument(
+ "--source-root", required=True, help="dataset directory holding meta/, data/, videos/"
+ )
+ lerobot.add_argument("--output-dir", required=True)
+ lerobot.add_argument(
+ "--camera",
+ action="append",
+ required=True,
+ metavar="STREAM=FEATURE",
+ help="policy stream and dataset video feature, in layout order, e.g. top=observation.images.top "
+ "wrist=observation.images.front (the batch key is images.)",
+ )
+ lerobot.add_argument("--state-key", default="observation.state")
+ lerobot.add_argument("--action-key", default="action")
+ lerobot.add_argument(
+ "--action-parameterization",
+ default="joint_delta",
+ choices=("absolute", "joint_delta"),
+ help="targets the statistics describe: the commands, or per-frame deltas (the SO-101 recipe)",
+ )
+ lerobot.add_argument(
+ "--absolute-action-dims",
+ default="-1",
+ help="comma-separated channels kept absolute under joint_delta (default: the last, the gripper); "
+ "'' for none",
+ )
+ lerobot.add_argument("--normalization-clip", type=float, default=6.0)
+ lerobot.add_argument("--chunk-size", type=int, default=32)
+ lerobot.add_argument(
+ "--val-episodes", type=int, default=0, help="hold out the last N eligible episodes (split: val)"
+ )
+ lerobot.add_argument(
+ "--strip-dead-windows",
+ type=float,
+ default=None,
+ metavar="FRACTION",
+ help="drop static episodes and windows whose frames are dead beyond this fraction (the recipe: 0.6)",
+ )
+ lerobot.add_argument("--dataset-id", default=None, help="Hub repo id to record")
+ lerobot.add_argument("--revision", default=None, help="dataset commit hash to record")
+ lerobot.add_argument("--only-available", action="store_true", help="keep only episodes whose files exist")
+ lerobot.add_argument("--hash-files", action="store_true", help="record SHA-256 of every referenced file")
+ evaluate = commands.add_parser(
+ "evaluate", help="score a policy export on the held-out windows of an indexed LeRobot dataset"
+ )
+ _add_checkpoint_arguments(evaluate)
+ evaluate.add_argument("--source-root", required=True)
+ evaluate.add_argument("--index-dir", required=True)
+ evaluate.add_argument("--split", default="val", help="val (default), train, or all")
+ evaluate.add_argument("--windows-per-episode", type=int, default=4)
+ evaluate.add_argument("--max-windows", type=int, default=None)
+ evaluate.add_argument("--seed", type=int, default=0)
+ evaluate.add_argument("--device", default="cuda")
+ evaluate.add_argument("--decoder", default="pyav")
+ evaluate.add_argument("--frame-hw", default="256,256", help="frames are rescaled to H,W before tiling")
+ evaluate.add_argument(
+ "--setting",
+ action="append",
+ default=[],
+ metavar="KEY=VALUE",
+ help="inference override; VALUE is JSON when it parses, otherwise a plain string",
+ )
+ evaluate.add_argument("--output", default=None, help="report JSON (per-window records included)")
+ train = commands.add_parser(
+ "train", help="run a finetune over an indexed dataset (single process or under torchrun)"
+ )
+ train.add_argument(
+ "--config",
+ required=True,
+ help="training JSON, see configs/droid/train.json and configs/so101/train.json",
+ )
+ train.add_argument(
+ "--override",
+ action="append",
+ default=[],
+ metavar="KEY=VALUE",
+ help="override a config field (JSON values)",
+ )
+ train.add_argument(
+ "--stop-after-steps",
+ type=int,
+ default=None,
+ metavar="N",
+ help="stop this invocation after N optimizer updates and write a checkpoint; keep the configured recipe",
+ )
+ train.add_argument(
+ "--timing-breakdown",
+ action="store_true",
+ help="log per-step CUDA stream phases and critical-rank times (adds profiling overhead)",
+ )
+ serve = commands.add_parser(
+ "serve-robolab", help="serve a policy export to RoboLab over the OpenPI protocol"
+ )
+ _add_checkpoint_arguments(serve)
+ serve.add_argument(
+ "--dtype",
+ choices=("bfloat16", "float32", "keep"),
+ default="bfloat16",
+ help="DiT serving dtype; cast on CPU before GPU placement (default: bfloat16)",
+ )
+ serve.add_argument("--host", default="0.0.0.0")
+ serve.add_argument("--port", type=int, default=8000)
+ serve.add_argument("--device", default="cuda")
+ serve.add_argument("--log-dir", default=None, help="record every query (npz + json) here")
+ serve.add_argument(
+ "--setting", action="append", default=[], metavar="KEY=VALUE", help="inference override"
+ )
+ _add_precision_arguments(serve, compile_default=True)
+ serve.add_argument(
+ "--warmup", type=int, default=1, help="requests answered before listening (compiles the graphs)"
+ )
+ replay = commands.add_parser(
+ "replay-fixtures", help="replay a recorded fixture collection through the adapter"
+ )
+ _add_checkpoint_arguments(replay)
+ replay.add_argument("--collection", required=True, help="collection.json")
+ replay.add_argument("--output", required=True)
+ replay.add_argument("--device", default="cuda")
+ replay.add_argument(
+ "--dtype",
+ choices=("bfloat16", "float32", "keep"),
+ default="keep",
+ help="DiT replay dtype; select bfloat16 to match the server default (default: keep)",
+ )
+ replay.add_argument("--atol", type=float, default=1e-3)
+ replay.add_argument("--setting", action="append", default=[], metavar="KEY=VALUE")
+ export = commands.add_parser(
+ "export-checkpoint", help="write an inference export from a training checkpoint's model or EMA"
+ )
+ export.add_argument("--checkpoint", required=True, help="a complete /step- directory")
+ export.add_argument("--output", required=True)
+ export.add_argument("--profile", default="model", help="model, ema_0p10 or ema_0p05")
+ export.add_argument(
+ "--dtype",
+ default="keep",
+ choices=("keep", "bfloat16", "float32"),
+ help="export weight dtype: keep (the checkpoint's fp32 masters, default) | bfloat16 (for serving, about 7x faster plans) | float32",
+ )
+ args = parser.parse_args()
+ if args.command == "prepare":
+ result = prepare_episode(args.metadata, args.arrays, args.output)
+ elif args.command == "validate-data":
+ result = validate_episode(args.directory).to_dict()
+ elif args.command == "prepare-droid":
+ from .data.droid.cosmos import convert_episode
+
+ result = convert_episode(args.source_root, args.lock, args.episode_index, args.output)
+ elif args.command == "index-droid":
+ from pathlib import Path
+
+ from .data.droid.index import ROWS_FILENAME, build_manifest, build_rows, write_manifest
+
+ out = Path(args.output_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ manifest = build_manifest(
+ args.source_root,
+ args.filter,
+ only_available=args.only_available,
+ hash_files=args.hash_files,
+ revision=args.revision,
+ )
+ rows = build_rows(args.source_root, manifest, out / ROWS_FILENAME)
+ write_manifest(manifest, out / "manifest.json")
+ result = {
+ "manifest": str(out / "manifest.json"),
+ "counts": manifest["counts"],
+ "rows_rejected": rows["rejected"],
+ }
+ elif args.command == "index-lerobot":
+ from .data.lerobot.index import index_dataset
+
+ cameras = {}
+ for item in args.camera:
+ stream, _, feature = item.partition("=")
+ if not _ or not stream or not feature:
+ raise SystemExit(f"--camera {item!r} is not STREAM=FEATURE")
+ cameras[stream] = feature
+ dims = [int(d) for d in args.absolute_action_dims.split(",") if d.strip()]
+ result = index_dataset(
+ args.source_root,
+ args.output_dir,
+ cameras,
+ action_parameterization=args.action_parameterization,
+ absolute_action_dims=dims if args.action_parameterization == "joint_delta" else (),
+ clip=args.normalization_clip,
+ strip_dead_windows=args.strip_dead_windows,
+ state_key=args.state_key,
+ action_key=args.action_key,
+ chunk_size=args.chunk_size,
+ val_episodes=args.val_episodes,
+ dataset_id=args.dataset_id,
+ revision=args.revision,
+ only_available=args.only_available,
+ hash_files=args.hash_files,
+ )
+ elif args.command == "evaluate":
+ from .inference.evaluate import evaluate_export
+
+ settings = _parse_settings(args.setting)
+ h, w = (int(x) for x in args.frame_hw.split(","))
+ report = evaluate_export(
+ args.checkpoint,
+ args.source_root,
+ args.index_dir,
+ output=args.output,
+ device=args.device,
+ revision=args.revision,
+ subfolder=args.subfolder,
+ settings=settings,
+ split=None if args.split == "all" else args.split,
+ windows_per_episode=args.windows_per_episode,
+ max_windows=args.max_windows,
+ decoder=args.decoder,
+ frame_hw=(h, w),
+ seed=args.seed,
+ )
+ result = {k: v for k, v in report.items() if k != "windows"}
+ elif args.command == "train":
+ from .training.trainer import TrainConfig, Trainer
+
+ result = Trainer(
+ TrainConfig.from_file(args.config, args.override),
+ stop_after_steps=args.stop_after_steps,
+ timing_breakdown=args.timing_breakdown,
+ ).run()
+ elif args.command in ("serve-robolab", "replay-fixtures"):
+ from .serving.robolab import RoboLabPolicy, load_serving_policy, replay_collection, serve
+
+ settings = _parse_settings(args.setting)
+ precision = dict(dtype=args.dtype, compile_dit=False, warmup=0) # replay compares eager actions
+ if args.command == "serve-robolab":
+ precision = dict(
+ dtype=args.dtype,
+ compile_dit=args.compile_dit,
+ offload_text_encoder=args.offload_text_encoder,
+ warmup=args.warmup,
+ )
+ policy = load_serving_policy(
+ args.checkpoint,
+ revision=args.revision,
+ subfolder=args.subfolder,
+ device=args.device,
+ settings=settings,
+ **precision,
+ )
+ if args.command == "serve-robolab":
+ adapter = RoboLabPolicy(policy, log_dir=args.log_dir)
+ print(
+ json.dumps(
+ {
+ "serving": args.checkpoint,
+ "host": args.host,
+ "port": args.port,
+ "serving_setup": policy.serving_setup,
+ **policy.config.to_dict(),
+ }
+ )
+ )
+ serve(adapter, host=args.host, port=args.port, metadata={"serving_setup": policy.serving_setup})
+ return
+ result = replay_collection(args.collection, RoboLabPolicy(policy), args.output, atol=args.atol)
+ elif args.command == "export-checkpoint":
+ from .training.checkpoint import export_policy
+
+ result = export_policy(
+ args.checkpoint,
+ args.output,
+ profile=args.profile,
+ dtype=None if args.dtype == "keep" else args.dtype,
+ )
+ else:
+ from .inference.offline import run_inference
+
+ settings = _parse_settings(args.setting)
+ result = run_inference(
+ args.checkpoint,
+ args.observation,
+ args.output,
+ task=args.task,
+ revision=args.revision,
+ subfolder=args.subfolder,
+ device=args.device,
+ compile_dit=args.compile_dit,
+ offload_text_encoder=args.offload_text_encoder,
+ settings=settings,
+ )
+ print(json.dumps(result, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/flux-umi/src/flux_action/config.py b/flux-umi/src/flux_action/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3e62ee51e770a4377c41d2c80eafc71f3f7cc75
--- /dev/null
+++ b/flux-umi/src/flux_action/config.py
@@ -0,0 +1,438 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Explicit policy contract; training-loop configuration is a separate concern."""
+
+import math
+import re
+from dataclasses import asdict, dataclass, field
+from typing import Literal
+
+from .processing import packing
+
+# Content streams of the full generative trunk, canonical order. The action policy feeds only ``video`` (predicted
+# frames) and ``video_cond`` (the observed frame); the others get dummy tokens that never enter the joint attention,
+# so a trunk without the image and audio streams predicts identical actions.
+CONTENT_STREAMS = ("video", "video_cond", "image", "image_cond", "audio", "audio_cond")
+REQUIRED_CONTENT_STREAMS = ("video", "video_cond")
+ACTION_PARAMETERIZATIONS = ("absolute", "joint_delta")
+
+# Inference settings the selected DROID checkpoint was chosen and benchmarked with: Cosmos UniPC,
+# four denoising steps, inference timestep shift 5 (distinct from the training shift 42), guidance
+# 4.0 on video tokens and 1.0 (none) on action tokens, and a 32-action open loop. They are not
+# defaults: apply them explicitly, e.g. PolicyConfig(**DROID_INFERENCE_SETTINGS, ...).
+DROID_INFERENCE_SETTINGS: dict[str, object] = {
+ "sampler": "cosmos_unipc",
+ "num_inference_steps": 4,
+ "sampler_shift": 5.0,
+ "guidance_scale": 4.0,
+ "guidance_scale_action": 1.0,
+ "n_action_steps": 32,
+}
+
+
+# Training-only performance flags: kernels / adapters / caching of the packed training path. They do not change the
+# training recipe (numerics stay within the documented bit-exact / approximately-lossless classes, see each flag's
+# comment), require the validated CUDA stack, and are cleared from exported (inference) configurations.
+TRAINING_PERF_FLAGS = (
+ "vae_cute_rmsnorm", "vae_cute_rope", "vae_natten_no_lse", "vae_natten_triton_tokperm", "vae_na3d_triton",
+ "vae_na3d_tma", "vae_fused_pointwise", "vae_ln_exact_fast", "vae_qk_fused", "vae_mlp_residual_fused",
+ "vae_fused_fc1_glu", "vae_merge_glue_fused", "vae_cuda_graph", "preprocess_batched", "prefetch_randomness",
+ "pack_cache", "dit_cute_qknorm", "dit_swiglu_native_out", "dit_swiglu_fused", "dit_qknorm_triton",
+ "dit_rope_triton", "dit_qknorm_rope_fused", "dit_norm_mod_gate_fused", "dit_time_embed_dedup", "dit_mod_rows",
+ "dit_fanout_linear", "dit_pe_cache", "dit_last_layer_rows", "dit_out_stage",
+)
+
+
+@dataclass
+class PolicyConfig:
+ action_dim: int = 8
+ action_modality: str = "action"
+ # How the cameras are composited onto the canvas: "droid" (three 360x640 cameras [wrist, left exterior,
+ # right exterior]: wrist full-res on top, exteriors half-res below, reflect-padded), "single" (one resized
+ # camera), "side_by_side" (two cameras, scene then wrist, each half the width) or "grid" (any number of
+ # cameras, any resolutions, each resized into a cell of a near-square grid in camera_keys order). The first
+ # three are the layouts our checkpoints were trained with; "grid" runs for any setup but no checkpoint was
+ # trained on it. camera_keys name the batch streams ("images.") in layout order.
+ camera_layout: str = "droid"
+ camera_keys: tuple[str, ...] = ("images.wrist", "images.left", "images.right")
+ canvas_hw: tuple[int, int] = (544, 736)
+ chunk_size: int = 32
+ n_action_steps: int = 32
+ fps: float = 15.0
+ action_scale: float = 2.0
+ gripper_flip_dims: tuple[int, ...] = (-1,)
+ # What the action tokens carry, relative to the dataset's action column. "absolute": the commands as
+ # stored (DROID). "joint_delta": per-frame differences a[t] - a[t-1] on every channel except
+ # absolute_action_dims, which stay absolute (SO-101: the gripper); a training window then needs the
+ # command before its first one (``action_prev`` in the batch), and inference integrates the predicted
+ # deltas onto the observed state (target[k] = state + sum(delta[:k + 1])), open loop.
+ action_parameterization: str = "absolute"
+ absolute_action_dims: tuple[int, ...] = ()
+ # Range normalization of the action targets and of the state token, per channel:
+ # x_norm = clip(2 (x - q01) / span - 1, -normalization_clip, normalization_clip) with span = q99 - q01, or 1
+ # where that is at most 1e-6. {"q01": [...], "q99": [...]} with action_dim entries each, or None for the
+ # identity (DROID radians and closed fractions need none). ``flux-action index-lerobot`` computes them; the
+ # trainer fills empty fields from the index and refuses bounds that disagree with it. Exports carry them.
+ action_normalization: dict[str, list[float]] | None = None
+ state_normalization: dict[str, list[float]] | None = None
+ normalization_clip: float = 6.0
+ # Training-time camera dropout: per window, the probability that a camera's frames are replaced by a flat
+ # mid-gray tile (level 128), drawn from the window's generator after the caption dropout; keys are
+ # camera_keys entries. The SO-101 recipe blanks the wrist camera in 20% of the windows.
+ camera_dropout: dict[str, float] = field(default_factory=dict)
+ trunk_weights: str | None = None
+ video_vae_id: str | None = None
+ text_encoder_id: str | None = None
+ dit_config: dict = field(default_factory=dict)
+ # Content streams the DiT is built with (besides the action modality). None =
+ # video/video_cond only. Explicit stream lists in existing exports are preserved on restore.
+ content_streams: tuple[str, ...] | None = None
+ # Seed of the xavier draw for fresh embodiment heads (their final layers are zero). The trainer sets it
+ # to the run seed so every rank builds identical heads.
+ head_init_seed: int = 0
+ torch_dtype: str = "bfloat16"
+ quantization: Literal[None, "fp8r"] = None
+ # Reference/training attention backend; prepared BF16/FP8r inference always uses PyTorch SDPA.
+ attn_mode: str = "torch"
+ # torch.compile the frozen video VAE and text encoder (the inference-side components; the DiT is not compiled).
+ compile_model: bool = False
+ # Inference encodes the conditioning frame alone. False retains the repeated-frame reference path;
+ # prepare_inference() always selects single-frame encoding. Training still encodes full videos.
+ single_frame_encode: bool = True
+ # Select the token layout explicitly; never infer it from the action dimensions.
+ inference_profile: str = "default"
+ # History layout shared by training and inference; exports own these settings.
+ n_obs_steps: int = 1
+ history_snapshots: int = 1
+ condition_on_past_actions: bool = False
+ video_position_fps: float = 24.0
+ text_fixed_length: int = 320
+ # No inference preset is selected by the training recipe. These are explicit choices.
+ sampler: str | None = None
+ num_inference_steps: int | None = None
+ guidance_scale: float | None = None
+ guidance_scale_action: float | None = None
+ sampler_shift: float | None = None
+ inference_seed: int = 0
+ # Training recipe; inference does not use these settings.
+ train_timestep_width: float = 0.75
+ train_timestep_shift: float = 42.0
+ separate_timesteps: bool = False
+ video_logit_mean: float = 1.08
+ video_logit_std: float = 1.0
+ conditioning_noise_max: float = 0.0
+ loss_reduction: str = "joint_tokens"
+ action_channel_weights: list[float] | None = None
+ action_loss_weight: float = 50.0
+ video_loss_weight: float = 1.0
+ # The winning GB200 run blanked the caption of 10% of the windows in its DROID loader (a hardcoded
+ # CFG_DROPOUT_RATE = 0.1, empty string through the same chat template); its P_UC_ACTION_PREDICTION = 0.0
+ # only switched off a second, packer-level dropout on top of that. Verified 2026-09-13.
+ caption_dropout: float = 0.1
+ # Training-time state dropout: per window, the probability that the entire normalized conditioning state is
+ # blanked (zeros), drawn from the window's generator after all image augmentation draws of the window encode
+ # and before the forward's timestep/noise draws. The UMI recipe blanks 50% of the windows.
+ state_dropout: float = 0.0
+ augment: bool = True
+ # Training windows encoded per video-VAE call (the VAE treats them independently; this trades
+ # activation memory for fewer kernel launches).
+ vae_batch_windows: int = 8
+ # Audited frozen encoder q/k RMSNorm; only active in training window encoding.
+ # Unsupported environments and inference retain the ordinary RMSNorm path.
+ vae_cute_rmsnorm: bool = False
+ # Audited frozen encoder half-RoPE; active only in training window encoding.
+ vae_cute_rope: bool = False
+ # Skip unused NATTEN LSE only for the audited frozen training encoder.
+ vae_natten_no_lse: bool = False
+ # Audited trainable DiT Q/K RMSNorm pointwise fusion; original ATen reductions.
+ dit_cute_qknorm: bool = False
+ # Original SwiGLU math with a fresh full gradient and no backward concatenation.
+ dit_swiglu_native_out: bool = False
+ # Encode the validated 33-frame causal prefix directly instead of padding it to 45.
+ # Opt in only after validating the selected VAE/backend; inference is unchanged.
+ vae_trim_causal_tail: bool = False
+ # Campaign-2 frozen-VAE / preprocessing options (all bit-exact vs the eager paths; training window encode only).
+ # Fused Triton token permute + per-stage q tile inside the no-LSE NATTEN forward (needs vae_natten_no_lse).
+ vae_natten_triton_tokperm: bool = False
+ # Triton 3-D neighborhood attention replacing NATTEN's FNA kernel in the frozen encoder (needs vae_natten_no_lse);
+ # same error vs fp64 as NATTEN but another accumulation order: approximately lossless, not bit-exact.
+ vae_na3d_triton: bool = False
+ # Fused Triton LayerNorm / GLU / residual+LN, channels-last patch embed, cached RoPE tables in the encoder.
+ vae_fused_pointwise: bool = False
+ # Capture the whole window encode in a CUDA graph (one replay per vae_batch_windows windows).
+ vae_cuda_graph: bool = False
+ # One batched preprocessing pass (pinned H2D, crop/resize/jitter/grid) for all windows of a micro-batch; torch.equal
+ # to the per-window torchvision path (the contrast mean and the blends stay per-window: ATen's reduction tree and
+ # the scalar-alpha FMA depend on the per-call shape).
+ preprocess_batched: bool = False
+ # Draw the forward's timesteps/noise inside prepare (same global-RNG order) and move them asynchronously.
+ prefetch_randomness: bool = False
+ # Training step prologue without host synchronization (bit-exact, default training profile only): position ids and
+ # the other layout-only DiT inputs are built once per packing layout and reused; the per-step timesteps are rounded
+ # on the host as before and uploaded from pinned memory asynchronously (see packing.PackCache).
+ pack_cache: bool = False
+ # Campaign-2 DiT kernels (training only; all opt-in, default off). Bit-exact vs eager unless noted.
+ dit_swiglu_fused: bool = False # one fused Triton kernel each for SwiGLU forward and backward
+ dit_qknorm_triton: bool = False # single-pass Triton Q/K RMSNorm fwd+bwd (ATen reduction order)
+ dit_rope_triton: bool = False # token-major Triton RoPE fwd+bwd (removes dq/dk transposes)
+ dit_norm_mod_gate_fused: bool = False # fused pre-norm+AdaLN modulation and gate+residual kernels
+ dit_time_embed_dedup: bool = False # time embedding / modulation per (stream, window) row; ~1-ulp bf16 drift
+ # Campaign-3 (2026-10-02) options, all opt-in. VAE ones are bit-exact vs the fused pointwise path.
+ vae_ln_exact_fast: bool = False # faster bit-exact Triton LayerNorm kernels (needs vae_fused_pointwise)
+ vae_qk_fused: bool = False # one Triton kernel for the encoder Q/K RMSNorm + 3-D RoPE (needs vae_fused_pointwise)
+ vae_mlp_residual_fused: bool = False # defer the encoder MLP residual add into the next block's residual+LN kernel
+ # Triton TMA/tcgen05 GEMM with the GLU fused into the fc1 epilogue for the encoder MLPs with C in {256, 512, 1024}
+ # (bit-exact vs cuBLAS fc1 + the GLU kernel; needs vae_fused_pointwise).
+ vae_fused_fc1_glu: bool = False
+ # Triton NA3D kernel with TMA halo loads, row-wise temporal mask and 4 CTAs/SM (bit-identical to the v1 kernel,
+ # ~1.2x faster in situ; needs vae_na3d_triton).
+ vae_na3d_tma: bool = False
+ # Gather-LayerNorm kernels for PatchMerging / TemporalMerging that also apply the deferred stage-final MLP residual
+ # (bit-exact; needs vae_fused_pointwise, vae_ln_exact_fast and vae_mlp_residual_fused).
+ vae_merge_glue_fused: bool = False
+ # AdaLN modulation handed to the blocks as per-(stream, window) rows with in-kernel segment-sum gradients: forward
+ # bit-exact; the row (modulation / time_in / vector_in) gradients differ from the per-token path by the fp32
+ # segment-sum order only, given the same bf16 rounding point of the rows -- under FSDP (cast_forward_inputs) the
+ # rows reach each block in bf16 and the per-block row sums are rounded to bf16 like the per-token path's
+ # (needs the two flags above it).
+ dit_mod_rows: bool = False
+ # One Triton kernel for the blocks' Q/K RMSNorm + RoPE, forward and backward (out/dq/dk bit-exact vs eager; the
+ # Q/K scale gradient differs by fp32 summation order, <= 1 bf16 ulp, like dit_qknorm_triton; supersedes
+ # dit_qknorm_triton + dit_rope_triton inside the blocks, which stay as the fallback).
+ dit_qknorm_rope_fused: bool = False
+ # q/k/v/mlp_in projections as one autograd Function whose backward accumulates the shared input gradient with
+ # cuBLASLt beta=1 epilogues instead of three bf16 add kernels (bit-identical; needs dit_mod_rows).
+ dit_fanout_linear: bool = False
+ # Position tables cached across steps (keyed on the host-known packing layout: per-window token counts and ids
+ # shapes; a layout change recomputes) and cast to the compute dtype once instead of at every block entry
+ # (bit-exact; needs dit_mod_rows).
+ dit_pe_cache: bool = False
+ # Final layer's LayerNorm + adaLN modulation through the fused row kernel (forward/dx/linear-grad bit-exact; adaLN row
+ # gradients differ by fp32 segment-sum order like the rest of dit_mod_rows; needs dit_mod_rows).
+ dit_last_layer_rows: bool = False
+ # Output stage of the blocks (attn_out GEMM + mlp_out GEMM + add + gate/residual) as one custom op, flux::out_stage,
+ # with the add folded into a cuBLASLt beta=1 epilogue where a per-shape self-check proves it bitwise (else mm + add);
+ # selective checkpointing can keep its outputs (ac_sac_save kind "out_stage") so a saving block's recompute skips both
+ # GEMMs, the add and the gate kernel (bit-exact; needs dit_mod_rows).
+ dit_out_stage: bool = False
+ # Peak trunk LR of the winning recipe: 2e-4 x LR_SCALE 0.96. Heads run at 5x.
+ optimizer_lr: float = 1.92e-4
+ optimizer_lr_heads_multiplier: float = 5.0
+
+ def __post_init__(self):
+ for name in ("vae_natten_triton_tokperm", "vae_na3d_triton", "vae_fused_pointwise", "vae_cuda_graph",
+ "preprocess_batched", "prefetch_randomness", "pack_cache", "dit_swiglu_fused", "dit_qknorm_triton",
+ "dit_rope_triton",
+ "dit_norm_mod_gate_fused", "dit_time_embed_dedup", "vae_ln_exact_fast", "vae_qk_fused",
+ "vae_mlp_residual_fused", "dit_mod_rows", "dit_qknorm_rope_fused", "dit_fanout_linear",
+ "dit_pe_cache", "dit_last_layer_rows", "dit_out_stage",
+ "vae_fused_fc1_glu", "vae_na3d_tma", "vae_merge_glue_fused"):
+ if type(getattr(self, name)) is not bool:
+ raise ValueError(f"{name} must be a boolean")
+ if self.dit_swiglu_fused and self.dit_swiglu_native_out:
+ raise ValueError("dit_swiglu_fused and dit_swiglu_native_out are alternatives")
+ if self.dit_qknorm_rope_fused and self.dit_cute_qknorm:
+ raise ValueError("dit_qknorm_rope_fused and dit_cute_qknorm are alternatives")
+ if self.dit_qknorm_triton and self.dit_cute_qknorm:
+ raise ValueError("dit_qknorm_triton and dit_cute_qknorm are alternatives")
+ if (self.vae_natten_triton_tokperm or self.vae_na3d_triton) and not self.vae_natten_no_lse:
+ raise ValueError("vae_natten_triton_tokperm / vae_na3d_triton require vae_natten_no_lse")
+ if self.vae_na3d_tma and not self.vae_na3d_triton:
+ raise ValueError("vae_na3d_tma requires vae_na3d_triton")
+ if self.vae_merge_glue_fused and not (self.vae_fused_pointwise and self.vae_ln_exact_fast and self.vae_mlp_residual_fused):
+ raise ValueError("vae_merge_glue_fused requires vae_fused_pointwise, vae_ln_exact_fast and vae_mlp_residual_fused")
+ if (self.vae_ln_exact_fast or self.vae_qk_fused or self.vae_mlp_residual_fused or self.vae_fused_fc1_glu) and not self.vae_fused_pointwise:
+ raise ValueError("vae_ln_exact_fast / vae_qk_fused / vae_mlp_residual_fused / vae_fused_fc1_glu require vae_fused_pointwise")
+ if self.dit_mod_rows and not (self.dit_norm_mod_gate_fused and self.dit_time_embed_dedup):
+ raise ValueError("dit_mod_rows requires dit_norm_mod_gate_fused and dit_time_embed_dedup")
+ if (self.dit_fanout_linear or self.dit_pe_cache or self.dit_last_layer_rows) and not self.dit_mod_rows:
+ raise ValueError("dit_fanout_linear / dit_pe_cache / dit_last_layer_rows require dit_mod_rows")
+ if self.dit_out_stage and not self.dit_mod_rows:
+ raise ValueError("dit_out_stage requires dit_mod_rows")
+ if (self.vae_fused_pointwise or self.vae_cuda_graph) and self.compile_model:
+ raise ValueError("vae_fused_pointwise / vae_cuda_graph are not validated with compile_model")
+ if (
+ isinstance(self.state_dropout, bool) or not isinstance(self.state_dropout, (int, float))
+ or not 0 <= self.state_dropout <= 1
+ ):
+ raise ValueError("state_dropout must be a float in [0, 1]")
+ if type(self.vae_natten_no_lse) is not bool:
+ raise ValueError("vae_natten_no_lse must be a boolean")
+ if type(self.dit_swiglu_native_out) is not bool:
+ raise ValueError("dit_swiglu_native_out must be a boolean")
+ if type(self.dit_cute_qknorm) is not bool:
+ raise ValueError("dit_cute_qknorm must be a boolean")
+ if type(self.vae_cute_rope) is not bool:
+ raise ValueError("vae_cute_rope must be a boolean")
+ if type(self.vae_cute_rmsnorm) is not bool:
+ raise ValueError("vae_cute_rmsnorm must be a boolean")
+ if self.inference_profile not in ("default", "history"):
+ raise ValueError("inference_profile must be default or history")
+ if not 1 <= self.history_snapshots <= self.n_obs_steps:
+ raise ValueError("history_snapshots must fit n_obs_steps")
+ if not math.isfinite(self.video_position_fps) or self.video_position_fps <= 0:
+ raise ValueError("video_position_fps must be finite and positive")
+ if not 1 <= self.text_fixed_length <= 8192:
+ raise ValueError("text_fixed_length must be between 1 and 8192")
+ if self.inference_profile != "history" and (self.n_obs_steps != 1 or self.condition_on_past_actions):
+ raise ValueError("observation/past-command history requires the history inference profile")
+ if self.inference_profile == "history" and self.gripper_flip_dims:
+ raise ValueError("history profiles require checkpoint-native channels without gripper flips")
+ if self.loss_reduction not in ("joint_tokens", "modalities"):
+ raise ValueError("loss_reduction must be joint_tokens or modalities")
+ if not 0 <= self.conditioning_noise_max <= 1:
+ raise ValueError("conditioning_noise_max must be between zero and one")
+ if (
+ not math.isfinite(self.video_logit_mean)
+ or not math.isfinite(self.video_logit_std)
+ or self.video_logit_std < 0
+ ):
+ raise ValueError("video logit parameters must be finite with nonnegative std")
+ if self.action_channel_weights is not None:
+ weights = self.action_channel_weights
+ if (
+ len(weights) != self.action_dim
+ or any(not math.isfinite(w) or w < 0 for w in weights)
+ or not any(weights)
+ ):
+ raise ValueError(
+ "action_channel_weights must contain action_dim nonnegative finite weights, at least one positive"
+ )
+ self.camera_keys = tuple(self.camera_keys)
+ self.canvas_hw = tuple(self.canvas_hw)
+ self.gripper_flip_dims = tuple(self.gripper_flip_dims)
+ assert self.action_dim >= 1 and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", self.action_modality), (
+ "invalid action modality"
+ )
+ assert self.action_modality not in (
+ "video",
+ "image",
+ "text",
+ "audio",
+ "action_prediction",
+ ), "reserved action modality"
+ if self.content_streams is not None:
+ self.content_streams = tuple(self.content_streams)
+ unknown = [s for s in self.content_streams if s not in CONTENT_STREAMS]
+ assert not unknown and len(set(self.content_streams)) == len(self.content_streams), (
+ "invalid content streams"
+ )
+ assert all(s in self.content_streams for s in REQUIRED_CONTENT_STREAMS), (
+ "missing required content streams"
+ )
+ assert self.camera_layout in packing.CAMERA_LAYOUTS, "invalid camera layout"
+ expected = {"droid": 3, "single": 1, "side_by_side": 2}.get(self.camera_layout) # grid: any number
+ n_keys = len(self.camera_keys)
+ assert not (
+ n_keys == 0
+ or len(set(self.camera_keys)) != n_keys
+ or (expected is not None and n_keys != expected)
+ ), "invalid camera keys"
+ assert len(self.canvas_hw) == 2 and all(x >= 32 and x % 32 == 0 for x in self.canvas_hw), (
+ "invalid canvas size"
+ )
+ assert self.camera_layout != "droid" or self.canvas_hw == (544, 736), "invalid DROID canvas"
+ assert self.chunk_size >= 1 and (self.inference_profile == "history" or self.chunk_size % 4 == 0), (
+ "invalid chunk size"
+ )
+ assert 1 <= self.n_action_steps <= self.chunk_size, "invalid action step count"
+ assert all(math.isfinite(x) and x > 0 for x in (self.fps, self.action_scale)), "invalid action timing"
+ assert all(-self.action_dim <= d < self.action_dim for d in self.gripper_flip_dims), (
+ "invalid gripper dimension"
+ )
+ assert len({d % self.action_dim for d in self.gripper_flip_dims}) == len(self.gripper_flip_dims), (
+ "duplicate gripper dimension"
+ )
+ self.absolute_action_dims = tuple(self.absolute_action_dims)
+ assert self.action_parameterization in ACTION_PARAMETERIZATIONS, "invalid action parameterization"
+ assert all(-self.action_dim <= d < self.action_dim for d in self.absolute_action_dims), (
+ "invalid absolute action dimension"
+ )
+ assert len({d % self.action_dim for d in self.absolute_action_dims}) == len(
+ self.absolute_action_dims
+ ), "duplicate absolute action dimension"
+ assert self.action_parameterization != "absolute" or not self.absolute_action_dims, (
+ "absolute actions cannot mix delta dimensions"
+ )
+ if self.action_parameterization == "joint_delta":
+ absolute = {d % self.action_dim for d in self.absolute_action_dims}
+ assert all(d % self.action_dim in absolute for d in self.gripper_flip_dims), (
+ "gripper dimensions must stay absolute"
+ )
+ for name in ("action_normalization", "state_normalization"):
+ value = getattr(self, name)
+ if value is None:
+ continue
+ assert set(value) == {"q01", "q99"}, "normalization requires q01 and q99"
+ q01, q99 = (list(map(float, value[k])) for k in ("q01", "q99"))
+ assert len(q01) == len(q99) == self.action_dim, "normalization width mismatch"
+ assert all(math.isfinite(x) for x in q01 + q99), "nonfinite normalization bound"
+ assert all(hi >= lo for lo, hi in zip(q01, q99, strict=True)), "reversed normalization bound"
+ setattr(self, name, {"q01": q01, "q99": q99})
+ assert math.isfinite(self.normalization_clip) and self.normalization_clip > 0, (
+ "invalid normalization clip"
+ )
+ self.camera_dropout = dict(self.camera_dropout)
+ assert self.torch_dtype in ("float32", "bfloat16"), "invalid torch dtype"
+ assert self.attn_mode in ("torch", "flash", "cudnn"), "invalid attention mode"
+ assert self.quantization in (None, "fp8r"), "invalid quantization"
+ assert self.quantization is None or self.torch_dtype == "bfloat16", "FP8r requires BF16"
+
+ def validate_training(self):
+ """Training uses the reference model and its augmentation settings."""
+ assert self.quantization is None, "training requires unquantized weights"
+ assert 0 <= self.caption_dropout <= 1, "invalid caption dropout"
+ assert 0 <= self.state_dropout <= 1, "invalid state dropout"
+ assert self.vae_batch_windows >= 1, "invalid VAE batch size"
+ if self.vae_trim_causal_tail and (self.inference_profile != "default" or self.window_frames != 33):
+ raise ValueError("vae_trim_causal_tail requires the default 33-frame training layout")
+ for key, probability in self.camera_dropout.items():
+ assert key in self.camera_keys, "unknown dropout camera"
+ assert 0 <= probability <= 1, "invalid camera dropout"
+
+ def validate_inference(self):
+ """Inference uses the checkpoint's sampler settings, without training augmentation."""
+ assert self.inference_profile in ("default", "history"), "invalid inference profile"
+ assert self.sampler in ("euler", "cosmos_unipc"), "invalid sampler"
+ assert self.num_inference_steps is not None and self.num_inference_steps >= 1, (
+ "invalid inference step count"
+ )
+ assert self.guidance_scale is not None and math.isfinite(self.guidance_scale), (
+ "invalid guidance scale"
+ )
+ assert self.sampler_shift is not None and math.isfinite(self.sampler_shift), "invalid sampler shift"
+ assert self.sampler_shift > 0, "sampler shift must be positive"
+ assert self.guidance_scale_action is None or math.isfinite(self.guidance_scale_action), (
+ "invalid action guidance"
+ )
+
+ @property
+ def conditioning_channels(self) -> int:
+ """Width of the ``_cond`` stream: the state, plus the previous command under past-action history."""
+ return self.action_dim * (2 if self.condition_on_past_actions else 1)
+
+ @property
+ def camera_order(self):
+ return self.camera_keys
+
+ @property
+ def window_frames(self):
+ return self.chunk_size + (self.n_obs_steps if self.inference_profile == "history" else 1)
+
+ @property
+ def latent_hw(self):
+ return packing.latent_hw(self.camera_layout, self.canvas_hw)
+
+ def to_dict(self):
+ return asdict(self)
diff --git a/flux-umi/src/flux_action/data/__init__.py b/flux-umi/src/flux_action/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/data/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/data/droid/__init__.py b/flux-umi/src/flux_action/data/droid/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/data/droid/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/data/droid/cosmos.py b/flux-umi/src/flux_action/data/droid/cosmos.py
new file mode 100644
index 0000000000000000000000000000000000000000..701ec9deba6ddcc570317b01e83b1539dede1307
--- /dev/null
+++ b/flux-umi/src/flux_action/data/droid/cosmos.py
@@ -0,0 +1,221 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Convert a checksum-pinned local Cosmos3-DROID episode to the decoded contract."""
+
+import hashlib
+import json
+import math
+import subprocess
+import tempfile
+from pathlib import Path
+
+import numpy as np
+
+from ...checkpoints.artifacts import sha256
+from ..schema import EpisodeMetadata
+from ..windows import valid_window_spans
+from .episodes import prepare_episode
+
+CAMERA_FEATURES = {
+ "wrist": "observation.image.wrist_image_left",
+ "left": "observation.image.exterior_image_1_left",
+ "right": "observation.image.exterior_image_2_left",
+}
+FILTER_PREFIX = "gs://xembodiment_data/r2d2/r2d2-data-full/"
+
+
+def filter_key(episode_id):
+ base = FILTER_PREFIX + episode_id.strip("/")
+ return f"{base}/recordings/MP4--{base}/trajectory.h5"
+
+
+def decode_frames(path, start, length, frame_hw=(360, 640)):
+ """Decode by integer frame index from the file start, without seeking or a lossy re-encode."""
+ h, w = frame_hw
+ result = subprocess.run(
+ [
+ "ffmpeg",
+ "-v",
+ "error",
+ "-threads",
+ "2",
+ "-i",
+ str(path),
+ "-vf",
+ f"trim=start_frame={start}:end_frame={start + length},setpts=PTS-STARTPTS",
+ "-frames:v",
+ str(length),
+ "-fps_mode",
+ "passthrough",
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgb24",
+ "pipe:1",
+ ],
+ check=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ if len(result.stdout) != length * h * w * 3:
+ raise ValueError("decoded video does not match the exact episode frame count and dimensions")
+ return np.frombuffer(result.stdout, np.uint8).reshape(length, h, w, 3)
+
+
+def convert_episode(source_root, lock_path, episode_index, output):
+ """Require every consumed source file to match the supplied artifact lock."""
+ import pyarrow.parquet as pq
+
+ root, lock_path, output = map(Path, (source_root, lock_path, output))
+ lock = json.loads(lock_path.read_text())
+ if lock.get("format_version") != 1 or lock.get("dataset_id") != "nvidia/Cosmos3-DROID":
+ raise ValueError("unsupported DROID source lock")
+ revision = lock["dataset_revision"]
+ if len(revision) != 40 or any(c not in "0123456789abcdef" for c in revision):
+ raise ValueError("dataset revision must be an immutable commit hash")
+ checked = {}
+
+ def verified(relative):
+ relative = str(relative)
+ path = (root / relative).resolve()
+ if not path.is_relative_to(root.resolve()):
+ raise ValueError("source path escapes the dataset directory")
+ expected = lock["files"].get(relative)
+ if expected is None:
+ raise ValueError(f"source file not covered by the lock: {relative}")
+ if not path.is_file():
+ raise FileNotFoundError(f"locked source file missing under {root}: {relative}")
+ if relative not in checked:
+ actual = sha256(path)
+ if actual != expected:
+ raise ValueError(f"source checksum mismatch: {relative}")
+ checked[relative] = actual
+ return path
+
+ info = json.loads(verified("success/meta/info.json").read_text())
+ if info["codebase_version"] != "v3.0" or info["fps"] != 15:
+ raise ValueError("expected compact LeRobot v3 DROID at 15 Hz")
+ columns = [
+ "episode_index",
+ "episode_id",
+ "tasks",
+ "length",
+ "data/chunk_index",
+ "data/file_index",
+ "dataset_from_index",
+ "dataset_to_index",
+ ]
+ for feature in CAMERA_FEATURES.values():
+ columns += [
+ f"videos/{feature}/{suffix}"
+ for suffix in ["chunk_index", "file_index", "from_timestamp", "to_timestamp"]
+ ]
+ matches = []
+ for name in lock["files"]:
+ if name.startswith("success/meta/episodes/") and name.endswith(".parquet"):
+ matches += pq.read_table(
+ verified(name), columns=columns, filters=[("episode_index", "=", episode_index)]
+ ).to_pylist()
+ if len(matches) != 1:
+ raise ValueError("episode must appear exactly once in the locked metadata files")
+ row = matches[0]
+ n = int(row["length"])
+ if row["dataset_to_index"] - row["dataset_from_index"] != n:
+ raise ValueError("episode data boundaries disagree with its length")
+ mapping = json.loads(verified(lock["filter_file"]).read_text())
+ ranges = mapping.get(filter_key(row["episode_id"]), [])
+ metadata = EpisodeMetadata(
+ episode_id=row["episode_id"],
+ source_version=f"nvidia/Cosmos3-DROID@{revision}",
+ split="success/train",
+ n_frames=n,
+ valid_ranges=ranges,
+ caption=row["tasks"][0],
+ )
+ if not valid_window_spans(n, ranges):
+ raise ValueError("episode has no complete window allowed by the pinned filter")
+ tasks = pq.read_table(verified("success/meta/tasks.parquet")).to_pylist()
+ task_lookup = {r.get("task", r.get("__index_level_0__")): r["task_index"] for r in tasks}
+ if metadata.caption not in task_lookup:
+ raise ValueError("episode caption absent from task metadata")
+ relative = "success/" + info["data_path"].format(
+ chunk_index=row["data/chunk_index"], file_index=row["data/file_index"]
+ )
+ state_columns = [
+ "episode_index",
+ "frame_index",
+ "index",
+ "timestamp",
+ "task_index",
+ "action.joint_position",
+ "action.gripper_position",
+ "observation.state.joint_positions",
+ "observation.state.gripper_position",
+ ]
+ rows = pq.read_table(
+ verified(relative), columns=state_columns, filters=[("episode_index", "=", episode_index)]
+ )
+ if rows.num_rows != n:
+ raise ValueError("data row count does not match the episode")
+ for key, expected in [
+ ("frame_index", np.arange(n)),
+ ("index", np.arange(row["dataset_from_index"], row["dataset_to_index"])),
+ ]:
+ if not np.array_equal(rows[key].to_numpy(), expected):
+ raise ValueError(f"non-contiguous {key}")
+ if not np.all(rows["task_index"].to_numpy() == task_lookup[metadata.caption]):
+ raise ValueError("data task_index disagrees with the episode caption")
+ times = rows["timestamp"].to_numpy()
+ expected_times = np.arange(n, dtype=np.float32) / np.float32(15)
+ if times.dtype != np.float32 or not np.array_equal(times.view(np.uint32), expected_times.view(np.uint32)):
+ raise ValueError("timestamps disagree with the native float32 15 Hz grid")
+ arrays = {"timestamps": times.astype(np.float64)}
+ for name, joints, gripper in [
+ ("state", "observation.state.joint_positions", "observation.state.gripper_position"),
+ ("action", "action.joint_position", "action.gripper_position"),
+ ]:
+ joint_array = np.asarray(rows[joints].to_pylist(), dtype=np.float32)
+ grip = np.asarray(rows[gripper].to_pylist(), dtype=np.float32)
+ if joint_array.shape != (n, 7) or grip.size != n:
+ raise ValueError("invalid joint/gripper shape")
+ arrays[name] = np.concatenate([joint_array, grip.reshape(n, 1)], axis=1)
+ for camera, feature in CAMERA_FEATURES.items():
+ prefix = f"videos/{feature}"
+ first, last = [float(row[f"{prefix}/{suffix}"]) * 15 for suffix in ["from_timestamp", "to_timestamp"]]
+ if (
+ not all(math.isclose(x, round(x), rel_tol=0, abs_tol=2e-5) for x in [first, last])
+ or round(last) - round(first) != n
+ ):
+ raise ValueError(f"{camera}: video boundaries disagree with the frame grid")
+ relative = "success/" + info["video_path"].format(
+ video_key=feature,
+ chunk_index=row[f"{prefix}/chunk_index"],
+ file_index=row[f"{prefix}/file_index"],
+ )
+ arrays[camera] = decode_frames(verified(relative), round(first), n)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix=".droid-convert-", dir=output.parent) as tmp:
+ tmp = Path(tmp)
+ np.savez_compressed(tmp / "arrays.npz", **arrays)
+ (tmp / "metadata.json").write_text(json.dumps(metadata.to_dict()))
+ result = prepare_episode(tmp / "metadata.json", tmp / "arrays.npz", output)
+ provenance = {
+ "format_version": 1,
+ "source_lock_sha256": sha256(lock_path),
+ "consumed_sha256": checked,
+ "episode_index": episode_index,
+ "decoded_rgb_sha256": {k: hashlib.sha256(arrays[k].tobytes()).hexdigest() for k in CAMERA_FEATURES},
+ }
+ (output / "source.json").write_text(json.dumps(provenance, indent=2) + "\n")
+ return result
diff --git a/flux-umi/src/flux_action/data/droid/episodes.py b/flux-umi/src/flux_action/data/droid/episodes.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f8e09182eca846f4b45b9b58d148d584a390f21
--- /dev/null
+++ b/flux-umi/src/flux_action/data/droid/episodes.py
@@ -0,0 +1,146 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Lossless intermediate episode preparation and aligned window loading.
+
+Input is decoded, synchronized DROID arrays with supplied valid-range metadata.
+The public Cosmos3-DROID adapter is implemented separately in ``cosmos.py``.
+"""
+
+import json
+import shutil
+import tempfile
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from ...checkpoints.artifacts import sha256
+from ..schema import EpisodeMetadata
+from ..windows import valid_window_spans
+
+CAMERAS = ("wrist", "left", "right")
+CAPTION_SEPARATOR = " | " # Cosmos3-DROID stores several paraphrases of one instruction in a single string
+
+
+def select_caption(caption, rng=None):
+ """One paraphrase of a stored caption: a random one with ``rng`` (the training recipe), else the first."""
+ alternatives = caption.split(CAPTION_SEPARATOR)
+ return rng.choice(alternatives) if rng is not None else alternatives[0]
+
+
+def validate_arrays(metadata, arrays):
+ n = metadata.n_frames
+ required = {*CAMERAS, "timestamps", "state", "action"}
+ if set(arrays) != required:
+ raise ValueError(f"episode arrays must have exactly {sorted(required)}")
+ for camera in CAMERAS:
+ if arrays[camera].shape != (n, 360, 640, 3) or arrays[camera].dtype != np.uint8:
+ raise ValueError(f"{camera} must be uint8 (N,360,640,3) RGB")
+ timestamps = arrays["timestamps"]
+ if timestamps.shape != (n,) or not np.isfinite(timestamps).all():
+ raise ValueError("timestamps must be finite (N,)")
+ if n > 1 and not np.allclose(np.diff(timestamps), 1 / metadata.fps, atol=2e-4, rtol=0):
+ raise ValueError("timestamps must be ordered and synchronized at 15 Hz")
+ for name in ("state", "action"):
+ value = arrays[name]
+ if (
+ value.shape != (n, 8)
+ or not np.issubdtype(value.dtype, np.floating)
+ or not np.isfinite(value).all()
+ ):
+ raise ValueError(f"{name} must be finite floating-point (N,8)")
+ if np.any((value[:, -1] < 0) | (value[:, -1] > 1)):
+ raise ValueError(f"{name} gripper must be a closed fraction in [0,1]")
+ if not valid_window_spans(n, metadata.valid_ranges):
+ raise ValueError("episode has no complete valid 33-frame window")
+
+
+def prepare_episode(metadata_path, arrays_path, output):
+ """Validate/copy a canonical NPZ episode. Same-input retries verify and reuse it."""
+ metadata_path, arrays_path, output = map(Path, (metadata_path, arrays_path, output))
+ metadata = EpisodeMetadata(**json.loads(metadata_path.read_text()))
+ source_hashes = {"metadata": sha256(metadata_path), "arrays": sha256(arrays_path)}
+ if output.exists():
+ previous = json.loads((output / "manifest.json").read_text())
+ if previous["source_sha256"] != source_hashes:
+ raise FileExistsError("destination belongs to different source inputs")
+ validate_episode(output)
+ return previous
+ with np.load(arrays_path, allow_pickle=False) as arrays:
+ validate_arrays(metadata, arrays)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ staging = Path(tempfile.mkdtemp(prefix=f".{output.name}-", dir=output.parent))
+ try:
+ shutil.copyfile(arrays_path, staging / "episode.npz")
+ (staging / "metadata.json").write_text(json.dumps(metadata.to_dict(), indent=2) + "\n")
+ manifest = {
+ "format_version": 1,
+ "source_sha256": source_hashes,
+ "sha256": {name: sha256(staging / name) for name in ("metadata.json", "episode.npz")},
+ "n_valid_starts": sum(c for _, c in valid_window_spans(metadata.n_frames, metadata.valid_ranges)),
+ }
+ (staging / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ staging.rename(output)
+ finally:
+ if staging.exists():
+ shutil.rmtree(staging)
+ return manifest
+
+
+def validate_episode(directory):
+ directory = Path(directory)
+ manifest = json.loads((directory / "manifest.json").read_text())
+ if manifest["format_version"] != 1:
+ raise ValueError("unsupported prepared episode format")
+ for name in ("metadata.json", "episode.npz"):
+ if sha256(directory / name) != manifest["sha256"].get(name):
+ raise ValueError(f"episode checksum mismatch: {name}")
+ metadata = EpisodeMetadata(**json.loads((directory / "metadata.json").read_text()))
+ with np.load(directory / "episode.npz", allow_pickle=False) as arrays:
+ validate_arrays(metadata, arrays)
+ return metadata
+
+
+def load_window(directory, start, chunk_size=32, rng=None):
+ """Return a batch of one: observations s:s+33, commands s:s+32, state at s.
+
+ Values remain in source units. The policy flips the gripper once and scales
+ the representation internally; preparation does neither transformation.
+ The caption is one paraphrase of the stored task, drawn with ``rng`` as in the
+ reference finetune, or the first one when no ``rng`` is given.
+ """
+ directory = Path(directory)
+ metadata = validate_episode(directory)
+ if (
+ isinstance(start, bool)
+ or not isinstance(start, int)
+ or not any(
+ first <= start < first + count
+ for first, count in valid_window_spans(metadata.n_frames, metadata.valid_ranges, chunk_size)
+ )
+ ):
+ raise ValueError("start is not a complete valid window")
+ with np.load(directory / "episode.npz", allow_pickle=False) as arrays:
+ batch = {
+ f"images.{camera}": torch.from_numpy(arrays[camera][start : start + chunk_size + 1].copy())
+ .permute(0, 3, 1, 2)
+ .float()
+ .div_(255)
+ .unsqueeze(0)
+ for camera in CAMERAS
+ }
+ batch["state"] = torch.from_numpy(arrays["state"][start].copy()).float()[None]
+ batch["action"] = torch.from_numpy(arrays["action"][start : start + chunk_size].copy()).float()[None]
+ batch["task"] = [select_caption(metadata.caption, rng)]
+ return batch
diff --git a/flux-umi/src/flux_action/data/droid/index.py b/flux-umi/src/flux_action/data/droid/index.py
new file mode 100644
index 0000000000000000000000000000000000000000..15b933b538ae51254fd1aeab2be9ba4123facf46
--- /dev/null
+++ b/flux-umi/src/flux_action/data/droid/index.py
@@ -0,0 +1,268 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Whole-dataset manifest for the compact Cosmos3-DROID layout.
+
+``build_manifest`` lists every episode of the ``success`` split, joins the keep-ranges filter and
+keeps the episodes with at least one complete window and aligned camera streams. ``build_rows``
+extracts state and action for every frame into one float32 array indexed by the dataset's
+global frame ``index`` (``rows[i] = state(8) + action(8)``), validated the way ``prepare-droid``
+validates a single episode. Training windows then read three video seeks and one array slice.
+"""
+
+import json
+import math
+import os
+from pathlib import Path
+
+import numpy as np
+
+from ...checkpoints.artifacts import sha256
+from ..windows import valid_window_spans
+from .cosmos import CAMERA_FEATURES, filter_key
+
+MANIFEST_FORMAT = 1
+ROWS_FILENAME = "rows.f32.npy"
+ROW_WIDTH = 16 # 7 joints + gripper for the state, then the same for the action
+EPISODE_COLUMNS = [
+ "episode_index",
+ "episode_id",
+ "tasks",
+ "length",
+ "data/chunk_index",
+ "data/file_index",
+ "dataset_from_index",
+ "dataset_to_index",
+] + [
+ f"videos/{feature}/{suffix}"
+ for feature in CAMERA_FEATURES.values()
+ for suffix in ("chunk_index", "file_index", "from_timestamp", "to_timestamp")
+]
+ROW_COLUMNS = [
+ "episode_index",
+ "frame_index",
+ "index",
+ "timestamp",
+ "task_index",
+ "action.joint_position",
+ "action.gripper_position",
+ "observation.state.joint_positions",
+ "observation.state.gripper_position",
+]
+
+
+def _read_info(root: Path) -> dict:
+ info = json.loads((root / "success/meta/info.json").read_text())
+ if info.get("codebase_version") != "v3.0" or info.get("fps") != 15:
+ raise ValueError("expected compact LeRobot v3 DROID at 15 Hz")
+ return info
+
+
+def build_manifest(
+ source_root,
+ filter_path,
+ *,
+ chunk_size: int = 32,
+ only_available: bool = False,
+ hash_files: bool = False,
+ revision: str | None = None,
+) -> dict:
+ """Scan ``success/meta/episodes`` and the filter into one JSON-ready manifest."""
+ import pyarrow.parquet as pq
+
+ root, filter_path = Path(source_root), Path(filter_path)
+ info = _read_info(root)
+ fps = int(info["fps"])
+ ranges_by_key = json.loads(filter_path.read_text())
+ counts = {"listed": 0, "eligible": 0, "no_valid_window": 0, "misaligned": 0, "unavailable": 0}
+ episodes, files, valid_total = [], {}, 0
+ for parquet in sorted((root / "success/meta/episodes").rglob("*.parquet")):
+ for row in pq.read_table(parquet, columns=EPISODE_COLUMNS).to_pylist():
+ counts["listed"] += 1
+ n = int(row["length"])
+ if row["dataset_to_index"] - row["dataset_from_index"] != n:
+ counts["misaligned"] += 1
+ continue
+ ranges = [list(map(int, r)) for r in ranges_by_key.get(filter_key(row["episode_id"]), [])]
+ n_valid = sum(c for _, c in valid_window_spans(n, ranges, chunk_size))
+ if n_valid == 0:
+ counts["no_valid_window"] += 1
+ continue
+ videos, aligned = {}, True
+ for camera, feature in CAMERA_FEATURES.items():
+ prefix = f"videos/{feature}"
+ first, last = (float(row[f"{prefix}/{s}"]) * fps for s in ("from_timestamp", "to_timestamp"))
+ if not all(math.isclose(x, round(x), rel_tol=0, abs_tol=2e-5) for x in (first, last)):
+ aligned = False
+ if round(last) - round(first) != n:
+ aligned = False
+ videos[camera] = {
+ "file": "success/"
+ + info["video_path"].format(
+ video_key=feature,
+ chunk_index=row[f"{prefix}/chunk_index"],
+ file_index=row[f"{prefix}/file_index"],
+ ),
+ "first_frame": int(round(first)),
+ }
+ if not aligned:
+ counts["misaligned"] += 1
+ continue
+ data_file = "success/" + info["data_path"].format(
+ chunk_index=row["data/chunk_index"], file_index=row["data/file_index"]
+ )
+ needed = [data_file, *(v["file"] for v in videos.values())]
+ if only_available and not all((root / f).is_file() for f in needed):
+ counts["unavailable"] += 1
+ continue
+ for f in needed:
+ files.setdefault(f, None)
+ counts["eligible"] += 1
+ valid_total += n_valid
+ episodes.append(
+ {
+ "episode_index": int(row["episode_index"]),
+ "episode_id": row["episode_id"],
+ "n_frames": n,
+ "caption": row["tasks"][0],
+ "valid_ranges": ranges,
+ "n_valid_starts": n_valid,
+ "data_file": data_file,
+ "from_index": int(row["dataset_from_index"]),
+ "videos": videos,
+ }
+ )
+ file_records = {}
+ for name in sorted(files):
+ path = root / name
+ record = {"bytes": path.stat().st_size if path.is_file() else None}
+ if hash_files and path.is_file():
+ record["sha256"] = sha256(path)
+ file_records[name] = record
+ counts["valid_starts_total"] = valid_total
+ return {
+ "format_version": MANIFEST_FORMAT,
+ "dataset_id": "nvidia/Cosmos3-DROID",
+ "dataset_revision": revision,
+ "filter_file": filter_path.name,
+ "filter_sha256": sha256(filter_path),
+ "fps": fps,
+ "chunk_size": chunk_size,
+ "total_frames": int(info["total_frames"]),
+ "camera_order": list(CAMERA_FEATURES),
+ "counts": counts,
+ "files": file_records,
+ "episodes": episodes,
+ }
+
+
+def write_manifest(manifest: dict, path) -> None:
+ """Write the manifest atomically: readers waiting for the file never see a partial one."""
+ path = Path(path)
+ tmp = path.with_name(path.name + ".tmp")
+ tmp.write_text(json.dumps(manifest, indent=1) + "\n")
+ os.replace(tmp, path)
+
+
+def load_manifest(path) -> dict:
+ manifest = json.loads(Path(path).read_text())
+ if (
+ manifest.get("format_version") != MANIFEST_FORMAT
+ or manifest.get("dataset_id") != "nvidia/Cosmos3-DROID"
+ ):
+ raise ValueError("unsupported DROID manifest")
+ return manifest
+
+
+def build_rows(source_root, manifest: dict, output) -> dict:
+ """Write ``rows.f32.npy`` (``total_frames x 16``) and drop episodes whose rows fail validation.
+
+ Rows are written at their global ``index``; unlisted frames stay NaN. Checks per episode:
+ contiguous ``frame_index`` and ``index``, float32 15 Hz timestamps, one ``task_index`` equal to
+ the caption's, finite values, gripper in ``[0, 1]``.
+ """
+ import pyarrow.parquet as pq
+
+ root, output = Path(source_root), Path(output)
+ info = _read_info(root)
+ tasks = pq.read_table(root / "success/meta/tasks.parquet").to_pylist()
+ task_index = {r.get("task", r.get("__index_level_0__")): r["task_index"] for r in tasks}
+ total = int(manifest["total_frames"])
+ output.parent.mkdir(parents=True, exist_ok=True)
+ rows = np.lib.format.open_memmap(output, mode="w+", dtype=np.float32, shape=(total, ROW_WIDTH))
+ rows[:] = np.nan
+ by_file: dict[str, list[dict]] = {}
+ for episode in manifest["episodes"]:
+ by_file.setdefault(episode["data_file"], []).append(episode)
+ kept, rejected = [], {}
+ for data_file, group in sorted(by_file.items()):
+ table = pq.read_table(root / data_file, columns=ROW_COLUMNS)
+ episode_col = table["episode_index"].to_numpy()
+ for episode in group:
+ n, start = episode["n_frames"], episode["from_index"]
+ mask = episode_col == episode["episode_index"]
+ part = table.filter(mask)
+ reason = _validate_rows(part, n, start, task_index.get(episode["caption"]), info["fps"])
+ if reason is not None:
+ rejected[episode["episode_id"]] = reason
+ continue
+ joints = np.asarray(part["observation.state.joint_positions"].to_pylist(), np.float32)
+ grip = np.asarray(part["observation.state.gripper_position"].to_pylist(), np.float32).reshape(
+ n, 1
+ )
+ act = np.asarray(part["action.joint_position"].to_pylist(), np.float32)
+ act_grip = np.asarray(part["action.gripper_position"].to_pylist(), np.float32).reshape(n, 1)
+ rows[start : start + n] = np.concatenate([joints, grip, act, act_grip], axis=1)
+ kept.append(episode)
+ rows.flush()
+ manifest["episodes"] = kept
+ manifest["counts"]["eligible"] = len(kept)
+ manifest["counts"]["rows_rejected"] = len(rejected)
+ manifest["counts"]["valid_starts_total"] = sum(e["n_valid_starts"] for e in kept)
+ manifest["rows"] = {"file": output.name, "sha256": sha256(output), "width": ROW_WIDTH}
+ return {"kept": len(kept), "rejected": rejected}
+
+
+def _validate_rows(part, n, start, expected_task, fps):
+ if part.num_rows != n:
+ return f"{part.num_rows} rows for {n} frames"
+ if not np.array_equal(part["frame_index"].to_numpy(), np.arange(n)):
+ return "non-contiguous frame_index"
+ if not np.array_equal(part["index"].to_numpy(), np.arange(start, start + n)):
+ return "non-contiguous index"
+ if expected_task is None or not np.all(part["task_index"].to_numpy() == expected_task):
+ return "task_index disagrees with the caption"
+ times = part["timestamp"].to_numpy()
+ grid = np.arange(n, dtype=np.float32) / np.float32(fps)
+ if times.dtype != np.float32 or not np.array_equal(times.view(np.uint32), grid.view(np.uint32)):
+ return "timestamps off the float32 15 Hz grid"
+ for joints, grip in (
+ ("observation.state.joint_positions", "observation.state.gripper_position"),
+ ("action.joint_position", "action.gripper_position"),
+ ):
+ j = np.asarray(part[joints].to_pylist(), np.float32)
+ g = np.asarray(part[grip].to_pylist(), np.float32)
+ if j.shape != (n, 7) or g.size != n or not (np.isfinite(j).all() and np.isfinite(g).all()):
+ return f"invalid {joints} shape or values"
+ if np.any((g < 0) | (g > 1)):
+ return f"{grip} outside [0, 1]"
+ return None
+
+
+def open_rows(path, total_frames: int) -> np.ndarray:
+ rows = np.load(path, mmap_mode="r")
+ if rows.dtype != np.float32 or rows.shape != (total_frames, ROW_WIDTH):
+ raise ValueError(
+ f"rows array must be float32 ({total_frames}, {ROW_WIDTH}), got {rows.dtype} {rows.shape}"
+ )
+ return rows
diff --git a/flux-umi/src/flux_action/data/droid/video.py b/flux-umi/src/flux_action/data/droid/video.py
new file mode 100644
index 0000000000000000000000000000000000000000..029e0c35ee6d97c12131ed6b412cb92ad37f121b
--- /dev/null
+++ b/flux-umi/src/flux_action/data/droid/video.py
@@ -0,0 +1,134 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Frame-exact window decoding from the compact Cosmos3-DROID AV1 files.
+
+The files hold several episodes back to back with a keyframe every second frame, so a window is
+read by seeking to the keyframe at or before its first frame and decoding forward. Two backends:
+
+* ``ffmpeg`` (default): the ``ffmpeg`` binary with an accurate input seek half a frame before the
+ target. Its RGB conversion is the one ``prepare-droid`` used, so windows equal the prepared
+ episodes byte for byte on the same machine.
+* ``pyav``: in-process through PyAV's bundled FFmpeg. About three times faster and free of
+ subprocesses, but its libswscale version may differ from the system binary's, which moves RGB
+ values by up to a few levels. Identical frames, not identical bytes, across backends.
+"""
+
+import shutil
+import subprocess
+from fractions import Fraction
+
+import numpy as np
+
+DECODERS = ("ffmpeg", "pyav")
+FRAME_HW = (360, 640)
+
+
+def decode_window(
+ path,
+ first_frame: int,
+ length: int,
+ *,
+ fps: int = 15,
+ frame_hw: tuple[int, int] = FRAME_HW,
+ decoder: str = "ffmpeg",
+ threads: int = 1,
+ resize: bool = False,
+) -> np.ndarray:
+ """``length`` RGB frames from file frame ``first_frame`` on: uint8 ``(length, H, W, 3)``.
+
+ ``frame_hw`` is the size the frames must have. With ``resize`` the decoded frames are scaled to it
+ (libswscale bilinear in both backends, the filter the SO-101 corpus was built with); without it, frames
+ of another size are an error, so a DROID window is never silently rescaled.
+ """
+ if first_frame < 0 or length < 1:
+ raise ValueError("first_frame must be non-negative and length positive")
+ if decoder == "ffmpeg":
+ return _decode_ffmpeg(str(path), first_frame, length, fps, frame_hw, threads, resize)
+ if decoder == "pyav":
+ return _decode_pyav(str(path), first_frame, length, fps, frame_hw, threads, resize)
+ raise ValueError(f"unknown decoder {decoder!r}; choose from {DECODERS}")
+
+
+def _decode_ffmpeg(path, first_frame, length, fps, frame_hw, threads, resize):
+ if shutil.which("ffmpeg") is None:
+ raise RuntimeError("the ffmpeg binary is not on PATH; install it or use decoder='pyav'")
+ h, w = frame_hw
+ # Accurate seeking keeps the first frame whose timestamp is >= -ss. Half a frame early lands
+ # exactly on ``first_frame`` without depending on decimal rounding of first_frame / fps.
+ seek = max(0.0, (first_frame - 0.5) / fps)
+ command = [
+ "ffmpeg",
+ "-nostdin",
+ "-v",
+ "error",
+ "-threads",
+ str(threads),
+ "-filter_threads",
+ str(threads),
+ "-ss",
+ f"{seek:.6f}",
+ "-i",
+ path,
+ "-frames:v",
+ str(length),
+ "-fps_mode",
+ "passthrough",
+ *(["-vf", f"scale={w}:{h}:flags=bilinear"] if resize else []),
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgb24",
+ "pipe:1",
+ ]
+ result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ expected = length * h * w * 3
+ if len(result.stdout) != expected:
+ raise ValueError(
+ f"{path}: expected {length} frames of {h}x{w} from frame {first_frame}, "
+ f"got {len(result.stdout) // (h * w * 3)}"
+ )
+ return np.frombuffer(bytearray(result.stdout), np.uint8).reshape(length, h, w, 3) # writable buffer
+
+
+def _decode_pyav(path, first_frame, length, fps, frame_hw, threads, resize):
+ import av
+
+ h, w = frame_hw
+ frames = []
+ with av.open(path) as container:
+ stream = container.streams.video[0]
+ stream.codec_context.thread_count = threads
+ time_base = stream.time_base
+ container.seek(
+ int(Fraction(first_frame, fps) / time_base), stream=stream, backward=True, any_frame=False
+ )
+ for frame in container.decode(stream):
+ index = round(float(frame.pts * time_base) * fps)
+ if index < first_frame:
+ continue
+ if index != first_frame + len(frames):
+ raise ValueError(
+ f"{path}: frame {first_frame + len(frames)} missing, decoder produced {index}"
+ )
+ if resize:
+ frames.append(frame.to_ndarray(format="rgb24", width=w, height=h))
+ else:
+ if (frame.height, frame.width) != (h, w):
+ raise ValueError(f"{path}: frames are {frame.height}x{frame.width}, expected {frame_hw}")
+ frames.append(frame.to_ndarray(format="rgb24"))
+ if len(frames) == length:
+ break
+ if len(frames) != length:
+ raise ValueError(f"{path}: only {len(frames)} of {length} frames from frame {first_frame}")
+ return np.stack(frames)
diff --git a/flux-umi/src/flux_action/data/lerobot/__init__.py b/flux-umi/src/flux_action/data/lerobot/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..44570ef232465538ff3e9edd4e1ed7b47dbeeaf1
--- /dev/null
+++ b/flux-umi/src/flux_action/data/lerobot/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""LeRobot datasets (v2.1 and v3.0 layouts) as a source of training windows."""
diff --git a/flux-umi/src/flux_action/data/lerobot/index.py b/flux-umi/src/flux_action/data/lerobot/index.py
new file mode 100644
index 0000000000000000000000000000000000000000..e34a5d570e323a6b4d934a319f9047b73818e711
--- /dev/null
+++ b/flux-umi/src/flux_action/data/lerobot/index.py
@@ -0,0 +1,709 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Whole-dataset manifest, rows array and normalization statistics for a LeRobot dataset.
+
+Two on-disk layouts are read, both as LeRobot writes them:
+
+* **v2.1** (also v2.0): ``meta/episodes.jsonl`` and ``meta/tasks.jsonl``, one parquet and one mp4 per
+ episode and camera (``data/chunk-000/episode_000012.parquet``,
+ ``videos/chunk-000//episode_000012.mp4``). The community SO-100/SO-101 datasets
+ are in this layout.
+* **v3.0**: ``meta/episodes/chunk-*/file-*.parquet`` and ``meta/tasks.parquet``, frames of many episodes
+ concatenated into data parquet files and one mp4 per camera and file, each episode addressed by its
+ ``dataset_from_index`` and the video's ``from_timestamp``.
+
+``build_manifest`` lists the episodes with at least one complete window, ``build_rows`` extracts the
+state and the action of every frame into one float32 array (``rows[i] = state(S) + action(A)`` at the
+dataset's global frame ``index``), ``build_statistics`` computes the per-channel 1st / 99th percentiles
+of the training targets and of the state that the policy normalizes with. A training window is then one
+video seek per camera and one slice of the rows array, as for DROID (``data/droid/index.py``).
+
+Windows start at frame 1 at the earliest (``MIN_START``): the recipe trains on per-frame joint deltas
+``a[t] - a[t-1]`` computed within the episode, so the action before the window's first action must exist.
+The window dataset hands it to the policy as ``action_prev``.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+
+from ...checkpoints.artifacts import sha256
+from ..droid.episodes import CAPTION_SEPARATOR
+from ..droid.index import ROWS_FILENAME, write_manifest
+from ..windows import valid_window_spans
+
+MANIFEST_FORMAT = 1
+KIND = "lerobot"
+STATISTICS_FILENAME = "statistics.json"
+STATISTICS_FORMAT = 1
+MIN_START = 1 # the first action of a window is a[s] - a[s-1]
+GRAY = "gray" # a camera stream the dataset lacks: the window dataset serves a flat mid-gray tile for it
+NORMALIZATION_CLIP = 6.0
+# Dead-window stripping, the corpus builder's definition: a frame is dead inside a stretch of at least
+# DEAD_SECONDS in which no joint of the state moves more than DEAD_THRESHOLD per frame; episodes moving less
+# than MIN_MOVING_FRACTION of their frames, or longer than LONG_EPISODE_SECONDS with more than
+# LONG_DEAD_FRACTION dead, are dropped; a window is stripped when more than the given fraction of its
+# frames is dead (the recipe used 0.6).
+DEAD_THRESHOLD = 0.1
+DEAD_SECONDS = 2.0
+MIN_MOVING_FRACTION = 0.02
+LONG_EPISODE_SECONDS = 300.0
+LONG_DEAD_FRACTION = 0.5
+DEGENERATE_SPAN = 1e-6 # a channel whose q99 - q01 is at most this uses span 1 (a gripper that never moved)
+ACTION_PARAMETERIZATIONS = ("absolute", "joint_delta")
+SUPPORTED_MAJOR_VERSIONS = (2, 3)
+
+__all__ = [
+ "KIND",
+ "GRAY",
+ "MANIFEST_FORMAT",
+ "MIN_START",
+ "NORMALIZATION_CLIP",
+ "ROWS_FILENAME",
+ "STATISTICS_FILENAME",
+ "apply_dead_window_filter",
+ "build_manifest",
+ "build_rows",
+ "build_statistics",
+ "load_manifest",
+ "load_statistics",
+ "read_info",
+ "write_manifest",
+ "write_statistics",
+]
+
+
+# ---- metadata -------------------------------------------------------------------------------
+def read_info(root) -> dict:
+ root = Path(root)
+ info = json.loads((root / "meta" / "info.json").read_text())
+ version = major_version(info)
+ if version not in SUPPORTED_MAJOR_VERSIONS:
+ raise ValueError(
+ f"unsupported LeRobot codebase_version {info.get('codebase_version')!r}; expected v2.x or v3.x"
+ )
+ fps = info.get("fps")
+ if not isinstance(fps, (int, float)) or fps <= 0 or not float(fps).is_integer():
+ raise ValueError(f"LeRobot fps must be a positive whole number, got {fps!r}")
+ if "features" not in info or "data_path" not in info or "video_path" not in info:
+ raise ValueError("meta/info.json must list features, data_path and video_path")
+ return info
+
+
+def major_version(info: dict) -> int:
+ text = str(info.get("codebase_version", "")).strip().lstrip("vV")
+ try:
+ return int(text.split(".")[0])
+ except ValueError as error:
+ raise ValueError(f"unreadable codebase_version {info.get('codebase_version')!r}") from error
+
+
+def feature_names(feature: dict, dim: int) -> list[str] | None:
+ """``names`` of a 1-D feature: a list of ``dim`` names, or the single list some datasets nest under one
+ key (``{"motors": [...]}``); anything else is unnamed."""
+ names = feature.get("names")
+ if isinstance(names, dict) and len(names) == 1:
+ names = next(iter(names.values()))
+ if isinstance(names, list) and len(names) == dim and all(isinstance(n, str) for n in names):
+ return list(names)
+ return None
+
+
+def vector_dim(features: dict, key: str) -> int:
+ feature = features.get(key)
+ if feature is None:
+ raise ValueError(f"feature {key!r} is not in the dataset; available: {sorted(features)}")
+ shape = feature.get("shape")
+ if not isinstance(shape, list) or len(shape) != 1 or int(shape[0]) < 1:
+ raise ValueError(f"feature {key!r} must be a 1-D vector, got shape {shape}")
+ return int(shape[0])
+
+
+def camera_hw(features: dict, key: str) -> tuple[int, int]:
+ feature = features.get(key)
+ if feature is None:
+ cams = sorted(k for k, f in features.items() if f.get("dtype") in ("video", "image"))
+ raise ValueError(f"camera feature {key!r} is not in the dataset; cameras: {cams}")
+ if feature.get("dtype") != "video":
+ raise ValueError(
+ f"camera feature {key!r} has dtype {feature.get('dtype')!r}; only video streams are read"
+ )
+ shape, names = list(feature["shape"]), feature.get("names")
+ if isinstance(names, list) and {"height", "width"} <= set(names):
+ return int(shape[names.index("height")]), int(shape[names.index("width")])
+ if len(shape) == 3 and shape[-1] in (1, 3):
+ return int(shape[0]), int(shape[1])
+ if len(shape) == 3 and shape[0] in (1, 3):
+ return int(shape[1]), int(shape[2])
+ raise ValueError(f"camera feature {key!r}: cannot read height and width from shape {shape}")
+
+
+def load_tasks(root: Path, version: int) -> dict[int, str]:
+ if version >= 3:
+ import pyarrow.parquet as pq
+
+ table = pq.read_table(root / "meta" / "tasks.parquet").to_pydict()
+ if "task_index" not in table:
+ return {i: str(t) for i, t in enumerate(table["task"])}
+ column = "task" if "task" in table else next((k for k in table if k != "task_index"), None)
+ if column is None:
+ raise ValueError("meta/tasks.parquet has no task column")
+ return {int(i): str(t) for i, t in zip(table["task_index"], table[column], strict=True)}
+ tasks = {}
+ for line in (root / "meta" / "tasks.jsonl").read_text().splitlines():
+ if line.strip():
+ row = json.loads(line)
+ tasks[int(row["task_index"])] = str(row["task"])
+ return tasks
+
+
+def _episode_caption(tasks: list[str]) -> str:
+ """Several tasks of one episode become paraphrases the loader picks from (``select_caption``)."""
+ return CAPTION_SEPARATOR.join(str(t).strip() for t in tasks if str(t).strip())
+
+
+def _list_episodes_v3(root: Path, info: dict, cameras: dict[str, str], fps: int, counts: dict) -> list[dict]:
+ import pyarrow.parquet as pq
+
+ columns = ["episode_index", "tasks", "length", "data/chunk_index", "data/file_index"]
+ columns += ["dataset_from_index", "dataset_to_index"]
+ columns += [
+ f"videos/{feature}/{suffix}"
+ for feature in cameras.values()
+ for suffix in ("chunk_index", "file_index", "from_timestamp", "to_timestamp")
+ ]
+ episodes = []
+ for parquet in sorted((root / "meta" / "episodes").rglob("*.parquet")):
+ for row in pq.read_table(parquet, columns=columns).to_pylist():
+ counts["listed"] += 1
+ n = int(row["length"])
+ if row["dataset_to_index"] - row["dataset_from_index"] != n:
+ counts["misaligned"] += 1
+ continue
+ videos, aligned = {}, True
+ for stream, feature in cameras.items():
+ prefix = f"videos/{feature}"
+ first, last = (float(row[f"{prefix}/{s}"]) * fps for s in ("from_timestamp", "to_timestamp"))
+ if not all(math.isclose(x, round(x), rel_tol=0, abs_tol=1e-3) for x in (first, last)):
+ aligned = False
+ if round(last) - round(first) != n:
+ aligned = False
+ videos[stream] = {
+ "file": info["video_path"].format(
+ video_key=feature,
+ chunk_index=row[f"{prefix}/chunk_index"],
+ file_index=row[f"{prefix}/file_index"],
+ ),
+ "first_frame": int(round(first)),
+ }
+ if not aligned:
+ counts["misaligned"] += 1
+ continue
+ episodes.append(
+ {
+ "episode_index": int(row["episode_index"]),
+ "n_frames": n,
+ "caption": _episode_caption(list(row["tasks"] or [])),
+ "data_file": info["data_path"].format(
+ chunk_index=row["data/chunk_index"], file_index=row["data/file_index"]
+ ),
+ "from_index": int(row["dataset_from_index"]),
+ "videos": videos,
+ }
+ )
+ return episodes
+
+
+def _list_episodes_v2(root: Path, info: dict, cameras: dict[str, str], counts: dict) -> list[dict]:
+ chunks_size = int(info.get("chunks_size", 1000))
+ episodes = []
+ for line in (root / "meta" / "episodes.jsonl").read_text().splitlines():
+ if not line.strip():
+ continue
+ row = json.loads(line)
+ counts["listed"] += 1
+ index = int(row["episode_index"])
+ chunk = index // max(1, chunks_size)
+ episodes.append(
+ {
+ "episode_index": index,
+ "n_frames": int(row["length"]),
+ "caption": _episode_caption(list(row.get("tasks") or [])),
+ "data_file": info["data_path"].format(episode_chunk=chunk, episode_index=index),
+ "from_index": None, # the global frame index of the episode's parquet; read by build_rows
+ "videos": {
+ stream: {
+ "file": info["video_path"].format(
+ episode_chunk=chunk, video_key=feature, episode_index=index
+ ),
+ "first_frame": 0,
+ }
+ for stream, feature in cameras.items()
+ },
+ }
+ )
+ return episodes
+
+
+def build_manifest(
+ source_root,
+ cameras: dict[str, str],
+ *,
+ state_key: str = "observation.state",
+ action_key: str = "action",
+ chunk_size: int = 32,
+ val_episodes: int = 0,
+ dataset_id: str | None = None,
+ revision: str | None = None,
+ only_available: bool = False,
+ hash_files: bool = False,
+) -> dict:
+ """List the episodes of a LeRobot dataset into one JSON-ready manifest.
+
+ ``cameras`` maps the stream names the policy sees (``images.``; layout order) to the dataset's
+ video features, e.g. ``{"top": "observation.images.top", "wrist": "observation.images.front"}``; the
+ value ``"gray"`` declares a stream the dataset lacks, served as a flat mid-gray tile (a single-camera
+ dataset trained with the two-tile layout of the SO-101 checkpoints). Episodes without a complete
+ ``chunk_size + 1`` frame window from frame ``MIN_START`` on, and v3 episodes whose video segments do not
+ start and end on whole frames spanning the episode, are counted and left out. ``only_available``
+ additionally drops episodes whose files are not on disk. The last ``val_episodes`` eligible episodes (by
+ index) are marked ``split: val`` and held out of training; the rest are ``train``.
+ """
+ root = Path(source_root)
+ if not cameras:
+ raise ValueError("name at least one camera: {stream: dataset feature}")
+ if val_episodes < 0:
+ raise ValueError("val_episodes must be non-negative")
+ info = read_info(root)
+ version, fps = major_version(info), int(info["fps"])
+ features = info["features"]
+ state_dim, action_dim = vector_dim(features, state_key), vector_dim(features, action_key)
+ video_cameras = {stream: feature for stream, feature in cameras.items() if feature != GRAY}
+ if not video_cameras:
+ raise ValueError("at least one camera must be a video feature of the dataset")
+ hw = {
+ stream: None if feature == GRAY else list(camera_hw(features, feature))
+ for stream, feature in cameras.items()
+ }
+ counts = {"listed": 0, "eligible": 0, "no_valid_window": 0, "misaligned": 0, "unavailable": 0}
+ listed = (
+ _list_episodes_v3(root, info, video_cameras, fps, counts)
+ if version >= 3
+ else _list_episodes_v2(root, info, video_cameras, counts)
+ )
+ episodes, files, valid_total = [], {}, 0
+ for episode in sorted(listed, key=lambda e: e["episode_index"]):
+ n = episode["n_frames"]
+ ranges = [[MIN_START, n]]
+ n_valid = sum(c for _, c in valid_window_spans(n, ranges, chunk_size))
+ if n_valid == 0:
+ counts["no_valid_window"] += 1
+ continue
+ needed = [episode["data_file"], *(v["file"] for v in episode["videos"].values())]
+ if only_available and not all((root / f).is_file() for f in needed):
+ counts["unavailable"] += 1
+ continue
+ for f in needed:
+ files.setdefault(f, None)
+ counts["eligible"] += 1
+ valid_total += n_valid
+ episodes.append(
+ {
+ "episode_index": episode["episode_index"],
+ "episode_id": f"episode_{episode['episode_index']:06d}",
+ "split": "train",
+ "n_frames": n,
+ "caption": episode["caption"],
+ "valid_ranges": ranges,
+ "n_valid_starts": n_valid,
+ "data_file": episode["data_file"],
+ "from_index": episode["from_index"],
+ "videos": {stream: episode["videos"].get(stream) for stream in cameras},
+ }
+ )
+ if val_episodes >= len(episodes) and episodes:
+ raise ValueError(f"val_episodes {val_episodes} would leave no training episode of {len(episodes)}")
+ for episode in episodes[len(episodes) - val_episodes :] if val_episodes else []:
+ episode["split"] = "val"
+ counts["train_episodes"] = sum(e["split"] == "train" for e in episodes)
+ counts["val_episodes"] = sum(e["split"] == "val" for e in episodes)
+ file_records = {}
+ for name in sorted(files):
+ path = root / name
+ record = {"bytes": path.stat().st_size if path.is_file() else None}
+ if hash_files and path.is_file():
+ record["sha256"] = sha256(path)
+ file_records[name] = record
+ counts["valid_starts_total"] = valid_total
+ return {
+ "format_version": MANIFEST_FORMAT,
+ "kind": KIND,
+ "dataset_id": dataset_id,
+ "dataset_revision": revision,
+ "codebase_version": info.get("codebase_version"),
+ "robot_type": info.get("robot_type"),
+ "fps": fps,
+ "chunk_size": chunk_size,
+ "min_start": MIN_START,
+ "action_prev": True,
+ "total_frames": int(info["total_frames"]),
+ "state_key": state_key,
+ "action_key": action_key,
+ "state_dim": state_dim,
+ "action_dim": action_dim,
+ "state_names": feature_names(features[state_key], state_dim),
+ "action_names": feature_names(features[action_key], action_dim),
+ "cameras": dict(cameras),
+ "camera_order": list(cameras),
+ "camera_hw": hw,
+ "counts": counts,
+ "files": file_records,
+ "episodes": episodes,
+ }
+
+
+def load_manifest(path) -> dict:
+ manifest = json.loads(Path(path).read_text())
+ if manifest.get("format_version") != MANIFEST_FORMAT or manifest.get("kind") != KIND:
+ raise ValueError("unsupported LeRobot manifest")
+ return manifest
+
+
+# ---- rows -----------------------------------------------------------------------------------
+def _vectors(column, n: int, dim: int, name: str) -> np.ndarray | str:
+ values = np.asarray(column.to_pylist(), dtype=np.float32)
+ if values.shape != (n, dim):
+ return f"{name} has shape {values.shape}, expected {(n, dim)}"
+ if not np.isfinite(values).all():
+ return f"{name} holds non-finite values"
+ return values
+
+
+def _validate_episode_rows(part, n: int, start: int, fps: int) -> str | None:
+ if part.num_rows != n:
+ return f"{part.num_rows} rows for {n} frames"
+ if not np.array_equal(part["frame_index"].to_numpy(), np.arange(n)):
+ return "non-contiguous frame_index"
+ if not np.array_equal(part["index"].to_numpy(), np.arange(start, start + n)):
+ return "non-contiguous index"
+ times = np.asarray(part["timestamp"].to_numpy(), dtype=np.float64)
+ if np.abs(times - np.arange(n) / fps).max() > 0.25 / fps:
+ return f"timestamps off the {fps} Hz grid"
+ return None
+
+
+def build_rows(source_root, manifest: dict, output) -> dict:
+ """Write ``rows.f32.npy`` (``total_frames x (state_dim + action_dim)``); drop episodes that fail validation.
+
+ Checks per episode: ``frame_index`` runs ``0 .. n-1``, ``index`` runs from the episode's global offset
+ (v3: ``dataset_from_index``; v2.1: the first ``index`` of its parquet), timestamps sit on the frame
+ grid, state and action are finite vectors of the declared width. Rows of dropped or unlisted frames
+ stay NaN. The manifest's episode list, counts, ``total_frames`` and ``rows`` record are updated.
+ """
+ import pyarrow.parquet as pq
+
+ root, output = Path(source_root), Path(output)
+ fps = int(manifest["fps"])
+ state_key, action_key = manifest["state_key"], manifest["action_key"]
+ state_dim, action_dim = int(manifest["state_dim"]), int(manifest["action_dim"])
+ width = state_dim + action_dim
+ columns = ["frame_index", "index", "timestamp", state_key, action_key]
+ v3 = all(e["from_index"] is not None for e in manifest["episodes"])
+ if not v3: # v2.1: one parquet per episode; its first global index is the episode's offset
+ for episode in manifest["episodes"]:
+ first = pq.read_table(root / episode["data_file"], columns=["index"])["index"]
+ episode["from_index"] = int(first[0].as_py()) if len(first) else 0
+ total = max(
+ int(manifest["total_frames"]), max(e["from_index"] + e["n_frames"] for e in manifest["episodes"])
+ )
+ output.parent.mkdir(parents=True, exist_ok=True)
+ rows = np.lib.format.open_memmap(output, mode="w+", dtype=np.float32, shape=(total, width))
+ rows[:] = np.nan
+ by_file: dict[str, list[dict]] = {}
+ for episode in manifest["episodes"]:
+ by_file.setdefault(episode["data_file"], []).append(episode)
+ kept, rejected = [], {}
+ for data_file, group in sorted(by_file.items()):
+ table = pq.read_table(root / data_file, columns=columns + ["episode_index"])
+ episode_col = table["episode_index"].to_numpy()
+ for episode in group:
+ n, start = episode["n_frames"], episode["from_index"]
+ part = table.filter(episode_col == episode["episode_index"])
+ reason = _validate_episode_rows(part, n, start, fps)
+ if reason is None:
+ state = _vectors(part[state_key], n, state_dim, state_key)
+ action = _vectors(part[action_key], n, action_dim, action_key)
+ reason = state if isinstance(state, str) else action if isinstance(action, str) else None
+ if reason is not None:
+ rejected[episode["episode_id"]] = reason
+ continue
+ rows[start : start + n] = np.concatenate([state, action], axis=1)
+ kept.append(episode)
+ rows.flush()
+ manifest["episodes"] = kept
+ manifest["total_frames"] = total
+ _recount(manifest)
+ manifest["counts"]["rows_rejected"] = len(rejected)
+ manifest["rows"] = {"file": output.name, "sha256": sha256(output), "width": width}
+ return {"kept": len(kept), "rejected": rejected}
+
+
+def _recount(manifest: dict) -> None:
+ counts, episodes = manifest["counts"], manifest["episodes"]
+ counts["eligible"] = len(episodes)
+ counts["valid_starts_total"] = sum(e["n_valid_starts"] for e in episodes)
+ counts["train_episodes"] = sum(e.get("split", "train") == "train" for e in episodes)
+ counts["val_episodes"] = sum(e.get("split", "train") == "val" for e in episodes)
+
+
+# ---- dead-window stripping ----------------------------------------------------------------
+def dead_mask(
+ states: np.ndarray, fps: float, *, threshold: float = DEAD_THRESHOLD, seconds: float = DEAD_SECONDS
+):
+ """``(mask, moving_fraction)``: frames inside stretches of at least ``seconds`` in which no joint moves
+ more than ``threshold`` per frame; frame 0 counts as moving (the corpus builder's definition)."""
+ step = np.abs(np.diff(np.asarray(states, dtype=np.float64), axis=0)).max(axis=1)
+ moving = np.concatenate([[True], step > threshold])
+ mask = np.zeros(len(states), dtype=bool)
+ min_run = max(1, int(round(seconds * fps)))
+ run_start = None
+ for i, m in enumerate(moving):
+ if not m and run_start is None:
+ run_start = i
+ elif m and run_start is not None:
+ if i - run_start >= min_run:
+ mask[run_start:i] = True
+ run_start = None
+ if run_start is not None and len(moving) - run_start >= min_run:
+ mask[run_start:] = True
+ return mask, float(moving.mean())
+
+
+def _ranges_of_starts(starts: list[int], chunk_size: int) -> list[list[int]]:
+ """Allowed window starts -> half-open frame ranges that ``valid_window_spans`` maps back onto exactly them."""
+ ranges: list[list[int]] = []
+ for s in starts:
+ if ranges and ranges[-1][1] == s + chunk_size: # consecutive start: extend the range by one frame
+ ranges[-1][1] = s + chunk_size + 1
+ else:
+ ranges.append([s, s + chunk_size + 1])
+ return ranges
+
+
+def apply_dead_window_filter(manifest: dict, rows: np.ndarray, *, max_dead_fraction: float) -> dict:
+ """Drop static episodes and strip the windows whose frames are dead beyond ``max_dead_fraction``.
+
+ Uses the state columns of the rows array. Episodes are dropped when fewer than ``MIN_MOVING_FRACTION`` of
+ their frames move, or when they last longer than ``LONG_EPISODE_SECONDS`` with more than
+ ``LONG_DEAD_FRACTION`` dead; the remaining episodes keep exactly the window starts whose ``chunk_size + 1``
+ frames are dead for at most ``max_dead_fraction`` (as ``valid_ranges``). Counts are recorded in the
+ manifest; returns them.
+ """
+ if not 0 <= max_dead_fraction <= 1:
+ raise ValueError("max_dead_fraction must lie in [0, 1]")
+ fps, chunk_size, state_dim = (
+ float(manifest["fps"]),
+ int(manifest["chunk_size"]),
+ int(manifest["state_dim"]),
+ )
+ kept, dropped = [], {"dead_static": 0, "dead_long": 0, "dead_no_window": 0}
+ removed_starts = 0
+ for episode in manifest["episodes"]:
+ start, n = episode["from_index"], episode["n_frames"]
+ states = np.asarray(rows[start : start + n, :state_dim], dtype=np.float64)
+ mask, moving = dead_mask(states, fps)
+ if moving < MIN_MOVING_FRACTION:
+ dropped["dead_static"] += 1
+ continue
+ if n > LONG_EPISODE_SECONDS * fps and mask.mean() > LONG_DEAD_FRACTION:
+ dropped["dead_long"] += 1
+ continue
+ before = [
+ s for f, c in valid_window_spans(n, episode["valid_ranges"], chunk_size) for s in range(f, f + c)
+ ]
+ starts = [s for s in before if mask[s : s + chunk_size + 1].mean() <= max_dead_fraction]
+ removed_starts += len(before) - len(starts)
+ if not starts:
+ dropped["dead_no_window"] += 1
+ continue
+ episode["valid_ranges"] = _ranges_of_starts(starts, chunk_size)
+ episode["n_valid_starts"] = len(starts)
+ assert sum(c for _, c in valid_window_spans(n, episode["valid_ranges"], chunk_size)) == len(starts), (
+ "valid window count mismatch"
+ )
+ kept.append(episode)
+ manifest["episodes"] = kept
+ _recount(manifest)
+ manifest["counts"].update(dropped)
+ manifest["counts"]["dead_starts_removed"] = removed_starts
+ manifest["dead_window_filter"] = {
+ "max_dead_fraction": max_dead_fraction,
+ "threshold": DEAD_THRESHOLD,
+ "seconds": DEAD_SECONDS,
+ "min_moving_fraction": MIN_MOVING_FRACTION,
+ "long_episode_seconds": LONG_EPISODE_SECONDS,
+ "long_dead_fraction": LONG_DEAD_FRACTION,
+ }
+ return {**dropped, "dead_starts_removed": removed_starts}
+
+
+def open_rows(path, total_frames: int, width: int) -> np.ndarray:
+ rows = np.load(path, mmap_mode="r")
+ if rows.dtype != np.float32 or rows.shape != (total_frames, width):
+ raise ValueError(
+ f"rows array must be float32 ({total_frames}, {width}), got {rows.dtype} {rows.shape}"
+ )
+ return rows
+
+
+# ---- normalization statistics ----------------------------------------------------------------
+def normalize_dims(dims, dim: int) -> tuple[int, ...]:
+ """Non-negative, sorted, distinct channel indices (negative values count from the end)."""
+ out = sorted({int(d) % dim for d in dims})
+ if any(not -dim <= int(d) < dim for d in dims):
+ raise ValueError(f"channel index outside the {dim} action channels: {list(dims)}")
+ return tuple(out)
+
+
+def action_targets(actions: np.ndarray, parameterization: str, absolute_dims: tuple[int, ...]) -> np.ndarray:
+ """The training targets of one episode's actions ``(n, A)``: the actions themselves (``absolute``), or
+ the per-frame deltas ``a[t] - a[t-1]`` with the first row zero and ``absolute_dims`` kept absolute
+ (``joint_delta``, the SO-101 recipe's parameterization and its builder's convention)."""
+ if parameterization == "absolute":
+ return actions.astype(np.float64)
+ if parameterization != "joint_delta":
+ raise ValueError(
+ f"unknown action parameterization {parameterization!r}; choose from {ACTION_PARAMETERIZATIONS}"
+ )
+ actions = actions.astype(np.float64)
+ targets = np.zeros_like(actions)
+ targets[1:] = actions[1:] - actions[:-1]
+ if absolute_dims:
+ targets[:, list(absolute_dims)] = actions[:, list(absolute_dims)]
+ return targets
+
+
+def build_statistics(
+ manifest: dict,
+ rows: np.ndarray,
+ *,
+ action_parameterization: str = "joint_delta",
+ absolute_action_dims=(-1,),
+ clip: float = NORMALIZATION_CLIP,
+) -> dict:
+ """Per-channel q01 / q99 of the action targets and of the state over every frame of the kept episodes.
+
+ The percentiles are ``numpy.percentile`` (linear interpolation) over float64 values, the targets of
+ ``action_targets`` per episode, over the train and the held-out episodes alike; this is the
+ computation the SO-101 community corpus reference (``configs/so101/community_corpus.json``) was built
+ with, so re-indexing one of its datasets reproduces the listed bounds.
+ """
+ if action_parameterization not in ACTION_PARAMETERIZATIONS:
+ raise ValueError(f"unknown action parameterization {action_parameterization!r}")
+ state_dim, action_dim = int(manifest["state_dim"]), int(manifest["action_dim"])
+ dims = (
+ normalize_dims(absolute_action_dims, action_dim) if action_parameterization == "joint_delta" else ()
+ )
+ states, targets, frames = [], [], 0
+ for episode in manifest["episodes"]:
+ start, n = episode["from_index"], episode["n_frames"]
+ block = np.asarray(rows[start : start + n], dtype=np.float64)
+ if not np.isfinite(block).all():
+ raise ValueError(f"episode {episode['episode_id']}: rows missing from the rows array")
+ states.append(block[:, :state_dim])
+ targets.append(action_targets(block[:, state_dim:], action_parameterization, dims))
+ frames += n
+ if not targets:
+ raise ValueError("no episodes to compute statistics from")
+ state, target = np.concatenate(states), np.concatenate(targets)
+
+ def bounds(values: np.ndarray) -> dict[str, list[float]]:
+ return {
+ "q01": [float(v) for v in np.percentile(values, 1, axis=0)],
+ "q99": [float(v) for v in np.percentile(values, 99, axis=0)],
+ }
+
+ return {
+ "format_version": STATISTICS_FORMAT,
+ "normalization": "range",
+ "formula": (
+ "x_norm = clip(2 * (x - q01) / span - 1, -clip, clip) with span = q99 - q01, or 1 where "
+ f"q99 - q01 <= {DEGENERATE_SPAN}"
+ ),
+ "clip": float(clip),
+ "episodes": len(targets),
+ "frames": frames,
+ "action": {
+ "parameterization": action_parameterization,
+ "absolute_dims": list(dims),
+ "names": manifest.get("action_names"),
+ **bounds(target),
+ },
+ "state": {"names": manifest.get("state_names"), **bounds(state)},
+ }
+
+
+def write_statistics(statistics: dict, path) -> None:
+ Path(path).write_text(json.dumps(statistics, indent=1) + "\n")
+
+
+def load_statistics(path) -> dict:
+ statistics = json.loads(Path(path).read_text())
+ if statistics.get("format_version") != STATISTICS_FORMAT or statistics.get("normalization") != "range":
+ raise ValueError("unsupported statistics file")
+ return statistics
+
+
+def index_dataset(
+ source_root,
+ output_dir,
+ cameras: dict[str, str],
+ *,
+ action_parameterization: str = "joint_delta",
+ absolute_action_dims=(-1,),
+ clip: float = NORMALIZATION_CLIP,
+ strip_dead_windows: float | None = None,
+ **manifest_kwargs: Any,
+) -> dict:
+ """``build_manifest`` + ``build_rows`` (+ ``apply_dead_window_filter``) + ``build_statistics`` into
+ ``output_dir``; returns a summary."""
+ out = Path(output_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ manifest = build_manifest(source_root, cameras, **manifest_kwargs)
+ rows_result = build_rows(source_root, manifest, out / ROWS_FILENAME)
+ rows = open_rows(out / ROWS_FILENAME, manifest["total_frames"], manifest["rows"]["width"])
+ if strip_dead_windows is not None:
+ apply_dead_window_filter(manifest, rows, max_dead_fraction=strip_dead_windows)
+ statistics = build_statistics(
+ manifest,
+ rows,
+ action_parameterization=action_parameterization,
+ absolute_action_dims=absolute_action_dims,
+ clip=clip,
+ )
+ write_statistics(statistics, out / STATISTICS_FILENAME)
+ write_manifest(manifest, out / "manifest.json")
+ return {
+ "manifest": str(out / "manifest.json"),
+ "statistics": str(out / STATISTICS_FILENAME),
+ "counts": manifest["counts"],
+ "rows_rejected": rows_result["rejected"],
+ "action": {k: statistics["action"][k] for k in ("parameterization", "absolute_dims", "q01", "q99")},
+ "state": {k: statistics["state"][k] for k in ("q01", "q99")},
+ }
diff --git a/flux-umi/src/flux_action/data/schema.py b/flux-umi/src/flux_action/data/schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..440630450fcf6ad028f104b40d6cc4b033d48cc0
--- /dev/null
+++ b/flux-umi/src/flux_action/data/schema.py
@@ -0,0 +1,62 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Versioned intermediate episode metadata. No implicit unit or gripper conversion."""
+
+import math
+from dataclasses import asdict, dataclass
+
+from .windows import valid_window_spans
+
+
+@dataclass(frozen=True)
+class EpisodeMetadata:
+ episode_id: str
+ source_version: str
+ split: str
+ n_frames: int
+ valid_ranges: tuple[tuple[int, int], ...]
+ caption: str
+ schema_version: int = 1
+ fps: float = 15.0
+ camera_order: tuple[str, ...] = ("wrist", "left", "right")
+ action_space: str = "absolute_joint_position"
+ joint_units: str = "radians"
+ gripper_convention: str = "closed_fraction"
+
+ def __post_init__(self):
+ object.__setattr__(self, "valid_ranges", tuple(tuple(r) for r in self.valid_ranges))
+ object.__setattr__(self, "camera_order", tuple(self.camera_order))
+ if self.schema_version != 1 or not self.episode_id or not self.source_version or not self.split:
+ raise ValueError("version 1 metadata requires episode_id, source_version and split")
+ if not isinstance(self.caption, str):
+ raise ValueError("caption must be a string")
+ if not math.isfinite(self.fps) or self.fps != 15.0:
+ raise ValueError("DROID intermediate requires 15 Hz timestamps")
+ if self.camera_order != ("wrist", "left", "right"):
+ raise ValueError("DROID cameras must be wrist, left, right")
+ if (self.action_space, self.joint_units, self.gripper_convention) != (
+ "absolute_joint_position",
+ "radians",
+ "closed_fraction",
+ ):
+ raise ValueError("expected absolute joints in radians and closed-fraction gripper")
+ valid_window_spans(self.n_frames, self.valid_ranges)
+ previous_end = 0
+ for start, end in self.valid_ranges:
+ if not 0 <= start < end <= self.n_frames or start < previous_end:
+ raise ValueError("prepared valid ranges must be ordered, disjoint and within the episode")
+ previous_end = end
+
+ def to_dict(self):
+ return asdict(self)
diff --git a/flux-umi/src/flux_action/data/umi/__init__.py b/flux-umi/src/flux_action/data/umi/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..92225c48b47898b660ba0048b1f7224792efe9d0
--- /dev/null
+++ b/flux-umi/src/flux_action/data/umi/__init__.py
@@ -0,0 +1 @@
+"""CPU-only preparation helpers for dual-hand UMI data."""
diff --git a/flux-umi/src/flux_action/data/umi/all_windows.py b/flux-umi/src/flux_action/data/umi/all_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..6514f6027053831edf5cf935d067692cca90f996
--- /dev/null
+++ b/flux-umi/src/flux_action/data/umi/all_windows.py
@@ -0,0 +1,137 @@
+"""Every legal UMI window once per epoch, with explicit global-batch tail padding."""
+
+import hashlib
+import math
+import os
+from functools import cached_property
+
+from flux_action.training.data import epoch_order, get_epoch_loader_state, set_epoch_loader_state
+
+from .dataset import UMIWindowDataset, build as build_visits
+
+SAMPLER_VERSION = "umi-all-windows-pad-v1"
+
+
+class AllWindowDataset(UMIWindowDataset):
+ def set_loader_state(self, state):
+ self._loader_state = state
+
+ def set_continuous_end(self, end_batch):
+ """Stream through epoch boundaries without resetting the DataLoader iterator."""
+ first = self.epoch * self.batches_per_rank + self.skip_batches
+ if end_batch <= first:
+ raise ValueError("continuous loader must have remaining batches")
+ self._continuous_end = end_batch
+
+ def _continuous_windows(self):
+ from torch.utils.data import get_worker_info
+
+ info = get_worker_info()
+ if info is None or info.num_workers != self.num_workers:
+ raise RuntimeError("continuous epochs require the configured multi-process loader")
+ first = self.epoch * self.batches_per_rank + self.skip_batches + info.id
+ for absolute_batch in range(first, self._continuous_end, self.num_workers):
+ epoch, batch = divmod(absolute_batch, self.batches_per_rank)
+ if epoch != self.epoch:
+ self.epoch = epoch
+ self.__dict__.pop("order", None)
+ self._states.clear()
+ self._videos.clear()
+ first_position = (batch * self.world_size + self.rank) * self.windows_per_rank
+ for position in range(first_position, first_position + self.windows_per_rank):
+ yield self.window(position)
+
+ def start_epoch(self, epoch, skip_batches):
+ if not 0 <= skip_batches <= self.batches_per_rank:
+ raise ValueError("skip_batches outside epoch")
+ if epoch < 0 or getattr(self, "_loader_state", None) is None:
+ raise ValueError("missing reusable loader state")
+ set_epoch_loader_state(self._loader_state, epoch, skip_batches)
+ self.epoch, self.skip_batches = epoch, skip_batches
+ self.__dict__.pop("order", None)
+
+ def __iter__(self):
+ if getattr(self, "_continuous_end", None) is not None:
+ return self._continuous_windows()
+ if getattr(self, "_loader_state", None) is not None:
+ self.epoch, self.skip_batches = get_epoch_loader_state(self._loader_state)
+ self.__dict__.pop("order", None)
+ self._states.clear()
+ return super().__iter__()
+
+ @cached_property
+ def window_index(self):
+ return [
+ (i, start)
+ for i, episode in enumerate(self.episodes)
+ for lo, hi in episode["start_ranges"]
+ for start in range(lo, hi)
+ ]
+
+ @property
+ def n_positions(self):
+ return len(self.window_index)
+
+ def epoch_batches(self, grad_accumulation):
+ self.grad_accumulation = grad_accumulation
+ self.global_batch = self.world_size * self.windows_per_rank * grad_accumulation
+ self.updates_per_epoch = math.ceil(self.n_positions / self.global_batch)
+ self.padded_positions = self.updates_per_epoch * self.global_batch
+ self.padding = self.padded_positions - self.n_positions
+ return self.updates_per_epoch * grad_accumulation
+
+ @cached_property
+ def order(self):
+ return epoch_order(self.n_positions, self.seed, self.epoch)
+
+ def rank_order(self):
+ # All ranks advance the same number of whole microbatches. Workers never drop a tail.
+ return [
+ p
+ for batch in range(self.batches_per_rank)
+ for p in range(
+ (batch * self.world_size + self.rank) * self.windows_per_rank,
+ (batch * self.world_size + self.rank + 1) * self.windows_per_rank,
+ )
+ ]
+
+ def worker_positions(self, worker_id):
+ first = self.skip_batches + (worker_id - self.skip_batches) % self.num_workers
+ return [
+ p
+ for batch in range(first, self.batches_per_rank, self.num_workers)
+ for p in range(
+ (batch * self.world_size + self.rank) * self.windows_per_rank,
+ (batch * self.world_size + self.rank + 1) * self.windows_per_rank,
+ )
+ ]
+
+ def identity(self, position):
+ if not 0 <= position < self.padded_positions:
+ raise ValueError("window position outside the epoch")
+ episode, start = self.window_index[self.order[position % self.n_positions]]
+ key = f"{SAMPLER_VERSION}:{self.seed}:{self.epoch}:{position}:{episode}:{start}"
+ window_seed = int.from_bytes(hashlib.sha256(key.encode()).digest()[:8], "big") % (2**63)
+ return episode, start, window_seed
+
+ def window(self, position):
+ episode, start, window_seed = self.identity(position)
+ return self.window_at(episode, start, window_seed=window_seed)
+
+
+def build(config, **kwargs):
+ if os.environ.get("UMI_BENCH_HOST_CACHE"):
+ raise ValueError("full-data training must decode its real source videos")
+ if not config.source_root or config.visits_per_epoch != 1:
+ raise ValueError("all-window epochs do not use episode visits")
+ if config.sampling_contract != SAMPLER_VERSION:
+ raise ValueError("missing or changed all-window sampling contract")
+ from pathlib import Path
+ from .dataset import load_training
+
+ root = Path(config.source_root)
+ if hashlib.sha256((root / "training_manifest.json").read_bytes()).hexdigest() != config.sampling_manifest_sha256:
+ raise ValueError("all-window manifest changed")
+ if load_training(root)["legal_starts"] != config.sampling_legal_starts:
+ raise ValueError("all-window count changed")
+ return build_visits(config, dataset_class=AllWindowDataset, **kwargs)
diff --git a/flux-umi/src/flux_action/data/umi/dataset.py b/flux-umi/src/flux_action/data/umi/dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a4f1667746d2e24881dfafa564ac90138f817a4
--- /dev/null
+++ b/flux-umi/src/flux_action/data/umi/dataset.py
@@ -0,0 +1,153 @@
+"""UMI windows on the upstream episode/worker sampling schedule."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from ...training.data import WindowDataset
+from ..droid.video import decode_window
+from .representation import REPRESENTATION, make_window
+
+
+def digest(path):
+ with Path(path).open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def training_path(root, relative):
+ relative = Path(relative)
+ path = root / relative
+ if relative.is_absolute() or ".." in relative.parts or not relative.parts:
+ raise ValueError("unsafe training asset path")
+ if not path.resolve().is_relative_to(root.resolve()):
+ raise ValueError("training asset escapes root")
+ return path
+
+
+MANIFEST_KIND = "umi-training-v1"
+
+
+def load_training(root):
+ """Read ``training_manifest.json`` + ``statistics.json`` written by ``tools/prepare_umi_lerobot_v3.py``."""
+ root = Path(root)
+ manifest = json.loads((root / "training_manifest.json").read_text())
+ contract = {
+ "kind": MANIFEST_KIND,
+ "representation": REPRESENTATION,
+ "fps": 30,
+ "chunk_size": 32,
+ "state_dim": 20,
+ "action_dim": 20,
+ }
+ for key, value in contract.items():
+ if manifest.get(key) != value:
+ raise ValueError(f"wrong UMI manifest contract: {key}={manifest.get(key)!r}, expected {value!r}")
+ if digest(root / "statistics.json") != manifest["statistics_sha256"]:
+ raise ValueError("statistics.json does not match the manifest")
+ if not manifest["episodes"] or len({e["session"] for e in manifest["episodes"]}) != len(manifest["episodes"]):
+ raise ValueError("empty manifest or duplicate sessions")
+ legal = 0
+ for index, episode in enumerate(manifest["episodes"]):
+ if episode["episode_index"] != index:
+ raise ValueError("episode_index must equal manifest position")
+ training_path(root, episode["states"])
+ if set(episode["videos"]) != set(manifest["camera_order"]):
+ raise ValueError("episode cameras differ from camera_order: " + episode["session"])
+ legal += sum(hi - lo for lo, hi in episode["start_ranges"])
+ if legal != manifest["legal_starts"]:
+ raise ValueError("legal_starts disagrees with the episode start ranges")
+ statistics = json.loads((root / "statistics.json").read_text())
+ for kind in ("state", "action"):
+ bounds = np.asarray([statistics[kind]["q01"], statistics[kind]["q99"]])
+ if bounds.shape != (2, 20) or not np.isfinite(bounds).all() or (bounds[1] < bounds[0]).any():
+ raise ValueError("invalid normalization bounds")
+ return manifest
+
+
+class UMIWindowDataset(WindowDataset):
+ def __init__(self, manifest, source_root, *, host_cache=None, **kwargs):
+ super().__init__(manifest, source_root, None, **kwargs)
+ self._states = {}
+ self._videos = {}
+ self.host_cache = Path(host_cache) if host_cache else None
+
+ def window_at(self, episode_position, start, *, task=None, window_seed=0):
+ episode = self.episodes[episode_position]
+ if not any(lo <= start < hi for lo, hi in episode["start_ranges"]):
+ raise ValueError("anchor outside legal range")
+ if not any(lo <= start - 1 and start + self.chunk_size < hi for lo, hi in episode["keep_ranges"]):
+ raise ValueError("window crosses physical keep boundary")
+ if episode_position not in self._states:
+ self._states[episode_position] = np.load(
+ Path(self.source_root) / episode["states"], mmap_mode="r"
+ )
+ states = self._states[episode_position]
+ if states.shape != (episode["n_frames"], 16):
+ raise ValueError("wrong source pose shape")
+ state, action = make_window(states, start, self.chunk_size)
+ item = {
+ "state": torch.from_numpy(state),
+ "action": torch.from_numpy(action),
+ "task": task or episode["caption"],
+ "episode_index": episode["episode_index"],
+ "start": start,
+ "window_seed": window_seed,
+ }
+ for camera in self.cameras:
+ if self.host_cache:
+ key = (episode_position, camera)
+ if key not in self._videos:
+ self._videos[key] = np.load(
+ self.host_cache / f"{episode['session']}-{camera}.npy", mmap_mode="r"
+ )
+ frames = self._videos[key][start : start + self.chunk_size + 1]
+ else:
+ frames = decode_window(
+ str(Path(self.source_root) / episode["videos"][camera]["file"]),
+ start,
+ self.chunk_size + 1,
+ fps=self.fps,
+ frame_hw=self.frame_hw,
+ decoder=self.decoder,
+ threads=1,
+ resize=True,
+ )
+ expected = (self.chunk_size + 1, *self.frame_hw, 3)
+ if frames.shape != expected or frames.dtype != np.uint8:
+ raise ValueError(f"bad decoded window: {frames.shape} != {expected}")
+ item[f"images.{camera}"] = torch.from_numpy(np.array(frames)).permute(0, 3, 1, 2).contiguous()
+ return item
+
+
+def build(config, *, dataset_class=UMIWindowDataset, **kwargs):
+ manifest = load_training(config.source_root)
+ statistics = json.loads((Path(config.source_root) / "statistics.json").read_text())
+ expected = {
+ "action_dim": 20,
+ "chunk_size": 32,
+ "fps": 30,
+ "action_parameterization": "absolute",
+ "gripper_flip_dims": [],
+ "camera_keys": ["images." + camera for camera in manifest["camera_order"]],
+ "action_normalization": {k: statistics["action"][k] for k in ("q01", "q99")},
+ "state_normalization": {k: statistics["state"][k] for k in ("q01", "q99")},
+ }
+ for key, value in expected.items():
+ actual = config.policy.get(key)
+ if isinstance(actual, tuple):
+ actual = list(actual)
+ if actual != value:
+ raise ValueError(f"policy disagrees with UMI data contract: {key}")
+ return dataset_class(
+ manifest,
+ config.source_root,
+ **kwargs,
+ frame_hw=config.frame_hw,
+ decoder=config.decoder,
+ visits_per_epoch=config.visits_per_epoch,
+ host_cache=os.environ.get("UMI_BENCH_HOST_CACHE"),
+ )
diff --git a/flux-umi/src/flux_action/data/umi/representation.py b/flux-umi/src/flux_action/data/umi/representation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee2e57faa486018bc4d8f9c6a43e5fef578f68e5
--- /dev/null
+++ b/flux-umi/src/flux_action/data/umi/representation.py
@@ -0,0 +1,79 @@
+"""Per-hand current-anchor UMI poses. Source quaternion order is wxyz."""
+
+import numpy as np
+
+REPRESENTATION = "umi-current-anchor-prev1-rot6d-columns-v1"
+
+
+def quaternion_matrix(q):
+ q = np.asarray(q, dtype=np.float64)
+ if q.shape[-1] != 4 or not np.isfinite(q).all():
+ raise ValueError("expected finite wxyz quaternions")
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if np.any(norm < 1e-8):
+ raise ValueError("zero quaternion")
+ w, x, y, z = np.moveaxis(q / norm, -1, 0)
+ return np.stack(
+ [
+ 1 - 2 * (y * y + z * z),
+ 2 * (x * y - z * w),
+ 2 * (x * z + y * w),
+ 2 * (x * y + z * w),
+ 1 - 2 * (x * x + z * z),
+ 2 * (y * z - x * w),
+ 2 * (x * z - y * w),
+ 2 * (y * z + x * w),
+ 1 - 2 * (x * x + y * y),
+ ],
+ axis=-1,
+ ).reshape(*q.shape[:-1], 3, 3)
+
+
+def matrix_to_rotation6d(matrix):
+ """Concatenate COLUMN 0 and COLUMN 1, not the first two rows."""
+ matrix = np.asarray(matrix)
+ return np.concatenate([matrix[..., :, 0], matrix[..., :, 1]], axis=-1)
+
+
+def rotation6d_to_matrix(values):
+ """Gram-Schmidt columns; reject degenerate inputs rather than inventing an axis."""
+ values = np.asarray(values, dtype=np.float64)
+ if values.shape[-1] != 6 or not np.isfinite(values).all():
+ raise ValueError("expected six finite rotation coordinates")
+ a, b = values[..., :3], values[..., 3:]
+ norm_a = np.linalg.norm(a, axis=-1, keepdims=True)
+ if np.any(norm_a < 1e-8):
+ raise ValueError("degenerate first column")
+ a = a / norm_a
+ b = b - np.sum(a * b, axis=-1, keepdims=True) * a
+ norm_b = np.linalg.norm(b, axis=-1, keepdims=True)
+ if np.any(norm_b < 1e-8):
+ raise ValueError("degenerate second column")
+ b = b / norm_b
+ return np.stack([a, b, np.cross(a, b)], axis=-1)
+
+
+def relative_hand(anchor, targets):
+ """inv(T_anchor) @ T_target, with target gripper degrees unchanged."""
+ rotation = quaternion_matrix(anchor[3:7])
+ target_rotation = quaternion_matrix(targets[..., 3:7])
+ translation = np.einsum("ji,...j->...i", rotation, targets[..., :3] - anchor[:3])
+ relative_rotation = np.einsum("ji,...jk->...ik", rotation, target_rotation)
+ return np.concatenate([translation, matrix_to_rotation6d(relative_rotation), targets[..., 7:8]], axis=-1)
+
+
+def make_window(states, start, chunk_size=32):
+ """Images use t..t+32; targets use t+1..t+32; state uses t-1 with gripper at t."""
+ states = np.asarray(states, dtype=np.float64)
+ if states.ndim != 2 or states.shape[1] != 16 or not np.isfinite(states).all():
+ raise ValueError("expected finite (frames, 16) states")
+ if chunk_size < 1 or start < 1 or start + chunk_size >= len(states):
+ raise ValueError("window lacks previous or future pose")
+ obs, actions = [], []
+ for offset in (0, 8):
+ hand = states[:, offset : offset + 8]
+ state = relative_hand(hand[start], hand[start - 1])
+ state[-1] = hand[start, 7]
+ obs.append(state)
+ actions.append(relative_hand(hand[start], hand[start + 1 : start + chunk_size + 1]))
+ return np.concatenate(obs).astype(np.float32), np.concatenate(actions, axis=-1).astype(np.float32)
diff --git a/flux-umi/src/flux_action/data/windows.py b/flux-umi/src/flux_action/data/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..66ce3c588f5d61b74791c69a9b77e4fe6b269276
--- /dev/null
+++ b/flux-umi/src/flux_action/data/windows.py
@@ -0,0 +1,70 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Compact valid-start sampling: one window per episode visit."""
+
+from collections.abc import Iterable, Sequence
+from numbers import Integral
+from random import Random
+
+
+def valid_window_spans(n_frames: int, valid_ranges: Sequence[Sequence[int]], chunk_size: int = 32):
+ """Return (first_start, count) spans for complete chunk_size+1 frame windows.
+
+ Ranges are half-open. Out-of-bounds endpoints are clipped to the episode.
+ Range order/multiplicity is preserved; prepared metadata should be disjoint.
+ Missing valid ranges are an error, never a request to use the whole episode.
+ """
+ if isinstance(n_frames, bool) or not isinstance(n_frames, Integral) or n_frames < 0:
+ raise ValueError("n_frames must be a nonnegative integer")
+ if isinstance(chunk_size, bool) or not isinstance(chunk_size, Integral) or chunk_size < 1:
+ raise ValueError("chunk_size must be a positive integer")
+ if valid_ranges is None:
+ raise ValueError("valid_ranges are required")
+ spans = []
+ for pair in valid_ranges:
+ if len(pair) != 2 or any(isinstance(x, bool) or not isinstance(x, Integral) for x in pair):
+ raise ValueError("valid_ranges must contain integer [start, end) pairs")
+ start, end = pair
+ if end < start:
+ raise ValueError("valid range end precedes start")
+ first = max(int(start), 0)
+ count = max(0, min(int(end) - chunk_size, n_frames - chunk_size) - first)
+ if count:
+ spans.append((first, count))
+ return spans
+
+
+def select_window_start(n_frames, valid_ranges, rng: Random, chunk_size=32) -> int | None:
+ spans = valid_window_spans(n_frames, valid_ranges, chunk_size)
+ total = sum(count for _, count in spans)
+ if total == 0:
+ return None
+ offset = rng.randrange(total)
+ for start, count in spans:
+ if offset < count:
+ return start + offset
+ offset -= count
+ raise AssertionError("unreachable valid-window offset")
+
+
+def sample_episode_visits(episodes: Iterable, rng: Random, chunk_size=32):
+ """Yield one (episode, start) per eligible input visit; caller owns visit order.
+
+ This deliberately does not flatten episodes into a globally window-weighted
+ dataset. Distributed order/sharding and resumable prefetch remain external.
+ """
+ for episode in episodes:
+ start = select_window_start(episode.n_frames, episode.valid_ranges, rng, chunk_size)
+ if start is not None:
+ yield episode, start
diff --git a/flux-umi/src/flux_action/hub.py b/flux-umi/src/flux_action/hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..9600aba15a8f2a5443f504ec42ebcc75ab037823
--- /dev/null
+++ b/flux-umi/src/flux_action/hub.py
@@ -0,0 +1,56 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+"""Resolve one policy package without downloading other embodiments or variants."""
+
+from pathlib import Path, PurePosixPath
+
+
+def looks_like_local_path(source: str) -> bool:
+ """A spec that reads as a filesystem path rather than a Hub ``namespace/name``: an explicit prefix,
+ more than one slash, a file suffix, or a first component that exists on disk (``outputs/...``)."""
+ parts = PurePosixPath(source).parts
+ return (
+ source.startswith(("/", ".", "~"))
+ or source.count("/") != 1
+ or source.endswith((".safetensors", ".json", ".pt", ".bin"))
+ or (bool(parts) and Path(parts[0]).exists())
+ )
+
+
+def resolve_policy_directory(
+ source: str | Path, *, revision: str | None = None, subfolder: str | None = None
+) -> Path:
+ """Resolve a local package or a Hub repository at one snapshot revision."""
+ folder = PurePosixPath(subfolder or "")
+ if folder.is_absolute() or ".." in folder.parts:
+ raise ValueError("subfolder must be a relative path within the policy repository")
+ path = Path(source).expanduser()
+ if path.is_dir():
+ if revision is not None:
+ raise ValueError("revision applies to a Hub repository, not a local directory")
+ package = path / folder
+ else:
+ if isinstance(source, Path) or looks_like_local_path(str(source)):
+ raise FileNotFoundError(
+ f"no such policy directory: {path}. Paths are relative to the working directory; download the "
+ f"package first (docs/setup.md), or pass a Hub repository as namespace/name to download it."
+ )
+ from huggingface_hub import snapshot_download
+
+ prefix = f"{folder}/" if folder.parts else ""
+ names = (
+ "config.json",
+ "config.native.json",
+ "manifest.json",
+ "model.safetensors",
+ "policy_preprocessor.json",
+ "policy_postprocessor.json",
+ "policy_preprocessor_step_*.safetensors",
+ "policy_postprocessor_step_*.safetensors",
+ )
+ snapshot = snapshot_download(
+ repo_id=str(source), revision=revision, allow_patterns=[prefix + name for name in names]
+ )
+ package = Path(snapshot) / folder
+ if not (package / "config.json").is_file():
+ raise FileNotFoundError(package / "config.json")
+ return package
diff --git a/flux-umi/src/flux_action/inference/__init__.py b/flux-umi/src/flux_action/inference/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/inference/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/inference/evaluate.py b/flux-umi/src/flux_action/inference/evaluate.py
new file mode 100644
index 0000000000000000000000000000000000000000..a63b18bcee308d2b9cea0eeb8a390bef1399411b
--- /dev/null
+++ b/flux-umi/src/flux_action/inference/evaluate.py
@@ -0,0 +1,191 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Offline evaluation of a policy export on the held-out windows of an indexed dataset.
+
+For every episode of the chosen split (``val`` by default: the episodes ``index-lerobot --val-episodes``
+held out), a fixed number of window starts spread evenly over the allowed starts is taken, the policy
+predicts from the window's first frame, state and caption, and the prediction is scored against the
+window's recorded commands two ways:
+
+* ``action_mse_normalized``: mean squared error between the predicted and the recorded targets in the
+ trained action space (normalized deltas for the SO-101 recipe). This is the quantity checkpoint
+ selection ranks by; it does not depend on the units of the dataset.
+* ``action_mse_raw``: mean squared error of the absolute commands in dataset units (degrees for
+ SO-101), per channel and overall, after denormalization and integration onto the observed state.
+ Under ``joint_delta`` this includes the offset between the observed state and the command before the
+ window (the leader-follower gap of teleoperated data): the recorded deltas are relative to that
+ command, deployment integrates onto the state, so even a perfect prediction scores that offset here.
+ History policies instead receive the recorded preceding commands and integrate onto the last one,
+ matching their explicit offline history inference contract.
+
+Windows and captions are deterministic (first paraphrase, no dropout), the sampler seed is the policy's
+``inference_seed``; two exports evaluated with the same arguments see identical inputs.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+from typing import Any
+
+import torch
+
+from ..checkpoints.artifacts import sha256
+from ..data.droid.index import ROWS_FILENAME
+from ..hub import resolve_policy_directory
+from ..policy import FluxActionPolicy
+from ..training.data import WindowDataset, collate_windows, load_manifest
+
+
+def spread(n: int, k: int) -> list[int]:
+ """``k`` indices spread evenly over ``range(n)``, first and last included, distinct and sorted."""
+ if n <= 0 or k <= 0:
+ return []
+ if k == 1 or n == 1:
+ return [0]
+ return sorted({round(j * (n - 1) / (k - 1)) for j in range(k)})
+
+
+def evaluate_policy(
+ policy: FluxActionPolicy,
+ source_root,
+ index_dir,
+ *,
+ split: str = "val",
+ windows_per_episode: int = 4,
+ max_windows: int | None = None,
+ decoder: str = "pyav",
+ frame_hw: tuple[int, int] = (256, 256),
+ seed: int = 0,
+) -> dict[str, Any]:
+ """Score ``policy`` on the split's windows; returns the report (per-window records included)."""
+ if windows_per_episode < 1:
+ raise ValueError("windows_per_episode must be positive")
+ index_dir = Path(index_dir)
+ manifest = load_manifest(index_dir / "manifest.json")
+ dataset = WindowDataset(
+ manifest,
+ source_root,
+ index_dir / ROWS_FILENAME,
+ seed=seed,
+ frame_hw=frame_hw,
+ decoder=decoder,
+ split=split,
+ n_obs_steps=policy.config.n_obs_steps if policy.config.inference_profile == "history" else None,
+ )
+ device = policy.device
+ records: list[dict[str, Any]] = []
+ raw_sum = torch.zeros(policy.config.action_dim, dtype=torch.float64)
+ started = time.perf_counter()
+ for position, episode in enumerate(dataset.episodes):
+ starts = dataset.valid_starts(position)
+ for i in spread(len(starts), windows_per_episode):
+ if max_windows is not None and len(records) >= max_windows:
+ break
+ batch = collate_windows([dataset.window_at(position, starts[i])])
+ batch = {k: (v.to(device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()}
+ observation = {
+ **{key: batch[key][:, 0] for key in policy.config.camera_order},
+ "state": batch["state"],
+ "task": batch["task"],
+ }
+ anchor = batch["state"]
+ if policy.config.inference_profile == "history":
+ observation.update(
+ {key: batch[key][:, : policy.config.n_obs_steps] for key in policy.config.camera_order}
+ )
+ observation["command_history"] = batch["command_history"]
+ anchor = batch["command_history"][:, -1]
+ predicted = policy.predict_normalized_targets(observation) # (1, K, D)
+ recorded = policy.training_targets(batch).to(predicted)
+ actions = policy.actions_from_targets(predicted, anchor)
+ raw_error = ((actions - batch["action"].float()) ** 2).mean(dim=(0, 1)).double().cpu()
+ raw_sum += raw_error
+ records.append(
+ {
+ "episode_index": episode["episode_index"],
+ "start": starts[i],
+ "task": batch["task"][0],
+ "action_mse_normalized": float(((predicted - recorded) ** 2).mean()),
+ "action_mse_raw": float(raw_error.mean()),
+ }
+ )
+ if not records:
+ raise ValueError(f"no windows in split {split!r}")
+ normalized = torch.tensor([r["action_mse_normalized"] for r in records], dtype=torch.float64)
+ raw = torch.tensor([r["action_mse_raw"] for r in records], dtype=torch.float64)
+ return {
+ "format_version": 1,
+ "split": split,
+ "dataset_id": manifest.get("dataset_id"),
+ "episodes": len(dataset.episodes),
+ "n_windows": len(records),
+ "windows_per_episode": windows_per_episode,
+ "action_mse_normalized": float(normalized.mean()),
+ "action_mse_normalized_median": float(normalized.median()),
+ "action_mse_raw": float(raw.mean()),
+ "action_mse_raw_per_channel": (raw_sum / len(records)).tolist(),
+ "action_names": manifest.get("action_names"),
+ "inference": {
+ k: getattr(policy.config, k)
+ for k in (
+ "sampler",
+ "num_inference_steps",
+ "sampler_shift",
+ "guidance_scale",
+ "guidance_scale_action",
+ "inference_seed",
+ "action_parameterization",
+ )
+ },
+ "seconds": time.perf_counter() - started,
+ "windows": records,
+ }
+
+
+def evaluate_export(
+ checkpoint,
+ source_root,
+ index_dir,
+ *,
+ revision: str | None = None,
+ subfolder: str | None = None,
+ output=None,
+ device: str = "cuda",
+ settings: dict[str, Any] | None = None,
+ video_vae=None,
+ text_encoder=None,
+ **kwargs: Any,
+) -> dict[str, Any]:
+ """Restore a policy export (optionally overriding inference settings), evaluate it, write ``output``."""
+ checkpoint = resolve_policy_directory(checkpoint, revision=revision, subfolder=subfolder)
+ policy = FluxActionPolicy.from_pretrained(
+ checkpoint, video_vae=video_vae, text_encoder=text_encoder, device=device
+ )
+ for key, value in (settings or {}).items():
+ if not hasattr(policy.config, key):
+ raise ValueError(f"unknown inference setting {key!r}")
+ setattr(policy.config, key, value)
+ policy.config.validate_inference()
+ policy.prepare_inference()
+ report = evaluate_policy(policy, source_root, index_dir, **kwargs)
+ report["checkpoint"] = str(checkpoint)
+ report["checkpoint_manifest"] = json.loads((checkpoint / "manifest.json").read_text())
+ report["index_manifest_sha256"] = sha256(Path(index_dir) / "manifest.json")
+ if output is not None:
+ output = Path(output)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(report, indent=1) + "\n")
+ return report
diff --git a/flux-umi/src/flux_action/inference/offline.py b/flux-umi/src/flux_action/inference/offline.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8f548ee0d7ef140f5a7e98f7424dd7b28a35ff5
--- /dev/null
+++ b/flux-umi/src/flux_action/inference/offline.py
@@ -0,0 +1,140 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Recorded offline inference on a decoded observation, without robot execution."""
+
+import json
+import platform
+import time
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from ..checkpoints.artifacts import sha256
+from ..config import PolicyConfig
+from ..hub import resolve_policy_directory
+from ..policy import FluxActionPolicy
+from .precision import prepare_for_serving
+
+
+def load_observation(path, config, task, device):
+ """Read one synchronized observation: HWC uint8 cameras and a float state vector."""
+ observation = {"task": [task]}
+ with np.load(path, allow_pickle=False) as arrays:
+ for key in config.camera_order:
+ frame = arrays[key]
+ assert frame.dtype == np.uint8 and frame.ndim == 3 and frame.shape[-1] == 3, (
+ "expected RGB uint8 frame"
+ )
+ assert config.camera_layout != "droid" or frame.shape[:2] == (360, 640), "DROID frame size"
+ pixels = torch.from_numpy(frame.copy()).permute(2, 0, 1)[None]
+ # Keep bytes for the SO-101 delivery profile: its policy normalizes on CPU
+ # before moving float pixels to the VAE device.
+ observation[key] = (
+ pixels.to(device=device)
+ if config.inference_profile == "history"
+ else pixels.to(device=device, dtype=torch.float32) / 255
+ )
+ state = arrays["state"]
+ assert state.shape == (config.action_dim,) and state.dtype.kind == "f" and np.isfinite(state).all(), (
+ "invalid state"
+ )
+ observation["state"] = torch.from_numpy(state.copy())[None].to(device=device, dtype=torch.float32)
+ return observation
+
+
+def run_inference(
+ checkpoint,
+ observation,
+ output,
+ *,
+ revision: str | None = None,
+ subfolder: str | None = None,
+ task,
+ device="cuda",
+ compile_dit: bool = False,
+ offload_text_encoder: bool = False,
+ settings: dict | None = None,
+):
+ """Restore a verified export and save actions alongside the effective run settings.
+
+ ``settings`` are explicit ``PolicyConfig`` overrides applied before validation, for exports that carry no
+ sampling settings (training exports); they are recorded in the report.
+
+ The serve-time knobs (``inference.precision``) are applied on the CPU-restored policy before it moves
+ to ``device``; with ``compile_dit`` the reported first-chunk time includes the compilation. The report's
+ ``gpu_memory_bytes`` gives the peak while loading and preparing, the bytes allocated afterwards, and the
+ peak during the chunk."""
+ output = Path(output)
+ if output.exists():
+ raise FileExistsError("choose a new output directory for each inference run")
+ checkpoint = resolve_policy_directory(checkpoint, revision=revision, subfolder=subfolder)
+ device = torch.device(device)
+ policy = FluxActionPolicy.from_pretrained(checkpoint, device="cpu")
+ if settings:
+ policy.config = PolicyConfig(**{**policy.config.to_dict(), **settings})
+ policy.config.validate_inference()
+ memory = {"peak_during_load": None, "allocated_after_load": None, "peak_during_chunk": None}
+ if device.type == "cuda":
+ torch.cuda.reset_peak_memory_stats(device)
+ setup = prepare_for_serving(
+ policy,
+ device=device,
+ compile_dit=compile_dit,
+ offload_text_encoder=offload_text_encoder,
+ )
+ if device.type == "cuda":
+ torch.cuda.synchronize(device)
+ memory["peak_during_load"] = torch.cuda.max_memory_allocated(device)
+ memory["allocated_after_load"] = torch.cuda.memory_allocated(device)
+ torch.cuda.reset_peak_memory_stats(device)
+ batch = load_observation(observation, policy.config, task, device)
+ if device.type == "cuda":
+ torch.cuda.synchronize(device)
+ started = time.perf_counter()
+ with torch.inference_mode():
+ actions = policy.predict_action_chunk(batch)
+ if device.type == "cuda":
+ torch.cuda.synchronize(device)
+ memory["peak_during_chunk"] = torch.cuda.max_memory_allocated(device)
+ elapsed = time.perf_counter() - started
+ expected = (1, policy.config.chunk_size, policy.config.action_dim)
+ assert tuple(actions.shape) == expected and torch.isfinite(actions).all(), "invalid action output"
+ report = {
+ "format_version": 1,
+ "checkpoint_manifest": json.loads((checkpoint / "manifest.json").read_text()),
+ "observation_sha256": sha256(observation),
+ "task": task,
+ "policy_config": policy.config.to_dict(),
+ "settings": dict(settings or {}),
+ "runtime": {
+ "python": platform.python_version(),
+ "torch": torch.__version__,
+ "cuda": torch.version.cuda,
+ "device": str(device),
+ "gpu": torch.cuda.get_device_name(device) if device.type == "cuda" else None,
+ },
+ "inference_seconds": elapsed,
+ "timing_scope": "first chunk including conditioning; excludes checkpoint loading"
+ + ("; includes DiT compilation" if compile_dit else ""),
+ "serving_setup": setup,
+ "gpu_memory_bytes": memory,
+ "actions_shape": list(actions.shape),
+ "encoder_integrity_verified": False,
+ }
+ output.mkdir(parents=True)
+ np.save(output / "actions.npy", actions.float().cpu().numpy(), allow_pickle=False)
+ report["actions_sha256"] = sha256(output / "actions.npy")
+ (output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
+ return report
diff --git a/flux-umi/src/flux_action/inference/precision.py b/flux-umi/src/flux_action/inference/precision.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ad8dd7cc7369b17d5c0f9bf90b7b56f233f97e7
--- /dev/null
+++ b/flux-umi/src/flux_action/inference/precision.py
@@ -0,0 +1,62 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Prepare a policy for the released CUDA inference path."""
+
+from __future__ import annotations
+
+import time
+from collections.abc import Callable
+from typing import Any
+
+import torch
+
+
+def prepare_for_serving(
+ policy,
+ *,
+ device: str | torch.device | None = None,
+ compile_dit: bool = False,
+ offload_text_encoder: bool = False,
+ warmup: int = 0,
+ warmup_fn: Callable[[], Any] | None = None,
+) -> dict[str, Any]:
+ assert warmup >= 0 and (not warmup or warmup_fn is not None), "warmup callback required"
+ if offload_text_encoder:
+ policy.set_text_encoder_offload(True)
+ if device is not None and str(policy.device) != str(device):
+ policy.to(device)
+
+ prepared = False
+ if policy.device.type == "cuda":
+ prepared = policy.prepare_inference(compile=compile_dit)
+ assert prepared or not compile_dit, "acceleration unavailable"
+
+ report: dict[str, Any] = {
+ "prepared": prepared,
+ "compile_dit": compile_dit,
+ "offload_text_encoder": offload_text_encoder,
+ }
+ if warmup:
+ times = []
+ for _ in range(warmup):
+ started = time.perf_counter()
+ warmup_fn()
+ if policy.device.type == "cuda":
+ torch.cuda.synchronize(policy.device)
+ times.append(time.perf_counter() - started)
+ report["warmup_seconds"] = times
+ return report
+
+
+__all__ = ["prepare_for_serving"]
diff --git a/flux-umi/src/flux_action/inference/sampling.py b/flux-umi/src/flux_action/inference/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..0deb508427393f0a02d9c3738d9ca4375a3e0da1
--- /dev/null
+++ b/flux-umi/src/flux_action/inference/sampling.py
@@ -0,0 +1,215 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Joint video + action denoising for policy inference.
+
+Two samplers over a dict of noised streams (``x_video`` and ``x_``):
+
+* ``cosmos_unipc_order2`` — the literal Cosmos UniPC (order 2, bh2, predict-x0)
+ our DROID policy was evaluated with: 4 steps, shift 5, CFG 3. One denoiser
+ call per step (the corrector does not re-evaluate the model), integer
+ scheduler ticks passed to the model as ``tick / 1000``.
+* ``euler`` — plain rectified-flow Euler on the shifted schedule, for reference.
+
+``cfg_two_pass`` runs the unconditional (empty caption) and conditional forward
+separately, exactly like the video pipeline, and combines per stream so the
+video and action streams can use different guidance scales.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+
+import numpy as np
+import torch
+from torch import Tensor
+
+Samples = dict[str, Tensor]
+
+
+def cfg_two_pass(
+ model,
+ flow: Samples,
+ fixed: dict[str, Tensor],
+ timesteps: dict[str, Tensor],
+ ctx_uc: tuple[Tensor, Tensor],
+ ctx_c: tuple[Tensor, Tensor],
+ cfg_by_key: dict[str, float],
+) -> Samples:
+ """pred = uc + cfg * (c - uc) per flow stream. ``fixed`` = ids, cond streams, vector."""
+
+ def forward(ctx: Tensor, ctx_ids: Tensor) -> dict[str, Tensor]:
+ return model(
+ **flow,
+ **fixed,
+ **timesteps,
+ ctx=ctx,
+ ctx_ids=ctx_ids,
+ timesteps_ctx=torch.zeros(ctx.shape[:2], device=ctx.device, dtype=ctx.dtype),
+ )
+
+ pred_uc = forward(*ctx_uc)
+ pred_c = forward(*ctx_c)
+ return {k: pred_uc[k] + cfg_by_key[k] * (pred_c[k] - pred_uc[k]) for k in flow}
+
+
+def timeshift(alpha: float, t: Tensor) -> Tensor:
+ return alpha * t / (1.0 + (alpha - 1.0) * t)
+
+
+def euler(
+ samples: Samples,
+ predict_velocity: Callable[[Samples, float], Samples],
+ *,
+ n_steps: int,
+ alpha: float,
+) -> Samples:
+ timesteps = timeshift(alpha, torch.linspace(1.0, 0.0, n_steps + 1)).tolist()
+ for t_curr, t_prev in zip(timesteps[:-1], timesteps[1:], strict=True):
+ pred = predict_velocity(samples, t_curr)
+ samples = {
+ k: (samples[k].float() + (t_prev - t_curr) * pred[k].float()).to(samples[k].dtype)
+ for k in samples
+ }
+ return samples
+
+
+def cosmos_unipc_schedule(
+ n_steps: int, shift: float, num_train_timesteps: int = 1000
+) -> tuple[Tensor, Tensor]:
+ """Cosmos' FlowUniPCMultistepScheduler grid: float sigmas for the solver, integer ticks for the model."""
+ if n_steps < 1:
+ raise ValueError(f"n_steps must be >= 1, got {n_steps}")
+ sigma_max = np.float32(1.0 - 1.0 / num_train_timesteps).item()
+ sigmas_np = np.linspace(sigma_max, 0.0, n_steps + 1).copy()[:-1]
+ sigmas_np = shift * sigmas_np / (1.0 + (shift - 1.0) * sigmas_np)
+ model_timesteps = torch.from_numpy((sigmas_np * num_train_timesteps).astype(np.int64))
+ sigmas = torch.from_numpy(np.concatenate([sigmas_np, [0.0]]).astype(np.float32))
+ return sigmas, model_timesteps
+
+
+def _bh_coefficients(h: Tensor, rks: list[Tensor], order: int, *, device, dtype, corrector: bool):
+ """bh2 predictor / corrector coefficients (predict_x0=True), as in Cosmos."""
+ hh = -h
+ h_phi_1 = torch.expm1(hh)
+ h_phi_k = h_phi_1 / hh - 1.0
+ b_h = torch.expm1(hh)
+ rks_t = torch.stack([rk.to(device=device) for rk in rks] + [torch.ones_like(h, device=device)])
+ rows, rhs = [], []
+ factorial_i = 1
+ for i in range(1, order + 1):
+ rows.append(torch.pow(rks_t, i - 1))
+ rhs.append((h_phi_k * factorial_i / b_h).to(device=device))
+ factorial_i *= i + 1
+ h_phi_k = h_phi_k / hh - 1.0 / factorial_i
+ matrix, rhs_t = torch.stack(rows), torch.stack(rhs)
+ if corrector:
+ rhos = (
+ torch.tensor([0.5], dtype=dtype, device=device)
+ if order == 1
+ else torch.linalg.solve(matrix, rhs_t).to(dtype)
+ )
+ elif order == 2:
+ rhos = torch.tensor([0.5], dtype=dtype, device=device) # Cosmos' simplified UniP order-2 coefficient
+ else:
+ rhos = None
+ return h_phi_1, b_h, rhos
+
+
+def cosmos_unipc_order2(
+ samples: Samples,
+ predict_velocity: Callable[[Samples, Tensor], Samples],
+ *,
+ n_steps: int,
+ shift: float,
+ num_train_timesteps: int = 1000,
+) -> Samples:
+ """Cosmos UniPC (order 2, bh2, predict-x0) over a dict of streams sharing one grid."""
+ keys = list(samples)
+ sigmas, model_timesteps = cosmos_unipc_schedule(n_steps, shift, num_train_timesteps)
+ solver_order = 2
+ model_outputs: list[Samples | None] = [None] * solver_order
+ lower_order_nums = 0
+ last_sample: Samples | None = None
+ this_order = 1
+
+ def alpha_sigma(s: Tensor) -> tuple[Tensor, Tensor]:
+ return 1.0 - s, s
+
+ def lam(s: Tensor) -> Tensor:
+ a, sg = alpha_sigma(s)
+ return torch.log(a) - torch.log(sg)
+
+ for step, tick in enumerate(model_timesteps):
+ velocity = predict_velocity(samples, tick)
+ sigma_cur = sigmas[step]
+ x0 = {k: samples[k].float() - sigma_cur * velocity[k].float() for k in keys}
+
+ if step > 0 and last_sample is not None: # UniC corrector, using the previous step's order
+ order_c = this_order
+ sigma_t, sigma_s0 = sigmas[step], sigmas[step - 1]
+ alpha_t, sig_t = alpha_sigma(sigma_t)
+ _, sig_s0 = alpha_sigma(sigma_s0)
+ h = lam(sigma_t) - lam(sigma_s0)
+ rks, hist = [], []
+ prev_x0 = model_outputs[-1]
+ for i in range(1, order_c):
+ older = model_outputs[-(i + 1)]
+ rk = (lam(sigmas[step - (i + 1)]) - lam(sigma_s0)) / h
+ rks.append(rk)
+ hist.append({k: (older[k] - prev_x0[k]) / rk for k in keys})
+ ex = samples[keys[0]]
+ h_phi_1, b_h, rhos_c = _bh_coefficients(
+ h, rks, order_c, device=ex.device, dtype=torch.float32, corrector=True
+ )
+ corrected = {}
+ for k in keys:
+ base = sig_t / sig_s0 * last_sample[k].float() - alpha_t * h_phi_1 * prev_x0[k]
+ residual = sum(rhos_c[i] * d[k] for i, d in enumerate(hist)) if hist else 0.0
+ corrected[k] = (base - alpha_t * b_h * (residual + rhos_c[-1] * (x0[k] - prev_x0[k]))).to(
+ samples[k].dtype
+ )
+ samples = corrected
+
+ model_outputs[0] = model_outputs[1]
+ model_outputs[1] = x0 # history holds the pre-correction x0, as in Cosmos
+
+ remaining = len(model_timesteps) - step
+ this_order = min(min(solver_order, remaining), lower_order_nums + 1)
+ last_sample = samples
+
+ sigma_t, sigma_s0 = sigmas[step + 1], sigmas[step] # UniP predictor
+ alpha_t, sig_t = alpha_sigma(sigma_t)
+ _, sig_s0 = alpha_sigma(sigma_s0)
+ h = lam(sigma_t) - lam(sigma_s0)
+ rks, hist = [], []
+ latest = model_outputs[-1]
+ for i in range(1, this_order):
+ older = model_outputs[-(i + 1)]
+ rk = (lam(sigmas[step - i]) - lam(sigma_s0)) / h
+ rks.append(rk)
+ hist.append({k: (older[k] - latest[k]) / rk for k in keys})
+ ex = samples[keys[0]]
+ h_phi_1, b_h, rhos_p = _bh_coefficients(
+ h, rks, this_order, device=ex.device, dtype=torch.float32, corrector=False
+ )
+ predicted = {}
+ for k in keys:
+ base = sig_t / sig_s0 * samples[k].float() - alpha_t * h_phi_1 * latest[k]
+ if hist:
+ base = base - alpha_t * b_h * sum(rhos_p[i] * d[k] for i, d in enumerate(hist))
+ predicted[k] = base.to(samples[k].dtype)
+ samples = predicted
+ if lower_order_nums < solver_order:
+ lower_order_nums += 1
+ return samples
diff --git a/flux-umi/src/flux_action/inference/so101.py b/flux-umi/src/flux_action/inference/so101.py
new file mode 100644
index 0000000000000000000000000000000000000000..73e3d19b0ae4d6881d6ace2dbf949e3fc36c9c1f
--- /dev/null
+++ b/flux-umi/src/flux_action/inference/so101.py
@@ -0,0 +1,198 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Load SO-101 policy packages without importing LeRobot."""
+
+import json
+from pathlib import Path
+
+import torch
+from safetensors.torch import load_file
+
+from ..config import PolicyConfig
+from ..hub import resolve_policy_directory
+from ..policy import FluxActionPolicy
+
+
+def _processor_statistics(bundle: Path, raw: dict) -> dict:
+ """Validate saved processors and read their checkpoint-owned quantiles."""
+ pre = json.loads((bundle / "policy_preprocessor.json").read_text())["steps"]
+ post = json.loads((bundle / "policy_postprocessor.json").read_text())["steps"]
+ expected_pre = [
+ "rename_observations_processor",
+ "to_batch_processor",
+ "device_processor",
+ "flux3_observation_history_normalizer",
+ "flux3_action_target_normalizer",
+ "flux3_camera_resize",
+ ]
+ expected_post = ["flux3_action_history_unnormalizer", "device_processor"]
+ names = [step["registry_name"] for step in pre]
+ if names != expected_pre or [step["registry_name"] for step in post] != expected_post:
+ raise ValueError("unsupported SO-101 processor pipeline; use the documented package revision")
+ if pre[0]["config"].get("rename_map"):
+ raise ValueError("delivery loader requires checkpoint camera keys without a saved rename_map")
+ if any(step["config"].get("float_dtype") is not None for step in (pre[2], post[1])):
+ raise ValueError("delivery loader requires processors that preserve observation dtype")
+ shared = {
+ "action_dim": 6,
+ "action_representation": raw["action_representation"],
+ "absolute_dims": raw["delta_absolute_dims"],
+ "normalization_clip": raw["normalization_clip"],
+ }
+ temporal = {name: raw[name] for name in ("n_obs_steps", "chunk_size")}
+ checks = [
+ (
+ pre[3],
+ {
+ **shared,
+ **temporal,
+ "camera_keys": raw["camera_keys"],
+ "condition_on_past_actions": raw["condition_on_past_actions"],
+ },
+ ),
+ (post[0], shared),
+ ]
+ checks.extend(
+ [
+ (pre[4], {**shared, **temporal}),
+ (pre[5], {"camera_keys": raw["camera_keys"], "camera_layout": raw["camera_layout"]}),
+ ]
+ )
+ for step, expected in checks:
+ if step["config"] != expected:
+ raise ValueError(f"processor {step['registry_name']} disagrees with the policy config")
+ states = []
+ for step in (pre[3], pre[4], post[0]):
+ filename = step["state_file"]
+ if Path(filename).name != filename:
+ raise ValueError("processor state_file must name a file inside the package")
+ states.append(load_file(str(bundle / filename)))
+ observation, output = states[0], states[-1]
+ action_keys = {"action.q01", "action.q99"}
+ target = states[1]
+ if (
+ set(observation) != action_keys | {"state.q01", "state.q99"}
+ or set(target) != action_keys
+ or set(output) != action_keys
+ ):
+ raise ValueError("processor states must contain exactly the action/state quantiles")
+ for key in action_keys:
+ if not torch.equal(observation[key], target[key]) or not torch.equal(target[key], output[key]):
+ raise ValueError("observation/action/output processors disagree on normalization")
+ for key, value in observation.items():
+ if value.shape != (6,) or not torch.isfinite(value).all():
+ raise ValueError(f"{key} must contain six finite quantiles")
+ return {
+ stream: {q: observation[f"{stream}.{q}"].float().tolist() for q in ("q01", "q99")}
+ for stream in ("state", "action")
+ }
+
+
+def load_policy(weights: str | Path, *, revision: str | None = None) -> FluxActionPolicy:
+ """Load model, robot contract and normalization from a local package or Hub repository.
+
+ The package must supply the current split processors and their saved quantiles.
+ """
+ bundle = resolve_policy_directory(weights, revision=revision)
+ for path in (
+ bundle / "model.safetensors",
+ bundle / "config.json",
+ ):
+ if not path.exists():
+ raise FileNotFoundError(path)
+ raw = json.loads((bundle / "config.json").read_text())
+ expected = {
+ "conditioning": "history",
+ "action_representation": "delta",
+ "delta_absolute_dims": [-1],
+ "camera_layout": "side_by_side",
+ "action_modality": "action",
+ "gripper_flip_dims": [],
+ "use_relative_actions": False,
+ "normalization_mapping": {"VISUAL": "IDENTITY", "STATE": "IDENTITY", "ACTION": "IDENTITY"},
+ }
+ mismatches = [name for name, value in expected.items() if raw.get(name) != value]
+ if raw.get("packer") is not None:
+ mismatches.append("packer")
+ if raw.get("output_features", {}).get("action", {}).get("shape") != [6]:
+ mismatches.append("output_features.action")
+ if raw.get("input_features", {}).get("observation.state", {}).get("shape") != [6]:
+ mismatches.append("input_features.observation.state")
+ if mismatches:
+ raise ValueError(f"unsupported SO-101 package: {', '.join(mismatches)}")
+ cameras = raw["camera_keys"]
+ if any(not key.startswith("observation.images.") for key in cameras):
+ raise ValueError("SO-101 camera keys must start with observation.images.")
+ stats = _processor_statistics(bundle, raw)
+ fields = {
+ name: raw[name]
+ for name in (
+ "n_obs_steps",
+ "history_snapshots",
+ "condition_on_past_actions",
+ "text_fixed_length",
+ "video_position_fps",
+ "chunk_size",
+ "n_action_steps",
+ "fps",
+ "action_scale",
+ "canvas_hw",
+ "normalization_clip",
+ "sampler",
+ "num_inference_steps",
+ "guidance_scale",
+ "guidance_scale_action",
+ "sampler_shift",
+ "inference_seed",
+ "separate_timesteps",
+ "video_logit_mean",
+ "video_logit_std",
+ "conditioning_noise_max",
+ "loss_reduction",
+ "action_channel_weights",
+ "action_loss_weight",
+ "video_loss_weight",
+ "train_timestep_width",
+ "train_timestep_shift",
+ )
+ }
+ config = PolicyConfig(
+ **fields,
+ inference_profile="history",
+ action_dim=6,
+ action_modality="action",
+ camera_layout="side_by_side",
+ camera_keys=tuple(key.removeprefix("observation.") for key in cameras),
+ gripper_flip_dims=(),
+ action_parameterization="joint_delta",
+ absolute_action_dims=(5,),
+ action_normalization={q: stats["action"][q] for q in ("q01", "q99")},
+ state_normalization={q: stats["state"][q] for q in ("q01", "q99")},
+ single_frame_encode=True,
+ torch_dtype=raw["dtype"],
+ attn_mode=raw["attn_mode"],
+ dit_config=raw.get("dit_config") or {},
+ video_vae_id=raw["video_vae_id"],
+ text_encoder_id=raw["text_encoder_id"],
+ )
+ config.validate_inference()
+ state = load_file(str(bundle / "model.safetensors"))
+ assert all(
+ value.dtype == getattr(torch, config.torch_dtype)
+ for value in state.values()
+ if value.is_floating_point()
+ ), "SO-101 checkpoint dtype disagrees with the policy config"
+ policy = FluxActionPolicy(config, _restore=True)
+ policy.load_state_dict(state, strict=True, assign=True)
+ return policy.eval()
diff --git a/flux-umi/src/flux_action/models/__init__.py b/flux-umi/src/flux_action/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/models/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/models/cute_qknorm_hybrid.py b/flux-umi/src/flux_action/models/cute_qknorm_hybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..5703ce0860f0b3392c01403af0a7728dcbea1d8e
--- /dev/null
+++ b/flux-umi/src/flux_action/models/cute_qknorm_hybrid.py
@@ -0,0 +1,340 @@
+"""Isolated hybrid DiT RMSNorm: native reductions/row math, CuTe pointwise.
+
+Production imports none of this file. CUDA compilation is lazy. This experimental
+private helper requires immutable Q/K projection inputs; it saves the original x
+for a connected higher-order fallback, unlike the original cast-only save path.
+The CPU oracle exercises the same custom-autograd boundary without importing DSL.
+No GPU numerical or performance claim is implied by the CPU oracle.
+"""
+from functools import lru_cache
+from typing import Optional
+
+import torch
+from torch import Tensor, nn
+
+AUDITED_TORCH_GIT = "449b1768410104d3ed79d3bcfe4ba1d65c7f22c0"
+
+
+def reference(x, scale):
+ dtype = x.dtype
+ x = x.float()
+ rrms = torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-6)
+ return (x * rrms).to(dtype=dtype) * scale
+
+
+def token_major_stride(shape):
+ b, h, n, d = shape
+ return (n * h * d, d, h * d, 1)
+
+
+def head_major_stride(shape):
+ b, h, n, d = shape
+ return (h * n * d, n * d, d, 1)
+
+
+def square_stride(shape):
+ _, h, n, d = shape
+ return token_major_stride(shape) if n > 1 else (h * d, d, d, 1)
+
+
+def unsupported_reason(x, scale, *, cpu_oracle=False):
+ if torch.compiler.is_compiling():
+ return "torch.compile uses the original expression"
+ if torch._C._are_functorch_transforms_active() or torch.autograd.forward_ad._current_level >= 0:
+ return "functional transforms/forward AD use the original expression"
+ if type(x) is not Tensor or type(scale) not in (Tensor, nn.Parameter):
+ return "tensor subclasses use the original expression"
+ if (str(torch.__version__).split("+")[0] != "2.10.0" or
+ torch.version.git_version != AUDITED_TORCH_GIT or torch.version.cuda != "13.0"):
+ return "only the audited Torch2.10/CUDA13.0 arithmetic is in scope"
+ if x.device != scale.device or x.device.type != ("cpu" if cpu_oracle else "cuda"):
+ return "same-device CUDA tensors required (CPU only through the explicit oracle)"
+ if x.layout != torch.strided or scale.layout != torch.strided:
+ return "dense strided tensors required"
+ if x.dtype != torch.bfloat16 or scale.dtype != torch.bfloat16:
+ return "both activation and materialized scale must be BF16"
+ if x.ndim != 4 or x.shape[1] != 24 or x.shape[-1] != 128 or any(n < 1 for n in x.shape):
+ return "expected nonempty (B,24,L,128) activation"
+ if x.stride() != token_major_stride(x.shape):
+ return "the complete audited token-major stride, including singleton axes, is required"
+ if scale.shape != (128,) or scale.stride() != (1,):
+ return "scale must be a contiguous128-element tensor"
+ if x.data_ptr() % 16 or scale.data_ptr() % 16:
+ return "activation/scale addresses must be16-byte aligned"
+ if x.shape[2] > 2147483647 or x.shape[0] > 65535:
+ return "CUDA grid limits exceeded"
+ return None
+
+
+@lru_cache(maxsize=1)
+def _kernel_type():
+ import cuda.bindings.driver as cuda
+ import cutlass
+ import cutlass.cute as cute
+ from cutlass import BFloat16, Float32, Int64, const_expr
+ from cutlass._mlir.dialects import llvm
+ from cutlass.cutlass_dsl import dsl_user_op
+
+ @dsl_user_op
+ def mul_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type, [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b)],
+ "mul.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip))
+
+ @dsl_user_op
+ def add_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type, [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b)],
+ "add.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip))
+
+ class QKNormPointwise128:
+ def __init__(self, kind, element_type):
+ self.kind = kind # 0 cast/square, 1 affine, 2 reduction products, 3 dx
+ self.vector = 128 // element_type.width
+ self.threads_per_head = 128 // self.vector
+ self.tile_heads = 128 // self.threads_per_head
+
+ @cute.jit
+ def __call__(self, a: cute.Tensor, b: Optional[cute.Tensor], c: Optional[cute.Tensor],
+ d: Optional[cute.Tensor], e: Optional[cute.Tensor],
+ o0: cute.Tensor, o1: Optional[cute.Tensor], stream: cuda.CUstream):
+ atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), a.element_type, num_bits_per_copy=128)
+ threads = cute.make_ordered_layout((self.tile_heads, self.threads_per_head), order=(1, 0))
+ tiled = cute.make_tiled_copy_tv(atom, threads, cute.make_layout((1, self.vector)))
+ self.kernel(a, b, c, d, e, o0, o1, tiled, atom).launch(
+ grid=[a.shape[2], a.shape[1] // self.tile_heads, a.shape[0]],
+ block=[128, 1, 1], stream=stream)
+
+ @cute.kernel
+ def kernel(self, a: cute.Tensor, b: Optional[cute.Tensor], c: Optional[cute.Tensor],
+ d: Optional[cute.Tensor], e: Optional[cute.Tensor],
+ o0: cute.Tensor, o1: Optional[cute.Tensor], tiled: cute.TiledCopy, atom: cute.CopyAtom):
+ tid, _, _ = cute.arch.thread_idx()
+ token0, ht0, batch0 = cute.arch.block_idx()
+ token, ht, batch = Int64(token0), Int64(ht0), Int64(batch0)
+ head = ht * self.tile_heads + tid // self.threads_per_head
+ first_dim = Int64(tid % self.threads_per_head) * self.vector
+ tile = (self.tile_heads, 128)
+ thread = tiled.get_slice(tid)
+ ga = cute.local_tile(a[batch, None, token, None], tile, (ht, 0))
+ ra = cute.make_rmem_tensor_like(thread.partition_S(ga))
+ cute.copy(atom, thread.partition_S(ga), ra)
+ r0 = cute.make_rmem_tensor_like(ra, o0.element_type)
+ r1 = None
+ if const_expr(o1 is not None):
+ r1 = cute.make_rmem_tensor_like(ra, o1.element_type)
+ # Backward's x_f is a different dtype/layout from its BF16 g input.
+ rb, rn = None, None
+ if const_expr(self.kind == 2 or self.kind == 3):
+ gb = cute.local_tile(b[batch, None, token, None], tile, (ht, 0))
+ rb = cute.make_rmem_tensor_like(ra, Float32)
+ b_atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), Float32, num_bits_per_copy=128)
+ cute.copy(b_atom, thread.partition_S(gb), rb)
+ if const_expr(self.kind == 2):
+ gn = cute.local_tile(d[batch, None, token, None], tile, (ht, 0))
+ rn = cute.make_rmem_tensor_like(ra, BFloat16)
+ cute.copy(atom, thread.partition_S(gn), rn)
+ assert cute.size(ra.shape) == self.vector
+ for i in cutlass.range(self.vector, unroll_full=True):
+ value = Float32(ra[i])
+ if const_expr(self.kind == 0):
+ r0[i] = value
+ r1[i] = mul_rn(value, value)
+ elif const_expr(self.kind == 1):
+ row_r = Float32(b[batch, head, token, 0])
+ scale = Float32(c[first_dim + i])
+ rounded_n = BFloat16(mul_rn(value, row_r))
+ r0[i] = rounded_n
+ r1[i] = BFloat16(mul_rn(Float32(rounded_n), scale))
+ elif const_expr(self.kind == 2):
+ scale = Float32(c[first_dim + i])
+ rounded_gn = BFloat16(mul_rn(value, scale))
+ r0[i] = mul_rn(Float32(rounded_gn), Float32(rb[i]))
+ r1[i] = BFloat16(mul_rn(value, Float32(rn[i])))
+ else:
+ scale = Float32(c[first_dim + i])
+ rounded_gn = BFloat16(mul_rn(value, scale))
+ direct = mul_rn(Float32(rounded_gn), Float32(d[batch, head, token, 0]))
+ twice_x = mul_rn(Float32(2.0), Float32(rb[i]))
+ square_branch = mul_rn(Float32(e[batch, head, token, 0]), twice_x)
+ r0[i] = BFloat16(add_rn(direct, square_branch))
+ go0 = cute.local_tile(o0[batch, None, token, None], tile, (ht, 0))
+ out_atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), o0.element_type,
+ num_bits_per_copy=min(128, self.vector * o0.element_type.width))
+ cute.copy(out_atom, r0, thread.partition_D(go0))
+ if const_expr(o1 is not None):
+ go1 = cute.local_tile(o1[batch, None, token, None], tile, (ht, 0))
+ out1_atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), o1.element_type,
+ num_bits_per_copy=min(128, self.vector * o1.element_type.width))
+ cute.copy(out1_atom, r1, thread.partition_D(go1))
+
+ return QKNormPointwise128
+
+
+@lru_cache(maxsize=64)
+def _compiled(kind, descriptions, capability):
+ import cutlass
+ import cutlass.cute as cute
+ types = {torch.bfloat16: cutlass.BFloat16, torch.float32: cutlass.Float32}
+ def fake(description):
+ if description is None:
+ return None
+ dtype, shape = description
+ if len(shape) == 1:
+ strides = (1,)
+ elif shape[-1] == 1:
+ strides = tuple(cute.sym_int64() for _ in shape[:-1]) + (1,)
+ else:
+ vector = {torch.bfloat16: 8, torch.float32: 4}[dtype]
+ strides = tuple(cute.sym_int64(divisibility=vector) for _ in shape[:-1]) + (1,)
+ return cute.runtime.make_fake_tensor(types[dtype], shape, stride=strides, assumed_align=16)
+ tensors = tuple(fake(description) for description in descriptions)
+ return cute.compile(_kernel_type()(kind, types[descriptions[0][0]]), *tensors,
+ cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), options="--enable-tvm-ffi")
+
+
+def _launch(kind, *tensors):
+ first = tensors[0]
+ descriptions = tuple(None if value is None else (value.dtype, tuple(value.shape)) for value in tensors)
+ with torch.cuda.device(first.device):
+ function = _compiled(kind, descriptions, torch.cuda.get_device_capability(first.device))
+ function(*tensors)
+
+
+def _empty(x, dtype, strides):
+ return torch.empty_strided(x.shape, strides, dtype=dtype, device=x.device)
+
+
+def _forward_parts(x, scale, backend, *, record=None):
+ if backend == "aten":
+ f = x.float()
+ square = f.pow(2)
+ else:
+ f = _empty(x, torch.float32, x.stride())
+ square = _empty(x, torch.float32, square_stride(x.shape))
+ _launch(0, x, None, None, None, None, f, square)
+ # Exact native mean and all small-row forward arithmetic.
+ rrms = torch.rsqrt(torch.mean(square, dim=-1, keepdim=True) + 1e-6)
+ if backend == "aten":
+ normalized = (f * rrms).to(x.dtype)
+ output = normalized * scale
+ else:
+ normalized = _empty(x, x.dtype, x.stride())
+ output = _empty(x, x.dtype, x.stride())
+ _launch(1, f, rrms, scale, None, None, normalized, output)
+ if record is not None:
+ record.update(f=f, square=square, rrms=rrms, normalized=normalized, output=output)
+ return output, f, rrms, normalized
+
+
+def _backward_parts(grad, f, rrms, normalized, scale, backend, *, record=None):
+ if backend == "aten":
+ scale_product = grad * normalized
+ rounded_gn = grad * scale
+ rrms_product = rounded_gn.float() * f
+ else:
+ rrms_product = _empty(grad, torch.float32, head_major_stride(grad.shape))
+ scale_product = _empty(grad, torch.bfloat16, head_major_stride(grad.shape))
+ _launch(2, grad, f, scale, normalized, None, rrms_product, scale_product)
+ # Do not change product dtype/layout or replace either native sum tree.
+ grad_scale = scale_product.sum_to_size(scale.shape)
+ grad_rrms = rrms_product.sum_to_size(rrms.shape)
+ cubed = rrms.pow(3)
+ half_grad = -0.5 * grad_rrms
+ grad_mean = half_grad * cubed
+ # Same ATen unary scalar division before broadcast; no reduction rearranged.
+ row_grad_square = grad_mean / f.shape[-1]
+ if backend == "aten":
+ direct = (grad * scale).float() * rrms
+ square_branch = row_grad_square * (2.0 * f)
+ grad_x = (direct + square_branch).to(grad.dtype)
+ else:
+ grad_x = _empty(grad, grad.dtype, head_major_stride(grad.shape))
+ _launch(3, grad, f, scale, rrms, row_grad_square, grad_x, None)
+ if record is not None:
+ record.update(scale_product=scale_product, rrms_product=rrms_product, grad_scale=grad_scale,
+ grad_rrms=grad_rrms, cubed=cubed, half_grad=half_grad, grad_mean=grad_mean,
+ row_grad_square=row_grad_square, grad_x=grad_x)
+ return grad_x, grad_scale
+
+
+def _reference_vjp(x, scale, grad, needs, *, create_graph):
+ # Explicit partial VJPs avoid autograd.grad over potentially related x/scale
+ # inputs, which could traverse their pre-existing graph and double-count it.
+ # Keep the original expand-then-div and pow(1) graph for higher derivatives.
+ with torch.set_grad_enabled(create_graph):
+ f = x.float()
+ rrms = torch.rsqrt(torch.mean(f ** 2, dim=-1, keepdim=True) + 1e-6)
+ normalized = (f * rrms).to(x.dtype)
+ scale_product = grad * normalized
+ rounded_gn = grad * scale
+ ds = scale_product.sum_to_size(scale.shape)
+ gn = rounded_gn.float()
+ rrms_product = gn * f
+ direct = gn * rrms
+ dr = rrms_product.sum_to_size(rrms.shape)
+ cubed = rrms.pow(3)
+ half_grad = -0.5 * dr
+ dm = half_grad * cubed
+ dp = dm.expand_as(f) / x.shape[-1]
+ twice = 2.0 * f.pow(1)
+ square_branch = dp * twice
+ dx = (direct + square_branch).to(x.dtype)
+ return (dx if needs[0] else None), (ds if needs[1] else None)
+
+
+class _HybridRMSNorm(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, scale, backend, require_kernel):
+ output, f, rrms, normalized = _forward_parts(x, scale, backend)
+ ctx.save_for_backward(x, scale, f, rrms, normalized)
+ ctx.backend, ctx.require_kernel = backend, require_kernel
+ ctx.set_materialize_grads(False)
+ return output
+
+ @staticmethod
+ def backward(ctx, grad):
+ if grad is None:
+ return None, None, None, None
+ x, scale, f, rrms, normalized = ctx.saved_tensors
+ needs = ctx.needs_input_grad[:2]
+ regular = (type(grad) is Tensor and grad.dtype == x.dtype and grad.device == x.device
+ and grad.layout == torch.strided and grad.stride() == head_major_stride(x.shape)
+ and grad.data_ptr() % 16 == 0)
+ create_graph = torch.is_grad_enabled()
+ if create_graph or not regular:
+ if not create_graph and not regular and ctx.require_kernel:
+ raise ValueError("The required hybrid backward needs an aligned head-major BF16 gradient")
+ dx, ds = _reference_vjp(x, scale, grad, needs, create_graph=create_graph)
+ else:
+ dx, ds = _backward_parts(grad, f, rrms, normalized, scale, ctx.backend)
+ dx, ds = (dx if needs[0] else None), (ds if needs[1] else None)
+ return dx, ds, None, None
+
+
+def rmsnorm_hybrid(x, scale, *, require_kernel=False, cpu_oracle=False):
+ """Private immutable-input experiment; cpu_oracle never calls/imports CuTe."""
+ reason = unsupported_reason(x, scale, cpu_oracle=cpu_oracle)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(reason)
+ return reference(x, scale)
+ backend = "aten" if cpu_oracle else "cute"
+ if not cpu_oracle and torch.cuda.get_device_capability(x.device) != (10, 3):
+ if require_kernel:
+ raise ValueError("This candidate is currently scoped to SM103")
+ return reference(x, scale)
+ return _HybridRMSNorm.apply(x, scale, backend, require_kernel)
+
+
+class HybridRMSNorm128(nn.Module):
+ """Isolated replacement with the original128-element scale parameter only."""
+ def __init__(self, dim=128, *, require_kernel=False, cpu_oracle=False):
+ super().__init__()
+ if dim != 128:
+ raise ValueError("Only D128 is in scope")
+ self.scale = nn.Parameter(torch.ones(dim))
+ self.require_kernel, self.cpu_oracle = require_kernel, cpu_oracle
+
+ def forward(self, x):
+ return rmsnorm_hybrid(x, self.scale, require_kernel=self.require_kernel, cpu_oracle=self.cpu_oracle)
diff --git a/flux-umi/src/flux_action/models/cute_rmsnorm_kernel.py b/flux-umi/src/flux_action/models/cute_rmsnorm_kernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..f06a5a9814e4d6771cd49c455f418bcfab6e0684
--- /dev/null
+++ b/flux-umi/src/flux_action/models/cute_rmsnorm_kernel.py
@@ -0,0 +1,188 @@
+"""Experimental frozen BF16/N=64 RMSNorm, preserving the torch 2.10 reduction.
+
+Production imports none of this module. No CUDA work occurs on import. The CuTe
+kernel still needs GPU compilation, numerical, sanitizer and timing validation.
+
+The reference is the actual SM103 vectorized_layer_norm_kernel:
+four sequential FP32 FMAs per 4-element group, downward shuffle tree, FP32
+division by 64, a separate epsilon add, hardware rsqrt, FP32 multiply, BF16 RNE.
+Eight independent rows share a 128-thread block, with 16 lanes per row. Tensor
+values never cross row boundaries; the result from each subgroup's first lane
+is broadcast before scaling. QKV view strides are read directly without copies.
+"""
+
+from functools import lru_cache
+
+import torch
+from torch import Tensor
+from torch.nn import functional as F
+
+AUDITED_TORCH_GIT = "449b1768410104d3ed79d3bcfe4ba1d65c7f22c0"
+
+
+def unsupported_reason(x: Tensor, normalized_shape=(64,), weight=None, eps=1e-5):
+ """Metadata-only scope guard. Ineligible calls use the ordinary torch API."""
+ if type(x) is not Tensor:
+ return "tensor subclasses use the original torch dispatch"
+ if (str(torch.__version__).split("+")[0] != "2.10.0"
+ or torch.version.git_version != AUDITED_TORCH_GIT or torch.version.cuda != "13.0"):
+ return "only the audited torch 2.10.0/CUDA 13.0 arithmetic is supported"
+ if torch.compiler.is_compiling():
+ return "torch.compile integration is outside this experiment"
+ if torch.is_grad_enabled() or x.requires_grad or (weight is not None and weight.requires_grad):
+ return "only frozen no_grad/inference calls are supported"
+ if tuple(normalized_shape) != (64,) or x.ndim < 2 or x.shape[-1] != 64:
+ return "only a single normalized dimension of 64 is supported"
+ if weight is not None:
+ return "affine RMSNorm is outside this experiment"
+ if eps != 1e-5:
+ return "only the VAE epsilon 1e-5 is supported"
+ if not x.is_cuda or x.dtype != torch.bfloat16:
+ return "CUDA BF16 input is required"
+ if any(size < 1 for size in x.shape):
+ return "empty dimensions are outside this experiment"
+ if x.stride(-1) != 1:
+ return "the normalized dimension must be contiguous"
+ if x.data_ptr() % 8 or any(stride % 4 for stride in x.stride()[:-1]):
+ return "each four-element BF16 vector must be 8-byte aligned"
+ if any(stride <= 0 for size, stride in zip(x.shape, x.stride()) if size > 1):
+ return "broadcast or negative outer strides are unsupported"
+ try:
+ x.view(-1, x.shape[-2], 64)
+ except RuntimeError:
+ return "outer dimensions must flatten as a view without copying"
+ if x.numel() // 64 > 2147483647:
+ return "row count exceeds this experiment's indexing contract"
+ return None
+
+
+@lru_cache(maxsize=1)
+def _kernel_type():
+ import cuda.bindings.driver as cuda
+ import cutlass
+ import cutlass.cute as cute
+ from cutlass import Float32, Int64
+ from cutlass._mlir.dialects import llvm
+ from cutlass.cutlass_dsl import dsl_user_op
+
+ @dsl_user_op
+ def fma_rn(a: Float32, b: Float32, c: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type,
+ [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b, c)],
+ "fma.rn.f32 $0, $1, $2, $3;", "=f,f,f,f", loc=loc, ip=ip))
+
+ @dsl_user_op
+ def add_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type,
+ [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b)],
+ "add.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip))
+
+ @dsl_user_op
+ def mul_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type,
+ [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b)],
+ "mul.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip))
+
+ @dsl_user_op
+ def div_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type,
+ [Float32(v).ir_value(loc=loc, ip=ip) for v in (a, b)],
+ "div.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip))
+
+ @dsl_user_op
+ def rsqrt_hardware(a: Float32, *, loc=None, ip=None) -> Float32:
+ # epsilon >= 1e-5 keeps every finite nonnegative sum's rsqrt argument
+ # normal, matching the observed torch rsqrtf normal-input MUFU.RSQ path.
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type, [Float32(a).ir_value(loc=loc, ip=ip)],
+ "rsqrt.approx.ftz.f32 $0, $1;", "=f,f", loc=loc, ip=ip))
+
+ class FrozenRMSNorm64:
+ @cute.jit
+ def __call__(self, mX: cute.Tensor, mY: cute.Tensor, stream: cuda.CUstream):
+ copy_atom = cute.make_copy_atom(
+ cute.nvgpu.CopyUniversalOp(), mX.element_type, num_bits_per_copy=64)
+ self.kernel(mX, mY, copy_atom).launch(
+ grid=[cute.ceil_div(mY.shape[0], 8), 1, 1], block=[128, 1, 1], stream=stream)
+
+ @cute.kernel
+ def kernel(self, mX: cute.Tensor, mY: cute.Tensor, copy_atom: cute.CopyAtom):
+ tidx, _, _ = cute.arch.thread_idx()
+ block, _, _ = cute.arch.block_idx()
+ row = Int64(block) * 8 + tidx // 16
+ lane = tidx % 16
+ valid = row < mY.shape[0]
+ # Invalid tail groups still execute the warp collectives. Mask only
+ # memory accesses, so a partly filled final warp is well-defined.
+ rX = cute.make_rmem_tensor((4,), mX.element_type)
+ rX.fill(0)
+ if valid:
+ token = row // mX.shape[1]
+ head = row % mX.shape[1]
+ gX = cute.local_tile(mX[token, head, None], (4,), (lane,))
+ cute.copy(copy_atom, gX, rX)
+ values = cute.make_rmem_tensor((4,), Float32)
+ values.store(rX.load().to(Float32))
+ partial = Float32(0.0)
+ for index in cutlass.range(4, unroll_full=True):
+ partial = fma_rn(values[index], values[index], partial)
+ # Original warp0 lanes16..31 contain +0. Retain its offset16 add.
+ partial = add_rn(partial, Float32(0.0))
+ for index in cutlass.range(4, unroll_full=True):
+ other = cute.arch.shuffle_sync_down(
+ partial, offset=8 >> index, mask=-1, mask_and_clamp=0x101F)
+ partial = add_rn(partial, other)
+ # Only the subgroup leader has the same reduction tree as torch.
+ total = cute.arch.shuffle_sync(partial, offset=0, mask=-1, mask_and_clamp=0x101F)
+ # Original inter-warp reduction merges empty warp2 and then warp1.
+ total = add_rn(total, Float32(0.0))
+ total = add_rn(total, Float32(0.0))
+ mean_square = div_rn(total, Float32(64.0))
+ inverse_rms = rsqrt_hardware(add_rn(mean_square, Float32(1e-5)))
+ for index in cutlass.range(4, unroll_full=True):
+ values[index] = mul_rn(values[index], inverse_rms)
+ rX.store(values.load().to(mX.element_type))
+ if valid:
+ gY = cute.local_tile(mY[row, None], (4,), (lane,))
+ cute.copy(copy_atom, rX, gY)
+
+ return FrozenRMSNorm64
+
+
+@lru_cache(maxsize=32)
+def _compiled(shape, capability):
+ import cutlass
+ import cutlass.cute as cute
+
+ source = cute.runtime.make_fake_tensor(
+ cutlass.BFloat16, shape,
+ stride=(cute.sym_int64(divisibility=4), cute.sym_int64(divisibility=4), 1),
+ assumed_align=8)
+ destination = cute.runtime.make_fake_tensor(
+ cutlass.BFloat16, (shape[0] * shape[1], 64), stride=(64, 1), assumed_align=8)
+ return cute.compile(
+ _kernel_type()(), source, destination,
+ cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), options="--enable-tvm-ffi")
+
+
+def rms_norm_cute(x: Tensor, normalized_shape=(64,), weight=None, eps=1e-5, *, require_kernel=False):
+ reason = unsupported_reason(x, normalized_shape, weight, eps)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(reason)
+ return F.rms_norm(x, normalized_shape, weight, eps)
+ source = x.view(-1, x.shape[-2], 64)
+ with torch.cuda.device(x.device):
+ capability = torch.cuda.get_device_capability(x.device)
+ if capability != (10, 3):
+ if require_kernel:
+ raise ValueError("The arithmetic contract is currently audited only for SM103")
+ return F.rms_norm(x, normalized_shape, weight, eps)
+ result = torch.empty(tuple(x.shape), dtype=x.dtype, device=x.device)
+ function = _compiled(tuple(source.shape), capability)
+ function(source, result.view(-1, 64))
+ return result
diff --git a/flux-umi/src/flux_action/models/cute_rope.py b/flux-umi/src/flux_action/models/cute_rope.py
new file mode 100644
index 0000000000000000000000000000000000000000..6736a1b4ca9d323dbec6a032238f312210951035
--- /dev/null
+++ b/flux-umi/src/flux_action/models/cute_rope.py
@@ -0,0 +1,297 @@
+"""Experimental, out-of-place FLUX RoPE using CuTe DSL.
+
+This module belongs to an isolated opt-in source candidate. Importing it does not
+initialize CUDA; compilation and launch happen only after an eligible CUDA call.
+Both output layouts preserve the original eager expression, including singleton
+strides. This remains an experimental candidate pending end-to-end validation.
+
+The copy layout follows the CuTe tiled_copy_2d pattern used by Quack's
+interleaved rotary kernel, without importing Quack. This consumes the complete
+2x2 matrix, retains FLUX's two FP32 multiplies followed by one FP32 add, and uses
+the matrix transpose in backward. Explicit PTX rounding prevents FMA contraction.
+"""
+
+from functools import lru_cache
+from typing import Optional
+
+import torch
+from torch import Tensor
+
+
+def apply_rope_reference(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
+ """Original eager expression from models/transformer.py, including casts."""
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
+
+
+def transpose_reference(grad: Tensor, freqs: Tensor, dtype: torch.dtype) -> Tensor:
+ """Differentiable fallback for backward; never assume an orthogonal matrix."""
+ pairs = grad.float().reshape(*grad.shape[:-1], -1, 2)
+ g0, g1 = pairs[..., 0], pairs[..., 1]
+ dx0 = freqs[..., 0, 0] * g0 + freqs[..., 1, 0] * g1
+ dx1 = freqs[..., 0, 1] * g0 + freqs[..., 1, 1] * g1
+ return torch.stack((dx0, dx1), dim=-1).reshape(grad.shape).to(dtype)
+
+
+def unsupported_reason(xq: Tensor, xk: Optional[Tensor], freqs: Tensor, *, backward=False) -> Optional[str]:
+ """Metadata-only guard; no CUDA synchronization, copying, or initialization."""
+ if torch.compiler.is_compiling():
+ return "torch.compile integration is outside this experimental contract"
+ if any(type(value) is not Tensor for value in (xq, freqs) + ((xk,) if xk is not None else ())):
+ return "tensor subclasses require the PyTorch reference"
+ if not xq.is_cuda or not freqs.is_cuda or (xk is not None and not xk.is_cuda):
+ return "CUDA tensors are required"
+ if xq.ndim != 4 or xq.shape[-1] != 128 or any(n < 1 for n in xq.shape):
+ return "Q/K must have nonempty shape (B, H, L, 128)"
+ if xq.dtype not in (torch.bfloat16, torch.float32):
+ return "Q/K dtype must be BF16 or FP32"
+ if freqs.dtype not in (torch.bfloat16, torch.float32):
+ return "frequency table dtype must be BF16 or FP32"
+ if freqs.requires_grad:
+ return "frequency-table gradients require the PyTorch reference"
+ batch, heads, tokens, _ = xq.shape
+ vector = 16 // xq.element_size()
+ heads_per_block = 128 // (128 // vector)
+ if heads % heads_per_block:
+ return f"head count must be divisible by {heads_per_block}"
+ # Packed training has L=309376. Tokens therefore use grid x, not grid y.
+ if tokens > 2147483647 or heads // heads_per_block > 65535 or batch > 65535:
+ return "shape must fit CUDA grid x/y/z limits"
+ if freqs.ndim != 6 or tuple(freqs.shape[1:]) != (1, tokens, 64, 2, 2):
+ return "frequency table must have shape (B or 1, 1, L, 64, 2, 2)"
+ if freqs.shape[0] not in (1, batch):
+ return "frequency batch dimension must be 1 or match Q/K"
+ if freqs.device != xq.device or not freqs.is_contiguous():
+ return "frequency table must be contiguous on the Q/K device"
+ token_major_stride = (tokens * heads * 128, 128, heads * 128, 1)
+ for value in (xq, xk):
+ if value is None:
+ continue
+ if value.shape != xq.shape or value.dtype != xq.dtype or value.device != xq.device:
+ return "Q/K shapes, dtypes and devices must match"
+ if not backward and any(actual != wanted for actual, wanted, size
+ in zip(value.stride(), token_major_stride, value.shape) if size > 1):
+ return "forward Q/K must have the validated dense token-major layout"
+ if value.stride(-1) != 1 or any(s < 0 or s % vector for s in value.stride()[:-1]):
+ return "Q/K require contiguous head dimensions and 16-byte-aligned row strides"
+ if value.data_ptr() % 16:
+ return "Q/K base addresses must have 16-byte alignment"
+ return None
+
+
+@lru_cache(maxsize=1)
+def _kernel_type():
+ """Build DSL definitions lazily; this does not compile or initialize CUDA."""
+ import cuda.bindings.driver as cuda
+ import cutlass
+ import cutlass.cute as cute
+ from cutlass import Float32, const_expr
+ from cutlass._mlir.dialects import llvm
+ from cutlass.cutlass_dsl import dsl_user_op
+
+ @dsl_user_op
+ def mul_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type,
+ [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)],
+ "mul.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip,
+ ))
+
+ @dsl_user_op
+ def add_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(
+ Float32.mlir_type,
+ [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)],
+ "add.rn.f32 $0, $1, $2;", "=f,f,f", loc=loc, ip=ip,
+ ))
+
+ class FluxRopeKernel:
+ def __init__(self, element_type, use_transpose):
+ self.vector = 128 // element_type.width
+ self.threads_per_head = 128 // self.vector
+ self.tile_heads = 128 // self.threads_per_head
+ self.use_transpose = use_transpose
+
+ @cute.jit
+ def __call__(
+ self, mQ: cute.Tensor, mK: Optional[cute.Tensor], mF: cute.Tensor,
+ mOQ: cute.Tensor, mOK: Optional[cute.Tensor], stream: cuda.CUstream,
+ ):
+ copy_atom = cute.make_copy_atom(
+ cute.nvgpu.CopyUniversalOp(), mQ.element_type, num_bits_per_copy=128,
+ )
+ thread_layout = cute.make_ordered_layout(
+ (self.tile_heads, self.threads_per_head), order=(1, 0),
+ )
+ tiled_copy = cute.make_tiled_copy_tv(
+ copy_atom, thread_layout, cute.make_layout((1, self.vector)),
+ )
+ self.kernel(mQ, mK, mF, mOQ, mOK, tiled_copy, copy_atom).launch(
+ grid=[mQ.shape[2], mQ.shape[1] // self.tile_heads, mQ.shape[0]],
+ block=[128, 1, 1], stream=stream,
+ )
+
+ @cute.kernel
+ def kernel(
+ self, mQ: cute.Tensor, mK: Optional[cute.Tensor], mF: cute.Tensor,
+ mOQ: cute.Tensor, mOK: Optional[cute.Tensor], tiled_copy: cute.TiledCopy,
+ copy_atom: cute.CopyAtom,
+ ):
+ tidx, _, _ = cute.arch.thread_idx()
+ token, head_tile, batch = cute.arch.block_idx()
+ tile = (self.tile_heads, 128)
+ gQ = cute.local_tile(mQ[batch, None, token, None], tile, (head_tile, 0))
+ gOQ = cute.local_tile(mOQ[batch, None, token, None], tile, (head_tile, 0))
+ thr = tiled_copy.get_slice(tidx)
+ tQgQ, tQgO = thr.partition_S(gQ), thr.partition_D(gOQ)
+ rQ = cute.make_rmem_tensor_like(tQgQ)
+ cute.copy(copy_atom, tQgQ, rQ)
+ q = cute.make_rmem_tensor_like(rQ, Float32)
+ q.store(rQ.load().to(Float32))
+ rK, k, tKgO = None, None, None
+ if const_expr(mK is not None):
+ gK = cute.local_tile(mK[batch, None, token, None], tile, (head_tile, 0))
+ gOK = cute.local_tile(mOK[batch, None, token, None], tile, (head_tile, 0))
+ tKgK, tKgO = thr.partition_S(gK), thr.partition_D(gOK)
+ rK = cute.make_rmem_tensor_like(tKgK)
+ cute.copy(copy_atom, tKgK, rK)
+ k = cute.make_rmem_tensor_like(rK, Float32)
+ k.store(rK.load().to(Float32))
+
+ # tiled_copy_2d maps each thread to one contiguous vector within a
+ # head. Every tile is full: the host checks D=128 and H%tile_heads=0.
+ assert cute.size(q.shape) == self.vector
+ pair_base = (tidx % self.threads_per_head) * (self.vector // 2)
+ table_batch = batch
+ if const_expr(mF.shape[0] == 1):
+ table_batch = 0
+ for i in cutlass.range(self.vector // 2, unroll_full=True):
+ pair = pair_base + i
+ f00 = Float32(mF[table_batch, 0, token, pair, 0, 0])
+ f01 = Float32(mF[table_batch, 0, token, pair, 0, 1])
+ f10 = Float32(mF[table_batch, 0, token, pair, 1, 0])
+ f11 = Float32(mF[table_batch, 0, token, pair, 1, 1])
+ if const_expr(self.use_transpose):
+ f01, f10 = f10, f01
+ q0, q1 = q[2 * i], q[2 * i + 1]
+ q[2 * i] = add_rn(mul_rn(f00, q0), mul_rn(f01, q1))
+ q[2 * i + 1] = add_rn(mul_rn(f10, q0), mul_rn(f11, q1))
+ if const_expr(mK is not None):
+ k0, k1 = k[2 * i], k[2 * i + 1]
+ k[2 * i] = add_rn(mul_rn(f00, k0), mul_rn(f01, k1))
+ k[2 * i + 1] = add_rn(mul_rn(f10, k0), mul_rn(f11, k1))
+ rQ.store(q.load().to(rQ.element_type))
+ cute.copy(copy_atom, rQ, tQgO)
+ if const_expr(mK is not None):
+ rK.store(k.load().to(rK.element_type))
+ cute.copy(copy_atom, rK, tKgO)
+
+ return FluxRopeKernel
+
+
+@lru_cache(maxsize=32)
+def _compiled(dtype, table_dtype, shape, table_shape, table_stride, paired, transpose, capability):
+ import cutlass
+ import cutlass.cute as cute
+
+ element_types = {torch.bfloat16: cutlass.BFloat16, torch.float32: cutlass.Float32}
+ element_type = element_types[dtype]
+ table_element_type = element_types[table_dtype]
+ vector = 128 // element_type.width
+ # Each tensor gets independent dynamic outer strides. In particular, a
+ # token-major forward input does not constrain the backward gradient layout.
+ def fake_activation():
+ return cute.runtime.make_fake_tensor(
+ element_type, shape,
+ stride=tuple(cute.sym_int64(divisibility=vector) for _ in shape[:-1]) + (1,),
+ assumed_align=16,
+ )
+
+ q, oq = fake_activation(), fake_activation()
+ k = fake_activation() if paired else None
+ ok = fake_activation() if paired else None
+ f = cute.runtime.make_fake_tensor(
+ table_element_type, table_shape, stride=table_stride, assumed_align=1,
+ )
+ return cute.compile(
+ _kernel_type()(element_type, transpose), q, k, f, oq, ok,
+ cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
+ options="--enable-tvm-ffi",
+ )
+
+
+def _allocate_outputs(xq: Tensor, xk: Optional[Tensor], transpose: bool):
+ """Forward retains token-major output; backward matches eager BHLD storage.
+
+ The eager expression's sum/select backward allocates contiguous (B,H,L,D)
+ gradients. Preserving that layout also preserves upstream reduction choices.
+ """
+ batch, heads, tokens, dim = xq.shape
+ if transpose:
+ oq = torch.empty(xq.shape, device=xq.device, dtype=xq.dtype)
+ else:
+ # TensorIterator's eager expression assigns these singleton-axis strides.
+ # Keep even ignored metadata identical for downstream attention consumers.
+ strides = (heads * dim * (tokens if batch > 1 else 1), dim,
+ heads * dim if tokens > 1 else dim, 1)
+ oq = torch.empty_strided(xq.shape, strides, device=xq.device, dtype=xq.dtype)
+ ok = (torch.empty_strided(oq.shape, oq.stride(), device=oq.device, dtype=oq.dtype)
+ if xk is not None else None)
+ return oq, ok
+
+
+def _rotate(xq: Tensor, xk: Optional[Tensor], freqs: Tensor, transpose: bool):
+ """Inputs must already satisfy unsupported_reason; output owns new storage."""
+ oq, ok = _allocate_outputs(xq, xk, transpose)
+ # TVM FFI supplies the current CUDA stream, matching Quack's launch contract.
+ with torch.cuda.device(xq.device):
+ function = _compiled(
+ xq.dtype, freqs.dtype, tuple(xq.shape), tuple(freqs.shape), tuple(freqs.stride()),
+ xk is not None, transpose, torch.cuda.get_device_capability(xq.device),
+ )
+ function(xq, xk, freqs, oq, ok)
+ return oq, ok
+
+
+class _RopeAutograd(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, xq, xk, freqs):
+ ctx.set_materialize_grads(False)
+ ctx.save_for_backward(freqs)
+ ctx.input_dtype = xq.dtype
+ return _rotate(xq, xk, freqs, transpose=False)
+
+ @staticmethod
+ def backward(ctx, gq, gk):
+ (freqs,) = ctx.saved_tensors
+ gq = gq if ctx.needs_input_grad[0] else None
+ gk = gk if ctx.needs_input_grad[1] else None
+ if gq is None and gk is None:
+ return None, None, None
+ first, second = (gq, gk) if gq is not None else (gk, None)
+ if torch.is_grad_enabled() or unsupported_reason(first, second, freqs, backward=True) is not None:
+ # Preserve higher derivatives and unusual upstream gradient strides.
+ dq = transpose_reference(gq, freqs, ctx.input_dtype) if gq is not None else None
+ dk = transpose_reference(gk, freqs, ctx.input_dtype) if gk is not None else None
+ else:
+ first_out, second_out = _rotate(first, second, freqs, transpose=True)
+ dq, dk = (first_out, second_out) if gq is not None else (None, first_out)
+ return dq, dk, None
+
+
+def apply_rope_cute(xq: Tensor, xk: Tensor, freqs: Tensor, *, require_kernel=False):
+ """Experimental replacement. Unsupported contracts retain eager autograd.
+
+ Set require_kernel=True in microbenchmarks so a forward fallback cannot be
+ mistaken for a CuTe result. Compile/launch failures intentionally propagate;
+ they are not hidden by a blanket exception handler.
+ """
+ reason = unsupported_reason(xq, xk, freqs)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(f"CuTe RoPE contract not satisfied: {reason}")
+ return apply_rope_reference(xq, xk, freqs)
+ return _RopeAutograd.apply(xq, xk, freqs)
diff --git a/flux-umi/src/flux_action/models/cute_vae_rope_kernel.py b/flux-umi/src/flux_action/models/cute_vae_rope_kernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb3aceda2c13f0667330187cb9b3fc3f40e93ec8
--- /dev/null
+++ b/flux-umi/src/flux_action/models/cute_vae_rope_kernel.py
@@ -0,0 +1,154 @@
+"""CPU-reviewed, GPU-UNVALIDATED frozen VAE half-RoPE CuTe prototype.
+
+No production integration. All GPU work must wait for explicit allocation by the
+coordinating agent. Unlike DiT RoPE, each BF16 product is rounded before the sum.
+Only no-grad, contiguous BF16 Q/K with D64 and complete 32-row tiles are eligible.
+Cos/sin generation is deliberately outside this candidate and remains unchanged.
+"""
+from functools import lru_cache
+import torch
+from torch import Tensor
+
+
+def reference(q, k, cos, sin):
+ def rotate(x):
+ low, high = x.chunk(2, dim=-1)
+ return x * cos + torch.cat((-high, low), dim=-1) * sin
+ return rotate(q), rotate(k)
+
+
+def unsupported_reason(q, k, cos, sin):
+ if torch.compiler.is_compiling():
+ return 'torch.compile integration is outside this prototype contract'
+ if any(type(x) is not Tensor for x in (q, k, cos, sin)):
+ return 'tensor subclasses require eager fallback'
+ if not all(x.is_cuda for x in (q, k, cos, sin)):
+ return 'CUDA tensors are required'
+ if torch.is_grad_enabled() or any(x.requires_grad for x in (q, k, cos, sin)):
+ return 'frozen no-grad tensors are required'
+ if q.ndim != 6 or q.shape[-1] != 64 or any(n < 1 for n in q.shape):
+ return 'Q/K must have nonempty (B,T,H,W,heads,64) shape'
+ if k.shape != q.shape:
+ return 'Q/K shapes must match'
+ b, t, h, w, heads, dim = q.shape
+ if cos.shape != (1, t, h, w, 1, dim) or sin.shape != cos.shape:
+ return 'cos/sin must have shape (1,T,H,W,1,64)'
+ if any(x.dtype != torch.bfloat16 or x.device != q.device or not x.is_contiguous()
+ for x in (q, k, cos, sin)):
+ return 'all inputs must be contiguous BF16 on the same CUDA device'
+ if any(x.data_ptr() % 16 for x in (q, k, cos, sin)):
+ return 'all input base addresses must be 16-byte aligned'
+ rows = q.numel() // 64
+ if rows % 32 or rows // 32 > 2147483647:
+ return 'complete 32-row tiles fitting CUDA grid.x are required'
+ return None
+
+
+@lru_cache(maxsize=1)
+def _kernel_type():
+ import cuda.bindings.driver as cuda
+ import cutlass
+ import cutlass.cute as cute
+ from cutlass import Float32, BFloat16
+ from cutlass._mlir.dialects import llvm
+ from cutlass.cutlass_dsl import dsl_user_op
+
+ @dsl_user_op
+ def mul_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(Float32.mlir_type,
+ [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)],
+ 'mul.rn.f32 $0, $1, $2;', '=f,f,f', loc=loc, ip=ip))
+
+ @dsl_user_op
+ def add_rn(a: Float32, b: Float32, *, loc=None, ip=None) -> Float32:
+ return Float32(llvm.inline_asm(Float32.mlir_type,
+ [Float32(a).ir_value(loc=loc, ip=ip), Float32(b).ir_value(loc=loc, ip=ip)],
+ 'add.rn.f32 $0, $1, $2;', '=f,f,f', loc=loc, ip=ip))
+
+ class VaeHalfRope:
+ def __init__(self, heads):
+ self.heads = heads
+
+ @cute.jit
+ def __call__(self, q: cute.Tensor, k: cute.Tensor, c: cute.Tensor, s: cute.Tensor,
+ oq: cute.Tensor, ok: cute.Tensor, stream: cuda.CUstream):
+ atom = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), cutlass.BFloat16, num_bits_per_copy=128)
+ threads = cute.make_ordered_layout((32, 4), order=(1, 0))
+ tiled = cute.make_tiled_copy_tv(atom, threads, cute.make_layout((1, 8)))
+ self.kernel(q, k, c, s, oq, ok, tiled, atom).launch(
+ grid=[q.shape[0] // 32, 1, 1], block=[128, 1, 1], stream=stream)
+
+ @cute.kernel
+ def kernel(self, q: cute.Tensor, k: cute.Tensor, c: cute.Tensor, s: cute.Tensor,
+ oq: cute.Tensor, ok: cute.Tensor, tiled: cute.TiledCopy, atom: cute.CopyAtom):
+ tid, _, _ = cute.arch.thread_idx()
+ block, _, _ = cute.arch.block_idx()
+ row = block * 32 + tid // 4
+ position = (row // self.heads) % c.shape[0]
+ pair_base = (tid % 4) * 8
+ tile = (32, 32)
+ thread = tiled.get_slice(tid)
+ tq0 = thread.partition_S(cute.local_tile(q[None, 0, None], tile, (block, 0)))
+ tq1 = thread.partition_S(cute.local_tile(q[None, 1, None], tile, (block, 0)))
+ tk0 = thread.partition_S(cute.local_tile(k[None, 0, None], tile, (block, 0)))
+ tk1 = thread.partition_S(cute.local_tile(k[None, 1, None], tile, (block, 0)))
+ toq0 = thread.partition_D(cute.local_tile(oq[None, 0, None], tile, (block, 0)))
+ toq1 = thread.partition_D(cute.local_tile(oq[None, 1, None], tile, (block, 0)))
+ tok0 = thread.partition_D(cute.local_tile(ok[None, 0, None], tile, (block, 0)))
+ tok1 = thread.partition_D(cute.local_tile(ok[None, 1, None], tile, (block, 0)))
+ rq0, rq1 = cute.make_rmem_tensor_like(tq0), cute.make_rmem_tensor_like(tq1)
+ rk0, rk1 = cute.make_rmem_tensor_like(tk0), cute.make_rmem_tensor_like(tk1)
+ cute.copy(atom, tq0, rq0); cute.copy(atom, tq1, rq1)
+ cute.copy(atom, tk0, rk0); cute.copy(atom, tk1, rk1)
+ assert cute.size(rq0.shape) == 8
+ for i in cutlass.range(8, unroll_full=True):
+ pair = pair_base + i
+ c0, c1 = Float32(c[position, 0, pair]), Float32(c[position, 1, pair])
+ s0, s1 = Float32(s[position, 0, pair]), Float32(s[position, 1, pair])
+ q0, q1 = Float32(rq0[i]), Float32(rq1[i])
+ k0, k1 = Float32(rk0[i]), Float32(rk1[i])
+ # Do not combine into FP32 mul/mul/add: eager rounds each product.
+ qp0 = Float32(BFloat16(mul_rn(q0, c0)))
+ qp1 = Float32(BFloat16(mul_rn(-q1, s0)))
+ qp2 = Float32(BFloat16(mul_rn(q1, c1)))
+ qp3 = Float32(BFloat16(mul_rn(q0, s1)))
+ kp0 = Float32(BFloat16(mul_rn(k0, c0)))
+ kp1 = Float32(BFloat16(mul_rn(-k1, s0)))
+ kp2 = Float32(BFloat16(mul_rn(k1, c1)))
+ kp3 = Float32(BFloat16(mul_rn(k0, s1)))
+ rq0[i], rq1[i] = BFloat16(add_rn(qp0, qp1)), BFloat16(add_rn(qp2, qp3))
+ rk0[i], rk1[i] = BFloat16(add_rn(kp0, kp1)), BFloat16(add_rn(kp2, kp3))
+ cute.copy(atom, rq0, toq0); cute.copy(atom, rq1, toq1)
+ cute.copy(atom, rk0, tok0); cute.copy(atom, rk1, tok1)
+ return VaeHalfRope
+
+
+@lru_cache(maxsize=32)
+def _compiled(rows, positions, heads, capability):
+ import cutlass
+ import cutlass.cute as cute
+ def fake(size):
+ return cute.runtime.make_fake_tensor(cutlass.BFloat16, (size, 2, 32), stride=(64, 32, 1), assumed_align=16)
+ return cute.compile(_kernel_type()(heads), fake(rows), fake(rows), fake(positions), fake(positions),
+ fake(rows), fake(rows), cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
+ options='--enable-tvm-ffi')
+
+
+def _launch(q, k, cos, sin):
+ rows = q.numel() // 64
+ positions = cos.numel() // 64
+ oq, ok = torch.empty(q.shape, device=q.device, dtype=q.dtype), torch.empty(k.shape, device=k.device, dtype=k.dtype)
+ with torch.cuda.device(q.device):
+ function = _compiled(rows, positions, q.shape[-2], torch.cuda.get_device_capability(q.device))
+ function(q.reshape(rows, 2, 32), k.reshape(rows, 2, 32), cos.reshape(positions, 2, 32),
+ sin.reshape(positions, 2, 32), oq.reshape(rows, 2, 32), ok.reshape(rows, 2, 32))
+ return oq, ok
+
+
+def apply_vae_rope(q, k, cos, sin, *, require_kernel=False):
+ reason = unsupported_reason(q, k, cos, sin)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(reason)
+ return reference(q, k, cos, sin)
+ return _launch(q, k, cos, sin)
diff --git a/flux-umi/src/flux_action/models/dit_cute_qknorm.py b/flux-umi/src/flux_action/models/dit_cute_qknorm.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a78d215ac6cbbaae884747145901d0b6315113e
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_cute_qknorm.py
@@ -0,0 +1,124 @@
+"""Opt-in training-only dispatch for the audited G2 DiT Q/K RMSNorms.
+
+Installation sets an ordinary Python flag on the original modules. Parameter,
+module and hook identities are retained, including across checkpoint/FSDP wraps.
+The tested CuTe implementation is copied byte-for-byte into the sibling module.
+"""
+from functools import lru_cache
+from importlib.metadata import PackageNotFoundError, version
+import hashlib
+import os
+from pathlib import Path
+
+from . import cute_qknorm_hybrid as kernel
+from .transformer import JointSingleSeq, ModeBlock, QKNorm, RMSNorm, SingleStreamBlock
+
+_REQUIRE_KERNEL = os.environ.get("FLUX_ACTION_CUTE_QKNORM_REQUIRE_KERNEL") == "1"
+_KERNEL_SHA256 = "a479eb38ac8b23b889d9ff35597b694aab23a1be84bb64d8e1f38c6bfd551322"
+_EXPECTED_QKNORMS = 53
+_EXPECTED_RMSNORMS = 106
+
+
+@lru_cache(maxsize=1)
+def dependency_versions():
+ result = {}
+ for name in ("nvidia-cutlass-dsl", "apache-tvm-ffi"):
+ try:
+ result[name] = version(name)
+ except PackageNotFoundError:
+ result[name] = None
+ return result
+
+
+def dependencies_supported():
+ return dependency_versions() == {
+ "nvidia-cutlass-dsl": "4.8.0", "apache-tvm-ffi": "0.1.14.post1"}
+
+
+def dispatch(layer, x):
+ """Caller already checked this original RMSNorm's installation/training flags."""
+ if not dependencies_supported():
+ if _REQUIRE_KERNEL:
+ raise RuntimeError("Required CuTe QKNorm dependencies are unavailable or unvalidated")
+ return kernel.reference(x, layer.scale)
+ return kernel.rmsnorm_hybrid(x, layer.scale, require_kernel=_REQUIRE_KERNEL)
+
+
+def _clean(name):
+ return name.replace("._checkpoint_wrapped_module", "")
+
+
+def inventory(dit):
+ pairs, norms = [], []
+ for name, layer in dit.named_modules():
+ if type(layer) is QKNorm:
+ pairs.append(_clean(name))
+ if type(layer) is RMSNorm:
+ norms.append((_clean(name), layer))
+ return pairs, norms
+
+
+def runtime_info(dit):
+ pairs, norms = inventory(dit)
+ enabled = [name for name, layer in norms if getattr(layer, "_cute_qknorm_enabled", False)]
+ info = {
+ "installed": len(enabled) == _EXPECTED_RMSNORMS,
+ "require_kernel": _REQUIRE_KERNEL,
+ "expected_qknorm_count": _EXPECTED_QKNORMS,
+ "actual_qknorm_count": len(pairs),
+ "expected_rmsnorm_count": _EXPECTED_RMSNORMS,
+ "actual_rmsnorm_count": len(norms),
+ "actual_dispatch_count": len(enabled),
+ "qknorm_names": pairs, "module_names": enabled,
+ "dependencies": dependency_versions(),
+ "dependencies_supported": dependencies_supported(),
+ "kernel_sha256": hashlib.sha256(Path(kernel.__file__).read_bytes()).hexdigest(),
+ "expected_kernel_sha256": _KERNEL_SHA256,
+ "scope": "audited G2 DiT Q/K RMSNorms, training only; original modules/parameters/hooks retained",
+ }
+ if _REQUIRE_KERNEL and (
+ not info["installed"] or len(pairs) != _EXPECTED_QKNORMS
+ or len(norms) != _EXPECTED_RMSNORMS or len(set(enabled)) != _EXPECTED_RMSNORMS
+ or not info["dependencies_supported"] or info["kernel_sha256"] != _KERNEL_SHA256
+ ):
+ raise RuntimeError(f"Required CuTe QKNorm runtime inventory failed: {info}")
+ return info
+
+
+def install_training_qknorm(dit, *, compile_model=False):
+ def unsupported(reason):
+ if _REQUIRE_KERNEL:
+ raise RuntimeError(f"Required CuTe QKNorm installation failed: {reason}")
+ return {"installed": False, "actual_dispatch_count": 0,
+ "expected_qknorm_count": _EXPECTED_QKNORMS,
+ "expected_rmsnorm_count": _EXPECTED_RMSNORMS,
+ "require_kernel": False, "reason": reason}
+
+ if compile_model:
+ return unsupported("compiled models retain original RMSNorm")
+ if type(dit) is not JointSingleSeq or (
+ dit.hidden_size, dit.num_heads, dit.depth, dit.depth_single_blocks, dit.depth_late_blocks
+ ) != (3072, 24, 5, 28, 0):
+ return unsupported("DiT architecture differs from audited G2 model")
+ if len(dit.content_mode_blocks) != 4 or not {"video", "video_cond"}.issubset(dit.content_mode_blocks):
+ return unsupported("G2 content-stream inventory differs")
+ pairs, norms = inventory(dit)
+ expected = []
+ for name, owner in dit.named_modules():
+ if type(owner) in (ModeBlock, SingleStreamBlock):
+ if owner.num_heads != 24 or owner.hidden_size != 3072 or type(owner.norm) is not QKNorm:
+ return unsupported("block Q/K norm contract differs")
+ expected.extend((f"{name}.norm.query_norm", f"{name}.norm.key_norm"))
+ if (len(pairs) != _EXPECTED_QKNORMS or len(norms) != _EXPECTED_RMSNORMS
+ or len(expected) != _EXPECTED_RMSNORMS or set(expected) != {name for name, _ in norms}
+ or len({id(layer.scale) for _, layer in norms}) != _EXPECTED_RMSNORMS
+ or any(tuple(layer.scale.shape) != (128,) or layer.scale.stride() != (1,) for _, layer in norms)):
+ return unsupported("full QKNorm/RMSNorm module or scale inventory differs")
+ if hashlib.sha256(Path(kernel.__file__).read_bytes()).hexdigest() != _KERNEL_SHA256:
+ return unsupported("CuTe kernel differs from the GPU-tested source")
+ if _REQUIRE_KERNEL and not dependencies_supported():
+ return unsupported("dependencies are unavailable or unvalidated")
+ # Atomic after every structural check; retain module/parameter/hook identity.
+ for _, layer in norms:
+ layer._cute_qknorm_enabled = True
+ return runtime_info(dit)
diff --git a/flux-umi/src/flux_action/models/dit_fanout_linear.py b/flux-umi/src/flux_action/models/dit_fanout_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..b70451c71d9916fb0e665de05a5c3ccc2b7dc4b5
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_fanout_linear.py
@@ -0,0 +1,67 @@
+"""Fan-out projections of a DiT block (q, k, v, mlp_in share one input) as one autograd Function.
+
+Forward: the same four ``F.linear`` calls as the modules (bit-identical outputs). Backward: the four weight gradients as
+autograd computes them (``x^T @ g`` per projection, same cuBLAS calls), and the input gradient accumulated with
+cuBLASLt ``beta=1`` epilogues (``dx = g_mlp @ W_mlp; dx.addmm_(g_v, W_v); dx.addmm_(g_k, W_k); dx.addmm_(g_q, W_q)``)
+instead of autograd's three separate bf16 ``add`` kernels over the [L, 3072] input gradient. The accumulation order is
+the one autograd uses for this block (the mlp_in gradient arrives first, then v, k, q), and cuBLASLt's ``beta=1``
+epilogue rounds exactly like the separate add (verified bitwise, see tests), so the result is bit-identical while
+saving ~1.2 ms per joint block (three 1.9 GB read-read-write passes become epilogue reads).
+
+This holds only when the four projections are the *only* consumers of ``x``: a block with ``gate_type`` set feeds
+the same input to ``gate_proj`` too, autograd then sums five gradients in an order the Function cannot reproduce
+(dx / modulation-row gradients differ by bf16 rounding), so ``fanout_linear`` falls back to the plain modules there.
+
+Enabled through ``dit_mod_rows.Config.fanout_linear`` (``PolicyConfig.dit_fanout_linear``).
+"""
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+
+class _FanOutLinear(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x: Tensor, wq: Tensor, wk: Tensor, wv: Tensor, wm: Tensor, bq, bk, bv):
+ q = F.linear(x, wq, bq)
+ k = F.linear(x, wk, bk)
+ v = F.linear(x, wv, bv)
+ m = F.linear(x, wm)
+ ctx.save_for_backward(x, wq, wk, wv, wm)
+ ctx.has_bias = (bq is not None, bk is not None, bv is not None)
+ return q, k, v, m
+
+ @staticmethod
+ def backward(ctx, gq: Tensor, gk: Tensor, gv: Tensor, gm: Tensor):
+ x, wq, wk, wv, wm = ctx.saved_tensors
+ K = x.shape[-1]
+ x2 = x.reshape(-1, K)
+ gq2, gk2, gv2, gm2 = (g.reshape(-1, g.shape[-1]) for g in (gq, gk, gv, gm))
+ # input gradient: autograd's order (last-created consumer first), cuBLASLt beta=1 accumulation
+ dx = torch.mm(gm2, wm)
+ dx.addmm_(gv2, wv)
+ dx.addmm_(gk2, wk)
+ dx.addmm_(gq2, wq)
+ # weight gradients exactly as MmBackward0 computes them: (x^T @ g) transposed to [N, K]
+ dwq = torch.mm(x2.t(), gq2).t()
+ dwk = torch.mm(x2.t(), gk2).t()
+ dwv = torch.mm(x2.t(), gv2).t()
+ dwm = torch.mm(x2.t(), gm2).t()
+ hb = ctx.has_bias
+ dbq = gq2.sum(0) if hb[0] else None
+ dbk = gk2.sum(0) if hb[1] else None
+ dbv = gv2.sum(0) if hb[2] else None
+ return dx.view_as(x), dwq, dwk, dwv, dwm, dbq, dbk, dbv
+
+
+def fanout_linear(x: Tensor, q_proj: nn.Linear, k_proj: nn.Linear, v_proj: nn.Linear, mlp_in: nn.Linear, *,
+ gated: bool = False):
+ """``(q_proj(x), k_proj(x), v_proj(x), mlp_in(x))`` with the fused-accumulation backward (training only).
+
+ ``gated``: the block also feeds ``x`` to ``gate_proj`` (``gate_type`` set) -- a fifth consumer whose gradient
+ autograd adds in an order this Function cannot reproduce, so the plain modules are used (bit-identical path)."""
+ if not torch.is_grad_enabled() or mlp_in.bias is not None or gated:
+ return q_proj(x), k_proj(x), v_proj(x), mlp_in(x)
+ return _FanOutLinear.apply(x, q_proj.weight, k_proj.weight, v_proj.weight, mlp_in.weight,
+ q_proj.bias, k_proj.bias, v_proj.bias)
diff --git a/flux-umi/src/flux_action/models/dit_mod_rows.py b/flux-umi/src/flux_action/models/dit_mod_rows.py
new file mode 100644
index 0000000000000000000000000000000000000000..77ff95a3878b9ec57859aeabdd904073268c1679
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_mod_rows.py
@@ -0,0 +1,1202 @@
+"""Row-indexed AdaLN modulation for the DiT blocks: no per-token shift/scale/gate tensors, no per-token gradients.
+
+Experiment dit-mod-rows. Nothing under src/flux_action is modified; the module is a
+drop-in companion of ``dit_norm_mod_gate`` (same per-element arithmetic, bit-exact forward / dx) and of
+``dit_time_embed_dedup`` (which today expands the per-(stream, window) modulation ROWS to per-token tensors with
+``ExpandRows`` and segment-sums the per-token gradients back).
+
+Today (production v4t) every single block (and its activation-checkpoint recompute) reads three expanded
+``[1, L, 3072]`` bf16 modulation tensors (3 x 1.9 GB at L = 309376), its backward writes three per-token gradient
+tensors of the same size, autograd accumulates them across the 28 blocks sharing one modulation set
+(``aten::add_``, 1.1 ms each) and ``ExpandRows.backward`` finally segment-sums them into rows. Here the kernels
+take the modulation as ROWS ``[R, N]`` plus a per-token row index / per-chunk tables (:class:`RowPlan`):
+
+* ``_ln_mod_rows_fwd_kernel``: ``dit_norm_mod_gate._ln_mod_fwd_kernel`` with the shift/scale row gathered through
+ ``idx[token]`` inside the kernel (rows may be fp32: they are rounded to bf16 in the kernel exactly like
+ ``ExpandRows``' ``rows.to(bf16)``). Bit-exact with the production kernel (same instructions).
+* ``_gate_res_rows_fwd_kernel`` (and the ``o1 + o2`` variant): ``bf16(x + bf16(gate[idx] * out))``, bit-exact.
+* ``_ln_mod_rows_bwd_kernel``: one 128-thread program per CHUNK (a run of <= T consecutive tokens that all belong
+ to one modulation row; chunks never straddle a row boundary). For every token it recomputes ``ln`` / ``a`` from
+ (x, scale row, mean, rstd), forms ``dy = bf16(g * a)``, accumulates ATen's two row statistics in ATen's order
+ and writes ``dx = bf16(bf16(dx_ln) + G)`` exactly like the production kernel (dx stays bit-exact), while
+ accumulating the per-token modulation gradients ``g`` (d_shift) and ``bf16(g * ln)`` (d_scale) in fp32
+ registers over the chunk's tokens. Per-chunk partial sums go to a ``[2, C, N]`` fp32 buffer; a second
+ deterministic kernel (:func:`_rows_reduce_kernel`) sums each row's chunks in chunk order. No atomics, no
+ per-token gradient tensor: the result is ``[R, N]`` fp32 for d_shift and d_scale.
+* ``_gate_res_rows_bwd_kernel``: the same chunked scheme for ``d_gate = sum_tokens bf16(G * out)`` (``out`` =
+ ``bf16(o1 + o2)`` in the fused-add variant) while writing ``d_out = bf16(G * gate[idx])`` per token.
+
+Numerics: forward outputs, ``mean``/``rstd``, ``dx`` and ``d_out`` are bitwise identical to the production fused
+kernels (verified at production shape, see test_exact.py). The row gradients are fp32 sums of the same bf16
+per-token values the production path produces (``ROUND_BF16=True``, default) in a different fp32 summation order:
+they equal fp64 segment sums of the per-token bf16 gradients to ~1e-7 relative, i.e. the accuracy class of
+``ExpandRows.backward``, *given the same bf16 rounding point of the rows*. That rounding point depends on the dtype
+the rows arrive in. Fed fp32 rows (plain module, no FSDP) the kernels round them to bf16 internally, return fp32
+row sums and autograd accumulates the 28 blocks' sums in fp32. Under FSDP2 with ``MixedPrecisionPolicy(
+cast_forward_inputs=True)`` (``training.distributed.shard_dit``) the ``ModRows`` NamedTuple is a pytree, so every
+block receives bf16 rows: the forward is unchanged (same bf16 values), but autograd rounds each block's fp32 row
+sums to bf16 before the cross-block fp32 accumulation -- the same rounding point as the eager / ``ExpandRows`` path
+(``rows.to(bf16)`` once per block, bf16 per-token gradient accumulation across blocks). Either way the shared
+modulation / ``time_in`` / ``vector_in`` gradients differ from the per-token path only by that fp32 summation order
+at the given rounding point, not bitwise. ``ROUND_BF16=False`` skips the per-token bf16 rounding (closer to the
+exact gradient, but not what the current path computes).
+
+Autograd interface (see :func:`ln_modulate_rows`, :func:`gate_residual_rows`, :class:`ModRows`)::
+
+ plan = row_plan(counts, device) # counts: tokens per (window, segment) row, cached
+ mod = ModRows(shift_rows, scale_rows, gate_rows, plan) # rows [R, N] fp32 (or bf16), any row pitch
+ combined, x_alias = ln_modulate_rows(x, mod, eps)
+ out = gate_residual_rows(x_alias, mod, o1, o2) # or gate_residual_rows(x_alias, mod, output)
+
+``install(dit_or_block)`` patches ``forward`` on ``SingleStreamBlock`` / ``ModeBlock`` instances with a
+dispatcher: a :class:`ModRows` modulation takes the row kernels, anything else runs the previously installed
+forward (the production ``dit_norm_mod_gate`` mirror or eager). :func:`forward_dedup_rows` is
+``dit_time_embed_dedup.forward_dedup`` with the ``per_token`` expansions replaced by :class:`ModRows`
+(``install_dedup_rows(dit)`` wires it, see the docstring for the exact diff).
+"""
+from __future__ import annotations
+
+import types
+from collections.abc import Sequence
+from typing import NamedTuple
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+
+try:
+ from flux_action.models import dit_norm_mod_gate as nmg
+except ImportError: # pragma: no cover
+ import dit_norm_mod_gate as nmg # type: ignore[no-redef]
+
+NUM_WARPS = 4 # 128 threads = one ATen vectorized_layer_norm / layer_norm_grad_input block
+LANES = tl.constexpr(128)
+GATE_BLOCK = 1024
+# N / 512 accumulators are spelled out in the LN backward (NJ <= 8, N <= 4096) and the gate / reduce kernels launch grid
+# (M, N // block), block = min(GATE_BLOCK, N), without a column mask, so N must be a multiple of that block (1536 / 2560 /
+# 3584 would leave their last N % 1024 columns unwritten). Other N fall back to the previous forward (``rows_fusable``).
+SUPPORTED_N = (512, 1024, 2048, 3072, 4096)
+assert all(n % 512 == 0 and n <= 4096 and n % min(GATE_BLOCK, n) == 0 for n in SUPPORTED_N)
+
+_welford_step = nmg._welford_step
+_welford_combine = nmg._welford_combine
+_split4 = nmg._split4
+
+
+class Config:
+ fanout_linear = False # q/k/v/mlp_in projections through dit_fanout_linear (beta=1 dX accumulation in backward)
+ last_layer_rows = False # final layer's LayerNorm + adaLN modulation through the fused row kernel (PolicyConfig.dit_last_layer_rows)
+ pe_cache = False # position tables cached across steps and pre-cast once (PolicyConfig.dit_pe_cache)
+ out_stage = False # attn_out + mlp_out + add + gate as one custom op, SAC-saveable (dit_out_stage; PolicyConfig.dit_out_stage)
+ """Tunables (set before the first call)."""
+ chunk_tokens = 64 # T: max tokens per backward chunk / program (LN backward); swept 8..128 at L=309376
+ gate_chunk_tokens = 64 # T for the gate backward
+ ln_bwd_stages = 3 # tl.range(num_stages) of the token loop in the LN backward (1 = plain loop); 3 best with keep_xg
+ gate_bwd_stages = 4 # idem for the gate backward
+ cache_a = True # keep bf16(1 + scale_row) in registers for the whole chunk (else re-read from L2)
+ keep_xg = True # keep the bf16 x/g tiles of pass 1 in registers for pass 2 (else re-load, L1/L2 hits)
+ bf16_row_copies = True # fp32 rows: make bf16 copies once per call (the kernels then load bf16 rows)
+ round_bf16 = True # per-token modulation gradients rounded to bf16 before the fp32 sum (= current path)
+ reduce_block = 1024
+ fuse_output_add = False # gate over (o1 + o2) in one kernel (dit_norm_mod_gate.Config.fuse_output_add)
+
+
+# ============================================================================================== plan / tables
+_plan_cache: dict[tuple, "RowPlan"] = {}
+_PLAN_CACHE_LIMIT = 64
+
+
+class RowPlan:
+ """Token -> modulation-row mapping of one packed sequence plus the chunk tables of the backward kernels.
+
+ ``counts[r]`` is the number of consecutive tokens that use row ``r`` (rows in token order, like
+ ``dit_time_embed_dedup``'s run counts). ``idx`` is the int32 per-token row index; chunks are runs of at most
+ ``T`` tokens inside one row, in token order, so the chunks of row ``r`` are ``[row_chunk_ptr[r],
+ row_chunk_ptr[r+1])``. Rows with zero tokens get no chunk (their gradient is zero).
+ """
+
+ def __init__(self, counts: Sequence[int], device: torch.device, T: int, gate_T: int):
+ self.counts = tuple(int(c) for c in counts)
+ if any(c < 0 for c in self.counts):
+ raise ValueError(f"negative run length in {self.counts}")
+ self.R = len(self.counts)
+ self.L = sum(self.counts)
+ self.device = torch.device(device)
+ self.T = int(T)
+ self.gate_T = int(gate_T)
+ rows = torch.repeat_interleave(torch.arange(self.R, dtype=torch.int32), torch.as_tensor(self.counts, dtype=torch.int64))
+ self.idx = rows.to(self.device)
+ self.device = self.idx.device # normalized (with index): compared against x.device in rows_fusable
+ self.tables = {}
+ for t in {self.T, self.gate_T}:
+ self.tables[t] = self._build_tables(t)
+
+ def _build_tables(self, T: int):
+ starts, lens, rws, ptr = [], [], [], [0]
+ pos = 0
+ for r, c in enumerate(self.counts):
+ for s in range(0, c, T):
+ starts.append(pos + s)
+ lens.append(min(T, c - s))
+ rws.append(r)
+ ptr.append(len(starts))
+ pos += c
+ dev = self.device
+ return dict(
+ C=len(starts),
+ start=torch.as_tensor(starts, dtype=torch.int32).to(dev),
+ len=torch.as_tensor(lens, dtype=torch.int32).to(dev),
+ row=torch.as_tensor(rws, dtype=torch.int32).to(dev),
+ ptr=torch.as_tensor(ptr, dtype=torch.int32).to(dev),
+ )
+
+ def table(self, T: int):
+ if T not in self.tables:
+ self.tables[T] = self._build_tables(T)
+ return self.tables[T]
+
+ def __repr__(self) -> str: # pragma: no cover
+ return f"RowPlan(R={self.R}, L={self.L}, T={self.T}, chunks={self.tables[self.T]['C']}, device={self.device})"
+
+
+def row_plan(counts: Sequence[int], device: torch.device | str, T: int | None = None, gate_T: int | None = None) -> RowPlan:
+ """Cached :class:`RowPlan` for ``counts`` on ``device``."""
+ T = Config.chunk_tokens if T is None else int(T)
+ gate_T = Config.gate_chunk_tokens if gate_T is None else int(gate_T)
+ key = (tuple(int(c) for c in counts), str(device), T, gate_T)
+ hit = _plan_cache.get(key)
+ if hit is None:
+ if len(_plan_cache) >= _PLAN_CACHE_LIMIT:
+ _plan_cache.clear()
+ hit = _plan_cache[key] = RowPlan(counts, torch.device(device), T, gate_T)
+ return hit
+
+
+class ModRows(NamedTuple):
+ """Modulation as rows: ``shift``/``scale``/``gate`` are ``[R, N]`` (fp32 or bf16; any row pitch, unit column
+ stride), ``plan`` maps tokens to rows. Replaces the ``(shift, scale, gate)`` per-token tuple a block receives."""
+ shift: Tensor
+ scale: Tensor
+ gate: Tensor
+ plan: RowPlan
+
+ def expand(self, out_dtype: torch.dtype = torch.bfloat16, out_shape=None) -> tuple[Tensor, Tensor, Tensor]:
+ """Per-token tensors (differentiable, ``dit_time_embed_dedup.ExpandRows``) for the eager fallback."""
+ from flux_action.models.dit_time_embed_dedup import expand_rows
+ shape = (1, self.plan.L, self.shift.shape[-1]) if out_shape is None else out_shape
+ return tuple(expand_rows(r, self.plan.counts, out_dtype, shape) for r in (self.shift, self.scale, self.gate))
+
+
+def _row_pitch(rows: Tensor, N: int) -> int:
+ if rows.dim() != 2 or rows.shape[1] != N or rows.stride(1) != 1 or rows.stride(0) < N:
+ raise ValueError(f"rows must be [R, {N}] with unit column stride, got shape {tuple(rows.shape)} strides {rows.stride()}")
+ return rows.stride(0)
+
+
+# ============================================================================================== forward kernels
+@triton.jit
+def _ln_mod_rows_fwd_kernel(x_ptr, shift_ptr, scale_ptr, idx_ptr, y_ptr, mean_ptr, rstd_ptr, M, sh_pitch, sc_pitch,
+ eps, n_float, N: tl.constexpr, ROWS_FP32: tl.constexpr):
+ """combined = bf16(bf16(bf16(1 + scale[idx]) * bf16(LN(x))) + shift[idx]); one token per 128-thread program.
+ Identical arithmetic to dit_norm_mod_gate._ln_mod_fwd_kernel; only the modulation address differs."""
+ NJ: tl.constexpr = (N // 4) // LANES
+ t = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ cnt = tl.zeros([LANES], tl.float32) + (4 * NJ)
+ row = tl.program_id(0)
+ rv = (tl.zeros([LANES, 4], tl.int32) + row) < M
+ rowc = tl.minimum(row, M - 1)
+ base = row.to(tl.int64) * N
+ mrow = tl.load(idx_ptr + rowc).to(tl.int64)
+ shbase = mrow * sh_pitch
+ scbase = mrow * sc_pitch
+ mean = tl.zeros([LANES], tl.float32)
+ m2 = tl.zeros([LANES], tl.float32)
+ for j in tl.static_range(NJ):
+ coffs = ((t * 4 + j * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ xv = tl.load(x_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ v0, v1, v2, v3 = _split4(xv)
+ mean, m2 = _welford_step(mean, m2, v0, 1.0 / (4 * j + 1))
+ mean, m2 = _welford_step(mean, m2, v1, 1.0 / (4 * j + 2))
+ mean, m2 = _welford_step(mean, m2, v2, 1.0 / (4 * j + 3))
+ mean, m2 = _welford_step(mean, m2, v3, 1.0 / (4 * j + 4))
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _welford_combine)
+ var = libdevice.div_rn(m2_t, n_float)
+ rstd = tl.rsqrt(var + eps)
+ if row < M:
+ tl.store(mean_ptr + row, mean_t)
+ tl.store(rstd_ptr + row, rstd)
+ for j in tl.static_range(NJ):
+ coffs = ((t * 4 + j * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ xv = tl.load(x_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ sc = tl.load(scale_ptr + scbase + coffs, mask=rv, other=0.0)
+ sh = tl.load(shift_ptr + shbase + coffs, mask=rv, other=0.0)
+ if ROWS_FP32:
+ sc = sc.to(tl.bfloat16) # ExpandRows: rows.to(bf16) before the gather
+ sh = sh.to(tl.bfloat16)
+ sc = sc.to(tl.float32)
+ sh = sh.to(tl.float32)
+ ln = (rstd * (xv - mean_t)).to(tl.bfloat16).to(tl.float32) # ATen: Y = rstd * (x - mean) -> bf16
+ a = (sc + 1.0).to(tl.bfloat16).to(tl.float32) # bf16(1 + scale)
+ b = (a * ln).to(tl.bfloat16).to(tl.float32) # bf16(a * ln)
+ y = (b + sh).to(tl.bfloat16) # bf16(b + shift)
+ tl.store(y_ptr + base + coffs, y, mask=rv)
+
+
+@triton.jit
+def _gate_res_rows_fwd_kernel(x_ptr, gate_ptr, idx_ptr, o1_ptr, o2_ptr, y_ptr, g_pitch, N: tl.constexpr,
+ BLOCK: tl.constexpr, TWO: tl.constexpr, ROWS_FP32: tl.constexpr):
+ """y = bf16(x + bf16(gate[idx] * o)) with o = o1 or bf16(o1 + o2); grid (tokens, N // BLOCK)."""
+ row = tl.program_id(0).to(tl.int64)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ xo = row * N + col
+ mrow = tl.load(idx_ptr + row).to(tl.int64)
+ gv = tl.load(gate_ptr + mrow * g_pitch + col)
+ if ROWS_FP32:
+ gv = gv.to(tl.bfloat16)
+ gv = gv.to(tl.float32)
+ xv = tl.load(x_ptr + xo).to(tl.float32)
+ ov = tl.load(o1_ptr + xo).to(tl.float32)
+ if TWO:
+ ov = (ov + tl.load(o2_ptr + xo).to(tl.float32)).to(tl.bfloat16).to(tl.float32)
+ tv = (gv * ov).to(tl.bfloat16).to(tl.float32)
+ tl.store(y_ptr + xo, (xv + tv).to(tl.bfloat16))
+
+
+# ============================================================================================== backward kernels
+@triton.jit
+def _ln_a_load(scale_ptr, scbase, coffs, ROWS_FP32: tl.constexpr):
+ sc = tl.load(scale_ptr + scbase + coffs)
+ if ROWS_FP32:
+ sc = sc.to(tl.bfloat16)
+ return (sc.to(tl.float32) + 1.0).to(tl.bfloat16).to(tl.float32) # a = bf16(1 + scale)
+
+
+@triton.jit
+def _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, coffs, a, mean, rstd, s1, s2, acc_sh, acc_sc,
+ P1: tl.constexpr, ROUND_BF16: tl.constexpr, HAS_RES: tl.constexpr):
+ """One 512-column slice of one token: modulation-gradient accumulation + ATen's stats (sequential k order).
+ Loads x, g and the residual gradient (all bf16) up front so the loop pipeliner prefetches every HBM read of
+ the next token; returns the raw tiles for pass 2."""
+ xr = tl.load(x_ptr + base + coffs)
+ gr = tl.load(g_ptr + base + coffs)
+ if HAS_RES:
+ rr = tl.load(gres_ptr + base + coffs)
+ else:
+ rr = gr
+ xv = xr.to(tl.float32)
+ gv = gr.to(tl.float32)
+ ln = (rstd * (xv - mean)).to(tl.bfloat16).to(tl.float32)
+ dsc = gv * ln
+ if ROUND_BF16:
+ dsc = dsc.to(tl.bfloat16).to(tl.float32) # eager: d_scale = bf16(g * ln) per token
+ acc_sh = acc_sh + gv
+ acc_sc = acc_sc + dsc
+ dy = (gv * a).to(tl.bfloat16).to(tl.float32) # eager materializes d_ln in bf16
+ d0, d1, d2, d3 = _split4(dy)
+ x0, x1, x2, x3 = _split4(xv)
+ s1 = s1 + d0
+ s1 = s1 + d1
+ s1 = s1 + d2
+ s1 = s1 + d3
+ if P1 == 0:
+ s2 = libdevice.fma(d0 * (x0 - mean), rstd, s2)
+ s2 = libdevice.fma(d1 * (x1 - mean), rstd, s2)
+ s2 = libdevice.fma(d2 * (x2 - mean), rstd, s2)
+ s2 = libdevice.fma(d3 * (x3 - mean), rstd, s2)
+ else:
+ s2 = s2 + (d0 * (x0 - mean)) * rstd
+ s2 = s2 + (d1 * (x1 - mean)) * rstd
+ s2 = s2 + (d2 * (x2 - mean)) * rstd
+ s2 = s2 + (d3 * (x3 - mean)) * rstd
+ return s1, s2, acc_sh, acc_sc, xr, gr, rr
+
+
+@triton.jit
+def _ln_bwd_pass2(x_ptr, g_ptr, xr, gr, rr, dx_ptr, base, coffs, a, mean, rstd, S1, S2, term1, n_float,
+ P2: tl.constexpr, HAS_RES: tl.constexpr, KEEP: tl.constexpr):
+ """dx for one 512-column slice (ATen layer_norm_grad_input_kernel_vectorized formula) + residual gradient.
+ KEEP: reuse the bf16 tiles of pass 1 (registers); else re-load x and g (L1/L2 hits)."""
+ if KEEP:
+ xv = xr.to(tl.float32)
+ gv = gr.to(tl.float32)
+ else:
+ xv = tl.load(x_ptr + base + coffs).to(tl.float32)
+ gv = tl.load(g_ptr + base + coffs).to(tl.float32)
+ dy = (gv * a).to(tl.bfloat16).to(tl.float32)
+ u = (xv - mean) * rstd
+ if P2 == 0:
+ f = libdevice.fma(-u, S2, n_float * dy)
+ elif P2 == 1:
+ f = n_float * dy - u * S2
+ else:
+ f = libdevice.fma(n_float, dy, -(u * S2))
+ f = f - S1
+ f = f * term1
+ dxb = f.to(tl.bfloat16)
+ if HAS_RES:
+ dxb = (dxb.to(tl.float32) + rr.to(tl.float32)).to(tl.bfloat16) # autograd: bf16(dx_ln + G)
+ tl.store(dx_ptr + base + coffs, dxb)
+
+
+@triton.jit
+def _ln_mod_rows_bwd_kernel(g_ptr, x_ptr, scale_ptr, mean_ptr, rstd_ptr, gres_ptr, dx_ptr,
+ cstart_ptr, clen_ptr, crow_ptr, part_ptr, C, sc_pitch, n_float,
+ N: tl.constexpr, HAS_RES: tl.constexpr, ROWS_FP32: tl.constexpr, ROUND_BF16: tl.constexpr,
+ P1: tl.constexpr, P2: tl.constexpr, CACHE_A: tl.constexpr, STAGES: tl.constexpr,
+ KEEP: tl.constexpr):
+ """One program per chunk (<= T consecutive tokens of one modulation row): dx per token (bit-exact with
+ dit_norm_mod_gate._ln_mod_bwd_kernel), fp32 partial sums of d_shift (= g) and d_scale (= bf16(g * ln)) over
+ the chunk's tokens -> part[0, c, :], part[1, c, :]. Explicit accumulators for up to 8 slices of 512 columns."""
+ NJ: tl.constexpr = (N // 4) // LANES
+ tl.static_assert(NJ <= 8, "N must be <= 4096")
+ t = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ c = tl.program_id(0)
+ start = tl.load(cstart_ptr + c)
+ length = tl.load(clen_ptr + c)
+ mrow = tl.load(crow_ptr + c).to(tl.int64)
+ scbase = mrow * sc_pitch
+ co0 = ((t * 4 + 0 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co1 = ((t * 4 + 1 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co2 = ((t * 4 + 2 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co3 = ((t * 4 + 3 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co4 = ((t * 4 + 4 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co5 = ((t * 4 + 5 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co6 = ((t * 4 + 6 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ co7 = ((t * 4 + 7 * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ z = tl.zeros([LANES, 4], tl.float32)
+ sh0 = z; sh1 = z; sh2 = z; sh3 = z; sh4 = z; sh5 = z; sh6 = z; sh7 = z
+ sc0 = z; sc1 = z; sc2 = z; sc3 = z; sc4 = z; sc5 = z; sc6 = z; sc7 = z
+ if CACHE_A:
+ a0 = _ln_a_load(scale_ptr, scbase, co0, ROWS_FP32)
+ if NJ > 1:
+ a1 = _ln_a_load(scale_ptr, scbase, co1, ROWS_FP32)
+ if NJ > 2:
+ a2 = _ln_a_load(scale_ptr, scbase, co2, ROWS_FP32)
+ if NJ > 3:
+ a3 = _ln_a_load(scale_ptr, scbase, co3, ROWS_FP32)
+ if NJ > 4:
+ a4 = _ln_a_load(scale_ptr, scbase, co4, ROWS_FP32)
+ if NJ > 5:
+ a5 = _ln_a_load(scale_ptr, scbase, co5, ROWS_FP32)
+ if NJ > 6:
+ a6 = _ln_a_load(scale_ptr, scbase, co6, ROWS_FP32)
+ if NJ > 7:
+ a7 = _ln_a_load(scale_ptr, scbase, co7, ROWS_FP32)
+ for i in tl.range(0, length, num_stages=STAGES):
+ tok = (start + i).to(tl.int64)
+ base = tok * N
+ mean = tl.load(mean_ptr + tok)
+ rstd = tl.load(rstd_ptr + tok)
+ s1 = tl.zeros([LANES], tl.float32)
+ s2 = tl.zeros([LANES], tl.float32)
+ if not CACHE_A:
+ a0 = _ln_a_load(scale_ptr, scbase, co0, ROWS_FP32)
+ s1, s2, sh0, sc0, x0, g0, r0 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co0, a0, mean, rstd, s1, s2, sh0, sc0, P1, ROUND_BF16, HAS_RES)
+ if NJ > 1:
+ if not CACHE_A:
+ a1 = _ln_a_load(scale_ptr, scbase, co1, ROWS_FP32)
+ s1, s2, sh1, sc1, x1, g1, r1 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co1, a1, mean, rstd, s1, s2, sh1, sc1, P1, ROUND_BF16, HAS_RES)
+ if NJ > 2:
+ if not CACHE_A:
+ a2 = _ln_a_load(scale_ptr, scbase, co2, ROWS_FP32)
+ s1, s2, sh2, sc2, x2, g2, r2 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co2, a2, mean, rstd, s1, s2, sh2, sc2, P1, ROUND_BF16, HAS_RES)
+ if NJ > 3:
+ if not CACHE_A:
+ a3 = _ln_a_load(scale_ptr, scbase, co3, ROWS_FP32)
+ s1, s2, sh3, sc3, x3, g3, r3 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co3, a3, mean, rstd, s1, s2, sh3, sc3, P1, ROUND_BF16, HAS_RES)
+ if NJ > 4:
+ if not CACHE_A:
+ a4 = _ln_a_load(scale_ptr, scbase, co4, ROWS_FP32)
+ s1, s2, sh4, sc4, x4, g4, r4 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co4, a4, mean, rstd, s1, s2, sh4, sc4, P1, ROUND_BF16, HAS_RES)
+ if NJ > 5:
+ if not CACHE_A:
+ a5 = _ln_a_load(scale_ptr, scbase, co5, ROWS_FP32)
+ s1, s2, sh5, sc5, x5, g5, r5 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co5, a5, mean, rstd, s1, s2, sh5, sc5, P1, ROUND_BF16, HAS_RES)
+ if NJ > 6:
+ if not CACHE_A:
+ a6 = _ln_a_load(scale_ptr, scbase, co6, ROWS_FP32)
+ s1, s2, sh6, sc6, x6, g6, r6 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co6, a6, mean, rstd, s1, s2, sh6, sc6, P1, ROUND_BF16, HAS_RES)
+ if NJ > 7:
+ if not CACHE_A:
+ a7 = _ln_a_load(scale_ptr, scbase, co7, ROWS_FP32)
+ s1, s2, sh7, sc7, x7, g7, r7 = _ln_bwd_pass1(x_ptr, g_ptr, gres_ptr, base, co7, a7, mean, rstd, s1, s2, sh7, sc7, P1, ROUND_BF16, HAS_RES)
+ S1 = tl.sum(s1, 0)
+ S2 = tl.sum(s2, 0)
+ one = tl.zeros_like(S1) + 1.0
+ term1 = libdevice.div_rn(one, n_float) * rstd # ATen: term1 = (1/N) * rstd (scalar)
+ _ln_bwd_pass2(x_ptr, g_ptr, x0, g0, r0, dx_ptr, base, co0, a0, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 1:
+ _ln_bwd_pass2(x_ptr, g_ptr, x1, g1, r1, dx_ptr, base, co1, a1, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 2:
+ _ln_bwd_pass2(x_ptr, g_ptr, x2, g2, r2, dx_ptr, base, co2, a2, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 3:
+ _ln_bwd_pass2(x_ptr, g_ptr, x3, g3, r3, dx_ptr, base, co3, a3, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 4:
+ _ln_bwd_pass2(x_ptr, g_ptr, x4, g4, r4, dx_ptr, base, co4, a4, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 5:
+ _ln_bwd_pass2(x_ptr, g_ptr, x5, g5, r5, dx_ptr, base, co5, a5, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 6:
+ _ln_bwd_pass2(x_ptr, g_ptr, x6, g6, r6, dx_ptr, base, co6, a6, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ if NJ > 7:
+ _ln_bwd_pass2(x_ptr, g_ptr, x7, g7, r7, dx_ptr, base, co7, a7, mean, rstd, S1, S2, term1, n_float, P2, HAS_RES, KEEP)
+ pbase = c.to(tl.int64) * N
+ qbase = (C + c).to(tl.int64) * N
+ tl.store(part_ptr + pbase + co0, sh0)
+ tl.store(part_ptr + qbase + co0, sc0)
+ if NJ > 1:
+ tl.store(part_ptr + pbase + co1, sh1)
+ tl.store(part_ptr + qbase + co1, sc1)
+ if NJ > 2:
+ tl.store(part_ptr + pbase + co2, sh2)
+ tl.store(part_ptr + qbase + co2, sc2)
+ if NJ > 3:
+ tl.store(part_ptr + pbase + co3, sh3)
+ tl.store(part_ptr + qbase + co3, sc3)
+ if NJ > 4:
+ tl.store(part_ptr + pbase + co4, sh4)
+ tl.store(part_ptr + qbase + co4, sc4)
+ if NJ > 5:
+ tl.store(part_ptr + pbase + co5, sh5)
+ tl.store(part_ptr + qbase + co5, sc5)
+ if NJ > 6:
+ tl.store(part_ptr + pbase + co6, sh6)
+ tl.store(part_ptr + qbase + co6, sc6)
+ if NJ > 7:
+ tl.store(part_ptr + pbase + co7, sh7)
+ tl.store(part_ptr + qbase + co7, sc7)
+
+
+@triton.jit
+def _gate_res_rows_bwd_kernel(G_ptr, gate_ptr, o1_ptr, o2_ptr, cstart_ptr, clen_ptr, crow_ptr, dout_ptr, part_ptr,
+ g_pitch, N: tl.constexpr, BLOCK: tl.constexpr, TWO: tl.constexpr, ROWS_FP32: tl.constexpr,
+ ROUND_BF16: tl.constexpr, WRITE_DO: tl.constexpr, STAGES: tl.constexpr):
+ """Per chunk x BLOCK columns: d_out = bf16(G * gate[row]) per token; part[c, cols] = sum_tokens bf16(G * o)."""
+ c = tl.program_id(0)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ start = tl.load(cstart_ptr + c)
+ length = tl.load(clen_ptr + c)
+ mrow = tl.load(crow_ptr + c).to(tl.int64)
+ gv = tl.load(gate_ptr + mrow * g_pitch + col)
+ if ROWS_FP32:
+ gv = gv.to(tl.bfloat16)
+ gv = gv.to(tl.float32)
+ acc = tl.zeros([BLOCK], tl.float32)
+ for i in tl.range(0, length, num_stages=STAGES):
+ off = (start + i).to(tl.int64) * N + col
+ Gv = tl.load(G_ptr + off).to(tl.float32)
+ ov = tl.load(o1_ptr + off).to(tl.float32)
+ if TWO:
+ ov = (ov + tl.load(o2_ptr + off).to(tl.float32)).to(tl.bfloat16).to(tl.float32)
+ dg = Gv * ov
+ if ROUND_BF16:
+ dg = dg.to(tl.bfloat16).to(tl.float32) # eager: d_gate = bf16(G * out) per token
+ acc = acc + dg
+ if WRITE_DO:
+ tl.store(dout_ptr + off, (Gv * gv).to(tl.bfloat16))
+ tl.store(part_ptr + c.to(tl.int64) * N + col, acc)
+
+
+@triton.jit
+def _rows_reduce_kernel(part_ptr, ptr_ptr, out_ptr, C, N: tl.constexpr, BLOCK: tl.constexpr):
+ """out[k, r, cols] = sum over chunks c in [ptr[r], ptr[r+1]) of part[k, c, cols] (sequential, deterministic).
+ grid (R, N // BLOCK, K)."""
+ r = tl.program_id(0)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ k = tl.program_id(2).to(tl.int64)
+ c0 = tl.load(ptr_ptr + r)
+ c1 = tl.load(ptr_ptr + r + 1)
+ acc = tl.zeros([BLOCK], tl.float32)
+ for c in range(c0, c1):
+ acc += tl.load(part_ptr + (k * C + c).to(tl.int64) * N + col)
+ nrows = tl.num_programs(0)
+ tl.store(out_ptr + (k * nrows + r).to(tl.int64) * N + col, acc)
+
+
+# ============================================================================================== host wrappers
+def _check_x(x: Tensor) -> tuple[Tensor, int, int]:
+ N = x.shape[-1]
+ if N not in SUPPORTED_N:
+ raise ValueError(f"unsupported hidden size {N}")
+ x2 = x.reshape(-1, N)
+ if not x2.is_contiguous():
+ raise ValueError("x must be contiguous")
+ return x2, x2.shape[0], N
+
+
+def ln_mod_rows_forward(x: Tensor, shift: Tensor, scale: Tensor, plan: RowPlan, eps: float):
+ """x [..., N] bf16 contiguous with plan.L tokens; shift/scale rows [R, N]. Returns (combined, mean, rstd)."""
+ x2, M, N = _check_x(x)
+ if M != plan.L or plan.R != shift.shape[0] or plan.R != scale.shape[0]:
+ raise ValueError(f"plan (L={plan.L}, R={plan.R}) does not match x ({M} tokens) / rows {tuple(shift.shape)}")
+ fp32 = shift.dtype == torch.float32
+ if scale.dtype != shift.dtype or shift.dtype not in (torch.float32, torch.bfloat16):
+ raise ValueError("shift/scale rows must both be fp32 or both bf16")
+ y = torch.empty_like(x)
+ mean = torch.empty(M, dtype=torch.float32, device=x.device)
+ rstd = torch.empty(M, dtype=torch.float32, device=x.device)
+ _ln_mod_rows_fwd_kernel[(M,)](x2, shift, scale, plan.idx, y, mean, rstd, M, _row_pitch(shift, N), _row_pitch(scale, N),
+ float(eps), float(N), N=N, ROWS_FP32=fp32, num_warps=NUM_WARPS, enable_fp_fusion=False)
+ return y, mean, rstd
+
+
+def rows_reduce(part: Tensor, ptr: Tensor, R: int) -> Tensor:
+ """part [K, C, N] fp32 chunk partials -> [K, R, N] fp32 per-row sums (chunk order, deterministic)."""
+ K, C, N = part.shape
+ out = torch.empty(K, R, N, dtype=torch.float32, device=part.device)
+ if R > 0:
+ block = min(Config.reduce_block, N)
+ if N % block:
+ raise ValueError(f"hidden size {N} is not a multiple of the reduce block {block}; supported: {SUPPORTED_N}")
+ _rows_reduce_kernel[(R, N // block, K)](part, ptr, out, C, N=N, BLOCK=block, num_warps=NUM_WARPS)
+ return out
+
+
+def ln_mod_rows_backward(g: Tensor, x: Tensor, scale: Tensor, plan: RowPlan, mean: Tensor, rstd: Tensor,
+ gres: Tensor | None, T: int | None = None):
+ """Returns (dx bf16 [like x], d_shift [R, N] fp32, d_scale [R, N] fp32). ``gres`` (same layout as x) is folded
+ into dx. Chunked programs + deterministic two-stage row reduction, no per-token gradient tensors."""
+ x2, M, N = _check_x(x)
+ g2 = g.reshape(-1, N)
+ assert g2.is_contiguous() and M == plan.L
+ if gres is not None:
+ gres = gres.reshape(-1, N)
+ assert gres.is_contiguous()
+ tab = plan.table(plan.T if T is None else T)
+ C = tab["C"]
+ dx = torch.empty_like(x)
+ part = torch.empty(2, max(C, 1), N, dtype=torch.float32, device=x.device)
+ if C > 0:
+ _ln_mod_rows_bwd_kernel[(C,)](g2, x2, scale, mean, rstd, gres if gres is not None else g2, dx, tab["start"], tab["len"],
+ tab["row"], part, C, _row_pitch(scale, N), float(N), N=N, HAS_RES=gres is not None,
+ ROWS_FP32=scale.dtype == torch.float32, ROUND_BF16=Config.round_bf16,
+ P1=nmg.Config.bwd_p1, P2=nmg.Config.bwd_p2, CACHE_A=Config.cache_a,
+ STAGES=Config.ln_bwd_stages, KEEP=Config.keep_xg, num_warps=NUM_WARPS, enable_fp_fusion=False)
+ sums = rows_reduce(part[:, :C] if C > 0 else part[:, :0], tab["ptr"], plan.R)
+ return dx, sums[0], sums[1]
+
+
+def gate_res_rows_forward(x: Tensor, gate: Tensor, plan: RowPlan, o1: Tensor, o2: Tensor | None = None) -> Tensor:
+ x2, M, N = _check_x(x)
+ assert M == plan.L and o1.is_contiguous() and (o2 is None or o2.is_contiguous())
+ y = torch.empty_like(x)
+ grid, block = nmg.gate_grid(M, N) # block = min(1024, N); SUPPORTED_N guarantees N % block == 0
+ _gate_res_rows_fwd_kernel[grid](x2, gate, plan.idx, o1, o1 if o2 is None else o2, y, _row_pitch(gate, N),
+ N=N, BLOCK=block, TWO=o2 is not None,
+ ROWS_FP32=gate.dtype == torch.float32, num_warps=NUM_WARPS,
+ enable_fp_fusion=False)
+ return y
+
+
+def gate_res_rows_backward(G: Tensor, gate: Tensor, plan: RowPlan, o1: Tensor, o2: Tensor | None = None,
+ need_dout: bool = True, T: int | None = None):
+ """Returns (d_out bf16 per token or None, d_gate [R, N] fp32)."""
+ G2, M, N = _check_x(G)
+ assert M == plan.L
+ tab = plan.table(plan.gate_T if T is None else T)
+ C = tab["C"]
+ dout = torch.empty_like(G) if need_dout else None
+ part = torch.empty(1, max(C, 1), N, dtype=torch.float32, device=G.device)
+ grid, block = nmg.gate_grid(C, N)
+ if C > 0:
+ _gate_res_rows_bwd_kernel[grid](G2, gate, o1, o1 if o2 is None else o2, tab["start"], tab["len"], tab["row"],
+ dout if dout is not None else G2, part, _row_pitch(gate, N), N=N,
+ BLOCK=block, TWO=o2 is not None, ROWS_FP32=gate.dtype == torch.float32,
+ ROUND_BF16=Config.round_bf16, WRITE_DO=need_dout,
+ STAGES=Config.gate_bwd_stages, num_warps=NUM_WARPS, enable_fp_fusion=False)
+ sums = rows_reduce(part[:, :C] if C > 0 else part[:, :0], tab["ptr"], plan.R)
+ return dout, sums[0]
+
+
+# ============================================================================================== autograd
+class _LNModulateRows(torch.autograd.Function):
+ """(combined, x_alias) = f(x, shift_rows, scale_rows); the residual gradient arriving through ``x_alias`` is
+ folded into dx inside the backward kernel (as in dit_norm_mod_gate._LNModulate)."""
+
+ @staticmethod
+ def forward(ctx, x, shift, scale, plan, eps):
+ ctx.set_materialize_grads(False) # an unused x_alias (last layer) arrives as None instead of a zero tensor
+ if Config.bf16_row_copies and shift.dtype == torch.float32:
+ shift, scale = shift.to(torch.bfloat16), scale.to(torch.bfloat16) # == ExpandRows' rows.to(bf16); tiny
+ combined, mean, rstd = ln_mod_rows_forward(x, shift, scale, plan, eps)
+ ctx.save_for_backward(x, scale, mean, rstd)
+ ctx.plan = plan
+ return combined, x
+
+ @staticmethod
+ def backward(ctx, g, gres):
+ x, scale, mean, rstd = ctx.saved_tensors
+ need_x, need_shift, need_scale = ctx.needs_input_grad[:3]
+ if g is None:
+ return (gres if need_x else None), None, None, None, None
+ if not g.is_contiguous():
+ g = g.contiguous()
+ if gres is not None and not gres.is_contiguous():
+ gres = gres.contiguous()
+ dx, dshift, dscale = ln_mod_rows_backward(g, x, scale, ctx.plan, mean, rstd, gres if need_x else None)
+ # fp32 row sums; autograd casts them to the rows' dtype (fp32 rows in the dedup path keep full precision)
+ return (dx if need_x else None), (dshift if need_shift else None), (dscale if need_scale else None), None, None
+
+
+class _GateResidualRows(torch.autograd.Function):
+ """x + gate[idx] * (o1 [+ o2]) with eager's bf16 roundings; d_gate as fp32 row sums."""
+
+ @staticmethod
+ def forward(ctx, x, gate, plan, o1, o2):
+ if Config.bf16_row_copies and gate.dtype == torch.float32:
+ gate = gate.to(torch.bfloat16)
+ ctx.save_for_backward(gate, o1) if o2 is None else ctx.save_for_backward(gate, o1, o2)
+ ctx.plan = plan
+ ctx.two = o2 is not None
+ return gate_res_rows_forward(x, gate, plan, o1, o2)
+
+ @staticmethod
+ def backward(ctx, G):
+ saved = ctx.saved_tensors
+ gate, o1 = saved[0], saved[1]
+ o2 = saved[2] if ctx.two else None
+ need_x, need_gate, need_o1, need_o2 = ctx.needs_input_grad[0], ctx.needs_input_grad[1], ctx.needs_input_grad[3], ctx.needs_input_grad[4]
+ if not G.is_contiguous():
+ G = G.contiguous()
+ dout, dgate = gate_res_rows_backward(G, gate, ctx.plan, o1, o2, need_dout=need_o1 or need_o2)
+ return (G if need_x else None), (dgate if need_gate else None), None, (dout if need_o1 else None), (dout if need_o2 else None)
+
+
+def ln_modulate_rows(x: Tensor, mod: ModRows, eps: float = 1e-6) -> tuple[Tensor, Tensor]:
+ """Fused ``bf16((1 + scale[idx]) * LayerNorm(x)) + shift[idx]``; returns (combined, x_alias)."""
+ return _LNModulateRows.apply(x, mod.shift, mod.scale, mod.plan, eps)
+
+
+def gate_residual_rows(x_alias: Tensor, mod: ModRows, o1: Tensor, o2: Tensor | None = None) -> Tensor:
+ """Fused ``x + gate[idx] * o1`` or ``x + gate[idx] * bf16(o1 + o2)``; feed the ``x_alias`` of
+ :func:`ln_modulate_rows` so the residual gradient is fused into the LN backward."""
+ return _GateResidualRows.apply(x_alias, mod.gate, mod.plan, o1, o2)
+
+
+# ============================================================================================== dispatch
+def rows_fusable(pre_norm: nn.Module, x: Tensor, mod: ModRows) -> bool:
+ if torch.compiler.is_compiling() or nmg._forward_ad_active():
+ return False
+ if type(pre_norm) is not nn.LayerNorm or pre_norm.elementwise_affine or pre_norm.weight is not None:
+ return False
+ if not (x.is_cuda and x.dtype == torch.bfloat16 and x.dim() >= 2 and x.is_contiguous()):
+ return False
+ n = x.shape[-1]
+ if n not in SUPPORTED_N or pre_norm.normalized_shape != (n,):
+ return False
+ if torch._C._functorch.is_functorch_wrapped_tensor(x):
+ return False
+ if x.numel() // n != mod.plan.L or mod.plan.device != x.device:
+ return False
+ for r in (mod.shift, mod.scale, mod.gate):
+ if r.dim() != 2 or r.shape != (mod.plan.R, n) or r.stride(1) != 1 or r.dtype not in (torch.float32, torch.bfloat16):
+ return False
+ return mod.shift.dtype == mod.scale.dtype
+
+
+class RowsState:
+ def __init__(self):
+ self.enabled = True
+ self.patched: list[tuple[nn.Module, object]] = []
+ self.calls_rows = 0
+ self.calls_other = 0
+
+
+def _projections(self, xin):
+ """q/k/v/mlp_in of the block on the (bf16) modulated input; same kernels either way, the fan-out Function only
+ changes how the backward accumulates the shared input gradient (bit-identical, see dit_fanout_linear)."""
+ if Config.fanout_linear and self.training:
+ from flux_action.models.dit_fanout_linear import fanout_linear
+
+ return fanout_linear(xin, self.q_proj, self.k_proj, self.v_proj, self.mlp_in,
+ gated=getattr(self, "gate_type", None) is not None)
+ return self.q_proj(xin), self.k_proj(xin), self.v_proj(xin), self.mlp_in(xin)
+
+
+def fused_single_forward_rows(self, x, ctx, pe, mod_x, mod_ctx, pag_strength=0.0, seqlens=None, *, _state, _prev):
+ """SingleStreamBlock.forward with ``mod_x`` given as :class:`ModRows` (packed joint sequence, ``ctx is None``)."""
+ import flux_action.models.transformer as T
+ from einops import rearrange
+
+ if not (isinstance(mod_x, ModRows) and _state.enabled and ctx is None and rows_fusable(self.pre_norm, x, mod_x)):
+ _state.calls_other += 1
+ if isinstance(mod_x, ModRows):
+ mod_x = mod_x.expand(x.dtype, (1, mod_x.plan.L, x.shape[-1]))
+ return _prev(x, ctx, pe, mod_x, mod_ctx, pag_strength=pag_strength, seqlens=seqlens)
+ _state.calls_rows += 1
+ combined, x_alias = ln_modulate_rows(x, mod_x, self.pre_norm.eps)
+ q, k, v, mlp = _projections(self, T._bf16_if_required(self.q_proj, combined))
+ q, k, v = (rearrange(t, "B L (H D) -> B H L D", H=self.num_heads) for t in (q, k, v))
+ q, k = T.qk_norm_rope(self.norm, q, k, v, pe)
+ attn = self.attention(q, k, v, self.attn_mode, seqlens)
+ attn = T.apply_pag(attn, v, pag_strength)
+ if Config.out_stage and self.gate_type is None:
+ from flux_action.models.dit_out_stage import output_stage
+
+ return None, output_stage(self, attn, mlp, x_alias, mod_x)
+ o1 = self.attn_out(T._bf16_if_required(self.attn_out, attn))
+ o2 = self.mlp_out(T._bf16_if_required(self.mlp_out, self.mlp_act(mlp)))
+ if self.gate_type is None:
+ if Config.fuse_output_add and o1.is_contiguous() and o2.is_contiguous():
+ return None, gate_residual_rows(x_alias, mod_x, o1, o2)
+ return None, gate_residual_rows(x_alias, mod_x, (o1 + o2).contiguous())
+ output = (o1 + o2) * F.silu(self.gate_proj(combined))
+ return None, gate_residual_rows(x_alias, mod_x, output.contiguous())
+
+
+def fused_mode_forward_rows(self, x, pe, mod, seqlens=None, *, _state, _prev):
+ """ModeBlock.forward with ``mod`` given as :class:`ModRows`."""
+ import flux_action.models.transformer as T
+ from einops import rearrange
+
+ if not (isinstance(mod, ModRows) and _state.enabled and rows_fusable(self.pre_norm, x, mod)):
+ _state.calls_other += 1
+ if isinstance(mod, ModRows):
+ mod = mod.expand(x.dtype, (1, mod.plan.L, x.shape[-1]))
+ return _prev(x, pe, mod, seqlens=seqlens)
+ _state.calls_rows += 1
+ x_mod, x_alias = ln_modulate_rows(x, mod, self.pre_norm.eps)
+ q, k, v, mlp = _projections(self, T._bf16_if_required(self.q_proj, x_mod))
+ q, k, v = (rearrange(t, "B L (H D) -> B H L D", H=self.num_heads) for t in (q, k, v))
+ q, k = T.qk_norm_rope(self.norm, q, k, v, pe)
+ attn = self.attention(q, k, v, self.attn_mode, seqlens)
+ if Config.out_stage and self.gate_type is None:
+ from flux_action.models.dit_out_stage import output_stage
+
+ return output_stage(self, attn, mlp, x_alias, mod)
+ o1 = self.attn_out(T._bf16_if_required(self.attn_out, attn))
+ o2 = self.mlp_out(T._bf16_if_required(self.mlp_out, self.mlp_act(mlp)))
+ if self.gate_type is None:
+ if Config.fuse_output_add and o1.is_contiguous() and o2.is_contiguous():
+ return gate_residual_rows(x_alias, mod, o1, o2)
+ return gate_residual_rows(x_alias, mod, (o1 + o2).contiguous())
+ output = (o1 + o2) * F.silu(self.gate_proj(x_mod))
+ return gate_residual_rows(x_alias, mod, output.contiguous())
+
+
+def install(module: nn.Module) -> RowsState:
+ """Patch ``forward`` on every SingleStreamBlock / ModeBlock instance under ``module``: :class:`ModRows`
+ modulations take the row kernels, anything else runs the forward that was bound before (production
+ ``dit_norm_mod_gate`` mirror or eager). No CUDA work at install time."""
+ from flux_action.models.transformer import ModeBlock, SingleStreamBlock
+
+ state = RowsState()
+ seen = set()
+ for m in [module, *module.modules()]:
+ if id(m) in seen:
+ continue
+ seen.add(id(m))
+ if type(m) is SingleStreamBlock:
+ fn = fused_single_forward_rows
+ elif type(m) is ModeBlock:
+ fn = fused_mode_forward_rows
+ else:
+ continue
+ prev_bound = m.__dict__.get("forward")
+ prev = prev_bound if prev_bound is not None else types.MethodType(type(m).forward, m)
+ state.patched.append((m, prev_bound))
+
+ def bound(self, *args, _fn=fn, _state=state, _prev=prev, **kwargs):
+ return _fn(self, *args, _state=_state, _prev=_prev, **kwargs)
+
+ m.forward = types.MethodType(bound, m)
+ return state
+
+
+def uninstall(state: RowsState) -> None:
+ for m, prev in reversed(state.patched):
+ if prev is None:
+ m.__dict__.pop("forward", None)
+ else:
+ m.forward = prev
+ state.patched.clear()
+
+
+# ============================================================================================== forward_dedup
+def forward_dedup_rows(self, ctx, ctx_ids, vector, timesteps_ctx, pag_single_layers=None, pag_strength=1.0,
+ seqlens=None, **kwargs):
+ """``dit_time_embed_dedup.forward_dedup`` with the modulation handed to the blocks as :class:`ModRows`.
+
+ Exact diff against ``forward_dedup`` (everything else is identical):
+
+ * mode blocks: ``early_content_mods[key] = tuple(per_token(c, counts) for c in chunks[:3])`` becomes
+ ``ModRows(*chunks[:3], row_plan(counts_by_mod[key], device))`` (same for ``early_txt_mod`` with
+ ``counts_ctx`` and for the late mods);
+ * joint single blocks: ``mod = tuple(per_token(stack(...).reshape(W*S, -1), counts_wm) for i in range(3))``
+ becomes ``ModRows(*(stack(...).reshape(W*S, -1) for i in range(3)), row_plan(counts_wm, device))``.
+
+ The rows stay fp32 ``[R, N]`` views of the ``modulation_rows`` GEMM output (row pitch 3N for the mode blocks,
+ contiguous for the joint rows); the kernels round them to bf16 exactly where ``ExpandRows`` did, and their
+ fp32 row gradients flow into the same fp32 row GEMMs. Blocks must have :func:`install` applied (``ModRows``
+ is otherwise expanded by the dispatcher's fallback).
+ """
+ from collections import defaultdict
+
+ import flux_action.models.dit_time_embed_dedup as D
+ from flux_action.models.transformer import timestep_embedding, window_major_order
+
+ if seqlens is None or not self.training:
+ return D._ORIGINAL_FORWARD(self, ctx, ctx_ids, vector, timesteps_ctx, pag_single_layers, pag_strength, seqlens, **kwargs)
+ settings = getattr(self, D._SETTINGS_ATTR, None) or {"check_constant_runs": "async"}
+ check = settings["check_constant_runs"]
+ assert vector.ndim == 2, "invalid vector shape"
+ batch_size = ctx.shape[0]
+ x_by_mod, ids_by_mod, ts_by_mod, lens_by_mod, names_by_mod = (defaultdict(list) for _ in range(5))
+ for k, v in self.sequence.items():
+ if k not in kwargs:
+ continue
+ assert k + "_ids" in kwargs and k + "_timesteps" in kwargs, "missing stream metadata"
+ x_by_mod[v].append(kwargs[k])
+ ids_by_mod[v].append(kwargs[k + "_ids"])
+ ts_by_mod[v].append(kwargs[k + "_timesteps"])
+ lens_by_mod[v].append(kwargs[k].shape[1])
+ names_by_mod[v].append(k)
+ active = list(x_by_mod.keys())
+ all_mods = sorted(self.in_channels.keys())
+ inactive = [m for m in all_mods if m not in active]
+ dummy_len = 2
+ if batch_size != 1:
+ raise ValueError(f"packed windows form one sequence of batch size 1, got {batch_size}")
+ ctx_lens = [int(n) for n in seqlens["ctx"]]
+ if sum(ctx_lens) != ctx.shape[1]:
+ raise ValueError(f"context token counts {ctx_lens} do not add up to {ctx.shape[1]}")
+ mod_lens: dict[str, list[int]] = {}
+ for m in active:
+ if len(names_by_mod[m]) != 1:
+ raise ValueError(f"packed windows need one stream per modality, {m} has {names_by_mod[m]}")
+ lens = [int(n) for n in seqlens[names_by_mod[m][0]]]
+ if len(lens) != len(ctx_lens) or sum(lens) != lens_by_mod[m][0]:
+ raise ValueError(f"{names_by_mod[m][0]}: window token counts {lens} do not match the stream")
+ mod_lens[m] = lens
+ device = x_by_mod[active[0]][0].device
+ dtype = x_by_mod[active[0]][0].dtype
+ for k in all_mods:
+ if k in active:
+ x_by_mod[k] = torch.cat(x_by_mod[k], 1)
+ ids_by_mod[k] = torch.cat(ids_by_mod[k], 1)
+ ts_by_mod[k] = torch.cat(ts_by_mod[k], 1)
+ else:
+ x_by_mod[k] = torch.zeros(batch_size, dummy_len, self.in_channels[k], device=device, dtype=dtype)
+ ids_by_mod[k] = torch.zeros(batch_size, dummy_len, 4, device=device, dtype=torch.int64)
+ ts_by_mod[k] = torch.zeros(batch_size, dummy_len, device=device, dtype=dtype)
+ counts_by_mod = {k: (mod_lens[k] if k in active else [dummy_len]) for k in all_mods}
+ counts_ctx = ctx_lens
+ verify = check != "off"
+ t_rows_by_mod, oks = {}, []
+ for k in all_mods:
+ t_rows_by_mod[k], ok = D.run_timesteps(ts_by_mod[k].reshape(-1), counts_by_mod[k], verify)
+ if ok is not None:
+ oks.append(ok)
+ t_rows_ctx, ok = D.run_timesteps(timesteps_ctx.reshape(-1), counts_ctx, verify)
+ if ok is not None:
+ oks.append(ok)
+ if oks:
+ all_ok = torch.stack(oks).all()
+ if check == "sync":
+ if not bool(all_ok):
+ return D._ORIGINAL_FORWARD(self, ctx, ctx_ids, vector, timesteps_ctx, pag_single_layers, pag_strength, seqlens, **kwargs)
+ else:
+ torch._assert_async(all_ok)
+ vector_emb = self.vector_in(vector)
+ vector_emb_f = vector_emb.float()
+ weight_dtype = self.time_in.in_layer.weight.dtype
+
+ def vec_rows_of(t_rows: Tensor) -> Tensor:
+ with torch.autocast(device_type=device.type, enabled=False):
+ vec = self.time_in(timestep_embedding(t_rows, 256, out_dtype=weight_dtype)).float()
+ vec = D.round_to(vec, dtype)
+ vec = D.round_to(vec + vector_emb_f, dtype)
+ return vec
+
+ vec_rows_by_mod = {k: vec_rows_of(t_rows_by_mod[k]) for k in all_mods}
+ vec_rows_ctx = vec_rows_of(t_rows_ctx)
+
+ # --- CHANGED: rows + plan instead of per-token expansion -------------------------------------------
+ def as_rows(chunks, counts) -> ModRows:
+ return ModRows(chunks[0], chunks[1], chunks[2], row_plan(counts, device))
+
+ early_content_mods = {}
+ for key in self.early_stream_modulations:
+ if key == "txt":
+ continue
+ chunks = D.modulation_rows(self.early_stream_modulations[key], vec_rows_by_mod[key], dtype)
+ early_content_mods[key] = as_rows(chunks[:3], counts_by_mod[key])
+ early_txt_mod = as_rows(D.modulation_rows(self.early_stream_modulations["txt"], vec_rows_ctx, dtype)[:3], counts_ctx)
+ single_rows = {}
+ for key in self.single_stream_modulations:
+ vec = vec_rows_ctx if key == "txt" else vec_rows_by_mod[key]
+ single_rows[key] = D.modulation_rows(self.single_stream_modulations[key], vec, dtype)[:3]
+ if self.depth_late_blocks > 0:
+ late_content_mods = {}
+ for key in self.late_stream_modulations:
+ if key == "txt":
+ continue
+ chunks = D.modulation_rows(self.late_stream_modulations[key], vec_rows_by_mod[key], dtype)
+ late_content_mods[key] = as_rows(chunks[:3], counts_by_mod[key])
+ late_txt_mod = as_rows(D.modulation_rows(self.late_stream_modulations["txt"], vec_rows_ctx, dtype)[:3], counts_ctx)
+ # --- END CHANGED ---------------------------------------------------------------------------------
+
+ content_by_mod = {k: self.emb_in[k](x_by_mod[k]) for k in all_mods}
+ txt = self.txt_in(ctx)
+ # Position tables: a pure function of the packing layout -> cached on the module keyed by the host-known layout
+ # (per-window token counts, ids shapes; a layout change recomputes, see _position_tables), and cast once to the
+ # blocks' compute dtype: the FSDP mixed-precision policy would otherwise cast the fp32 table to bf16 at every block
+ # entry (53 casts/step, each kept alive for the recompute).
+ if Config.pe_cache:
+ layout = (tuple(counts_ctx), tuple(active), tuple((k, tuple(counts_by_mod[k])) for k in all_mods))
+ pe_by_mod, pe_ctx = _position_tables(self, ids_by_mod, ctx_ids, all_mods, getattr(self, PE_CAST_ATTR, None),
+ layout, check)
+ else:
+ pe_by_mod = {k: self.pe_embedder(ids_by_mod[k]) for k in all_mods}
+ pe_ctx = self.pe_embedder(ctx_ids)
+ for d in range(self.depth):
+ for m in all_mods:
+ content_by_mod[m] = self.content_mode_blocks[m][d](content_by_mod[m], pe_by_mod[m], early_content_mods[m], seqlens=mod_lens.get(m))
+ txt = self.txt_mode_blocks[d](txt, pe_ctx, early_txt_mod, seqlens=ctx_lens)
+ img = torch.cat([content_by_mod[k] for k in active], dim=1)
+ pe_content = torch.cat([pe_by_mod[k] for k in active], dim=2)
+ pe = torch.cat((pe_ctx, pe_content), dim=2)
+ order, inverse, window_lens = window_major_order([ctx_lens, *(mod_lens[k] for k in active)], img.device)
+ n_windows = len(ctx_lens)
+ segments = ["txt", *active]
+ counts_wm = [int(n) for w in range(n_windows) for n in (ctx_lens[w], *(mod_lens[k][w] for k in active))]
+ # --- CHANGED: window-major rows [W * S, N] (fp32, contiguous) + plan --------------------------------
+ mod = ModRows(*(torch.stack([single_rows[s][i] for s in segments], dim=1).reshape(n_windows * len(segments), -1)
+ for i in range(3)), row_plan(counts_wm, device))
+ # --- END CHANGED ---------------------------------------------------------------------------------
+ seq = torch.cat((txt, img), dim=1)[:, order]
+ pe = pe[:, :, order]
+ for i, block in enumerate(self.single_blocks):
+ layer_pag = pag_strength if (pag_single_layers and i in pag_single_layers) else 0.0
+ _, seq = block(seq, None, pe, mod, None, pag_strength=layer_pag, seqlens=window_lens)
+ txt, img = torch.split(seq[:, inverse], [txt.shape[1], img.shape[1]], dim=1)
+ img_by_mod = {}
+ pos = 0
+ for k in active:
+ length = sum(lens_by_mod[k])
+ img_by_mod[k] = img[:, pos: pos + length]
+ pos += length
+ for k in inactive:
+ img_by_mod[k] = content_by_mod[k]
+ if self.depth_late_blocks > 0:
+ for d in range(self.depth_late_blocks):
+ for m in all_mods:
+ img_by_mod[m] = self.late_content_mode_blocks[m][d](img_by_mod[m], pe_by_mod[m], late_content_mods[m], seqlens=mod_lens.get(m))
+ txt = self.late_txt_mode_blocks[d](txt, pe_ctx, late_txt_mod, seqlens=ctx_lens)
+ final = {k: last_layer_forward_rows(self.final_layer[k], img_by_mod[k], vec_rows_by_mod[k], counts_by_mod[k], dtype) for k in all_mods}
+ out = {}
+ for k in active:
+ pos = 0
+ for name, length in zip(names_by_mod[k], lens_by_mod[k], strict=True):
+ out[name] = final[k][:, pos: pos + length]
+ pos += length
+ return out
+
+
+def last_layer_forward_rows(layer, x: Tensor, vec_rows: Tensor, counts, vec_dtype: torch.dtype) -> Tensor:
+ """``dit_time_embed_dedup.last_layer_forward_dedup`` with the LayerNorm + ``(1 + scale) * ln + shift`` done by the
+ fused row kernel: same roundings (fp32 rows -> bf16, ``1 + scale`` in bf16, product and sum each rounded once),
+ no per-token expansion of the two modulation tensors and no three eager passes over ``x``; row gradients are the
+ kernel's fp32 segment sums (the expansion's backward did the same sums in another order)."""
+ import flux_action.models.dit_time_embed_dedup as D
+
+ if not (Config.last_layer_rows and x.is_cuda and x.dtype == torch.bfloat16):
+ return D.last_layer_forward_dedup(layer, x, vec_rows, counts, vec_dtype)
+ lin = layer.adaLN_modulation[1]
+ shift_w, scale_w = lin.weight.chunk(2)
+ with torch.autocast(device_type=x.device.type, enabled=False):
+ s = D.round_to(F.silu(vec_rows), vec_dtype)
+ scale_rows = F.linear(s, D._fp32_weight(scale_w))
+ shift_rows = F.linear(s, D._fp32_weight(shift_w))
+ mod = ModRows(shift_rows, scale_rows, scale_rows, row_plan(counts, x.device))
+ if not rows_fusable(layer.norm_final, x, mod):
+ return D.last_layer_forward_dedup(layer, x, vec_rows, counts, vec_dtype)
+ combined, _ = ln_modulate_rows(x, mod, layer.norm_final.eps)
+ return layer.linear(combined)
+
+
+_PE_CACHE_ATTR = "_flux_pe_cache"
+PE_CAST_ATTR = "_flux_pe_cast_dtype" # set by training.distributed.shard_dit to the blocks' FSDP compute dtype
+
+
+def _position_tables(self, ids_by_mod: dict, ctx_ids: Tensor, all_mods: list, cast_dtype, layout, check: str = "async"):
+ """``pe_embedder`` outputs for every stream and the context, reused across steps while the packing LAYOUT is
+ unchanged. With ``cast_dtype`` set (FSDP training, ``cast_forward_inputs``) the fp32 tables are cast once here
+ instead of at every block entry; the values the blocks see are identical, the per-block cast kernels and their
+ recompute-held copies disappear.
+
+ The cache key is host-known: ``layout`` (the per-window context token counts and the per-modality per-window token
+ counts of this call), the shape / dtype / device of every ids tensor and ``cast_dtype``. The packing builds the ids
+ as a pure function of exactly these quantities plus the fixed training layout (latent grid, position fps, chunk
+ length; see ``processing.packing.PackCache``), so a key hit means identical ids; any layout change (a window
+ whose caption lands in another bucket, another window count, ...) is a key change and recomputes -- no device
+ comparison decides the hit, so a legitimate change can never trip a device-side assert.
+
+ ``check``: ``"sync"`` additionally compares the ids on the host at every hit and recomputes on a mismatch (one
+ device sync per step); ``"async"`` (default) compares on the device and **asserts** (``torch._assert_async``, like
+ the timestep invariant of ``forward_dedup_rows``): a hit whose ids differ from the cached ones -- only possible if
+ the fixed layout parameters of the packing changed under one module instance -- stops the run loudly instead of
+ silently serving stale tables (the flag behind ``pe_cache_verified`` is kept for diagnostics); ``"off"`` skips the
+ comparison."""
+ key_ids = [ids_by_mod[k] for k in all_mods] + [ctx_ids]
+ key = (cast_dtype, tuple(layout), tuple((tuple(t.shape), t.dtype, str(t.device)) for t in key_ids))
+ cache = self.__dict__.get(_PE_CACHE_ATTR)
+ if cache is not None and cache["key"] == key:
+ hit = True
+ if check == "sync":
+ hit = all(torch.equal(a, b) for a, b in zip(cache["ids"], key_ids))
+ elif check != "off":
+ same = torch.stack([(a == b).all() for a, b in zip(cache["ids"], key_ids)]).all()
+ cache["ok"] = cache["ok"] & same # diagnostics (pe_cache_verified)
+ torch._assert_async(same) # stale tables must never be used silently (review, MR !1)
+ if hit:
+ cache["hits"] += 1
+ return dict(cache["pe_by_mod"]), cache["pe_ctx"]
+ cast = (lambda t: t.to(cast_dtype)) if cast_dtype is not None else (lambda t: t)
+ pe_by_mod = {k: cast(self.pe_embedder(ids_by_mod[k])) for k in all_mods}
+ pe_ctx = cast(self.pe_embedder(ctx_ids))
+ self.__dict__[_PE_CACHE_ATTR] = {
+ "key": key, "ids": [t.clone() for t in key_ids], "pe_by_mod": dict(pe_by_mod), "pe_ctx": pe_ctx,
+ "ok": torch.ones((), dtype=torch.bool, device=ctx_ids.device),
+ "hits": cache["hits"] if cache is not None else 0, "builds": (cache["builds"] + 1) if cache is not None else 1,
+ }
+ return pe_by_mod, pe_ctx
+
+
+def pe_cache_stats(dit: nn.Module) -> dict | None:
+ """Cumulative ``{"builds", "hits"}`` of the position-table cache (None before the first cached call)."""
+ cache = dit.__dict__.get(_PE_CACHE_ATTR)
+ return None if cache is None else {"builds": cache["builds"], "hits": cache["hits"]}
+
+
+def pe_cache_verified(dit: nn.Module) -> bool:
+ """True unless an ``"async"``-mode hit ever served tables whose ids differed from the cached ones (host sync)."""
+ cache = dit.__dict__.get(_PE_CACHE_ATTR)
+ return True if cache is None else bool(cache["ok"].item())
+
+
+def install_dedup_rows(dit: nn.Module) -> RowsState:
+ """``install_training_time_embed_dedup`` must already be installed (its checks apply); binds
+ :func:`forward_dedup_rows` as the instance forward and installs the row dispatchers on all blocks."""
+ import flux_action.models.dit_time_embed_dedup as D
+
+ if not D.is_installed(dit):
+ raise RuntimeError("install_training_time_embed_dedup(dit) first")
+ dit.__dict__["forward"] = types.MethodType(forward_dedup_rows, dit)
+ return install(dit)
+
+
+# ============================================================================================== reference / tests
+def make_rows_inputs(counts: Sequence[int], N: int, device, seed: int = 0, x_std: float = 1.0, x_mean: float = 0.0,
+ mod_std: float = 0.5, rows_dtype=torch.float32, pitch: int | None = None):
+ """Random bf16 token tensors and modulation rows (fp32 by default, optionally views with row pitch ``pitch``)."""
+ gen = torch.Generator(device=device).manual_seed(seed)
+ L, R = sum(counts), len(counts)
+
+ def rnd(std, mean=0.0, shape=(L, N)):
+ return (torch.randn(*shape, device=device, generator=gen) * std + mean).to(torch.bfloat16)
+
+ x = rnd(x_std, x_mean)
+ if pitch is None:
+ rows = [(torch.randn(R, N, device=device, generator=gen) * mod_std).to(rows_dtype) for _ in range(3)]
+ else:
+ buf = (torch.randn(R, pitch, device=device, generator=gen) * mod_std).to(rows_dtype)
+ rows = [buf[:, i * N:(i + 1) * N] for i in range(3)]
+ o1, o2, g, G = rnd(1.0), rnd(1.0), rnd(1.0), rnd(1.0)
+ return x, rows[0], rows[1], rows[2], o1, o2, g, G
+
+
+def _compare(a: Tensor, b: Tensor) -> dict:
+ af, bf = a.double(), b.double()
+ diff = (af - bf).abs()
+ if a.dtype == b.dtype:
+ same = a.view(torch.int16) == b.view(torch.int16) if a.dtype == torch.bfloat16 else (a == b)
+ n_same = int(same.sum().item())
+ else:
+ n_same = int((af == bf).sum().item())
+ return {"max_abs": diff.max().item() if a.numel() else 0.0,
+ "rel_l2": (diff.norm() / bf.norm().clamp_min(1e-30)).item() if a.numel() else 0.0,
+ "bitwise_fraction": n_same / max(a.numel(), 1), "n_diff": a.numel() - n_same}
+
+
+def current_path(x, shift, scale, gate, o1, o2, g, G, counts, eps, fuse_add):
+ """The production dedup path: ExpandRows -> dit_norm_mod_gate fused kernels; row gradients via
+ ExpandRows.backward (fp32 segment sums of the per-token bf16 gradients). Also returns the per-token grads."""
+ from flux_action.models.dit_time_embed_dedup import expand_rows
+ N = x.shape[-1]
+ L = sum(counts)
+ xl = x.detach().requires_grad_(True)
+ rows = [r.detach().requires_grad_(True) for r in (shift, scale, gate)]
+ tok = [expand_rows(r, counts, torch.bfloat16, (L, N)) for r in rows]
+ tok_leaf = [t.detach().requires_grad_(True) for t in tok] # to capture the per-token bf16 gradients
+ combined, xa = nmg.ln_modulate(xl, tok_leaf[0], tok_leaf[1], eps)
+ o1l = o1.detach().requires_grad_(True)
+ o2l = o2.detach().requires_grad_(True)
+ if fuse_add:
+ res = nmg.gate_residual2(xa, tok_leaf[2], o1l, o2l)
+ else:
+ res = nmg.gate_residual(xa, tok_leaf[2], o1l + o2l)
+ torch.autograd.backward([combined, res], [g, G])
+ per_token = [t.grad for t in tok_leaf]
+ torch.autograd.backward(tok, per_token) # ExpandRows.backward: fp32 segment sums
+ return dict(combined=combined.detach(), res=res.detach(), dx=xl.grad, do1=o1l.grad, do2=o2l.grad,
+ dshift=rows[0].grad, dscale=rows[1].grad, dgate=rows[2].grad,
+ tok_dshift=per_token[0], tok_dscale=per_token[1], tok_dgate=per_token[2])
+
+
+def rows_path(x, shift, scale, gate, o1, o2, g, G, plan, eps, fuse_add):
+ xl = x.detach().requires_grad_(True)
+ rows = [r.detach().requires_grad_(True) for r in (shift, scale, gate)]
+ mod = ModRows(rows[0], rows[1], rows[2], plan)
+ combined, xa = ln_modulate_rows(xl, mod, eps)
+ o1l = o1.detach().requires_grad_(True)
+ o2l = o2.detach().requires_grad_(True)
+ res = gate_residual_rows(xa, mod, o1l, o2l) if fuse_add else gate_residual_rows(xa, mod, o1l + o2l)
+ torch.autograd.backward([combined, res], [g, G])
+ return dict(combined=combined.detach(), res=res.detach(), dx=xl.grad, do1=o1l.grad, do2=o2l.grad,
+ dshift=rows[0].grad, dscale=rows[1].grad, dgate=rows[2].grad)
+
+
+def fp64_segment_sums(per_token: Tensor, counts: Sequence[int]) -> Tensor:
+ """fp64 segment sums of a per-token tensor (reference for the row gradients)."""
+ out = []
+ pos = 0
+ for c in counts:
+ out.append(per_token[pos:pos + c].double().sum(0) if c > 0 else torch.zeros(per_token.shape[-1], dtype=torch.float64, device=per_token.device))
+ pos += c
+ return torch.stack(out)
+
+
+def selftest(counts: Sequence[int] = (80, 2048, 256, 32, 1) * 4, N: int = 3072, device="cuda", eps: float = 1e-6,
+ verbose: bool = True, fuse_add: bool = False, rows_dtype=torch.float32, pitch: int | None = None,
+ T: int | None = None, seed: int = 1) -> dict:
+ """Forward / dx / d_out bitwise vs the production fused path; row gradients vs fp64 segment sums of the
+ production per-token gradients and vs ExpandRows' fp32 sums."""
+ if not nmg.Config.bwd_variant_selected:
+ nmg.Config.bwd_variant_selected = True # production default (verified at production shape)
+ x, shift, scale, gate, o1, o2, g, G = make_rows_inputs(counts, N, device, seed=seed, rows_dtype=rows_dtype, pitch=pitch)
+ plan = row_plan(counts, device, T=T, gate_T=T)
+ ref = current_path(x, shift, scale, gate, o1, o2, g, G, list(counts), eps, fuse_add)
+ cur = rows_path(x, shift, scale, gate, o1, o2, g, G, plan, eps, fuse_add)
+ res = {k: _compare(cur[k], ref[k]) for k in ("combined", "res", "dx", "do1", "do2")}
+ res["exact_fwd_dx_dout"] = all(res[k]["bitwise_fraction"] == 1.0 for k in ("combined", "res", "dx", "do1", "do2"))
+ for name in ("dshift", "dscale", "dgate"):
+ ref64 = fp64_segment_sums(ref["tok_" + name], counts)
+ res[name + "_vs_fp64"] = _compare(cur[name], ref64.to(cur[name].dtype)) | {"ref_rel_l2_current_vs_fp64": _compare(ref[name], ref64.to(ref[name].dtype))["rel_l2"]}
+ res[name + "_vs_current"] = _compare(cur[name], ref[name])
+ if verbose:
+ for k, v in res.items():
+ print(k, v)
+ return res
+
+
+if __name__ == "__main__":
+ r = selftest()
+ print("exact fwd/dx/dout:", r["exact_fwd_dx_dout"])
+ r = selftest(fuse_add=True, pitch=3 * 3072, counts=(2048,) * 8, verbose=False)
+ print("fuse_add + pitch 3N + equal runs: exact fwd/dx/dout:", r["exact_fwd_dx_dout"],
+ {k: r[k]["rel_l2"] for k in ("dshift_vs_fp64", "dscale_vs_fp64", "dgate_vs_fp64")})
diff --git a/flux-umi/src/flux_action/models/dit_norm_mod_gate.py b/flux-umi/src/flux_action/models/dit_norm_mod_gate.py
new file mode 100644
index 0000000000000000000000000000000000000000..6293f2fdb48c28e4c605e518fac1f68ae95e259a
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_norm_mod_gate.py
@@ -0,0 +1,798 @@
+"""Fused pre-norm + AdaLN modulation and fused gate + residual for the DiT blocks (Triton, bit-exact target).
+
+Experiment dit-norm-mod-gate. Nothing under src/flux_action is modified;
+``install(dit_or_block)`` monkeypatches ``forward`` on ``SingleStreamBlock`` / ``ModeBlock`` *instances* with a
+mirror of the eager forward whose two pointwise regions call the fused autograd functions below. For
+production the orchestrator can instead add the two call sites to ``transformer.py`` (see ``fused_single_forward``
+/ ``fused_mode_forward``; both are line-for-line the eager code with ``ln_modulate`` / ``gate_residual``).
+
+Reference semantics (transformer.py, bf16 tensors, fp32 math, bf16 RNE rounding after every ATen op)::
+
+ ln = LayerNorm(x, eps=1e-6, no affine) # ATen vectorized_layer_norm_kernel
+ a = bf16(1 + scale)
+ combined = bf16(bf16(a * ln) + shift)
+ out_blk = bf16(x + bf16(gate * output))
+
+Backward (eager autograd of that graph): d_shift = d_combined (alias); d_scale = bf16(d_combined * ln);
+d_ln = bf16(d_combined * a); dx_ln = ATen layer_norm_grad_input_kernel_vectorized(d_ln, x, mean, rstd) (fp32 math,
+bf16 out); d_gate = bf16(G * output); d_output = bf16(G * gate); dx = bf16(dx_ln + G) (autograd accumulation of
+the two paths into ``x``).
+
+Kernels (all one 128-thread program == one ATen block, replicating ATen's arithmetic order instruction by
+instruction; FMA contraction disabled, explicit libdevice.fma / div_rn where nvcc contracts):
+
+* ``_ln_mod_fwd_kernel``: Welford statistics in ATen's lane/vector order (lane t owns the 4-element vectors
+ t + 128*j), shuffle/smem combine tree, ``rsqrt(div_rn(m2, N) + eps)``, then the three modulation roundings;
+ writes ``combined`` (bf16) and per-row ``mean``/``rstd`` (fp32) for backward. The per-element ``1.f/new_count``
+ of cuWelfordOnlineSum is a compile-time constant here (counts are 1..24 for every lane), verified bitwise
+ against ``div.rn`` at import time.
+* ``_ln_mod_bwd_kernel``: recomputes ``ln`` and ``a`` from (x, scale, mean, rstd), writes ``d_scale``, forms
+ ``d_ln`` in registers, accumulates ATen's two row statistics in its order (per-lane sequential, then
+ BlockReduceSum tree), and writes ``dx`` with the residual gradient ``G`` folded in (bf16(bf16(dx_ln) + G)).
+ ``d_shift`` is the incoming gradient itself (no kernel).
+* ``_gate_res_fwd_kernel`` / ``_gate_res_bwd_kernel``: 16-byte vectorized elementwise kernels; the backward
+ returns ``G`` itself as the gradient of ``x``.
+
+The modulation tensors may be strided views (``Modulation.forward`` chunks a [.., 3*N] tensor: row stride 3N for
+the mode blocks; the packed single-block path has contiguous [1, L, N] tensors): every kernel takes a row stride.
+
+Autograd wiring: ``ln_modulate`` returns ``(combined, x_alias)`` where ``x_alias`` is ``x`` re-emitted as an output
+of the same autograd node; ``gate_residual`` consumes ``x_alias`` so the residual gradient G reaches
+``_LNModulate.backward`` and the accumulation ``dx = bf16(dx_ln + G)`` happens inside the backward kernel
+(bit-identical to autograd's own bf16 accumulation, one kernel fewer).
+"""
+from __future__ import annotations
+
+import types
+from contextlib import contextmanager
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+
+NUM_WARPS = 4 # 128 threads = one ATen vectorized_layer_norm / layer_norm_grad_input block
+LANES = tl.constexpr(128)
+GATE_BLOCK = 1024
+# N/4 must be a multiple of the 128 lanes (LN kernels) and N a multiple of the gate block min(GATE_BLOCK, N): the gate /
+# residual kernels launch grid (M, N // block) without a column mask, so N = 1536 (or any N % 1024 != 0 above 1024)
+# would leave the last N % 1024 columns unwritten. Other N take the eager path (``fusable`` / ``_gate_fusable``).
+SUPPORTED_N = (512, 1024, 2048, 3072, 4096, 6144, 8192)
+assert all(n % 512 == 0 and n % min(GATE_BLOCK, n) == 0 for n in SUPPORTED_N)
+
+# ------------------------------------------------------------------------------------------- Welford pieces
+@triton.jit
+def _welford_step(mean, m2, val, RCP: tl.constexpr):
+ """ATen cuWelfordOnlineSum with the compile-time reciprocal of the new count (nvcc contracts both
+ mul+add pairs into FMAs; 1.f/new_count is rcp.rn == div.rn(1, n), folded here)."""
+ delta = val - mean
+ rcp = tl.full([LANES], RCP, tl.float32)
+ new_mean = libdevice.fma(delta, rcp, mean)
+ new_m2 = libdevice.fma(delta, val - new_mean, m2)
+ return new_mean, new_m2
+
+
+@triton.jit
+def _welford_combine(mean_a, m2_a, cnt_a, mean_b, m2_b, cnt_b):
+ """ATen cuWelfordCombine(dataB=own (a), dataA=shuffled partner (b)); contraction pattern verified bitwise
+ by the VAE fusion experiment (variant 0) and re-verified here at N=3072."""
+ delta = mean_a - mean_b
+ count = cnt_b + cnt_a
+ one = tl.zeros_like(count) + 1.0
+ coef = libdevice.div_rn(one, count)
+ n_a = cnt_b * coef
+ n_b = cnt_a * coef
+ mean = libdevice.fma(n_a, mean_b, n_b * mean_a)
+ sig = libdevice.fma((delta * delta) * cnt_b, n_b, m2_b + m2_a)
+ pos = count > 0
+ return tl.where(pos, mean, 0.0), tl.where(pos, sig, 0.0), count
+
+
+@triton.jit
+def _split4(v):
+ """[128, 4] -> four [128] tensors (columns 0, 1, 2, 3)."""
+ x3 = tl.reshape(v, [LANES, 2, 2])
+ a, b = tl.split(x3) # a = cols (0, 2), b = cols (1, 3)
+ v0, v2 = tl.split(a)
+ v1, v3 = tl.split(b)
+ return v0, v1, v2, v3
+
+
+# ------------------------------------------------------------------------------------------- LN + modulation fwd
+@triton.jit
+def _ln_mod_fwd_kernel(x_ptr, shift_ptr, scale_ptr, y_ptr, mean_ptr, rstd_ptr, M, mod_stride, eps, n_float,
+ N: tl.constexpr, ROWS: tl.constexpr):
+ """combined = bf16(bf16(bf16(1 + scale) * bf16(LN(x))) + shift); one row per 128-thread program (ROWS rows
+ sequentially). Lane t reads the 4-element vectors t + 128*j, like ATen (vec_size 4 for every dtype)."""
+ NJ: tl.constexpr = (N // 4) // LANES
+ t = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ cnt = tl.zeros([LANES], tl.float32) + (4 * NJ)
+ pid = tl.program_id(0)
+ for r in range(ROWS):
+ row = pid * ROWS + r
+ rv = (tl.zeros([LANES, 4], tl.int32) + row) < M
+ base = row.to(tl.int64) * N
+ mbase = row.to(tl.int64) * mod_stride
+ mean = tl.zeros([LANES], tl.float32)
+ m2 = tl.zeros([LANES], tl.float32)
+ for j in tl.static_range(NJ):
+ coffs = ((t * 4 + j * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ xv = tl.load(x_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ v0, v1, v2, v3 = _split4(xv)
+ mean, m2 = _welford_step(mean, m2, v0, 1.0 / (4 * j + 1))
+ mean, m2 = _welford_step(mean, m2, v1, 1.0 / (4 * j + 2))
+ mean, m2 = _welford_step(mean, m2, v2, 1.0 / (4 * j + 3))
+ mean, m2 = _welford_step(mean, m2, v3, 1.0 / (4 * j + 4))
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _welford_combine)
+ var = libdevice.div_rn(m2_t, n_float)
+ rstd = tl.rsqrt(var + eps)
+ if row < M:
+ tl.store(mean_ptr + row, mean_t)
+ tl.store(rstd_ptr + row, rstd)
+ for j in tl.static_range(NJ):
+ coffs = ((t * 4 + j * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ xv = tl.load(x_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ sc = tl.load(scale_ptr + mbase + coffs, mask=rv, other=0.0).to(tl.float32)
+ sh = tl.load(shift_ptr + mbase + coffs, mask=rv, other=0.0).to(tl.float32)
+ ln = (rstd * (xv - mean_t)).to(tl.bfloat16).to(tl.float32) # ATen: Y = rstd * (x - mean) -> bf16
+ a = (sc + 1.0).to(tl.bfloat16).to(tl.float32) # bf16(1 + scale)
+ b = (a * ln).to(tl.bfloat16).to(tl.float32) # bf16(a * ln)
+ y = (b + sh).to(tl.bfloat16) # bf16(b + shift)
+ tl.store(y_ptr + base + coffs, y, mask=rv)
+
+
+# ------------------------------------------------------------------------------------------- LN + modulation bwd
+@triton.jit
+def _ln_mod_bwd_kernel(g_ptr, x_ptr, scale_ptr, mean_ptr, rstd_ptr, gres_ptr, dscale_ptr, dx_ptr, M, mod_stride,
+ n_float, N: tl.constexpr, ROWS: tl.constexpr, HAS_RES: tl.constexpr, WRITE_DSCALE: tl.constexpr,
+ P1: tl.constexpr, P2: tl.constexpr, WRITE_DX: tl.constexpr):
+ """d_scale = bf16(g * ln); dy = bf16(g * bf16(1 + scale)); dx = bf16(LN_grad_input(dy, x, mean, rstd)) [+ G].
+ P1/P2 select the FMA-contraction pattern of ATen's layer_norm_grad_input_kernel_vectorized (chosen by the
+ import-time self-test: the one that is bitwise identical to ATen). ``dscale_ptr`` / ``dx_ptr`` are only written
+ with ``WRITE_DSCALE`` / ``WRITE_DX`` (the host passes ``g`` itself as the unused sink, which must stay intact: it
+ is returned as ``d_shift``)."""
+ NJ: tl.constexpr = (N // 4) // LANES
+ t = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ pid = tl.program_id(0)
+ for r in range(ROWS):
+ row = pid * ROWS + r
+ rv = (tl.zeros([LANES, 4], tl.int32) + row) < M
+ rowc = tl.minimum(row, M - 1)
+ base = row.to(tl.int64) * N
+ mbase = row.to(tl.int64) * mod_stride
+ mean = tl.load(mean_ptr + rowc)
+ rstd = tl.load(rstd_ptr + rowc)
+ s1 = tl.zeros([LANES], tl.float32)
+ s2 = tl.zeros([LANES], tl.float32)
+ for j in tl.static_range(NJ):
+ coffs = ((t * 4 + j * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ xv = tl.load(x_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ gv = tl.load(g_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ sc = tl.load(scale_ptr + mbase + coffs, mask=rv, other=0.0).to(tl.float32)
+ ln = (rstd * (xv - mean)).to(tl.bfloat16).to(tl.float32)
+ a = (sc + 1.0).to(tl.bfloat16).to(tl.float32)
+ if WRITE_DSCALE:
+ tl.store(dscale_ptr + base + coffs, (gv * ln).to(tl.bfloat16), mask=rv)
+ dy = (gv * a).to(tl.bfloat16).to(tl.float32) # eager materializes d_ln in bf16
+ d0, d1, d2, d3 = _split4(dy)
+ x0, x1, x2, x3 = _split4(xv)
+ # ATen: stats_x1 += c_loss * gamma(=1); stats_x2 += c_loss * gamma * (c_h - mean) * rstd (sequential k)
+ s1 = s1 + d0
+ s1 = s1 + d1
+ s1 = s1 + d2
+ s1 = s1 + d3
+ if P1 == 0:
+ s2 = libdevice.fma(d0 * (x0 - mean), rstd, s2)
+ s2 = libdevice.fma(d1 * (x1 - mean), rstd, s2)
+ s2 = libdevice.fma(d2 * (x2 - mean), rstd, s2)
+ s2 = libdevice.fma(d3 * (x3 - mean), rstd, s2)
+ else:
+ s2 = s2 + (d0 * (x0 - mean)) * rstd
+ s2 = s2 + (d1 * (x1 - mean)) * rstd
+ s2 = s2 + (d2 * (x2 - mean)) * rstd
+ s2 = s2 + (d3 * (x3 - mean)) * rstd
+ S1 = tl.sum(s1, 0)
+ S2 = tl.sum(s2, 0)
+ one = tl.zeros_like(S1) + 1.0
+ term1 = libdevice.div_rn(one, n_float) * rstd
+ for j in tl.static_range(NJ):
+ coffs = ((t * 4 + j * (4 * LANES))[:, None] + c4[None, :]).to(tl.int64)
+ xv = tl.load(x_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ gv = tl.load(g_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ sc = tl.load(scale_ptr + mbase + coffs, mask=rv, other=0.0).to(tl.float32)
+ a = (sc + 1.0).to(tl.bfloat16).to(tl.float32)
+ dy = (gv * a).to(tl.bfloat16).to(tl.float32)
+ u = (xv - mean) * rstd
+ if P2 == 0:
+ f = libdevice.fma(-u, S2, n_float * dy) # f = fH*dy; f -= u*S2 (fma)
+ elif P2 == 1:
+ f = n_float * dy - u * S2 # no contraction
+ else:
+ f = libdevice.fma(n_float, dy, -(u * S2)) # fma on the first product
+ f = f - S1
+ f = f * term1
+ dxb = f.to(tl.bfloat16)
+ if HAS_RES:
+ gr = tl.load(gres_ptr + base + coffs, mask=rv, other=0.0).to(tl.float32)
+ dxb = (dxb.to(tl.float32) + gr).to(tl.bfloat16) # autograd: bf16(dx_ln + G)
+ if WRITE_DX:
+ tl.store(dx_ptr + base + coffs, dxb, mask=rv)
+
+
+# ------------------------------------------------------------------------------------------- gate + residual
+@triton.jit
+def _gate_res_fwd_kernel(x_ptr, gate_ptr, o_ptr, y_ptr, gate_stride, N: tl.constexpr, BLOCK: tl.constexpr):
+ """y = bf16(x + bf16(gate * o)); grid (rows, N // BLOCK)."""
+ row = tl.program_id(0).to(tl.int64)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ xo = row * N + col
+ go = row * gate_stride + col
+ xv = tl.load(x_ptr + xo).to(tl.float32)
+ gv = tl.load(gate_ptr + go).to(tl.float32)
+ ov = tl.load(o_ptr + xo).to(tl.float32)
+ tv = (gv * ov).to(tl.bfloat16).to(tl.float32)
+ tl.store(y_ptr + xo, (xv + tv).to(tl.bfloat16))
+
+
+@triton.jit
+def _gate_res_bwd_kernel(g_ptr, gate_ptr, o_ptr, dgate_ptr, do_ptr, gate_stride, N: tl.constexpr, BLOCK: tl.constexpr,
+ WRITE_DGATE: tl.constexpr, WRITE_DO: tl.constexpr):
+ """d_gate = bf16(G * o); d_o = bf16(G * gate)."""
+ row = tl.program_id(0).to(tl.int64)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ xo = row * N + col
+ go = row * gate_stride + col
+ gv = tl.load(g_ptr + xo).to(tl.float32)
+ if WRITE_DGATE:
+ ov = tl.load(o_ptr + xo).to(tl.float32)
+ tl.store(dgate_ptr + xo, (gv * ov).to(tl.bfloat16))
+ if WRITE_DO:
+ mv = tl.load(gate_ptr + go).to(tl.float32)
+ tl.store(do_ptr + xo, (gv * mv).to(tl.bfloat16))
+
+
+@triton.jit
+def _gate_res2_fwd_kernel(x_ptr, gate_ptr, o1_ptr, o2_ptr, y_ptr, gate_stride, N: tl.constexpr, BLOCK: tl.constexpr):
+ """y = bf16(x + bf16(gate * bf16(o1 + o2))): the eager ``attn_out(..) + mlp_out(..)`` bf16 add folded in."""
+ row = tl.program_id(0).to(tl.int64)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ xo = row * N + col
+ go = row * gate_stride + col
+ o = (tl.load(o1_ptr + xo).to(tl.float32) + tl.load(o2_ptr + xo).to(tl.float32)).to(tl.bfloat16).to(tl.float32)
+ xv = tl.load(x_ptr + xo).to(tl.float32)
+ gv = tl.load(gate_ptr + go).to(tl.float32)
+ tv = (gv * o).to(tl.bfloat16).to(tl.float32)
+ tl.store(y_ptr + xo, (xv + tv).to(tl.bfloat16))
+
+
+@triton.jit
+def _gate_res2_bwd_kernel(g_ptr, gate_ptr, o1_ptr, o2_ptr, dgate_ptr, do_ptr, gate_stride, N: tl.constexpr,
+ BLOCK: tl.constexpr, WRITE_DGATE: tl.constexpr, WRITE_DO: tl.constexpr):
+ """d_gate = bf16(G * bf16(o1 + o2)); d_o (shared by o1 and o2, like AddBackward) = bf16(G * gate)."""
+ row = tl.program_id(0).to(tl.int64)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ xo = row * N + col
+ go = row * gate_stride + col
+ gv = tl.load(g_ptr + xo).to(tl.float32)
+ if WRITE_DGATE:
+ o = (tl.load(o1_ptr + xo).to(tl.float32) + tl.load(o2_ptr + xo).to(tl.float32)).to(tl.bfloat16).to(tl.float32)
+ tl.store(dgate_ptr + xo, (gv * o).to(tl.bfloat16))
+ if WRITE_DO:
+ mv = tl.load(gate_ptr + go).to(tl.float32)
+ tl.store(do_ptr + xo, (gv * mv).to(tl.bfloat16))
+
+
+# ------------------------------------------------------------------------------------------- host wrappers
+class Config:
+ """Tunables (set before the first call). ``bwd_p1``/``bwd_p2`` are fixed by ``select_backward_variant``."""
+ fwd_rows = 1
+ bwd_rows = 1
+ bwd_p1 = 0 # stats_x2 accumulation: fma(dy*(x-mean), rstd, acc) (ATen, verified bitwise at 309376x3072)
+ bwd_p2 = 1 # grad input: f = fH*dy - u*S2 without contraction (ATen, verified bitwise at 309376x3072)
+ bwd_variant_selected = False
+ fuse_output_add = False # gate_residual over (o1 + o2): fold the attn_out + mlp_out add into the gate kernel
+
+
+def _row_stride(mod: Tensor, x: Tensor) -> int | None:
+ """Row stride if ``mod`` is a row-regular view with the same shape as ``x`` (unit last stride, constant row
+ pitch across all leading dims), else None."""
+ if mod.shape != x.shape or mod.dtype != x.dtype or mod.device != x.device:
+ return None
+ n = x.shape[-1]
+ if mod.dim() == 1:
+ return n if mod.stride(0) == 1 else None
+ if mod.stride(-1) != 1:
+ return None
+ pitch = mod.stride(-2)
+ if pitch < n:
+ return None
+ expected = pitch * mod.shape[-2]
+ for d in range(mod.dim() - 3, -1, -1):
+ if mod.shape[d] != 1 and mod.stride(d) != expected:
+ return None
+ expected *= mod.shape[d]
+ return pitch
+
+
+def ln_mod_forward(x: Tensor, shift: Tensor, scale: Tensor, eps: float):
+ """x: (..., N) bf16 contiguous; shift/scale: same shape, unit last stride, row-regular. Returns
+ (combined bf16, mean fp32 [rows], rstd fp32 [rows])."""
+ N = x.shape[-1]
+ x2 = x.reshape(-1, N)
+ M = x2.shape[0]
+ sh_stride = _row_stride(shift, x)
+ sc_stride = _row_stride(scale, x)
+ assert sh_stride is not None and sc_stride == sh_stride, "shift/scale must share one row stride"
+ y = torch.empty_like(x)
+ mean = torch.empty(M, dtype=torch.float32, device=x.device)
+ rstd = torch.empty(M, dtype=torch.float32, device=x.device)
+ rows = Config.fwd_rows
+ grid = (triton.cdiv(M, rows),)
+ _ln_mod_fwd_kernel[grid](x2, shift, scale, y, mean, rstd, M, sh_stride, float(eps), float(N),
+ N=N, ROWS=rows, num_warps=NUM_WARPS, enable_fp_fusion=False)
+ return y, mean, rstd
+
+
+def ln_mod_backward(g: Tensor, x: Tensor, scale: Tensor, mean: Tensor, rstd: Tensor, gres: Tensor | None,
+ need_dscale: bool = True, need_dx: bool = True):
+ """Returns (dx bf16 or None, d_scale bf16 or None). ``gres`` (same layout as x) is added into dx."""
+ N = x.shape[-1]
+ x2 = x.reshape(-1, N)
+ M = x2.shape[0]
+ sc_stride = _row_stride(scale, x)
+ assert sc_stride is not None
+ g2 = g.reshape(-1, N)
+ assert g2.is_contiguous()
+ dx = torch.empty_like(x) if need_dx else None
+ dscale = torch.empty_like(x) if need_dscale else None
+ if gres is not None:
+ gres = gres.reshape(-1, N)
+ assert gres.is_contiguous()
+ rows = Config.bwd_rows
+ grid = (triton.cdiv(M, rows),)
+ # g2 doubles as the sink pointer of every output that is not needed; the kernel never writes a sink
+ # (WRITE_DSCALE / WRITE_DX), so g -- returned by the autograd Function as d_shift -- is never mutated.
+ _ln_mod_bwd_kernel[grid](g2, x2, scale, mean, rstd, gres if gres is not None else g2,
+ dscale if dscale is not None else g2, dx if dx is not None else g2, M, sc_stride, float(N),
+ N=N, ROWS=rows, HAS_RES=gres is not None, WRITE_DSCALE=need_dscale, WRITE_DX=need_dx,
+ P1=Config.bwd_p1, P2=Config.bwd_p2, num_warps=NUM_WARPS, enable_fp_fusion=False)
+ if not need_dx:
+ dx = None
+ return dx, dscale
+
+
+def gate_grid(M: int, N: int) -> tuple[tuple[int, int], int]:
+ """Launch grid ``(rows, column blocks)`` and block of the unmasked gate / residual kernels; ``N`` must be a
+ multiple of ``min(GATE_BLOCK, N)`` (every column is written exactly once), else ValueError."""
+ block = min(GATE_BLOCK, N)
+ if N % block:
+ raise ValueError(f"hidden size {N} is not a multiple of the gate block {block}; supported: {SUPPORTED_N}")
+ return (M, N // block), block
+
+
+def gate_res_forward(x: Tensor, gate: Tensor, out: Tensor) -> Tensor:
+ N = x.shape[-1]
+ M = x.numel() // N
+ gstride = _row_stride(gate, x)
+ assert gstride is not None and out.is_contiguous()
+ y = torch.empty_like(x)
+ grid, block = gate_grid(M, N)
+ _gate_res_fwd_kernel[grid](x, gate, out, y, gstride, N=N, BLOCK=block, num_warps=NUM_WARPS,
+ enable_fp_fusion=False)
+ return y
+
+
+def gate_res_backward(G: Tensor, gate: Tensor, out: Tensor, need_dgate: bool = True, need_dout: bool = True):
+ N = G.shape[-1]
+ M = G.numel() // N
+ gstride = _row_stride(gate, G)
+ assert gstride is not None and G.is_contiguous() and out.is_contiguous()
+ dgate = torch.empty_like(G) if need_dgate else None
+ dout = torch.empty_like(G) if need_dout else None
+ grid, block = gate_grid(M, N)
+ _gate_res_bwd_kernel[grid](G, gate, out, dgate if dgate is not None else G, dout if dout is not None else G,
+ gstride, N=N, BLOCK=block, WRITE_DGATE=need_dgate, WRITE_DO=need_dout,
+ num_warps=NUM_WARPS, enable_fp_fusion=False)
+ return dgate, dout
+
+
+def gate_res2_forward(x: Tensor, gate: Tensor, o1: Tensor, o2: Tensor) -> Tensor:
+ N = x.shape[-1]
+ M = x.numel() // N
+ gstride = _row_stride(gate, x)
+ assert gstride is not None and o1.is_contiguous() and o2.is_contiguous()
+ y = torch.empty_like(x)
+ grid, block = gate_grid(M, N)
+ _gate_res2_fwd_kernel[grid](x, gate, o1, o2, y, gstride, N=N, BLOCK=block, num_warps=NUM_WARPS,
+ enable_fp_fusion=False)
+ return y
+
+
+def gate_res2_backward(G: Tensor, gate: Tensor, o1: Tensor, o2: Tensor, need_dgate: bool = True, need_dout: bool = True):
+ N = G.shape[-1]
+ M = G.numel() // N
+ gstride = _row_stride(gate, G)
+ assert gstride is not None and G.is_contiguous()
+ dgate = torch.empty_like(G) if need_dgate else None
+ dout = torch.empty_like(G) if need_dout else None
+ grid, block = gate_grid(M, N)
+ _gate_res2_bwd_kernel[grid](G, gate, o1, o2, dgate if dgate is not None else G, dout if dout is not None else G,
+ gstride, N=N, BLOCK=block, WRITE_DGATE=need_dgate, WRITE_DO=need_dout,
+ num_warps=NUM_WARPS, enable_fp_fusion=False)
+ return dgate, dout
+
+
+# ------------------------------------------------------------------------------------------- autograd
+class _LNModulate(torch.autograd.Function):
+ """(combined, x_alias) = f(x, shift, scale). ``x_alias`` is ``x`` re-emitted as an output of this node so that
+ the residual branch's gradient is accumulated into dx inside the backward kernel."""
+
+ @staticmethod
+ def forward(ctx, x, shift, scale, eps):
+ combined, mean, rstd = ln_mod_forward(x, shift, scale, eps)
+ ctx.save_for_backward(x, scale, mean, rstd)
+ return combined, x
+
+ @staticmethod
+ def backward(ctx, g, gres):
+ x, scale, mean, rstd = ctx.saved_tensors
+ need_x, need_shift, need_scale = ctx.needs_input_grad[:3]
+ if g is None:
+ # only the residual path is live: dx = G, nothing else
+ return (gres if need_x else None), None, None, None
+ if not g.is_contiguous():
+ g = g.contiguous()
+ if gres is not None and not gres.is_contiguous():
+ gres = gres.contiguous()
+ dx, dscale = ln_mod_backward(g, x, scale, mean, rstd, gres if need_x else None,
+ need_dscale=need_scale, need_dx=need_x)
+ return dx, (g if need_shift else None), dscale, None
+
+
+class _GateResidual(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, gate, out):
+ ctx.save_for_backward(gate, out)
+ return gate_res_forward(x, gate, out)
+
+ @staticmethod
+ def backward(ctx, G):
+ gate, out = ctx.saved_tensors
+ need_x, need_gate, need_out = ctx.needs_input_grad
+ if not G.is_contiguous():
+ G = G.contiguous()
+ dgate, dout = gate_res_backward(G, gate, out, need_dgate=need_gate, need_dout=need_out)
+ return (G if need_x else None), dgate, dout
+
+
+class _GateResidual2(torch.autograd.Function):
+ """x + gate * (o1 + o2) with eager's three bf16 roundings; o1/o2 (not their sum) are saved for backward."""
+
+ @staticmethod
+ def forward(ctx, x, gate, o1, o2):
+ ctx.save_for_backward(gate, o1, o2)
+ return gate_res2_forward(x, gate, o1, o2)
+
+ @staticmethod
+ def backward(ctx, G):
+ gate, o1, o2 = ctx.saved_tensors
+ need_x, need_gate, need_o1, need_o2 = ctx.needs_input_grad
+ if not G.is_contiguous():
+ G = G.contiguous()
+ dgate, dout = gate_res2_backward(G, gate, o1, o2, need_dgate=need_gate, need_dout=need_o1 or need_o2)
+ return (G if need_x else None), dgate, (dout if need_o1 else None), (dout if need_o2 else None)
+
+
+def gate_residual2(x_alias: Tensor, gate: Tensor, o1: Tensor, o2: Tensor) -> Tensor:
+ """Fused ``x + gate * (o1 + o2)`` (eager: bf16 add, bf16 mul, bf16 add)."""
+ return _GateResidual2.apply(x_alias, gate, o1, o2)
+
+
+def ln_modulate(x: Tensor, shift: Tensor, scale: Tensor, eps: float = 1e-6) -> tuple[Tensor, Tensor]:
+ """Fused ``bf16((1 + scale) * LayerNorm(x)) + shift`` (eps, no affine). Returns (combined, x_alias); feed
+ ``x_alias`` (not ``x``) to :func:`gate_residual` so the residual gradient is fused into the LN backward."""
+ return _LNModulate.apply(x, shift, scale, eps)
+
+
+def gate_residual(x_alias: Tensor, gate: Tensor, out: Tensor) -> Tensor:
+ """Fused ``x + gate * out`` (two bf16 roundings like eager)."""
+ return _GateResidual.apply(x_alias, gate, out)
+
+
+# ------------------------------------------------------------------------------------------- dispatch
+def _forward_ad_active() -> bool:
+ try:
+ import torch.autograd.forward_ad as fwAD
+ return getattr(fwAD, "_current_level", -1) >= 0
+ except Exception: # pragma: no cover
+ return False
+
+
+def fusable(pre_norm: nn.Module, x: Tensor, *mods: Tensor) -> bool:
+ """True when the fused kernels apply (bf16 CUDA, contiguous x, N supported, row-regular mod views, no
+ compile/forward-AD/functorch)."""
+ if torch.compiler.is_compiling() or _forward_ad_active():
+ return False
+ if type(pre_norm) is not nn.LayerNorm or pre_norm.elementwise_affine or pre_norm.weight is not None:
+ return False
+ if not (x.is_cuda and x.dtype == torch.bfloat16 and x.dim() >= 2 and x.is_contiguous()):
+ return False
+ n = x.shape[-1]
+ if n not in SUPPORTED_N or pre_norm.normalized_shape != (n,):
+ return False
+ if torch._C._functorch.is_functorch_wrapped_tensor(x):
+ return False
+ strides = [_row_stride(m, x) for m in mods]
+ return all(s is not None for s in strides) and strides[0] == strides[1]
+
+
+# ------------------------------------------------------------------------------------------- block forwards
+class FusedState:
+ def __init__(self):
+ self.enabled = True
+ self.patched: list[tuple[nn.Module, object]] = []
+ self.calls_fused = 0
+ self.calls_eager = 0
+
+
+@contextmanager
+def disabled(state: FusedState):
+ prev = state.enabled
+ state.enabled = False
+ try:
+ yield
+ finally:
+ state.enabled = prev
+
+
+def _modulate(self, state, x, shift, scale):
+ if state.enabled and fusable(self.pre_norm, x, shift, scale):
+ state.calls_fused += 1
+ return ln_modulate(x, shift, scale, self.pre_norm.eps)
+ state.calls_eager += 1
+ return (1 + scale) * self.pre_norm(x) + shift, x
+
+
+def _gate_fusable(x: Tensor, gate: Tensor, *outs: Tensor) -> bool:
+ if torch.compiler.is_compiling() or _forward_ad_active():
+ return False
+ if not (x.is_cuda and x.dtype == torch.bfloat16 and x.is_contiguous() and x.shape[-1] in SUPPORTED_N):
+ return False
+ if torch._C._functorch.is_functorch_wrapped_tensor(x):
+ return False
+ for o in outs:
+ if not (o.shape == x.shape and o.dtype == torch.bfloat16 and o.is_contiguous()):
+ return False
+ return _row_stride(gate, x) is not None
+
+
+def _gate(self, state, x_alias, gate, out):
+ if state.enabled and _gate_fusable(x_alias, gate, out):
+ return gate_residual(x_alias, gate, out)
+ return x_alias + gate * out
+
+
+def _gate2(self, state, x_alias, gate, o1, o2):
+ """output = o1 + o2; x + gate * output -- one kernel when ``Config.fuse_output_add``."""
+ if state.enabled and Config.fuse_output_add and _gate_fusable(x_alias, gate, o1, o2):
+ return gate_residual2(x_alias, gate, o1, o2)
+ return _gate(self, state, x_alias, gate, o1 + o2)
+
+
+def fused_single_forward(self, x, ctx, pe, mod_x, mod_ctx, pag_strength=0.0, seqlens=None, *, _state):
+ """Mirror of SingleStreamBlock.forward with the two fused regions."""
+ import flux_action.models.transformer as T
+ from einops import rearrange
+
+ mod_shift_x, mod_scale_x, mod_gate_x = mod_x
+ if ctx is None:
+ combined, x_alias = _modulate(self, _state, x, mod_shift_x, mod_scale_x)
+ else:
+ mod_shift_ctx, mod_scale_ctx, mod_gate_ctx = mod_ctx
+ x_mod, x_alias = _modulate(self, _state, x, mod_shift_x, mod_scale_x)
+ ctx_mod, ctx_alias = _modulate(self, _state, ctx, mod_shift_ctx, mod_scale_ctx)
+ combined = torch.cat((ctx_mod, x_mod), dim=1)
+
+ q = rearrange(self.q_proj(T._bf16_if_required(self.q_proj, combined)), "B L (H D) -> B H L D", H=self.num_heads)
+ k = rearrange(self.k_proj(T._bf16_if_required(self.k_proj, combined)), "B L (H D) -> B H L D", H=self.num_heads)
+ v = rearrange(self.v_proj(T._bf16_if_required(self.v_proj, combined)), "B L (H D) -> B H L D", H=self.num_heads)
+ mlp = self.mlp_in(T._bf16_if_required(self.mlp_in, combined))
+
+ q, k = T.qk_norm_rope(self.norm, q, k, v, pe)
+ attn = self.attention(q, k, v, self.attn_mode, seqlens)
+ attn = T.apply_pag(attn, v, pag_strength)
+
+ o1 = self.attn_out(T._bf16_if_required(self.attn_out, attn))
+ o2 = self.mlp_out(T._bf16_if_required(self.mlp_out, self.mlp_act(mlp)))
+ if ctx is None and self.gate_type is None:
+ return None, _gate2(self, _state, x_alias, mod_gate_x, o1, o2)
+ output = o1 + o2
+ if self.gate_type is not None:
+ output = output * F.silu(self.gate_proj(combined))
+
+ if ctx is None:
+ return None, _gate(self, _state, x_alias, mod_gate_x, output)
+ ctx_out, x_out = torch.split(output, [ctx.shape[1], x.shape[1]], dim=1)
+ return _gate(self, _state, ctx_alias, mod_gate_ctx, ctx_out), _gate(self, _state, x_alias, mod_gate_x, x_out)
+
+
+def fused_mode_forward(self, x, pe, mod, seqlens=None, *, _state):
+ """Mirror of ModeBlock.forward with the two fused regions."""
+ import flux_action.models.transformer as T
+ from einops import rearrange
+
+ mod_shift, mod_scale, mod_gate = mod
+ x_mod, x_alias = _modulate(self, _state, x, mod_shift, mod_scale)
+
+ q = rearrange(self.q_proj(T._bf16_if_required(self.q_proj, x_mod)), "B L (H D) -> B H L D", H=self.num_heads)
+ k = rearrange(self.k_proj(T._bf16_if_required(self.k_proj, x_mod)), "B L (H D) -> B H L D", H=self.num_heads)
+ v = rearrange(self.v_proj(T._bf16_if_required(self.v_proj, x_mod)), "B L (H D) -> B H L D", H=self.num_heads)
+ mlp = self.mlp_in(T._bf16_if_required(self.mlp_in, x_mod))
+
+ q, k = T.qk_norm_rope(self.norm, q, k, v, pe)
+ attn = self.attention(q, k, v, self.attn_mode, seqlens)
+
+ o1 = self.attn_out(T._bf16_if_required(self.attn_out, attn))
+ o2 = self.mlp_out(T._bf16_if_required(self.mlp_out, self.mlp_act(mlp)))
+ if self.gate_type is None:
+ return _gate2(self, _state, x_alias, mod_gate, o1, o2)
+ output = (o1 + o2) * F.silu(self.gate_proj(x_mod))
+ return _gate(self, _state, x_alias, mod_gate, output)
+
+
+def install(module: nn.Module, *, select_variant: bool = False) -> FusedState:
+ """Patch ``forward`` on every SingleStreamBlock / ModeBlock instance under ``module`` (a JointSingleSeq or a
+ single block). Returns the state whose ``.enabled`` routes back to eager when False. No CUDA work is done at
+ install time (the trainer builds the DiT on meta/CPU); ``select_variant=True`` runs the optional GPU
+ self-check of the backward contraction pattern (the default is already verified at production shape)."""
+ from flux_action.models.transformer import ModeBlock, SingleStreamBlock
+
+ state = FusedState()
+ mods = [module] + list(module.modules())
+ seen = set()
+ for m in mods:
+ if id(m) in seen:
+ continue
+ seen.add(id(m))
+ if type(m) is SingleStreamBlock:
+ fn = fused_single_forward
+ elif type(m) is ModeBlock:
+ fn = fused_mode_forward
+ else:
+ continue
+ state.patched.append((m, m.__dict__.get("forward")))
+
+ def bound(self, *args, _fn=fn, _state=state, **kwargs):
+ return _fn(self, *args, _state=_state, **kwargs)
+
+ m.forward = types.MethodType(bound, m)
+ if select_variant and not Config.bwd_variant_selected:
+ select_backward_variant()
+ return state
+
+
+def uninstall(state: FusedState) -> None:
+ for m, prev in reversed(state.patched):
+ if prev is None:
+ m.__dict__.pop("forward", None)
+ else:
+ m.forward = prev
+ state.patched.clear()
+
+
+# ------------------------------------------------------------------------------------------- self-tests
+def _compare(a: Tensor, b: Tensor) -> dict:
+ af, bf = a.float(), b.float()
+ diff = (af - bf).abs()
+ same = (a.view(torch.int16) == b.view(torch.int16)) if a.dtype == b.dtype == torch.bfloat16 else (a == b)
+ n_same = int(same.sum().item()) # exact count (an fp32 .mean() over 1e9 elements rounds to 0.99999994)
+ return {"max_abs": diff.max().item(), "rel_l2": (diff.norm() / bf.norm().clamp_min(1e-30)).item(),
+ "bitwise_fraction": n_same / a.numel(), "n_diff": a.numel() - n_same}
+
+
+def check_reciprocals(device="cuda") -> bool:
+ """The folded 1/k constants (k = 1..N/512) must equal div.rn(1, k) (ATen's 1.f/new_count)."""
+ ks = torch.arange(1, 65, device=device, dtype=torch.float32)
+ gpu = torch.ones_like(ks) / ks
+ host = torch.tensor([1.0 / k for k in range(1, 65)], dtype=torch.float32, device=device)
+ return bool(torch.equal(gpu, host))
+
+
+def _eager_reference(x, shift, scale, gate, out, g, G, eps):
+ x = x.detach().requires_grad_(True)
+ shift = shift.detach().requires_grad_(True)
+ scale = scale.detach().requires_grad_(True)
+ gate = gate.detach().requires_grad_(True)
+ out = out.detach().requires_grad_(True)
+ combined = (1 + scale) * F.layer_norm(x, (x.shape[-1],), None, None, eps) + shift
+ res = x + gate * out
+ torch.autograd.backward([combined, res], [g, G])
+ return dict(combined=combined.detach(), res=res.detach(), dx=x.grad, dshift=shift.grad, dscale=scale.grad,
+ dgate=gate.grad, dout=out.grad)
+
+
+def _fused_reference(x, shift, scale, gate, out, g, G, eps):
+ x = x.detach().requires_grad_(True)
+ shift = shift.detach().requires_grad_(True)
+ scale = scale.detach().requires_grad_(True)
+ gate = gate.detach().requires_grad_(True)
+ out = out.detach().requires_grad_(True)
+ combined, x_alias = ln_modulate(x, shift, scale, eps)
+ res = gate_residual(x_alias, gate, out)
+ torch.autograd.backward([combined, res], [g, G])
+ return dict(combined=combined.detach(), res=res.detach(), dx=x.grad, dshift=shift.grad, dscale=scale.grad,
+ dgate=gate.grad, dout=out.grad)
+
+
+def make_inputs(M, N, device, seed=0, x_std=1.0, x_mean=0.0, mod_std=0.5, mod_stride=None):
+ """Random bf16 inputs; mod tensors optionally as chunk views of a [M, 3N]-pitch buffer (mode-block layout)."""
+ gen = torch.Generator(device=device).manual_seed(seed)
+
+ def rnd(std, mean=0.0, shape=(M, N)):
+ return (torch.randn(*shape, device=device, generator=gen) * std + mean).to(torch.bfloat16)
+
+ x = rnd(x_std, x_mean)
+ if mod_stride is None:
+ shift, scale, gate = rnd(mod_std), rnd(mod_std), rnd(mod_std)
+ else:
+ buf = rnd(mod_std, shape=(M, mod_stride))
+ shift, scale, gate = buf[:, :N], buf[:, N:2 * N], buf[:, 2 * N:3 * N]
+ out = rnd(1.0)
+ g = rnd(1.0)
+ G = rnd(1.0)
+ return x, shift, scale, gate, out, g, G
+
+
+def select_backward_variant(device="cuda", M=4096, N=3072, eps=1e-6, verbose=False) -> tuple[int, int]:
+ """Confirm the (P1, P2) contraction pattern whose dx is bitwise identical to ATen's LayerNorm backward.
+ The default (0, 1) was selected at production shape (309376 x 3072, three input regimes: 0 differing elements;
+ the other patterns differ in 55-410 elements); ties at small shapes keep the default (strict improvement only)."""
+ x, shift, scale, gate, out, g, G = make_inputs(M, N, device, seed=7)
+ ref = _eager_reference(x, shift, scale, gate, out, g, G, eps)
+ default = (Config.bwd_p1, Config.bwd_p2)
+ candidates = [default] + [(p1, p2) for p1 in (0, 1) for p2 in (0, 1, 2) if (p1, p2) != default]
+ best, best_diff = default, None
+ for p1, p2 in candidates:
+ Config.bwd_p1, Config.bwd_p2 = p1, p2
+ cur = _fused_reference(x, shift, scale, gate, out, g, G, eps)
+ n_diff = _compare(cur["dx"], ref["dx"])["n_diff"]
+ if verbose:
+ print(f"variant P1={p1} P2={p2}: dx n_diff {n_diff}")
+ if best_diff is None or n_diff < best_diff:
+ best, best_diff = (p1, p2), n_diff
+ Config.bwd_p1, Config.bwd_p2 = best
+ Config.bwd_variant_selected = True
+ if verbose:
+ print("selected", best, "n_diff", best_diff)
+ return best
+
+
+def selftest(device="cuda", M=8192, N=3072, eps=1e-6, verbose=True, mod_stride=None) -> dict:
+ """Exactness of every output and gradient vs eager at a moderate shape (use test_exact.py for production shape)."""
+ assert check_reciprocals(device), "folded Welford reciprocals differ from div.rn"
+ if not Config.bwd_variant_selected:
+ select_backward_variant(device, verbose=verbose)
+ x, shift, scale, gate, out, g, G = make_inputs(M, N, device, seed=1, mod_stride=mod_stride)
+ ref = _eager_reference(x, shift, scale, gate, out, g, G, eps)
+ cur = _fused_reference(x, shift, scale, gate, out, g, G, eps)
+ _, mean_ref, rstd_ref = torch.native_layer_norm(x, (N,), None, None, eps)
+ _, mean_cur, rstd_cur = ln_mod_forward(x, shift, scale, eps)
+ res = {k: _compare(cur[k], ref[k]) for k in ref}
+ res["mean"] = _compare(mean_cur.flatten(), mean_ref.flatten())
+ res["rstd"] = _compare(rstd_cur.flatten(), rstd_ref.flatten())
+ ok = all(v["bitwise_fraction"] == 1.0 for v in res.values())
+ res["all_bit_exact"] = ok
+ if verbose:
+ for k, v in res.items():
+ print(k, v)
+ print("ALL BIT-EXACT:", ok)
+ return res
+
+
+if __name__ == "__main__":
+ selftest()
+ selftest(mod_stride=3 * 3072)
diff --git a/flux-umi/src/flux_action/models/dit_out_stage.py b/flux-umi/src/flux_action/models/dit_out_stage.py
new file mode 100644
index 0000000000000000000000000000000000000000..8547f02c34c2cecff961920e4a4bd0a1dbfc22f2
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_out_stage.py
@@ -0,0 +1,221 @@
+"""Output stage of a DiT block (attn_out GEMM + mlp_out GEMM + their add + gate/residual) as ONE custom op.
+
+Experiment A-1 of the phase-3 plan (``flux::out_stage``). In the row-modulation block forwards
+(``dit_mod_rows.fused_single_forward_rows`` / ``fused_mode_forward_rows``) the output stage is today
+
+ o1 = attn_out(attn); o2 = mlp_out(swiglu); s = bf16(o1 + o2); y = gate_residual_rows(x_alias, mod, s)
+
+i.e. two ``aten.mm``, one ``aten.add`` and the gate kernel, four autograd nodes. Here it is one operator
+``flux::out_stage(attn, sw, Wo, W2, x, gate_rows, idx, tables...) -> (y, s)``:
+
+* forward: ``o1 = attn @ Wo^T`` then ``o1.addmm_(sw, W2^T)`` -- cuBLASLt's ``beta = 1`` epilogue rounds exactly like the
+ separate ``o1 + o2`` (``bf16(bf16(acc) + C)``) at the production shapes (verified bitwise over 950M elements), so the add
+ kernel disappears. At small-M shapes cuBLAS uses split-K and the epilogue is **not** bit-exact: a one-time per-shape
+ self-check (``torch.equal`` of ``addmm_`` against ``mm + add`` on the first call's real operands, cached per
+ (M, K1, K2, N, dtype, device, alignment)) decides, fail-closed, and non-exact shapes run ``mm + mm + add``. Then
+ ``y = bf16(x + bf16(gate[idx] * s))`` with ``dit_mod_rows._gate_res_rows_fwd_kernel`` (same launch as today).
+* backward: ``dout = bf16(G * gate[idx])`` and ``d_gate = sum_tokens bf16(G * s)`` from ``_gate_res_rows_bwd_kernel`` +
+ ``rows_reduce`` (today's gate backward), then ``MmBackward0``'s own calls ``d_attn = dout @ Wo``, ``dWo = dout^T @ attn``,
+ ``d_sw = dout @ W2``, ``dW2 = dout^T @ sw`` (same operand layouts, so cuBLAS picks the same kernels), ``dx = G``.
+ Every value is bitwise what autograd computes today.
+* selective checkpointing: the SAC dispatch modes see one op (the inner GEMMs run below the mode), so
+ ``training.distributed._SacPolicy`` kind ``out_stage`` can MUST_SAVE ``(y, s)``: the recompute pops them and never runs the
+ body -- attn_out GEMM, mlp_out GEMM, add and gate kernel of a saving block are gone from the backward. Memory is that of
+ saving ``mlp_out`` today (one hidden-width tensor ``s``; ``y`` aliases the block output that is kept anyway). Saving
+ ``out_stage`` instead of ``sdpa`` ("swap") trades the SDPA forward (~7 ms) for both GEMMs + add + gate (~18 ms).
+
+Enabled through ``dit_mod_rows.Config.out_stage`` (:func:`install`; ``PolicyConfig.dit_out_stage``).
+"""
+from __future__ import annotations
+
+import torch
+from torch import Tensor, nn
+
+from flux_action.models import dit_mod_rows as mr
+from flux_action.models import dit_norm_mod_gate as nmg
+
+
+class Config:
+ epilogue = True # beta=1 epilogue for the second GEMM where the per-shape self-check proved it bitwise (else mm + add)
+
+
+class State:
+ def __init__(self):
+ self.calls_fused = 0
+ self.calls_eager = 0
+ self.exact: dict[tuple, bool] = {} # shape key -> epilogue bitwise equal to mm + add
+
+
+STATE = State()
+_ALIGN_CAP = 256 # cuBLASLt heuristics see pointer alignment capped at 256 B
+
+
+def _alignment(t: Tensor) -> int:
+ p, a = t.data_ptr(), _ALIGN_CAP
+ while a > 1 and p % a:
+ a //= 2
+ return a
+
+
+def _shape_key(attn2: Tensor, sw2: Tensor, wo: Tensor, w2: Tensor) -> tuple:
+ return (attn2.shape[0], attn2.shape[1], sw2.shape[1], wo.shape[0], str(attn2.dtype), attn2.device.index,
+ min(_alignment(t) for t in (attn2, sw2, wo, w2)))
+
+
+def combine(attn2: Tensor, sw2: Tensor, wo: Tensor, w2: Tensor) -> Tensor:
+ """``bf16(attn2 @ wo^T + sw2 @ w2^T)`` [M, N] with the production rounding (bf16 GEMM outputs, one bf16 add)."""
+ o1 = torch.mm(attn2, wo.t()) # == F.linear(attn, wo): same aten.mm call
+ if not Config.epilogue:
+ return o1 + torch.mm(sw2, w2.t())
+ key = _shape_key(attn2, sw2, wo, w2)
+ exact = STATE.exact.get(key)
+ if exact is None: # first call at this shape: decide on the real operands
+ ref = o1 + torch.mm(sw2, w2.t())
+ o1.addmm_(sw2, w2.t())
+ STATE.exact[key] = bool(torch.equal(o1, ref))
+ return ref
+ if exact:
+ return o1.addmm_(sw2, w2.t())
+ return o1 + torch.mm(sw2, w2.t())
+
+
+def _gate_bf16(gate: Tensor) -> Tensor:
+ if mr.Config.bf16_row_copies and gate.dtype == torch.float32:
+ return gate.to(torch.bfloat16) # == ExpandRows' rows.to(bf16); tiny [R, N]
+ return gate
+
+
+def _gate_forward(x2: Tensor, gate: Tensor, idx: Tensor, s2: Tensor) -> Tensor:
+ M, N = x2.shape
+ y = torch.empty_like(x2)
+ grid, block = nmg.gate_grid(M, N) # unmasked kernel: N % block == 0 (checked again by ``applies``)
+ mr._gate_res_rows_fwd_kernel[grid](x2, gate, idx, s2, s2, y, mr._row_pitch(gate, N), N=N, BLOCK=block,
+ TWO=False, ROWS_FP32=gate.dtype == torch.float32,
+ num_warps=mr.NUM_WARPS, enable_fp_fusion=False)
+ return y
+
+
+def _gate_backward(G2: Tensor, gate: Tensor, s2: Tensor, cstart: Tensor, clen: Tensor, crow: Tensor, cptr: Tensor,
+ need_dout: bool):
+ """(d_out bf16 [M, N] or None, d_gate fp32 [R, N]) exactly as ``dit_mod_rows.gate_res_rows_backward``."""
+ M, N = G2.shape
+ C, R = cstart.numel(), gate.shape[0]
+ dout = torch.empty_like(G2) if need_dout else None
+ part = torch.empty(1, max(C, 1), N, dtype=torch.float32, device=G2.device)
+ grid, block = nmg.gate_grid(C, N)
+ if C > 0:
+ mr._gate_res_rows_bwd_kernel[grid](G2, gate, s2, s2, cstart, clen, crow, dout if dout is not None else G2,
+ part, mr._row_pitch(gate, N), N=N, BLOCK=block, TWO=False,
+ ROWS_FP32=gate.dtype == torch.float32, ROUND_BF16=mr.Config.round_bf16,
+ WRITE_DO=need_dout, STAGES=mr.Config.gate_bwd_stages,
+ num_warps=mr.NUM_WARPS, enable_fp_fusion=False)
+ sums = mr.rows_reduce(part[:, :C] if C > 0 else part[:, :0], cptr, R)
+ return dout, sums[0]
+
+
+@torch.library.custom_op("flux::out_stage", mutates_args=(), device_types="cuda")
+def _out_stage(attn: Tensor, sw: Tensor, wo: Tensor, w2: Tensor, x: Tensor, gate: Tensor, idx: Tensor,
+ cstart: Tensor, clen: Tensor, crow: Tensor, cptr: Tensor) -> tuple[Tensor, Tensor]:
+ N = x.shape[-1]
+ x2 = x.reshape(-1, N)
+ s2 = combine(attn.reshape(-1, attn.shape[-1]), sw.reshape(-1, sw.shape[-1]), wo, w2)
+ y = _gate_forward(x2, _gate_bf16(gate), idx, s2)
+ return y.view(x.shape), s2.view(x.shape)
+
+
+@_out_stage.register_fake
+def _(attn, sw, wo, w2, x, gate, idx, cstart, clen, crow, cptr):
+ return torch.empty_like(x), torch.empty_like(x)
+
+
+def _setup_context(ctx, inputs, output):
+ attn, sw, wo, w2, x, gate, idx, cstart, clen, crow, cptr = inputs
+ ctx.set_materialize_grads(False) # ``s`` is unused downstream: its grad arrives as None, not zeros
+ ctx.save_for_backward(attn, sw, wo, w2, gate, output[1])
+ ctx.tables = (cstart, clen, crow, cptr)
+
+
+def _backward(ctx, grad_y, grad_s):
+ attn, sw, wo, w2, gate, s = ctx.saved_tensors
+ cstart, clen, crow, cptr = ctx.tables
+ need = ctx.needs_input_grad
+ if grad_y is None and grad_s is None:
+ return (None,) * 11
+ N = s.shape[-1]
+ need_dout = need[0] or need[1] or need[2] or need[3]
+ dout, dgate = None, None
+ if grad_y is not None:
+ G = grad_y if grad_y.is_contiguous() else grad_y.contiguous()
+ dout, dgate = _gate_backward(G.reshape(-1, N), _gate_bf16(gate), s.reshape(-1, N), cstart, clen, crow, cptr,
+ need_dout)
+ if grad_s is not None: # never in the block (s is discarded); autograd's bf16 accumulation
+ gs = grad_s.reshape(-1, N)
+ dout = gs if dout is None else dout + gs
+ attn2, sw2 = attn.reshape(-1, attn.shape[-1]), sw.reshape(-1, sw.shape[-1])
+ # MmBackward0 for mm(x2, W.t()) with a contiguous W: dX = G.mm(W); dW = G.t().mm(x2) (same calls, same cuBLAS kernels)
+ d_attn = dout.mm(wo).view(attn.shape) if need[0] else None
+ d_sw = dout.mm(w2).view(sw.shape) if need[1] else None
+ dwo = dout.t().mm(attn2) if need[2] else None
+ dw2 = dout.t().mm(sw2) if need[3] else None
+ dx = (grad_y if need[4] and grad_y is not None else None)
+ return d_attn, d_sw, dwo, dw2, dx, (dgate if need[5] else None), None, None, None, None, None
+
+
+_out_stage.register_autograd(_backward, setup_context=_setup_context)
+OP = torch.ops.flux.out_stage.default
+
+
+# ============================================================================================== block glue
+def applies(block: nn.Module, attn: Tensor, sw: Tensor, x_alias: Tensor, mod: mr.ModRows) -> bool:
+ """The op replaces the output stage only for bias-free bf16 CUDA linears on contiguous operands (else eager)."""
+ if block.attn_out.bias is not None or block.mlp_out.bias is not None:
+ return False
+ wo, w2 = block.attn_out.weight, block.mlp_out.weight
+ if not all(t.dtype == torch.bfloat16 for t in (attn, sw, x_alias, wo, w2)):
+ return False
+ if not (attn.is_cuda and attn.is_contiguous() and sw.is_contiguous() and x_alias.is_contiguous()
+ and wo.is_contiguous() and w2.is_contiguous()):
+ return False
+ if attn.shape != x_alias.shape or sw.shape[:-1] != attn.shape[:-1]:
+ return False
+ N = x_alias.shape[-1]
+ if N not in mr.SUPPORTED_N or wo.shape != (N, attn.shape[-1]) or w2.shape != (N, sw.shape[-1]):
+ return False
+ if torch.compiler.is_compiling() or nmg._forward_ad_active() or torch._C._functorch.is_functorch_wrapped_tensor(attn):
+ return False
+ return mod.gate.dim() == 2 and mod.gate.shape == (mod.plan.R, N) and mod.gate.stride(1) == 1 and mod.plan.L * N == x_alias.numel()
+
+
+def output_stage(block: nn.Module, attn: Tensor, mlp: Tensor, x_alias: Tensor, mod: mr.ModRows) -> Tensor:
+ """``x + gate[idx] * bf16(attn_out(attn) + mlp_out(mlp_act(mlp)))`` for a block without ``gate_proj``: the fused op
+ where :func:`applies`, otherwise the eager output stage of ``dit_mod_rows`` (same values either way)."""
+ import flux_action.models.transformer as T
+
+ attn = T._bf16_if_required(block.attn_out, attn)
+ sw = T._bf16_if_required(block.mlp_out, block.mlp_act(mlp))
+ if applies(block, attn, sw, x_alias, mod):
+ STATE.calls_fused += 1
+ plan = mod.plan
+ tab = plan.table(plan.gate_T)
+ y, _s = OP(attn, sw, block.attn_out.weight, block.mlp_out.weight, x_alias, mod.gate, plan.idx,
+ tab["start"], tab["len"], tab["row"], tab["ptr"])
+ return y
+ STATE.calls_eager += 1
+ o1 = block.attn_out(attn)
+ o2 = block.mlp_out(sw)
+ if mr.Config.fuse_output_add and o1.is_contiguous() and o2.is_contiguous():
+ return mr.gate_residual_rows(x_alias, mod, o1, o2)
+ return mr.gate_residual_rows(x_alias, mod, (o1 + o2).contiguous())
+
+
+def install(require_kernel: bool = True) -> State:
+ """Route the row-modulation block forwards' output stage through ``flux::out_stage``
+ (sets ``dit_mod_rows.Config.out_stage``; needs ``dit_mod_rows`` installed on the blocks)."""
+ if require_kernel and not torch.cuda.is_available():
+ raise RuntimeError("dit_out_stage needs CUDA (Triton gate kernels, cuBLAS epilogue)")
+ mr.Config.out_stage = True
+ return STATE
+
+
+def uninstall(state: State | None = None) -> None:
+ mr.Config.out_stage = False
diff --git a/flux-umi/src/flux_action/models/dit_qknorm_rope_fused.py b/flux-umi/src/flux_action/models/dit_qknorm_rope_fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..c43cbea79508d58bac1015fb8beb1ccd77c56f49
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_qknorm_rope_fused.py
@@ -0,0 +1,577 @@
+"""Fused Q/K RMSNorm + RoPE (forward and backward) in Triton for the G2 DiT (head_dim 128), bit-exact with the
+sequential production pair ``dit_qknorm_triton.rmsnorm_triton`` -> ``dit_rope_triton.apply_rope_triton`` (all
+outputs, including the dscale partial sums). Versus eager: ``out``/``dq``/``dk`` are bit-exact; ``dscale`` (the
+Q/K RMSNorm scale gradient) differs by fp32 summation order only (per-program partials instead of ATen's
+column-reduce tree), i.e. by at most 1 bf16 ulp after rounding -- see ``dit_qknorm_triton``.
+
+Campaign-3 kernel (experiment dit-qknorm-rope-fused); installed through the
+``transformer.qk_norm_rope`` seam by ``install()``.
+
+Why one kernel: the sequential pair writes the normalised q/k (bf16, 2 x 1.58 GB at L = 309376) and reads them back in
+the RoPE kernel; in backward the RoPE^T output makes the same round trip into the RMSNorm backward. The fused kernels
+keep those intermediates in registers and run q AND k in one launch (the 1 KB fp32 RoPE table row of a token is loaded
+once per tile and reused for both tensors and all heads of that token).
+
+Arithmetic (identical to the two production kernels, see their docstrings; everything with ``enable_fp_fusion=False``):
+
+ forward, per row of 128 (fp32 math unless stated)
+ s = sum_128(x * x) in torch 2.10 Reduce.cuh order: 32 lanes x 4 contiguous elements,
+ sequential per lane, then the 16,8,4,2,1 shuffle tree
+ rrms = rsqrt.approx(s * (1/128) + eps)
+ n = bf16(x * rrms)
+ y = bf16(fp32(n) * scale) <- the sequential pair's HBM intermediate (never written here)
+ out[2p] = bf16(f00 * y[2p] + f01 * y[2p+1]) f = freqs[l, p] (fp32 or bf16 table promoted exactly)
+ out[2p+1] = bf16(f10 * y[2p] + f11 * y[2p+1]) two fp32 products, one fp32 add, bf16 round
+ backward (g = incoming bf16 gradient of out)
+ gr[2p] = bf16(f00 * g[2p] + f10 * g[2p+1]) transposed rotation == dit_rope_triton backward
+ gr[2p+1] = bf16(f01 * g[2p] + f11 * g[2p+1]) <- the sequential pair's second HBM intermediate
+ gn = bf16(gr * scale); direct = gn * rrms; d_rrms = sum_128(gn * x) (ATen order)
+ dx = bf16(direct + ((-0.5 * d_rrms) * rrms^3 * (1/128)) * (2 * x))
+ dscale += bf16(gr * bf16(x * rrms)) fp32 per-program partials, identical grouping to
+ _qknorm_bwd_kernel (ROWS=2, ITERS=32: rows [64p, 64p+64)
+ accumulated in iteration order, acc[0] + acc[1]), then
+ the same ``part.sum(0).to(bf16)`` second stage
+ (not ATen's reduction tree: <= 1 bf16 ulp from eager)
+
+The ATen reduction order is obtained the way ``dit_qknorm_triton`` does it: the tile is ``[ROWS, 128]`` with
+``ROWS == num_warps`` so Triton maps one row to one warp (sizePerThread [1, 4]) and ``tl.sum(axis=1)`` reduces 4
+elements sequentially per lane followed by the xor butterfly 16..1. The RoPE pair arithmetic uses
+``reshape/split/join`` on the same tile (pairs live inside a lane's 4 elements), the per-row statistics are stored
+in token-major row order ``[B, L, H]`` like the production kernel. ``TREE=0`` selects the explicit
+layout-independent fold tree (``_aten_sum128``) as a fallback; the natural layout is verified bitwise by the tests.
+
+Layouts: q/k are the production token-major views ``[B, H, L, 128]`` (strides ``(., 128, H*128, 1)``) or any view with
+``stride(-1) == 1``, 16-byte aligned rows and no expanded (stride-0, size > 1) dim -- the two production contracts
+checked by ``unsupported_reason``; outputs and dq/dk are allocated with the inputs' strides (token-major for
+production, so cuDNN SDPA sees exactly what it sees today and the ViewBackward into the projection GEMM is a view).
+``DENSE=1`` (all tensors exactly token-major dense) replaces the per-row div/mod address arithmetic by ``r * 128``.
+The table is ``(B or 1, 1, L, 64, 2, 2)`` contiguous fp32/bf16, non-differentiable (``dit_rope_triton`` contract).
+
+Usage::
+
+ from dit_qknorm_rope_fused import qk_norm_rope, install
+ q, k = qk_norm_rope(q, k, pe, scale_q, scale_k) # == apply_rope_triton(*(rmsnorm_triton(.) for q, k), pe)
+ install(dit, require_kernel=True) # re-bind SingleStreamBlock / ModeBlock forwards
+"""
+from __future__ import annotations
+
+import types
+from typing import Optional
+
+import torch
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+
+from flux_action.models import dit_qknorm_triton as QN
+from flux_action.models import dit_rope_triton as RP
+from flux_action.models.dit_qknorm_triton import _aten_sum128 # explicit ATen fold tree (TREE=0 fallback)
+
+D = 128
+EPS = 1e-6
+# Forward: any grouping is exact (no cross-row sums); tuned by bench_isolated.py --sweep.
+FWD_ROWS, FWD_ITERS, FWD_WARPS = 2, 16, 2
+# Backward: fixed by the dscale partial-sum structure of dit_qknorm_triton._qknorm_bwd_kernel (64 rows per program).
+BWD_ROWS, BWD_ITERS, BWD_WARPS = QN.BWD_ROWS, QN.BWD_ITERS, QN.BWD_WARPS
+TREE = 1
+# EXACT=1: the RoPE products/sums (and the norm-backward mul+add) are emitted as explicit scalar ``mul.rn.f32`` /
+# ``add.rn.f32`` PTX. Without it LLVM packs the in-lane pairs into ``mul.rn.f32x2`` / ``add.rn.f32x2`` and the
+# CUDA 13.0 ptxas contracts those into FFMA2 on sm_103 *despite* ``--fmad=false`` (enable_fp_fusion=False), which
+# changes ~2.5e-5 of the bf16 outputs by 1 ulp at rounding ties with an fp32 table. ``dit_rope_triton`` uses the
+# same ``_mul_rn`` / ``_add_rn`` guard, so both kernels are bit-exact with eager for fp32 and bf16 tables.
+EXACT = 1
+
+
+class Config:
+ fwd = (FWD_ROWS, FWD_ITERS, FWD_WARPS)
+ fwd_kernel = "tok" # "tok": token-major schedule (table once per token); "rows": row-blocked schedule
+ fwd_tok = 1 # tokens per program for the token-major forward (sweep: 1 > 2 > 4)
+ tree = TREE
+ exact = EXACT
+ bwd_segmented = True
+
+
+@triton.jit
+def _mul_rn(a, b):
+ return tl.inline_asm_elementwise("mul.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, is_pure=True, pack=1)
+
+
+@triton.jit
+def _add_rn(a, b):
+ return tl.inline_asm_elementwise("add.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, is_pure=True, pack=1)
+
+
+@triton.jit
+def _rot(fa, xa, fb, xb, EXACT: tl.constexpr):
+ """fa*xa + fb*xb as two fp32 products and one fp32 add (ATen's separate kernels), never an FMA."""
+ if EXACT:
+ return _add_rn(_mul_rn(fa, xa), _mul_rn(fb, xb))
+ else:
+ return fa * xa + fb * xb
+
+
+# ------------------------------------------------------------------------------------------------ kernels
+@triton.jit
+def _offs(r, H, L, sb, sh, sl, DENSE: tl.constexpr):
+ """Token-major row r = (b*L + l)*H + h -> element offset (int64), batch and token index."""
+ h = r % H
+ bl = r // H
+ l = bl % L
+ b = bl // L
+ if DENSE:
+ off = r.to(tl.int64) * 128
+ else:
+ off = b.to(tl.int64) * sb + h.to(tl.int64) * sh + l.to(tl.int64) * sl
+ return off, b, l
+
+
+@triton.jit
+def _table_shared(f_ptr, sfb, b0, l0, valid):
+ """One token's table row [64 pairs, 2 (i), 2 (j)] -> f00, f01, f10, f11 as [1, 64] (broadcast over rows)."""
+ fidx = tl.arange(0, 256)
+ f = tl.load(f_ptr + b0.to(tl.int64) * sfb + l0.to(tl.int64) * 256 + fidx, mask=(fidx < 256) & valid, other=0.0).to(tl.float32)
+ fi0, fi1 = tl.split(tl.reshape(f, [64, 2, 2])) # j = 0 / j = 1 -> [64, 2]
+ f00, f10 = tl.split(fi0) # (i=0,j=0), (i=1,j=0)
+ f01, f11 = tl.split(fi1) # (i=0,j=1), (i=1,j=1)
+ return f00[None, :], f01[None, :], f10[None, :], f11[None, :]
+
+
+@triton.jit
+def _table_rows(f_ptr, sfb, b, l, rmask, ROWS: tl.constexpr):
+ """Per-row table rows -> f00, f01, f10, f11 as [ROWS, 64] (rows of a tile may belong to different tokens)."""
+ fidx = tl.arange(0, 256)
+ foff = (b.to(tl.int64) * sfb + l.to(tl.int64) * 256)[:, None] + fidx[None, :]
+ f = tl.load(f_ptr + foff, mask=rmask[:, None], other=0.0).to(tl.float32)
+ fi0, fi1 = tl.split(tl.reshape(f, [ROWS, 64, 2, 2]))
+ f00, f10 = tl.split(fi0)
+ f01, f11 = tl.split(fi1)
+ return f00, f01, f10, f11
+
+
+@triton.jit
+def _fwd_rows(x_ptr, o_ptr, rrms_ptr, scale, xoff, ooff, rr, rmask, col, f00, f01, f10, f11, eps,
+ ROWS: tl.constexpr, TREE: tl.constexpr, EXACT: tl.constexpr):
+ """RMSNorm (ATen order) -> bf16 -> * scale -> bf16 -> RoPE -> bf16 for a [ROWS, 128] tile; stores out and rrms."""
+ m = rmask[:, None]
+ x = tl.load(x_ptr + xoff[:, None] + col[None, :], mask=m, other=0.0).to(tl.float32)
+ if TREE == 1:
+ s = tl.sum(x * x, axis=1) # one warp per row: lane 4-sum + butterfly 16..1
+ else:
+ s = _aten_sum128(tl.reshape(x * x, [ROWS, 32, 4]), ROWS, 1)
+ mean = s * (1.0 / 128) # MeanOps::project (exact power-of-two factor)
+ rrms = tl.rsqrt(mean + eps) # rsqrt.approx == ATen ::rsqrt
+ n = (x * rrms[:, None]).to(tl.bfloat16) # (f * rrms).to(bf16)
+ y = (n.to(tl.float32) * scale[None, :]).to(tl.bfloat16).to(tl.float32) # bf16 * bf16 scale == RoPE input
+ y0, y1 = tl.split(tl.reshape(y, [ROWS, 64, 2])) # even / odd of each pair (in-lane)
+ o0 = _rot(f00, y0, f01, y1, EXACT) # mul, mul, add (never contracted)
+ o1 = _rot(f10, y0, f11, y1, EXACT)
+ o = tl.reshape(tl.join(o0, o1), [ROWS, 128]).to(tl.bfloat16)
+ tl.store(o_ptr + ooff[:, None] + col[None, :], o, mask=m)
+ # per-row statistic written from the tile layout (lane 0 of each row) -- no [ROWS] layout conversion
+ tl.store(rrms_ptr + rr[:, None] + 0 * col[None, :], tl.broadcast_to(rrms[:, None], [ROWS, 128]), mask=m & (col[None, :] == 0))
+
+
+@triton.jit
+def _bwd_rows(g_ptr, x_ptr, rrms_ptr, dx_ptr, scale, goff, xoff, doff, rr, rmask, col, f00, f01, f10, f11, acc,
+ ROWS: tl.constexpr, TREE: tl.constexpr, EXACT: tl.constexpr):
+ """RoPE^T (bf16 round) then the RMSNorm backward of _qknorm_bwd_kernel for a [ROWS, 128] tile; returns acc."""
+ m = rmask[:, None]
+ g = tl.load(g_ptr + goff[:, None] + col[None, :], mask=m, other=0.0).to(tl.float32)
+ g0, g1 = tl.split(tl.reshape(g, [ROWS, 64, 2]))
+ r0 = _rot(f00, g0, f10, g1, EXACT) # transposed rotation (dit_rope_triton TRANSPOSE)
+ r1 = _rot(f01, g0, f11, g1, EXACT)
+ gr = tl.reshape(tl.join(r0, r1), [ROWS, 128]).to(tl.bfloat16).to(tl.float32) # the RoPE-bwd bf16 output
+ x = tl.load(x_ptr + xoff[:, None] + col[None, :], mask=m, other=0.0).to(tl.float32)
+ rrms = tl.load(rrms_ptr + rr, mask=rmask, other=0.0) # [ROWS] (a stride-0 tile load changes the tile
+ rr2 = rrms[:, None] # layout and breaks the ATen reduction order)
+ gn = (gr * scale[None, :]).to(tl.bfloat16).to(tl.float32) # bf16 MulBackward0, then .float()
+ direct = gn * rr2 # grad of f in f * rrms
+ if TREE == 1:
+ d_rrms = tl.sum(gn * x, axis=1) # sum_to_size over the row (ATen order)
+ else:
+ d_rrms = _aten_sum128(tl.reshape(gn * x, [ROWS, 32, 4]), ROWS, 1)
+ cubed = (rrms * rrms) * rrms # result.pow(3)
+ d_mean = (-0.5 * d_rrms) * cubed # rsqrt_backward
+ rgs = d_mean * (1.0 / 128) # mean_backward (exact)
+ if EXACT: # pow_backward: grad * (2 * f), then the add
+ dx = _add_rn(direct, _mul_rn(rgs[:, None] + tl.zeros_like(x), 2.0 * x)).to(tl.bfloat16)
+ else:
+ dx = (direct + rgs[:, None] * (2.0 * x)).to(tl.bfloat16)
+ tl.store(dx_ptr + doff[:, None] + col[None, :], dx, mask=m)
+ n = (x * rr2).to(tl.bfloat16).to(tl.float32) # recomputed normalised (bitwise fwd)
+ sp = (gr * n).to(tl.bfloat16).to(tl.float32) # bf16 grad * normalised
+ acc += tl.where(m, sp, 0.0)
+ return acc
+
+
+@triton.jit
+def _fused_fwd_kernel(q_ptr, k_ptr, sq_ptr, sk_ptr, f_ptr, oq_ptr, ok_ptr, rq_ptr, rk_ptr, H, L, R, eps,
+ sqb, sqh, sql, skb, skh, skl, soqb, soqh, soql, sokb, sokh, sokl, sfb,
+ ROWS: tl.constexpr, ITERS: tl.constexpr, TREE: tl.constexpr, DENSE: tl.constexpr,
+ SHARED_F: tl.constexpr, EXACT: tl.constexpr):
+ pid = tl.program_id(0)
+ col = tl.arange(0, 128)
+ scale_q = tl.load(sq_ptr + col).to(tl.float32)
+ scale_k = tl.load(sk_ptr + col).to(tl.float32)
+ for it in range(ITERS):
+ r0 = (pid * ITERS + it) * ROWS
+ r = r0 + tl.arange(0, ROWS)
+ rmask = r < R
+ qoff, b, l = _offs(r, H, L, sqb, sqh, sql, DENSE)
+ koff, _, _ = _offs(r, H, L, skb, skh, skl, DENSE)
+ oqoff, _, _ = _offs(r, H, L, soqb, soqh, soql, DENSE)
+ okoff, _, _ = _offs(r, H, L, sokb, sokh, sokl, DENSE)
+ rr = r.to(tl.int64)
+ if SHARED_F: # H % ROWS == 0: the tile is one token
+ bl0 = r0 // H
+ f00, f01, f10, f11 = _table_shared(f_ptr, sfb, bl0 // L, bl0 % L, r0 < R)
+ else:
+ f00, f01, f10, f11 = _table_rows(f_ptr, sfb, b, l, rmask, ROWS)
+ _fwd_rows(q_ptr, oq_ptr, rq_ptr, scale_q, tl.multiple_of(qoff, 8), tl.multiple_of(oqoff, 8), rr, rmask, col,
+ f00, f01, f10, f11, eps, ROWS, TREE, EXACT)
+ _fwd_rows(k_ptr, ok_ptr, rk_ptr, scale_k, tl.multiple_of(koff, 8), tl.multiple_of(okoff, 8), rr, rmask, col,
+ f00, f01, f10, f11, eps, ROWS, TREE, EXACT)
+
+
+@triton.jit
+def _fused_fwd_tok_kernel(q_ptr, k_ptr, sq_ptr, sk_ptr, f_ptr, oq_ptr, ok_ptr, rq_ptr, rk_ptr, H, L, NT, eps,
+ sqb, sqh, sql, skb, skh, skl, soqb, soqh, soql, sokb, sokh, sokl, sfb,
+ ROWS: tl.constexpr, TOK: tl.constexpr, TREE: tl.constexpr, DENSE: tl.constexpr,
+ EXACT: tl.constexpr):
+ """Token-major forward: a program owns TOK consecutive tokens; the RoPE table row of a token is loaded (and
+ laid out) once and reused by the H/ROWS head tiles of q and k. Bit-identical to the row kernel (no
+ cross-row arithmetic in the forward); only the schedule differs."""
+ pid = tl.program_id(0)
+ col = tl.arange(0, 128)
+ hh = tl.arange(0, ROWS)
+ scale_q = tl.load(sq_ptr + col).to(tl.float32)
+ scale_k = tl.load(sk_ptr + col).to(tl.float32)
+ for t in range(TOK):
+ bl = pid * TOK + t # flattened (b, l) token index
+ valid = bl < NT
+ b0 = bl // L
+ l0 = bl % L
+ f00, f01, f10, f11 = _table_shared(f_ptr, sfb, b0, l0, valid)
+ for hc in range(0, H, ROWS):
+ h = hc + hh
+ rmask = (h < H) & valid
+ r = bl * H + h
+ qoff, _, _ = _offs(r, H, L, sqb, sqh, sql, DENSE)
+ koff, _, _ = _offs(r, H, L, skb, skh, skl, DENSE)
+ oqoff, _, _ = _offs(r, H, L, soqb, soqh, soql, DENSE)
+ okoff, _, _ = _offs(r, H, L, sokb, sokh, sokl, DENSE)
+ rr = r.to(tl.int64)
+ _fwd_rows(q_ptr, oq_ptr, rq_ptr, scale_q, tl.multiple_of(qoff, 8), tl.multiple_of(oqoff, 8), rr, rmask, col,
+ f00, f01, f10, f11, eps, ROWS, TREE, EXACT)
+ _fwd_rows(k_ptr, ok_ptr, rk_ptr, scale_k, tl.multiple_of(koff, 8), tl.multiple_of(okoff, 8), rr, rmask, col,
+ f00, f01, f10, f11, eps, ROWS, TREE, EXACT)
+
+
+@triton.jit
+def _fused_bwd_kernel(gq_ptr, gk_ptr, q_ptr, k_ptr, rq_ptr, rk_ptr, sq_ptr, sk_ptr, f_ptr, dq_ptr, dk_ptr,
+ pq_ptr, pk_ptr, H, L, R,
+ sgqb, sgqh, sgql, sgkb, sgkh, sgkl, sqb, sqh, sql, skb, skh, skl,
+ sdqb, sdqh, sdql, sdkb, sdkh, sdkl, sfb,
+ ROWS: tl.constexpr, ITERS: tl.constexpr, TREE: tl.constexpr, DENSE: tl.constexpr,
+ SHARED_F: tl.constexpr, EXACT: tl.constexpr, SEGMENTED: tl.constexpr, MAXSEG: tl.constexpr):
+ pid = tl.program_id(0)
+ col = tl.arange(0, 128)
+ scale_q = tl.load(sq_ptr + col).to(tl.float32)
+ scale_k = tl.load(sk_ptr + col).to(tl.float32)
+ acc_q = tl.zeros([ROWS, 128], tl.float32)
+ acc_k = tl.zeros([ROWS, 128], tl.float32)
+ if SEGMENTED:
+ # rows [pid*ROWS*ITERS, +ROWS*ITERS) in ascending ROWS-tiles exactly like the ITERS loop below, but grouped
+ # into token segments (tile-aligned because H % ROWS == 0 and the block start is a multiple of ROWS):
+ # the table row is loaded and laid out once per segment instead of once per tile.
+ r_end = tl.minimum((pid + 1) * ROWS * ITERS, R)
+ r_seg = pid * ROWS * ITERS
+ hh = tl.arange(0, ROWS)
+ for seg in range(MAXSEG):
+ bl = r_seg // H
+ seg_end = tl.minimum((bl + 1) * H, r_end)
+ f00, f01, f10, f11 = _table_shared(f_ptr, sfb, bl // L, bl % L, r_seg < r_end)
+ for rbase in range(r_seg, seg_end, ROWS):
+ r = rbase + hh
+ rmask = r < R
+ gqoff, _, _ = _offs(r, H, L, sgqb, sgqh, sgql, DENSE)
+ gkoff, _, _ = _offs(r, H, L, sgkb, sgkh, sgkl, DENSE)
+ qoff, _, _ = _offs(r, H, L, sqb, sqh, sql, DENSE)
+ koff, _, _ = _offs(r, H, L, skb, skh, skl, DENSE)
+ dqoff, _, _ = _offs(r, H, L, sdqb, sdqh, sdql, DENSE)
+ dkoff, _, _ = _offs(r, H, L, sdkb, sdkh, sdkl, DENSE)
+ rr = r.to(tl.int64)
+ acc_q = _bwd_rows(gq_ptr, q_ptr, rq_ptr, dq_ptr, scale_q, tl.multiple_of(gqoff, 8), tl.multiple_of(qoff, 8),
+ tl.multiple_of(dqoff, 8), rr, rmask, col, f00, f01, f10, f11, acc_q, ROWS, TREE, EXACT)
+ acc_k = _bwd_rows(gk_ptr, k_ptr, rk_ptr, dk_ptr, scale_k, tl.multiple_of(gkoff, 8), tl.multiple_of(koff, 8),
+ tl.multiple_of(dkoff, 8), rr, rmask, col, f00, f01, f10, f11, acc_k, ROWS, TREE, EXACT)
+ r_seg = seg_end
+ for it in range(ITERS * (1 - SEGMENTED)):
+ r0 = (pid * ITERS + it) * ROWS
+ r = r0 + tl.arange(0, ROWS)
+ rmask = r < R
+ gqoff, b, l = _offs(r, H, L, sgqb, sgqh, sgql, DENSE)
+ gkoff, _, _ = _offs(r, H, L, sgkb, sgkh, sgkl, DENSE)
+ qoff, _, _ = _offs(r, H, L, sqb, sqh, sql, DENSE)
+ koff, _, _ = _offs(r, H, L, skb, skh, skl, DENSE)
+ dqoff, _, _ = _offs(r, H, L, sdqb, sdqh, sdql, DENSE)
+ dkoff, _, _ = _offs(r, H, L, sdkb, sdkh, sdkl, DENSE)
+ rr = r.to(tl.int64)
+ if SHARED_F:
+ bl0 = r0 // H
+ f00, f01, f10, f11 = _table_shared(f_ptr, sfb, bl0 // L, bl0 % L, r0 < R)
+ else:
+ f00, f01, f10, f11 = _table_rows(f_ptr, sfb, b, l, rmask, ROWS)
+ acc_q = _bwd_rows(gq_ptr, q_ptr, rq_ptr, dq_ptr, scale_q, tl.multiple_of(gqoff, 8), tl.multiple_of(qoff, 8),
+ tl.multiple_of(dqoff, 8), rr, rmask, col, f00, f01, f10, f11, acc_q, ROWS, TREE, EXACT)
+ acc_k = _bwd_rows(gk_ptr, k_ptr, rk_ptr, dk_ptr, scale_k, tl.multiple_of(gkoff, 8), tl.multiple_of(koff, 8),
+ tl.multiple_of(dkoff, 8), rr, rmask, col, f00, f01, f10, f11, acc_k, ROWS, TREE, EXACT)
+ tl.store(pq_ptr + pid.to(tl.int64) * 128 + col, tl.sum(acc_q, axis=0))
+ tl.store(pk_ptr + pid.to(tl.int64) * 128 + col, tl.sum(acc_k, axis=0))
+
+
+# ------------------------------------------------------------------------------------------------- host
+def _s3(t: Tensor):
+ sb, sh, sl, _ = t.stride()
+ return sb, sh, sl
+
+
+def _is_token_major_dense(t: Tensor) -> bool:
+ B, H, L, _ = t.shape
+ s = t.stride()
+ ok = s[1] == 128 and s[2] == H * 128 and s[3] == 1
+ return ok and (B == 1 or s[0] == L * H * 128)
+
+
+def _rows_ok(t: Tensor) -> bool:
+ return t.stride(-1) == 1 and not any(s % 8 for s in t.stride()[:-1] if s != 0) and t.data_ptr() % 16 == 0
+
+
+def unsupported_reason(q: Tensor, k: Tensor, pe: Tensor, scale_q: Tensor, scale_k: Tensor) -> Optional[str]:
+ """Metadata-only contract check: both production contracts (QKNorm per tensor, RoPE for the pair) must hold."""
+ r = QN.unsupported_reason(q, scale_q)
+ if r is None:
+ r = QN.unsupported_reason(k, scale_k)
+ if r is None:
+ r = RP.unsupported_reason(q, k, pe)
+ if r is None and q.shape[1] * q.shape[2] * q.shape[0] // (BWD_ROWS * BWD_ITERS) + 1 > 2 ** 31 - 1:
+ r = "row count exceeds int32 grid arithmetic"
+ return r
+
+
+def _fwd(q: Tensor, k: Tensor, pe: Tensor, scale_q: Tensor, scale_k: Tensor, eps: float, *,
+ rows: int = None, iters: int = None, warps: int = None, tree: int = None, exact: int = None,
+ kernel: str = None, tok: int = None):
+ B, H, L, _ = q.shape
+ R = B * H * L
+ oq = torch.empty_strided(q.shape, q.stride(), dtype=q.dtype, device=q.device)
+ ok = torch.empty_strided(k.shape, k.stride(), dtype=k.dtype, device=k.device)
+ rq = torch.empty((B, L, H), dtype=torch.float32, device=q.device) # token-major row order like dit_qknorm_triton
+ rk = torch.empty((B, L, H), dtype=torch.float32, device=q.device)
+ rows, iters, warps = (rows or Config.fwd[0], iters or Config.fwd[1], warps or Config.fwd[2])
+ tree = Config.tree if tree is None else tree
+ exact = Config.exact if exact is None else exact
+ sfb = 0 if pe.shape[0] == 1 else pe.stride(0)
+ dense = all(_is_token_major_dense(t) for t in (q, k, oq, ok))
+ kernel = Config.fwd_kernel if kernel is None else kernel
+ if kernel == "tok":
+ tok = Config.fwd_tok if tok is None else tok
+ NT = B * L
+ _fused_fwd_tok_kernel[(triton.cdiv(NT, tok),)](q, k, scale_q, scale_k, pe, oq, ok, rq, rk, H, L, NT, float(eps),
+ *_s3(q), *_s3(k), *_s3(oq), *_s3(ok), sfb,
+ ROWS=rows, TOK=tok, TREE=tree, DENSE=dense, EXACT=exact,
+ num_warps=warps, enable_fp_fusion=False)
+ return oq, ok, rq, rk
+ grid = (triton.cdiv(R, rows * iters),)
+ _fused_fwd_kernel[grid](q, k, scale_q, scale_k, pe, oq, ok, rq, rk, H, L, R, float(eps),
+ *_s3(q), *_s3(k), *_s3(oq), *_s3(ok), sfb,
+ ROWS=rows, ITERS=iters, TREE=tree, DENSE=dense, SHARED_F=(H % rows == 0), EXACT=exact,
+ num_warps=warps, enable_fp_fusion=False)
+ return oq, ok, rq, rk
+
+
+def _bwd(gq: Tensor, gk: Tensor, q: Tensor, k: Tensor, rq: Tensor, rk: Tensor, scale_q: Tensor, scale_k: Tensor,
+ pe: Tensor, *, tree: int = None, exact: int = None, segmented: bool = None):
+ B, H, L, _ = q.shape
+ R = B * H * L
+ if not _rows_ok(gq):
+ gq = gq.contiguous()
+ if not _rows_ok(gk):
+ gk = gk.contiguous()
+ dq = torch.empty_strided(q.shape, q.stride(), dtype=q.dtype, device=q.device)
+ dk = torch.empty_strided(k.shape, k.stride(), dtype=k.dtype, device=k.device)
+ rows, iters, warps = BWD_ROWS, BWD_ITERS, BWD_WARPS
+ tree = Config.tree if tree is None else tree
+ exact = Config.exact if exact is None else exact
+ nprog = triton.cdiv(R, rows * iters)
+ pq = torch.empty((nprog, D), dtype=torch.float32, device=q.device)
+ pk = torch.empty((nprog, D), dtype=torch.float32, device=q.device)
+ sfb = 0 if pe.shape[0] == 1 else pe.stride(0)
+ dense = all(_is_token_major_dense(t) for t in (gq, gk, q, k, dq, dk))
+ segmented = Config.bwd_segmented if segmented is None else segmented
+ segmented = bool(segmented and H % rows == 0)
+ maxseg = (rows * iters + H - 1) // H + 1 if segmented else 1
+ _fused_bwd_kernel[(nprog,)](gq, gk, q, k, rq, rk, scale_q, scale_k, pe, dq, dk, pq, pk, H, L, R,
+ *_s3(gq), *_s3(gk), *_s3(q), *_s3(k), *_s3(dq), *_s3(dk), sfb,
+ ROWS=rows, ITERS=iters, TREE=tree, DENSE=dense, SHARED_F=(H % rows == 0), EXACT=exact,
+ SEGMENTED=int(segmented), MAXSEG=maxseg, num_warps=warps, enable_fp_fusion=False)
+ dsq = pq.sum(dim=0).to(scale_q.dtype) # same deterministic second stage as dit_qknorm_triton._bwd
+ dsk = pk.sum(dim=0).to(scale_k.dtype)
+ return dq, dk, dsq, dsk
+
+
+def sequential_reference(q: Tensor, k: Tensor, pe: Tensor, scale_q: Tensor, scale_k: Tensor, *, require_kernel=False):
+ """The production pair: Triton RMSNorm per tensor, then the paired token-major Triton RoPE."""
+ q = QN.rmsnorm_triton(q, scale_q, require_kernel=require_kernel)
+ k = QN.rmsnorm_triton(k, scale_k, require_kernel=require_kernel)
+ return RP.apply_rope_triton(q, k, pe, require_kernel=require_kernel)
+
+
+def eager_reference(q: Tensor, k: Tensor, pe: Tensor, scale_q: Tensor, scale_k: Tensor):
+ return RP.apply_rope_reference(QN.reference(q, scale_q), QN.reference(k, scale_k), pe)
+
+
+class _QKNormRope(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, q, k, pe, scale_q, scale_k, eps):
+ oq, ok, rq, rk = _fwd(q, k, pe, scale_q, scale_k, eps)
+ ctx.save_for_backward(q, k, pe, scale_q, scale_k, rq, rk)
+ ctx.eps = eps
+ ctx.set_materialize_grads(False)
+ return oq, ok
+
+ @staticmethod
+ def backward(ctx, gq, gk):
+ if gq is None and gk is None:
+ return None, None, None, None, None, None
+ q, k, pe, scale_q, scale_k, rq, rk = ctx.saved_tensors
+ if torch.is_grad_enabled(): # double backward: differentiable eager expression
+ with torch.enable_grad():
+ qq, kk = q.detach().requires_grad_(True), k.detach().requires_grad_(True)
+ sq, sk = scale_q.detach().requires_grad_(True), scale_k.detach().requires_grad_(True)
+ oq, ok = eager_reference(qq, kk, pe, sq, sk)
+ outs, grads = zip(*[(o, g) for o, g in ((oq, gq), (ok, gk)) if g is not None])
+ dq, dk, dsq, dsk = torch.autograd.grad(outs, (qq, kk, sq, sk), grads, create_graph=True, allow_unused=True)
+ return dq, dk, None, dsq, dsk, None
+ gq_ = gq if gq is not None else torch.zeros_like(q)
+ gk_ = gk if gk is not None else torch.zeros_like(k)
+ dq, dk, dsq, dsk = _bwd(gq_, gk_, q, k, rq, rk, scale_q, scale_k, pe)
+ needs = ctx.needs_input_grad
+ return ((dq if needs[0] and gq is not None else None), (dk if needs[1] and gk is not None else None), None,
+ (dsq if needs[3] and gq is not None else None), (dsk if needs[4] and gk is not None else None), None)
+
+
+def qk_norm_rope(q: Tensor, k: Tensor, pe: Tensor, scale_q: Tensor, scale_k: Tensor, eps: float = EPS, *,
+ require_kernel: bool = False) -> tuple[Tensor, Tensor]:
+ """``apply_rope(rmsnorm(q, scale_q), rmsnorm(k, scale_k), pe)`` in one forward / one backward kernel.
+
+ Inputs: q/k bf16 ``[B, H, L, 128]`` (production token-major views accepted as is), pe ``(B or 1, 1, L, 64, 2, 2)``
+ fp32/bf16 contiguous, scale bf16 ``[128]`` (the FSDP-cast parameter). Unsupported inputs run the sequential
+ production pair (which falls back to eager itself) unless ``require_kernel``.
+ """
+ reason = unsupported_reason(q, k, pe, scale_q, scale_k)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(f"fused QKNorm+RoPE contract not satisfied: {reason}")
+ return sequential_reference(q, k, pe, scale_q, scale_k)
+ return _QKNormRope.apply(q, k, pe, scale_q, scale_k, eps)
+
+
+# ------------------------------------------------------------------------------------------------ install
+class InstallState:
+ def __init__(self, require_kernel: bool):
+ self.require_kernel = require_kernel
+ self.enabled = True
+ self.calls_fused = 0
+ self.calls_seam = 0
+ self.prev = None
+
+
+def _fused_seam(norm, q, k, v, pe, *, _st: InstallState):
+ """``transformer.qk_norm_rope`` replacement: one fused call in training mode when the contract holds, otherwise
+ the block's own ``norm`` + ``transformer.apply_rope`` (whatever production installed)."""
+ import flux_action.models.transformer as T
+
+ if _st.enabled and norm.training:
+ sq, sk = norm.query_norm.scale, norm.key_norm.scale
+ reason = unsupported_reason(q, k, pe, sq, sk)
+ if reason is None:
+ _st.calls_fused += 1
+ return _QKNormRope.apply(q, k, pe, sq, sk, EPS)
+ if _st.require_kernel:
+ raise ValueError(f"fused QKNorm+RoPE contract not satisfied: {reason}")
+ _st.calls_seam += 1
+ q, k = norm(q, k, v)
+ return T.apply_rope(q, k, pe)
+
+
+def install(require_kernel: bool = False) -> InstallState:
+ """Route ``flux_action.models.transformer.qk_norm_rope`` (the norm+RoPE seam of every block forward: eager,
+ ``dit_norm_mod_gate`` and ``dit_mod_rows`` mirrors look it up at call time) to the fused kernel. No module or
+ parameter is touched (FSDP2 / checkpoint_wrapper unaffected); install after ``dit_qknorm_triton`` /
+ ``dit_rope_triton`` so they remain the fallback."""
+ import flux_action.models.transformer as T
+
+ st = InstallState(require_kernel)
+ st.prev = T.qk_norm_rope
+ T.qk_norm_rope = lambda norm, q, k, v, pe, _st=st: _fused_seam(norm, q, k, v, pe, _st=_st)
+ return st
+
+
+def uninstall(st: InstallState) -> None:
+ import flux_action.models.transformer as T
+
+ if st.prev is not None:
+ T.qk_norm_rope = st.prev
+ st.prev = None
+
+
+# ------------------------------------------------------------------------------------------------ self-test
+def self_test(L: int = 4834, H: int = 24, seed: int = 0, verbose: bool = True, pe_dtype=torch.float32) -> dict:
+ """Bitwise check of out/dq/dk/dscale vs the sequential production pair on token-major views (raises on failure)."""
+ from flux_action.models.dit_qknorm_triton import compare
+ from flux_action.models.transformer import rope
+
+ torch.manual_seed(seed)
+ dev = torch.device("cuda")
+ mk = lambda s: (torch.randn(1, L, H * D, device=dev) * s).to(torch.bfloat16)
+ bq, bk = mk(1.7), mk(1.3)
+ sq = (1.0 + 0.5 * torch.randn(D, device=dev)).to(torch.bfloat16)
+ sk = torch.linspace(-1.375, 2.625, D, device=dev).to(torch.bfloat16)
+ pos = torch.randint(0, 64, (1, L, 4), device=dev).float()
+ pe = torch.cat([rope(pos[..., i], 32, 10000) for i in range(4)], dim=-3).unsqueeze(1).to(pe_dtype).contiguous()
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ res = {}
+ for name, fn in (("eager", eager_reference), ("seq", lambda *a: sequential_reference(*a, require_kernel=True)),
+ ("fused", lambda *a: qk_norm_rope(*a, require_kernel=True))):
+ xq, xk = bq.clone().requires_grad_(True), bk.clone().requires_grad_(True)
+ s1, s2 = sq.clone().requires_grad_(True), sk.clone().requires_grad_(True)
+ oq, ok = fn(view(xq), view(xk), pe, s1, s2)
+ torch.manual_seed(seed + 1)
+ gq = (torch.randn_like(oq) * 1e-3).to(torch.bfloat16)
+ gk = (torch.randn_like(ok) * 1e-3).to(torch.bfloat16)
+ torch.autograd.backward((oq, ok), (gq, gk))
+ res[name] = dict(oq=oq, ok=ok, dq=xq.grad, dk=xk.grad, dsq=s1.grad, dsk=s2.grad, strides=tuple(oq.stride()))
+ keys = ("oq", "ok", "dq", "dk", "dsq", "dsk")
+ out = {key: compare(res["fused"][key], res["eager"][key]) for key in keys}
+ out["vs_seq"] = {key: compare(res["fused"][key], res["seq"][key]) for key in keys}
+ out["seq_vs_eager"] = {key: compare(res["seq"][key], res["eager"][key]) for key in keys}
+ out["strides_seq"], out["strides_fused"] = res["seq"]["strides"], res["fused"]["strides"]
+ if verbose:
+ for key in keys:
+ print(f" {key}: fused vs eager n_diff {out[key]['n_bits_differ']} | fused vs seq n_diff {out['vs_seq'][key]['n_bits_differ']}"
+ f" | seq vs eager n_diff {out['seq_vs_eager'][key]['n_bits_differ']} (max_abs {out['seq_vs_eager'][key]['max_abs']:.2e})")
+ for key in keys:
+ if key in ("dsq", "dsk"): # fp32 summation order: <= 1 bf16 ulp from eager (bitwise vs the sequential pair)
+ ulp = (res["fused"][key].view(torch.int16).int() - res["eager"][key].view(torch.int16).int()).abs().max()
+ assert int(ulp) <= 1 and out["vs_seq"][key]["n_bits_differ"] == 0, (key, out[key], out["vs_seq"][key])
+ else:
+ assert out[key]["n_bits_differ"] == 0, (key, out[key])
+ return out
+
+
+if __name__ == "__main__":
+ self_test()
+ self_test(L=4833, H=24, seed=1)
+ self_test(L=1023, H=7, seed=2, pe_dtype=torch.bfloat16)
+ print("self_test OK")
diff --git a/flux-umi/src/flux_action/models/dit_qknorm_triton.py b/flux-umi/src/flux_action/models/dit_qknorm_triton.py
new file mode 100644
index 0000000000000000000000000000000000000000..caff563d82b0a7d5d871257a7243e16834e99654
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_qknorm_triton.py
@@ -0,0 +1,391 @@
+"""Single-pass fused Q/K RMSNorm (forward + backward) in Triton for the G2 DiT (head_dim 128).
+
+Experiment dit-qknorm-layout. Replaces ``cute_qknorm_hybrid`` (4 CuTe pointwise launches + ATen
+mean/sum reductions, ~9.5 GB of fp32 intermediates per Q/K call) by ONE Triton kernel per direction.
+
+Eager semantics reproduced (``RMSNorm.forward`` in models/transformer.py, bf16 ``x`` and bf16 ``scale``)::
+
+ f = x.float()
+ rrms = torch.rsqrt(torch.mean(f**2, dim=-1, keepdim=True) + 1e-6)
+ out = (f * rrms).to(bf16) * scale # bf16(bf16(f*rrms) * scale)
+
+and its autograd chain (MulBackward0 through the bf16 cast, RsqrtBackward, MeanBackward, PowBackward)::
+
+ gn = bf16(g * scale) # bf16 mul of the output's MulBackward0
+ gnf = gn.float()
+ direct = gnf * rrms
+ d_rrms = sum_128(gnf * f) # fp32 row reduction
+ d_mean = (-0.5 * d_rrms) * ((rrms*rrms)*rrms) # ATen: -0.5 * grad * result.pow(3)
+ dx = bf16(direct + (d_mean / 128) * (2 * f))
+ dscale = bf16( sum_rows( bf16(g * bf16(f*rrms)) ) ) # fp32 accumulation, bf16 result like eager
+
+Arithmetic is bit-exact with eager (ATen) including the 128-element reduction order: torch 2.10's
+``Reduce.cuh`` vectorises the 128-wide fp32 row over 32 lanes x 4 contiguous elements (sequential per
+lane) and then uses a decreasing-offset shuffle tree (16, 8, 4, 2, 1). The kernel loads every row as a
+``[32, 4]`` tile (4 contiguous elements per thread) and reduces with ``tl.sum`` over the 4-element axis
+first (sequential in-thread) and then over the 32 lanes (xor butterfly 16..1 == the same tree), so the
+mean / sum match ATen bitwise (verified by ``aten_tree_probe.py`` and ``self_test``). ``rsqrt`` is the
+same MUFU approximation ATen uses. FMA contraction is disabled (``enable_fp_fusion=False``). The only
+non-bitwise quantity is ``dscale``: its 7.4M-term fp32 accumulation uses per-program partials and a
+deterministic second-stage sum instead of ATen's column-reduce tree, then rounds to bf16 like eager. The fp32
+sums differ from ATen's before rounding, so ``dscale`` differs from eager by at most 1 bf16 ulp (observed in
+~5-8 % of calls at production L; ``out``/``dx`` are always bit-identical). The result is deterministic.
+
+Layouts: inputs are the token-major views ``[B, H, L, 128]`` with strides ``(L*H*128, 128, H*128, 1)``
+produced by ``rearrange(proj(x), "B L (H D) -> B H L D")``; any strides with ``stride(-1) == 1``,
+16-byte aligned rows and no overlapping rows (an expanded dim -- stride 0 with size > 1 -- is rejected
+because the output and ``dx`` below would alias) are accepted directly (no ``.contiguous()``). The forward
+output and ``dx`` are written with the *input's* strides (token-major), so the ``rearrange`` ViewBackward
+into the projection GEMM is a view: this removes the 56 x 2.8 ms ``[1, L, 24, 128]`` transpose copies per step that the
+head-major ``dx`` of the hybrid causes. The incoming gradient may have any strides (the CuTe RoPE
+backward emits head-major contiguous gradients).
+
+Saved for backward: ``x`` (the GEMM output, bf16), ``scale`` and ``rrms`` (fp32, 4 B per row, [B, L, H] order) -- not the
+9.5 GB of fp32 ``f``/``normalized`` the hybrid keeps.
+
+Usage::
+
+ from qknorm_triton import rmsnorm_triton, install
+ y = rmsnorm_triton(x, scale) # drop-in for cute_qknorm_hybrid.rmsnorm_hybrid
+ install(dit) # monkeypatch every QKNorm RMSNorm instance
+ self_test() # exactness + fp64 accuracy report (GPU)
+
+Environment for Triton on sm_103a: TRITON_PTXAS_PATH=,
+CC/CXX= (set before the first launch).
+"""
+from __future__ import annotations
+
+import os
+import types
+from typing import Optional
+
+import torch
+from torch import Tensor, nn
+
+
+import triton # noqa: E402
+import triton.language as tl # noqa: E402
+
+D = 128
+D_C = tl.constexpr(128)
+EPS = 1e-6
+# Tuned on L20D (SM103): rows per program, tiles per program (backward), warps.
+FWD_ROWS, FWD_ITERS, FWD_WARPS = 2, 32, 2 # ROWS must equal num_warps (one row per warp); best of sweep
+BWD_ROWS, BWD_ITERS, BWD_WARPS = 2, 32, 2 # 64 rows per program -> 59 MB of fp32 dscale partials
+
+
+def reference(x: Tensor, scale: Tensor) -> Tensor:
+ """The original eager expression (models/transformer.py RMSNorm.forward)."""
+ dtype = x.dtype
+ x = x.float()
+ rrms = torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-6)
+ return (x * rrms).to(dtype=dtype) * scale
+
+
+# --------------------------------------------------------------------------------------- kernels
+@triton.jit
+def _row_offsets(r, H, L, sb, sh, sl):
+ """Token-major row enumeration r = (b*L + l)*H + h -> element offset (int64)."""
+ h = r % H
+ bl = r // H
+ l = bl % L
+ b = bl // L
+ off = b.to(tl.int64) * sb + h.to(tl.int64) * sh + l.to(tl.int64) * sl
+ rr = r.to(tl.int64) # row statistics are stored in this token-major row order ([B, L, H] contiguous)
+ return off, rr
+
+
+@triton.jit
+def _fold2(p, ROWS: tl.constexpr, N: tl.constexpr):
+ """[ROWS, 2N] -> [ROWS, N]: p[:, :N] + p[:, N:] (one shfl_down level of ATen's block_x_reduce)."""
+ a, b = tl.split(tl.permute(tl.reshape(p, [ROWS, 2, N]), (0, 2, 1)))
+ return a + b
+
+
+@triton.jit
+def _aten_sum128(v, ROWS: tl.constexpr, TREE: tl.constexpr):
+ """Sum of a [ROWS, 32, 4] fp32 tile over the last two axes in torch 2.10's Reduce.cuh order.
+
+ ATen (vectorize_input, input_vec_size 4, block_width 32): lane t accumulates its 4 contiguous
+ elements sequentially, then shfl_down offsets 16, 8, 4, 2, 1 (lane t += lane t+offset).
+ TREE=1: in-thread sequential 4-sum (tl.sum over a per-thread axis) + explicit fold tree == ATen bitwise.
+ TREE=0: natural tl.sum over both axes (layout-dependent tree; NOT ATen's order) -- for comparison only.
+ """
+ if TREE == 0:
+ return tl.sum(tl.sum(v, axis=2), axis=1)
+ p = tl.sum(v, axis=2) # [ROWS, 32]: ((x0 + x1) + x2) + x3 per lane
+ p = _fold2(p, ROWS, 16)
+ p = _fold2(p, ROWS, 8)
+ p = _fold2(p, ROWS, 4)
+ p = _fold2(p, ROWS, 2)
+ a, b = tl.split(tl.reshape(p, [ROWS, 1, 2]))
+ return tl.reshape(a + b, [ROWS])
+
+
+@triton.jit
+def _qknorm_fwd_kernel(x_ptr, scale_ptr, y_ptr, rrms_ptr, H, L, R,
+ sxb, sxh, sxl, syb, syh, syl,
+ ROWS: tl.constexpr, ITERS: tl.constexpr, TREE: tl.constexpr):
+ """ROWS == num_warps: Triton maps one 128-element row to one warp (32 lanes x 4 contiguous elements,
+ 8-byte vectors); ``tl.sum`` then reduces 4 elements sequentially per lane and xor-butterflies the
+ 32 lanes (16, 8, 4, 2, 1) == torch 2.10 Reduce.cuh's vectorised 128-wide reduction, bitwise."""
+ pid = tl.program_id(0)
+ col = tl.arange(0, 128)
+ scale = tl.load(scale_ptr + col).to(tl.float32)
+ for it in range(ITERS):
+ r = (pid * ITERS + it) * ROWS + tl.arange(0, ROWS)
+ rmask = r < R
+ xoff, rr = _row_offsets(r, H, L, sxb, sxh, sxl)
+ yoff, _ = _row_offsets(r, H, L, syb, syh, syl)
+ xoff = tl.multiple_of(xoff, 8)
+ yoff = tl.multiple_of(yoff, 8)
+ m = rmask[:, None]
+ x = tl.load(x_ptr + xoff[:, None] + col[None, :], mask=m, other=0.0).to(tl.float32)
+ if TREE == 1:
+ s = tl.sum(x * x, axis=1)
+ else: # explicit ATen fold tree (layout independent, slower)
+ s = _aten_sum128(tl.reshape(x * x, [ROWS, 32, 4]), ROWS, 1)
+ mean = s * (1.0 / 128) # MeanOps::project (exact power-of-two factor)
+ rrms = tl.rsqrt(mean + 1e-6) # rsqrt.approx == ATen's ::rsqrt (verified bitwise)
+ n = (x * rrms[:, None]).to(tl.bfloat16) # (f * rrms).to(bf16)
+ y = (n.to(tl.float32) * scale[None, :]).to(tl.bfloat16) # bf16 * bf16 scale
+ tl.store(y_ptr + yoff[:, None] + col[None, :], y, mask=m)
+ tl.store(rrms_ptr + rr, rrms, mask=rmask)
+
+
+@triton.jit
+def _qknorm_bwd_kernel(g_ptr, x_ptr, rrms_ptr, scale_ptr, dx_ptr, part_ptr, H, L, R,
+ sgb, sgh, sgl, sxb, sxh, sxl, sdb, sdh, sdl,
+ ROWS: tl.constexpr, ITERS: tl.constexpr, TREE: tl.constexpr):
+ pid = tl.program_id(0)
+ col = tl.arange(0, 128)
+ scale = tl.load(scale_ptr + col).to(tl.float32)
+ acc = tl.zeros([ROWS, 128], tl.float32)
+ for it in range(ITERS):
+ r = (pid * ITERS + it) * ROWS + tl.arange(0, ROWS)
+ rmask = r < R
+ goff, rr = _row_offsets(r, H, L, sgb, sgh, sgl)
+ xoff, _ = _row_offsets(r, H, L, sxb, sxh, sxl)
+ doff, _ = _row_offsets(r, H, L, sdb, sdh, sdl)
+ goff = tl.multiple_of(goff, 8)
+ xoff = tl.multiple_of(xoff, 8)
+ doff = tl.multiple_of(doff, 8)
+ rrms = tl.load(rrms_ptr + rr, mask=rmask, other=0.0)
+ m = rmask[:, None]
+ g = tl.load(g_ptr + goff[:, None] + col[None, :], mask=m, other=0.0).to(tl.float32)
+ x = tl.load(x_ptr + xoff[:, None] + col[None, :], mask=m, other=0.0).to(tl.float32)
+ gn = (g * scale[None, :]).to(tl.bfloat16).to(tl.float32) # bf16 MulBackward0, then .float()
+ rr2 = rrms[:, None]
+ direct = gn * rr2 # grad of f in f * rrms
+ if TREE == 1:
+ d_rrms = tl.sum(gn * x, axis=1) # sum_to_size over the row (ATen order)
+ else:
+ d_rrms = _aten_sum128(tl.reshape(gn * x, [ROWS, 32, 4]), ROWS, 1)
+ cubed = (rrms * rrms) * rrms # result.pow(3) == x*x*x
+ d_mean = (-0.5 * d_rrms) * cubed # rsqrt_backward
+ rgs = d_mean * (1.0 / 128) # mean_backward: / 128 (exact)
+ dx = (direct + rgs[:, None] * (2.0 * x)).to(tl.bfloat16) # pow_backward: grad * (2 * f)
+ tl.store(dx_ptr + doff[:, None] + col[None, :], dx, mask=m)
+ n = (x * rr2).to(tl.bfloat16).to(tl.float32) # recomputed normalized (bitwise fwd)
+ sp = (g * n).to(tl.bfloat16).to(tl.float32) # bf16 grad * normalized
+ acc += tl.where(m, sp, 0.0)
+ tl.store(part_ptr + pid.to(tl.int64) * D_C + col, tl.sum(acc, axis=0))
+
+
+# ---------------------------------------------------------------------------------------- host
+def _strides3(t: Tensor) -> tuple[int, int, int]:
+ sb, sh, sl, _ = t.stride()
+ return sb, sh, sl
+
+
+def unsupported_reason(x: Tensor, scale: Tensor) -> Optional[str]:
+ """Metadata-only contract check (no CUDA work)."""
+ if torch.compiler.is_compiling():
+ return "torch.compile uses the original expression"
+ if torch._C._are_functorch_transforms_active() or torch.autograd.forward_ad._current_level >= 0:
+ return "functional transforms / forward AD use the original expression"
+ if type(x) is not Tensor or type(scale) not in (Tensor, nn.Parameter):
+ return "tensor subclasses use the original expression"
+ if not x.is_cuda or scale.device != x.device:
+ return "same-device CUDA tensors required"
+ if x.dtype != torch.bfloat16 or scale.dtype != torch.bfloat16:
+ return "activation and (FSDP-cast) scale must both be bf16"
+ if x.ndim != 4 or x.shape[-1] != D or any(n < 1 for n in x.shape):
+ return "expected nonempty (B, H, L, 128) activation"
+ if x.stride(-1) != 1 or any(s % 8 for s in x.stride()[:-1] if s != 0):
+ return "rows must be contiguous and 16-byte aligned"
+ if any(s == 0 and n > 1 for s, n in zip(x.stride()[:-1], x.shape[:-1])):
+ return "expanded (stride-0) dims alias rows of the output / dx" # empty_strided(x.shape, x.stride()) below
+ if x.data_ptr() % 16 or scale.data_ptr() % 16:
+ return "16-byte aligned base addresses required"
+ if scale.shape != (D,) or scale.stride() != (1,):
+ return "scale must be a contiguous 128-element tensor"
+ if x.numel() // D > 2 ** 31 - 1:
+ return "row count exceeds int32 grid arithmetic"
+ return None
+
+
+def _dense_like(x: Tensor, dtype: torch.dtype) -> Tensor:
+ """New tensor with x's shape and strides (token-major for the production views)."""
+ return torch.empty_strided(x.shape, x.stride(), dtype=dtype, device=x.device)
+
+
+def _fwd(x: Tensor, scale: Tensor, *, tree: int = 1, rows: int = None, iters: int = None, warps: int = None):
+ B, H, L, _ = x.shape
+ R = B * H * L
+ y = _dense_like(x, x.dtype)
+ rrms = torch.empty((B, L, H), dtype=torch.float32, device=x.device) # token-major row order (contiguous writes)
+ rows, iters, warps = rows or FWD_ROWS, iters or FWD_ITERS, warps or FWD_WARPS
+ grid = (triton.cdiv(R, rows * iters),)
+ _qknorm_fwd_kernel[grid](x, scale, y, rrms, H, L, R, *_strides3(x), *_strides3(y),
+ ROWS=rows, ITERS=iters, TREE=tree, num_warps=warps, enable_fp_fusion=False)
+ return y, rrms
+
+
+def _bwd(g: Tensor, x: Tensor, rrms: Tensor, scale: Tensor, *, tree: int = 1, rows: int = None, iters: int = None, warps: int = None):
+ B, H, L, _ = x.shape
+ R = B * H * L
+ if g.stride(-1) != 1 or any(s % 8 for s in g.stride()[:-1] if s != 0) or g.data_ptr() % 16:
+ g = g.contiguous()
+ dx = _dense_like(x, x.dtype)
+ rows, iters, warps = rows or BWD_ROWS, iters or BWD_ITERS, warps or BWD_WARPS
+ nprog = triton.cdiv(R, rows * iters)
+ part = torch.empty((nprog, D), dtype=torch.float32, device=x.device)
+ _qknorm_bwd_kernel[(nprog,)](g, x, rrms, scale, dx, part, H, L, R,
+ *_strides3(g), *_strides3(x), *_strides3(dx),
+ ROWS=rows, ITERS=iters, TREE=tree, num_warps=warps, enable_fp_fusion=False)
+ dscale = part.sum(dim=0).to(scale.dtype) # deterministic second stage (fixed shape -> fixed ATen order)
+ return dx, dscale
+
+
+class _TritonRMSNorm(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, scale):
+ y, rrms = _fwd(x, scale)
+ ctx.save_for_backward(x, scale, rrms)
+ ctx.set_materialize_grads(False)
+ return y
+
+ @staticmethod
+ def backward(ctx, g):
+ if g is None:
+ return None, None
+ x, scale, rrms = ctx.saved_tensors
+ if torch.is_grad_enabled(): # double backward: fall back to the differentiable expression
+ with torch.enable_grad():
+ xx = x.detach().requires_grad_(True)
+ ss = scale.detach().requires_grad_(True)
+ out = reference(xx, ss)
+ dx, ds = torch.autograd.grad(out, (xx, ss), g, create_graph=True)
+ return dx, ds
+ dx, dscale = _bwd(g, x, rrms, scale)
+ needs = ctx.needs_input_grad
+ return (dx if needs[0] else None), (dscale if needs[1] else None)
+
+
+def rmsnorm_triton(x: Tensor, scale: Tensor, *, require_kernel: bool = False) -> Tensor:
+ """Drop-in for ``cute_qknorm_hybrid.rmsnorm_hybrid``; unsupported inputs use the eager expression."""
+ reason = unsupported_reason(x, scale)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(f"Triton QKNorm contract not satisfied: {reason}")
+ return reference(x, scale)
+ return _TritonRMSNorm.apply(x, scale)
+
+
+def _patched_forward(self, x, *, require_kernel):
+ if self.training and x.is_cuda:
+ return rmsnorm_triton(x, self.scale, require_kernel=require_kernel)
+ return reference(x, self.scale)
+
+
+def install(root: nn.Module, *, require_kernel: bool = False) -> list[str]:
+ """Monkeypatch the ``forward`` of every Q/K ``RMSNorm`` instance under ``root`` (DiT or a block).
+
+ Module / parameter / hook identity is retained (FSDP and checkpoint wrappers keep working); the
+ bf16 FSDP-cast ``self.scale`` is read at call time. Returns the patched module names.
+ """
+ from flux_action.models.transformer import QKNorm, RMSNorm # local import: no side effects at import
+
+ patched = []
+ for name, mod in root.named_modules():
+ if type(mod) is QKNorm:
+ for sub in ("query_norm", "key_norm"):
+ layer = getattr(mod, sub)
+ if type(layer) is RMSNorm:
+ layer.forward = types.MethodType(
+ lambda self, x, _rk=require_kernel: _patched_forward(self, x, require_kernel=_rk), layer)
+ patched.append(f"{name}.{sub}".replace("._checkpoint_wrapped_module", ""))
+ return patched
+
+
+def uninstall(root: nn.Module) -> int:
+ n = 0
+ for _, mod in root.named_modules():
+ if "forward" in mod.__dict__:
+ del mod.__dict__["forward"]
+ n += 1
+ return n
+
+
+# ----------------------------------------------------------------------------------- self test
+def compare(a: Tensor, b: Tensor) -> dict:
+ """max abs / rel L2 / bitwise fraction (a vs b); also counts sign-of-zero-only and value differences."""
+ a32, b32 = a.float(), b.float()
+ diff = (a32 - b32).abs()
+ res = {"max_abs": diff.max().item(), "rel_l2": (diff.norm() / b32.norm().clamp_min(1e-30)).item()}
+ if a.dtype == b.dtype:
+ it = torch.int16 if a.dtype == torch.bfloat16 else torch.int32
+ neq = a.contiguous().view(it) != b.contiguous().view(it)
+ res["bitwise"] = 1.0 - neq.float().mean().item()
+ res["n_bits_differ"] = int(neq.sum().item())
+ res["n_values_differ"] = int((diff > 0).sum().item()) # bits differ but value equal == signed zero
+ else:
+ res["bitwise"] = float("nan")
+ return res
+
+
+def self_test(L: int = 4834, H: int = 24, seed: int = 0, verbose: bool = True) -> dict:
+ """Exactness vs eager autograd on token-major views (out, dx bit-exact; dscale within 1 bf16 ulp: fp32 partial-sum
+ order) + fp64 accuracy; raises on failure."""
+ torch.manual_seed(seed)
+ dev = torch.device("cuda")
+ base = (torch.randn(1, L, H * D, device=dev) * 1.7).to(torch.bfloat16)
+ scale = (1.0 + 0.5 * torch.randn(D, device=dev)).to(torch.bfloat16)
+ x_ref = base.clone().requires_grad_(True)
+ x_new = base.clone().requires_grad_(True)
+ s_ref = scale.clone().requires_grad_(True)
+ s_new = scale.clone().requires_grad_(True)
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ out_ref = reference(view(x_ref), s_ref)
+ out_new = rmsnorm_triton(view(x_new), s_new, require_kernel=True)
+ g = (torch.randn_like(out_ref) * 1e-3).to(torch.bfloat16).contiguous() # head-major grad like CuTe RoPE bwd
+ out_ref.backward(g)
+ out_new.backward(g)
+ res = {"out": compare(out_new, out_ref), "dx": compare(x_new.grad, x_ref.grad),
+ "dscale": compare(s_new.grad, s_ref.grad),
+ "out_strides": tuple(out_new.stride()), "in_strides": tuple(view(x_new).stride())}
+ # fp64 reference from the same bf16 inputs
+ xd = view(base).double()
+ sd = scale.double()
+ xd.requires_grad_(True); sd.requires_grad_(True)
+ rr = torch.rsqrt(torch.mean(xd ** 2, -1, keepdim=True) + 1e-6)
+ od = (xd * rr) * sd
+ od.backward(g.double())
+ for k, (ref, new) in {"out": (out_ref, out_new), "dx": (x_ref.grad, x_new.grad)}.items():
+ tgt = od if k == "out" else xd.grad.permute(0, 2, 1, 3).reshape(1, L, H * D)
+ res[f"{k}_vs_fp64_eager"] = (ref.double() - tgt).abs().max().item()
+ res[f"{k}_vs_fp64_triton"] = (new.double() - tgt).abs().max().item()
+ res["dscale_vs_fp64_eager"] = (s_ref.grad.double() - sd.grad).abs().max().item()
+ res["dscale_vs_fp64_triton"] = (s_new.grad.double() - sd.grad).abs().max().item()
+ if verbose:
+ for k, v in res.items():
+ print(f" {k}: {v}")
+ assert res["out"]["bitwise"] == 1.0, res["out"]
+ assert res["dx"]["bitwise"] == 1.0, res["dx"]
+ assert res["dscale"]["rel_l2"] < 1e-2, res["dscale"]
+ return res
+
+
+if __name__ == "__main__":
+ self_test()
diff --git a/flux-umi/src/flux_action/models/dit_rope_triton.py b/flux-umi/src/flux_action/models/dit_rope_triton.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8cec08b02b1c7751a4f5acaef6f88ee61d87a0e
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_rope_triton.py
@@ -0,0 +1,223 @@
+"""Token-major Triton RoPE (forward + backward) for the G2 DiT, bit-exact with the eager ``apply_rope``.
+
+Experiment dit-qknorm-layout (B). Eager (models/transformer.py)::
+
+ xq_ = xq.float().reshape(..., 64, 1, 2)
+ out = freqs[..., 0] * xq_[..., 0] + freqs[..., 1] * xq_[..., 1] # two fp32 multiplies + one fp32 add
+ return out.reshape(xq.shape).type_as(xq) # bf16 round
+
+i.e. ``y[2p] = f00*x[2p] + f01*x[2p+1]``, ``y[2p+1] = f10*x[2p] + f11*x[2p+1]`` with ``f = freqs[l, p]``
+(bf16 or fp32 table, promoted to fp32 exactly). Backward (MulBackward0 + sum over the pair axis) is the
+transpose: ``dx[2p] = f00*g[2p] + f10*g[2p+1]``, ``dx[2p+1] = f01*g[2p] + f11*g[2p+1]``. Kernels run with
+``enable_fp_fusion=False`` so the products are rounded before the add exactly like ATen's separate kernels.
+
+Layout: q/k are consumed with arbitrary strides (``stride(-1) == 1``, no stride-0 dim of size > 1: the
+outputs would alias); the outputs (forward AND backward) are allocated with the *input's* strides, i.e. token-major ``(L*H*128, 128, H*128, 1)`` for the production
+views, so cuDNN SDPA receives the BSHD layout it already gets today and the gradient handed to the QKNorm
+backward is token-major too (the CuTe kernel writes head-major gradients in backward). One program handles
+one token for both Q and K (24 heads each, 3 chunks of 8 heads x 128 = 16-byte vectors) and loads the
+512-byte table row once.
+
+Usage::
+
+ from rope_triton import apply_rope_triton, install
+ q, k = apply_rope_triton(q, k, pe) # drop-in for transformer.apply_rope / cute_rope.apply_rope_cute
+ install() # patch flux_action.models.transformer.apply_rope (module-level)
+"""
+from __future__ import annotations
+
+import os
+from typing import Optional
+
+import torch
+from torch import Tensor
+
+
+import triton # noqa: E402
+import triton.language as tl # noqa: E402
+
+D = 128
+HB = 8 # heads per chunk: 8 x 128 bf16 = 2 KB == 128 threads x 16 bytes
+NUM_WARPS = 4
+
+
+def apply_rope_reference(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
+
+
+@triton.jit
+def _mul_rn(a, b):
+ return tl.inline_asm_elementwise("mul.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, is_pure=True, pack=1)
+
+
+@triton.jit
+def _add_rn(a, b):
+ return tl.inline_asm_elementwise("add.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype=tl.float32, is_pure=True, pack=1)
+
+
+@triton.jit
+def _rotate_rows(x_ptr, o_ptr, off, hm, col, f00, f01, f10, f11, HB: tl.constexpr):
+ x = tl.load(x_ptr + off[:, None] + col[None, :], mask=hm[:, None], other=0.0).to(tl.float32) # [HB, 128]
+ x0, x1 = tl.split(tl.reshape(x, [HB, 64, 2])) # even / odd
+ # mul, mul, add as explicit scalar .rn PTX: with plain ``*``/``+`` LLVM packs the pairs into f32x2 ops which the
+ # CUDA 13 ptxas contracts into FFMA2 despite --fmad=false (1-ulp bf16 deviations at rounding ties, fp32 tables).
+ y0 = _add_rn(_mul_rn(f00[None, :], x0), _mul_rn(f01[None, :], x1))
+ y1 = _add_rn(_mul_rn(f10[None, :], x0), _mul_rn(f11[None, :], x1))
+ y = tl.reshape(tl.join(y0, y1), [HB, 128]).to(tl.bfloat16)
+ tl.store(o_ptr + off[:, None] + col[None, :], y, mask=hm[:, None])
+
+
+@triton.jit
+def _rope_kernel(q_ptr, k_ptr, f_ptr, oq_ptr, ok_ptr, H, L,
+ sqb, sqh, sql, skb, skh, skl, sfb,
+ soqb, soqh, soql, sokb, sokh, sokl,
+ HB: tl.constexpr, TRANSPOSE: tl.constexpr, HAS_K: tl.constexpr):
+ l = tl.program_id(0).to(tl.int64)
+ b = tl.program_id(1).to(tl.int64)
+ fidx = tl.arange(0, 256)
+ f = tl.load(f_ptr + b * sfb + l * 256 + fidx).to(tl.float32) # [64 pairs, 2 (i), 2 (j)] contiguous
+ fi0, fi1 = tl.split(tl.reshape(f, [64, 2, 2])) # j = 0 / j = 1
+ f00, f10 = tl.split(fi0) # (i=0,j=0), (i=1,j=0)
+ f01, f11 = tl.split(fi1) # (i=0,j=1), (i=1,j=1)
+ if TRANSPOSE:
+ f01, f10 = f10, f01
+ col = tl.arange(0, 128)
+ for hc in range(0, H, HB):
+ h = hc + tl.arange(0, HB)
+ hm = h < H
+ qoff = tl.multiple_of(b * sqb + l * sql + h.to(tl.int64) * sqh, 8)
+ oqoff = tl.multiple_of(b * soqb + l * soql + h.to(tl.int64) * soqh, 8)
+ _rotate_rows(q_ptr, oq_ptr, qoff, hm, col, f00, f01, f10, f11, HB)
+ if HAS_K:
+ koff = tl.multiple_of(b * skb + l * skl + h.to(tl.int64) * skh, 8)
+ okoff = tl.multiple_of(b * sokb + l * sokl + h.to(tl.int64) * sokh, 8)
+ _rotate_rows(k_ptr, ok_ptr, koff, hm, col, f00, f01, f10, f11, HB)
+ # NOTE: when both Q and K share one output layout the two stores of a chunk are independent.
+
+
+def _s3(t: Tensor):
+ sb, sh, sl, _ = t.stride()
+ return sb, sh, sl
+
+
+def unsupported_reason(xq: Tensor, xk: Optional[Tensor], freqs: Tensor) -> Optional[str]:
+ if torch.compiler.is_compiling():
+ return "torch.compile uses the eager expression"
+ if type(xq) is not Tensor or type(freqs) is not Tensor or (xk is not None and type(xk) is not Tensor):
+ return "tensor subclasses use the eager expression"
+ if not xq.is_cuda or not freqs.is_cuda or (xk is not None and not xk.is_cuda):
+ return "CUDA tensors required"
+ if xq.ndim != 4 or xq.shape[-1] != D or any(n < 1 for n in xq.shape):
+ return "Q/K must be (B, H, L, 128)"
+ if xq.dtype != torch.bfloat16:
+ return "bf16 Q/K required"
+ if freqs.dtype not in (torch.bfloat16, torch.float32) or freqs.requires_grad:
+ return "table must be a non-differentiable bf16/fp32 tensor"
+ B, Hh, L, _ = xq.shape
+ if freqs.ndim != 6 or tuple(freqs.shape[1:]) != (1, L, 64, 2, 2) or freqs.shape[0] not in (1, B) or not freqs.is_contiguous():
+ return "table must be contiguous (B or 1, 1, L, 64, 2, 2)"
+ for v in (xq, xk):
+ if v is None:
+ continue
+ if v.shape != xq.shape or v.dtype != xq.dtype or v.device != xq.device:
+ return "Q/K shape/dtype/device must match"
+ if v.stride(-1) != 1 or any(s % 8 for s in v.stride()[:-1] if s != 0) or v.data_ptr() % 16:
+ return "rows must be contiguous and 16-byte aligned"
+ if any(s == 0 and n > 1 for s, n in zip(v.stride()[:-1], v.shape[:-1])):
+ return "expanded (stride-0) dims alias rows of the output" # outputs use the input's strides (_rotate)
+ if L > 2 ** 31 - 1 or B > 65535:
+ return "grid limits"
+ return None
+
+
+def _rotate(xq: Tensor, xk: Optional[Tensor], freqs: Tensor, transpose: bool):
+ B, H, L, _ = xq.shape
+ oq = torch.empty_strided(xq.shape, xq.stride(), dtype=xq.dtype, device=xq.device)
+ ok = torch.empty_strided(xk.shape, xk.stride(), dtype=xk.dtype, device=xk.device) if xk is not None else None
+ sfb = 0 if freqs.shape[0] == 1 else freqs.stride(0)
+ kk = xk if xk is not None else xq
+ okk = ok if ok is not None else oq
+ _rope_kernel[(L, B)](xq, kk, freqs, oq, okk, H, L, *_s3(xq), *_s3(kk), sfb, *_s3(oq), *_s3(okk),
+ HB=HB, TRANSPOSE=transpose, HAS_K=xk is not None, num_warps=NUM_WARPS, enable_fp_fusion=False)
+ return oq, ok
+
+
+class _RopeTriton(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, xq, xk, freqs):
+ ctx.set_materialize_grads(False)
+ ctx.save_for_backward(freqs)
+ ctx.dtype = xq.dtype
+ return _rotate(xq, xk, freqs, transpose=False)
+
+ @staticmethod
+ def backward(ctx, gq, gk):
+ (freqs,) = ctx.saved_tensors
+ gq = gq if ctx.needs_input_grad[0] else None
+ gk = gk if ctx.needs_input_grad[1] else None
+ if gq is None and gk is None:
+ return None, None, None
+ first, second = (gq, gk) if gq is not None else (gk, None)
+ if torch.is_grad_enabled() or unsupported_reason(first, second, freqs) is not None:
+ from flux_action.models.cute_rope import transpose_reference
+ dq = transpose_reference(gq, freqs, ctx.dtype) if gq is not None else None
+ dk = transpose_reference(gk, freqs, ctx.dtype) if gk is not None else None
+ return dq, dk, None
+ o1, o2 = _rotate(first, second, freqs, transpose=True)
+ return (o1, o2, None) if gq is not None else (None, o1, None)
+
+
+def apply_rope_triton(xq: Tensor, xk: Tensor, freqs: Tensor, *, require_kernel: bool = False):
+ reason = unsupported_reason(xq, xk, freqs)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(f"Triton RoPE contract not satisfied: {reason}")
+ return apply_rope_reference(xq, xk, freqs)
+ return _RopeTriton.apply(xq, xk, freqs)
+
+
+def install(*, require_kernel: bool = False):
+ """Route ``flux_action.models.transformer.apply_rope`` to the Triton kernel (blocks call the module global)."""
+ import flux_action.models.transformer as tr
+ tr._CUTE_ROPE_ENABLED = False
+ tr.apply_rope = lambda xq, xk, pe, _rk=require_kernel: apply_rope_triton(xq, xk, pe, require_kernel=_rk)
+ return tr.apply_rope
+
+
+def self_test(L: int = 4834, H: int = 24, seed: int = 0, verbose: bool = True) -> dict:
+ from flux_action.models.transformer import rope
+ import sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from .dit_qknorm_triton import compare
+ torch.manual_seed(seed)
+ dev = torch.device("cuda")
+ mk = lambda: (torch.randn(1, L, H * D, device=dev) * 1.3).to(torch.bfloat16)
+ bq, bk = mk(), mk()
+ pos = torch.randint(0, 64, (1, L, 4), device=dev).float()
+ pe = torch.cat([rope(pos[..., i], 32, 10000) for i in range(4)], dim=-3).unsqueeze(1).to(torch.bfloat16)
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ res = {}
+ for name, fn in (("eager", apply_rope_reference), ("triton", lambda a, b, c: apply_rope_triton(a, b, c, require_kernel=True))):
+ xq = bq.clone().requires_grad_(True); xk = bk.clone().requires_grad_(True)
+ oq, ok = fn(view(xq), view(xk), pe)
+ torch.manual_seed(seed + 1)
+ gq = (torch.randn_like(oq) * 1e-3).to(torch.bfloat16); gk = (torch.randn_like(ok) * 1e-3).to(torch.bfloat16)
+ (oq.float().mul(gq.float()).sum() + ok.float().mul(gk.float()).sum()).backward() if False else torch.autograd.backward((oq, ok), (gq, gk))
+ res[name] = (oq, ok, xq.grad, xk.grad, tuple(oq.stride()))
+ out = {"oq": compare(res["triton"][0], res["eager"][0]), "ok": compare(res["triton"][1], res["eager"][1]),
+ "dq": compare(res["triton"][2], res["eager"][2]), "dk": compare(res["triton"][3], res["eager"][3]),
+ "strides_eager": res["eager"][4], "strides_triton": res["triton"][4]}
+ if verbose:
+ for k, v in out.items():
+ print(f" {k}: {v}")
+ for k in ("oq", "ok", "dq", "dk"):
+ assert out[k]["n_values_differ"] == 0, (k, out[k])
+ return out
+
+
+if __name__ == "__main__":
+ self_test()
diff --git a/flux-umi/src/flux_action/models/dit_swiglu_fused.py b/flux-umi/src/flux_action/models/dit_swiglu_fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f1641cc2b362299811ed2b183d47fe0ffd69ed5
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_swiglu_fused.py
@@ -0,0 +1,448 @@
+"""Bit-exact fused SwiGLU (forward + backward) Triton kernels for the DiT MLP activation.
+
+Experiment dit-swiglu-fused. Nothing under src/flux_action is modified;
+``install(module)`` monkeypatches ``forward`` on ``SiLUActivation`` *instances*; ``swiglu_fused(x)`` is a
+drop-in for ``SiLUActivation.forward`` / ``swiglu_native_out.swiglu_native_out``.
+
+Reference semantics (transformer.SiLUActivation on bf16 ``x = cat(x1, x2)``, ATen CUDA kernels):
+ forward y = bf16( f32(bf16(silu(x1))) * f32(x2) ) silu(x) = x / (1 + expf(-x)) in fp32
+ backward dg = bf16( f32(grad) * f32(x2) ) (mul backward, bf16 rounding)
+ dx1 = bf16( silu_backward(dg, x1) ) with s = 1/(1+expf(-x)); dy*s*(1 + x*(1-s)) in fp32
+ dx2 = bf16( f32(grad) * f32(bf16(silu(x1))) )
+ dx = cat(dx1, dx2) -> one contiguous tensor shaped like x
+The kernels replicate the exact ATen arithmetic: libdevice ``__nv_expf`` (same algorithm nvcc uses for
+``expf``), IEEE ``div.rn.f32`` / ``rcp.rn.f32`` emitted through inline PTX (so denormals are *not* flushed,
+like nvcc's default ``-ftz=false``; libdevice's ``__nv_fdiv_rn`` would be ftz under Triton's reflect flag),
+fp32 mul/add with contraction disabled (``enable_fp_fusion=False``) and one explicit ``fma`` where nvcc
+contracts ``1 + x*(1-s)``. Everything is verified bitwise against ATen in ``selftest()`` (all 65536 bf16
+gate values x 256 (grad, up) pairs, random data, masked odd shapes) and in ``exact_prod.py`` at the
+production shape [1, 309376, 18432].
+
+Only ``x`` is saved for backward (silu is recomputed): -5.7 GB of saved activations per DiT block
+compared with the eager / native-out graphs that keep the bf16 gate.
+
+Dispatch mirrors swiglu_native_out_adapter: torch.compile tracing, functorch transforms, forward-mode AD,
+non-bf16 / non-CUDA / non-contiguous / odd-last-dim inputs and double-backward fall back to the original
+eager expression (or to the original autograd graph for create_graph).
+"""
+from __future__ import annotations
+
+import os
+import types
+from dataclasses import dataclass, field
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+
+__all__ = ["swiglu_fused", "swiglu_forward", "swiglu_backward", "FusedSwiGLU", "install", "uninstall",
+ "unsupported_reason", "selftest", "FusedState"]
+
+# Tile configuration (BLOCK_R rows x BLOCK_C columns per program, num_warps); tuned at [309376, 2*9216] on
+# the SM103 with tune.py. Overridable for experiments.
+FWD_TILE = {"BLOCK_R": 1, "BLOCK_C": 1024, "num_warps": 2} # 16 elems/thread, 2.83 ms (6.05 TB/s) at [309376, 18432]
+BWD_TILE = {"BLOCK_R": 1, "BLOCK_C": 512, "num_warps": 2} # 8 elems/thread, 4.68 ms (6.09 TB/s)
+# DIV_MODE 0: inline PTX div.rn.f32 / rcp.rn.f32 (IEEE, no ftz: matches nvcc -ftz=false exactly, incl. denormals)
+# DIV_MODE 1: libdevice __nv_fdiv_rn / __nv_frcp_rn (ftz under Triton's nvvm-reflect-ftz; differs on denormals)
+DIV_MODE = 0
+# silu_backward contraction variant actually emitted by nvcc for ATen's `dy * s * (1 + x * (1 - s))`.
+# 0: (dy*s) * fma(x, 1-s, 1) 1: (dy*s) * (1 + x*(1-s)) uncontracted 2: dy * (s * fma(x, 1-s, 1))
+BWD_VARIANT = 0
+
+
+# ----------------------------------------------------------------------------------------- arithmetic
+@triton.jit
+def _div_rn(a, b, MODE: tl.constexpr):
+ """IEEE round-to-nearest-even fp32 division a / b (ATen: nvcc -prec-div=true -ftz=false)."""
+ if MODE == 0:
+ return tl.inline_asm_elementwise("div.rn.f32 $0, $1, $2;", "=f,f,f", [a, b],
+ dtype=tl.float32, is_pure=True, pack=1)
+ else:
+ return libdevice.div_rn(a, b)
+
+
+@triton.jit
+def _rcp_rn(b, MODE: tl.constexpr):
+ """IEEE round-to-nearest-even fp32 reciprocal (== div_rn(1, b) bitwise; nvcc emits rcp.rn for 1.f/x)."""
+ if MODE == 0:
+ return tl.inline_asm_elementwise("rcp.rn.f32 $0, $1;", "=f,f", [b], dtype=tl.float32,
+ is_pure=True, pack=1)
+ else:
+ return libdevice.rcp_rn(b)
+
+
+@triton.jit
+def _silu_den(x):
+ """1 + expf(-x) in fp32; libdevice __nv_expf is the algorithm nvcc's expf uses (ftz is irrelevant: a
+ denormal exp result is absorbed by the 1 + ...)."""
+ one = tl.zeros_like(x) + 1.0
+ return one + libdevice.exp(-x)
+
+
+# ------------------------------------------------------------------------------------------- forward
+@triton.jit
+def _swiglu_fwd_kernel(x_ptr, y_ptr, M, H, n_cb,
+ BLOCK_R: tl.constexpr, BLOCK_C: tl.constexpr,
+ EVEN_R: tl.constexpr, EVEN_C: tl.constexpr, DIV: tl.constexpr):
+ """y[m, c] = bf16(f32(bf16(silu(x[m, c]))) * f32(x[m, H + c])) for a BLOCK_R x BLOCK_C tile.
+ Column tiles are the fastest-varying program index (consecutive programs read consecutive 2 KB runs)."""
+ pid = tl.program_id(0)
+ pid_r = pid // n_cb
+ pid_c = pid - pid_r * n_cb
+ rows = (pid_r * BLOCK_R + tl.arange(0, BLOCK_R)).to(tl.int64)
+ cols = pid_c * BLOCK_C + tl.arange(0, BLOCK_C)
+ xoff = rows[:, None] * (2 * H) + cols[None, :]
+ yoff = rows[:, None] * H + cols[None, :]
+ if EVEN_R and EVEN_C:
+ x1 = tl.load(x_ptr + xoff)
+ x2 = tl.load(x_ptr + xoff + H)
+ else:
+ mask = (rows < M)[:, None] & (cols < H)[None, :]
+ x1 = tl.load(x_ptr + xoff, mask=mask, other=0.0)
+ x2 = tl.load(x_ptr + xoff + H, mask=mask, other=0.0)
+ x1f = x1.to(tl.float32)
+ gate = _div_rn(x1f, _silu_den(x1f), DIV).to(tl.bfloat16) # ATen silu_kernel + bf16 RNE
+ y = (gate.to(tl.float32) * x2.to(tl.float32)).to(tl.bfloat16) # MulFunctor + bf16 RNE
+ if EVEN_R and EVEN_C:
+ tl.store(y_ptr + yoff, y)
+ else:
+ tl.store(y_ptr + yoff, y, mask=mask)
+
+
+# ------------------------------------------------------------------------------------------ backward
+@triton.jit
+def _swiglu_bwd_kernel(x_ptr, g_ptr, dx_ptr, M, H, n_cb,
+ BLOCK_R: tl.constexpr, BLOCK_C: tl.constexpr,
+ EVEN_R: tl.constexpr, EVEN_C: tl.constexpr, DIV: tl.constexpr, VARIANT: tl.constexpr):
+ """dx[m, c] = silu_backward(bf16(g*x2), x1); dx[m, H + c] = bf16(g * bf16(silu(x1))); silu recomputed."""
+ pid = tl.program_id(0)
+ pid_r = pid // n_cb
+ pid_c = pid - pid_r * n_cb
+ rows = (pid_r * BLOCK_R + tl.arange(0, BLOCK_R)).to(tl.int64)
+ cols = pid_c * BLOCK_C + tl.arange(0, BLOCK_C)
+ xoff = rows[:, None] * (2 * H) + cols[None, :]
+ goff = rows[:, None] * H + cols[None, :]
+ if EVEN_R and EVEN_C:
+ x1 = tl.load(x_ptr + xoff)
+ x2 = tl.load(x_ptr + xoff + H)
+ g = tl.load(g_ptr + goff)
+ else:
+ mask = (rows < M)[:, None] & (cols < H)[None, :]
+ x1 = tl.load(x_ptr + xoff, mask=mask, other=0.0)
+ x2 = tl.load(x_ptr + xoff + H, mask=mask, other=0.0)
+ g = tl.load(g_ptr + goff, mask=mask, other=0.0)
+ x1f = x1.to(tl.float32)
+ gf = g.to(tl.float32)
+ one = tl.zeros_like(x1f) + 1.0
+ den = one + libdevice.exp(-x1f)
+ gate = _div_rn(x1f, den, DIV).to(tl.bfloat16) # the bf16 silu output eager saved
+ dx2 = (gf * gate.to(tl.float32)).to(tl.bfloat16) # grad * rounded_gate
+ dgate = (gf * x2.to(tl.float32)).to(tl.bfloat16).to(tl.float32) # grad * right, rounded to bf16
+ s = _rcp_rn(den, DIV) # sigmoid = 1 / (1 + expf(-x))
+ if VARIANT == 0:
+ dx1 = (dgate * s) * libdevice.fma(x1f, one - s, one)
+ elif VARIANT == 1:
+ dx1 = (dgate * s) * (one + x1f * (one - s))
+ else:
+ dx1 = dgate * (s * libdevice.fma(x1f, one - s, one))
+ if EVEN_R and EVEN_C:
+ tl.store(dx_ptr + xoff, dx1.to(tl.bfloat16))
+ tl.store(dx_ptr + xoff + H, dx2)
+ else:
+ tl.store(dx_ptr + xoff, dx1.to(tl.bfloat16), mask=mask)
+ tl.store(dx_ptr + xoff + H, dx2, mask=mask)
+
+
+# ------------------------------------------------------------------------------------------ launchers
+def _as_2d(x: Tensor):
+ H2 = x.shape[-1]
+ return x.view(-1, H2), H2 // 2
+
+
+def swiglu_forward(x: Tensor, *, tile: dict | None = None, div_mode: int | None = None) -> Tensor:
+ """bf16 fused forward of ``silu(x1) * x2`` with ``x1, x2 = x.chunk(2, -1)``; x contiguous bf16 CUDA."""
+ assert x.dtype == torch.bfloat16 and x.is_cuda and x.is_contiguous() and x.shape[-1] % 2 == 0
+ t = tile or FWD_TILE
+ x2d, H = _as_2d(x)
+ M = x2d.shape[0]
+ y = torch.empty((*x.shape[:-1], H), dtype=x.dtype, device=x.device)
+ if M == 0 or H == 0:
+ return y
+ br, bc = t["BLOCK_R"], t["BLOCK_C"]
+ n_rb, n_cb = triton.cdiv(M, br), triton.cdiv(H, bc)
+ _swiglu_fwd_kernel[(n_rb * n_cb,)](
+ x2d, y, M, H, n_cb, BLOCK_R=br, BLOCK_C=bc, EVEN_R=(M % br == 0), EVEN_C=(H % bc == 0),
+ DIV=(DIV_MODE if div_mode is None else div_mode), num_warps=t["num_warps"], enable_fp_fusion=False)
+ return y
+
+
+def swiglu_backward(x: Tensor, grad: Tensor, *, tile: dict | None = None, div_mode: int | None = None,
+ variant: int | None = None) -> Tensor:
+ """Fused dx (shaped like x, contiguous) from saved x and the bf16 output gradient; silu recomputed."""
+ assert x.dtype == torch.bfloat16 and x.is_cuda and x.is_contiguous() and x.shape[-1] % 2 == 0
+ assert grad.dtype == torch.bfloat16 and grad.device == x.device
+ if not grad.is_contiguous():
+ grad = grad.contiguous()
+ t = tile or BWD_TILE
+ x2d, H = _as_2d(x)
+ M = x2d.shape[0]
+ assert grad.shape == (*x.shape[:-1], H), (grad.shape, x.shape)
+ dx = torch.empty_like(x)
+ if M == 0 or H == 0:
+ return dx
+ br, bc = t["BLOCK_R"], t["BLOCK_C"]
+ n_rb, n_cb = triton.cdiv(M, br), triton.cdiv(H, bc)
+ _swiglu_bwd_kernel[(n_rb * n_cb,)](
+ x2d, grad.view(-1, H), dx.view(-1, 2 * H), M, H, n_cb, BLOCK_R=br, BLOCK_C=bc,
+ EVEN_R=(M % br == 0), EVEN_C=(H % bc == 0), DIV=(DIV_MODE if div_mode is None else div_mode),
+ VARIANT=(BWD_VARIANT if variant is None else variant), num_warps=t["num_warps"],
+ enable_fp_fusion=False)
+ return dx
+
+
+# ------------------------------------------------------------------------------------------- autograd
+def swiglu_reference(x: Tensor) -> Tensor:
+ """The unchanged SiLUActivation expression, including its bf16 intermediate."""
+ x1, x2 = x.chunk(2, dim=-1)
+ return F.silu(x1) * x2
+
+
+def _reference_vjp(x: Tensor, grad: Tensor, *, create_graph: bool) -> Tensor:
+ with torch.enable_grad():
+ xr = x.detach().requires_grad_(True) if not x.requires_grad else x
+ (result,) = torch.autograd.grad(swiglu_reference(xr), xr, grad, create_graph=create_graph)
+ return result
+
+
+class FusedSwiGLU(torch.autograd.Function):
+ """Saves only x; backward recomputes silu(x1) inside the fused kernel."""
+
+ @staticmethod
+ def forward(ctx, x):
+ ctx.set_materialize_grads(False)
+ ctx.save_for_backward(x)
+ return swiglu_forward(x)
+
+ @staticmethod
+ def backward(ctx, grad):
+ if grad is None:
+ return None
+ (x,) = ctx.saved_tensors
+ create_graph = torch.is_grad_enabled()
+ if (create_graph or type(grad) is not Tensor or grad.layout != torch.strided
+ or grad.dtype != x.dtype or grad.device != x.device):
+ return _reference_vjp(x, grad, create_graph=create_graph)
+ return swiglu_backward(x, grad)
+
+
+def unsupported_reason(x: Tensor) -> str | None:
+ """Metadata-only decision; None means the fused kernels can run."""
+ if torch.compiler.is_compiling():
+ return "torch.compile uses the original graph"
+ if torch._C._are_functorch_transforms_active():
+ return "torch.func transforms use the original graph"
+ if torch.autograd.forward_ad._current_level >= 0:
+ return "forward-mode AD uses the original graph"
+ if type(x) is not Tensor or x.layout != torch.strided:
+ return "Tensor subclasses and non-strided layouts use the original graph"
+ if x.ndim < 1 or x.shape[-1] < 2 or x.shape[-1] % 2 or x.numel() == 0:
+ return "a nonempty even last dimension is required"
+ if not x.is_contiguous():
+ return "only contiguous inputs are supported"
+ if x.device.type != "cuda" or x.dtype != torch.bfloat16:
+ return "the fused kernels support only bf16 CUDA tensors"
+ return None
+
+
+def swiglu_fused(x: Tensor, *, require: bool = False, inference: bool = True) -> Tensor:
+ """Drop-in for ``SiLUActivation.forward``: fused kernels when supported, otherwise the eager expression."""
+ reason = unsupported_reason(x)
+ if reason is not None:
+ if require:
+ raise ValueError(reason)
+ return swiglu_reference(x)
+ if not torch.is_grad_enabled() or not x.requires_grad:
+ return swiglu_forward(x) if inference else swiglu_reference(x)
+ return FusedSwiGLU.apply(x)
+
+
+# -------------------------------------------------------------------------------------------- install
+@dataclass
+class FusedState:
+ enabled: bool = True
+ require: bool = False
+ inference: bool = True
+ patched: list = field(default_factory=list) # (name, module, previous __dict__ forward or None, prev native flag)
+
+
+def _fused_activation_forward(self, x: Tensor) -> Tensor:
+ state = self._swiglu_fused_state
+ if state.enabled and (self.training or state.inference):
+ return swiglu_fused(x, require=state.require, inference=state.inference)
+ x1, x2 = x.chunk(2, dim=-1)
+ return self.gate_fn(x1) * x2
+
+
+def install(module: nn.Module, *, require: bool = False, inference: bool = True,
+ activation_cls=None) -> FusedState:
+ """Monkeypatch ``forward`` on every SiLUActivation instance under ``module`` (FSDP/checkpoint wrappers
+ included). Disables the native-out flag on those instances (the two paths are alternatives; the
+ native-out adapter's gate_reason() would otherwise reject the patched forward). Returns the state used
+ by ``uninstall``; ``state.enabled = False`` routes every patched module back to eager."""
+ if activation_cls is None:
+ from flux_action.models.transformer import SiLUActivation as activation_cls
+ state = FusedState(require=require, inference=inference)
+ for name, layer in module.named_modules():
+ if type(layer) is activation_cls:
+ if type(layer.gate_fn) is not nn.SiLU or layer.gate_fn.inplace:
+ raise RuntimeError(f"{name}: modified SiLU gate")
+ prev_fwd = layer.__dict__.get("forward")
+ prev_native = layer.__dict__.get("_swiglu_native_out_enabled")
+ layer._swiglu_native_out_enabled = False
+ layer._swiglu_fused_state = state
+ layer.forward = types.MethodType(_fused_activation_forward, layer)
+ state.patched.append((name, layer, prev_fwd, prev_native))
+ if require and not state.patched:
+ raise RuntimeError("no SiLUActivation instances found")
+ return state
+
+
+def uninstall(state: FusedState) -> None:
+ for _, layer, prev_fwd, prev_native in state.patched:
+ if prev_fwd is None:
+ layer.__dict__.pop("forward", None)
+ else:
+ layer.forward = prev_fwd
+ if prev_native is None:
+ layer.__dict__.pop("_swiglu_native_out_enabled", None)
+ else:
+ layer._swiglu_native_out_enabled = prev_native
+ layer.__dict__.pop("_swiglu_fused_state", None)
+ state.patched.clear()
+ state.enabled = False
+
+
+# ------------------------------------------------------------------------------------------- testing
+def bitwise_report(a: Tensor, b: Tensor) -> dict:
+ """NaN-aware bitwise comparison of two equal-shape bf16/fp32 tensors (NaN == NaN counts as a match,
+ but differing NaN payloads are reported separately)."""
+ assert a.shape == b.shape and a.dtype == b.dtype, (a.shape, b.shape, a.dtype, b.dtype)
+ ia = a.view(torch.int16 if a.dtype == torch.bfloat16 else torch.int32)
+ ib = b.view(torch.int16 if b.dtype == torch.bfloat16 else torch.int32)
+ same_bits = ia == ib
+ both_nan = torch.isnan(a) & torch.isnan(b)
+ match = same_bits | both_nan
+ n = a.numel()
+ out = {"n": n, "bitwise_fraction": match.sum().item() / max(n, 1),
+ "mismatches": int((~match).sum().item()),
+ "nan_payload_diffs": int((both_nan & ~same_bits).sum().item())}
+ if out["mismatches"]:
+ fin = torch.isfinite(a) & torch.isfinite(b)
+ d = torch.where(fin, (a.float() - b.float()).abs(), torch.zeros_like(a, dtype=torch.float32))
+ out["max_abs_diff"] = d.max().item()
+ out["rel_l2"] = (d.norm() / b.float()[fin].norm().clamp_min(1e-30)).item()
+ out["nonfinite_mismatches"] = int((~match & ~fin).sum().item())
+ return out
+
+
+def _bf16_all_patterns(device) -> Tensor:
+ return torch.arange(-32768, 32768, dtype=torch.int32, device=device).to(torch.int16).view(torch.bfloat16)
+
+
+def _edge_values(device) -> Tensor:
+ vals = [0.0, -0.0, 1.0, -1.0, 0.5, -3.0, 7.0, 1e-3, -2e-2, 64.0, -64.0, 87.5, -87.5, 88.0, -88.0, 88.5,
+ -88.5, 89.0, -89.0, 100.0, -100.0, 1e4, -3e4, 3.0e38, -3.0e38, float("inf"), -float("inf"),
+ float("nan"), 1e-38, -1e-38, 1e-39, -1e-39, 2e-40, -5e-41, 1e-45, 9.2e-41]
+ return torch.tensor(vals, dtype=torch.bfloat16, device=device)
+
+
+def _wide_values(n: int, device, gen) -> Tensor:
+ """Log-uniform magnitudes over the whole bf16 normal range, random signs, plus the edge values."""
+ e = torch.rand(n, generator=gen, device=device) * 250.0 - 125.0
+ v = torch.exp2(e) * torch.where(torch.rand(n, generator=gen, device=device) < 0.5, -1.0, 1.0)
+ v = v.to(torch.bfloat16)
+ edge = _edge_values(device)
+ v[: edge.numel()] = edge
+ return v
+
+
+def _eager_fwd_bwd(x: Tensor, grad: Tensor):
+ xr = x.detach().clone().requires_grad_(True)
+ with torch.enable_grad():
+ y = swiglu_reference(xr)
+ (dx,) = torch.autograd.grad(y, xr, grad)
+ return y.detach(), dx
+
+
+def _check(name, a, b, results, verbose=True, diagnostic=False):
+ rep = bitwise_report(a, b)
+ ok = rep["mismatches"] == 0
+ results.append((name, ok, rep, diagnostic))
+ if verbose:
+ tag = "alt" if diagnostic else ("OK " if ok else "BAD")
+ print(f" {tag} {name}: {rep}")
+ return ok
+
+
+def selftest(device="cuda", verbose=True, variants=(0, 1, 2), div_modes=(0, 1)) -> bool:
+ """Exhaustive + random bitwise verification against ATen. Prints and returns ALL BIT-EXACT."""
+ results = []
+ gen = torch.Generator(device=device).manual_seed(1234)
+ # (1) all 65536 bf16 gate values x 256 (up, grad) pairs covering the whole bf16 range + edge values
+ C = 256
+ x1 = _bf16_all_patterns(device)[:, None].expand(65536, C)
+ x2 = _wide_values(C, device, gen)[None, :].expand(65536, C)
+ grad = _wide_values(C, device, gen).flip(0)[None, :].expand(65536, C).contiguous()
+ x = torch.cat([x1, x2], dim=-1).contiguous()
+ y_ref, dx_ref = _eager_fwd_bwd(x, grad)
+ for dm in div_modes:
+ diag = dm != DIV_MODE
+ _check(f"exhaustive fwd (all bf16 gates x {C}) div_mode={dm}", swiglu_forward(x, div_mode=dm), y_ref,
+ results, verbose, diagnostic=diag)
+ for v in variants:
+ _check(f"exhaustive bwd div_mode={dm} variant={v}", swiglu_backward(x, grad, div_mode=dm, variant=v),
+ dx_ref, results, verbose, diagnostic=diag or v != BWD_VARIANT)
+ # direct check of the two bf16 halves against the ATen kernels themselves (variant/div as configured)
+ dg = (grad * x2).contiguous()
+ dx1_ref = torch.ops.aten.silu_backward(dg, x1.contiguous())
+ dx = swiglu_backward(x, grad)
+ _check("exhaustive dx1 vs aten.silu_backward(bf16(grad*x2), x1)", dx[:, :C], dx1_ref, results, verbose)
+ _check("exhaustive dx2 vs bf16(grad*silu(x1))", dx[:, C:], grad * F.silu(x1.contiguous()), results, verbose)
+ # (2) exhaustive gate as the *up* half too (x2 over all patterns, x1 wide): exercises x2 denormals/inf
+ xs = torch.cat([x2, x1], dim=-1).contiguous()
+ y_ref, dx_ref = _eager_fwd_bwd(xs, grad)
+ _check("exhaustive up-half fwd", swiglu_forward(xs), y_ref, results, verbose)
+ _check("exhaustive up-half bwd", swiglu_backward(xs, grad), dx_ref, results, verbose)
+ # (3) random production-like data (N(0,3) activations, small grads) at a packed length, and odd shapes
+ shapes = [(1, 4096, 18432), (1, 128, 18432), (3, 5, 2000), (2, 7, 6), (10, 2), (1, 2417, 18432), (5, 1, 3, 2 * 1030)]
+ for shp in shapes:
+ xr = (torch.randn(shp, generator=gen, device=device) * 3.0).to(torch.bfloat16)
+ gr = (torch.randn((*shp[:-1], shp[-1] // 2), generator=gen, device=device) * 0.02).to(torch.bfloat16)
+ y_ref, dx_ref = _eager_fwd_bwd(xr, gr)
+ _check(f"random fwd {shp}", swiglu_forward(xr), y_ref, results, verbose)
+ _check(f"random bwd {shp}", swiglu_backward(xr, gr), dx_ref, results, verbose)
+ # autograd Function end to end (also non-contiguous grad -> .contiguous() inside)
+ xa = xr.clone().requires_grad_(True)
+ ya = FusedSwiGLU.apply(xa)
+ (dxa,) = torch.autograd.grad(ya, xa, gr)
+ _check(f"autograd.Function fwd {shp}", ya.detach(), y_ref, results, verbose)
+ _check(f"autograd.Function bwd {shp}", dxa, dx_ref, results, verbose)
+ # (4) dispatch fallbacks: non-contiguous input / fp32 input use the eager expression
+ xr = (torch.randn((4, 8, 64), generator=gen, device=device) * 3.0).to(torch.bfloat16)
+ assert unsupported_reason(xr.transpose(0, 1)) is not None
+ assert unsupported_reason(xr.float()) is not None
+ assert torch.equal(swiglu_fused(xr.transpose(0, 1)), swiglu_reference(xr.transpose(0, 1)))
+ ok = all(r[1] for r in results if not r[3])
+ n_main = sum(1 for r in results if not r[3])
+ print(f"ALL BIT-EXACT: {ok} (configured DIV_MODE={DIV_MODE}, BWD_VARIANT={BWD_VARIANT}; {n_main} checks; "
+ f"'alt' lines are diagnostics of the other arithmetic variants)")
+ return ok
+
+
+if __name__ == "__main__":
+ torch.cuda.set_device(0)
+ print(torch.__version__, triton.__version__, torch.cuda.get_device_name(0))
+ selftest()
diff --git a/flux-umi/src/flux_action/models/dit_time_embed_dedup.py b/flux-umi/src/flux_action/models/dit_time_embed_dedup.py
new file mode 100644
index 0000000000000000000000000000000000000000..3faf497407f176974e48a3bc5cbaf727d5f96c56
--- /dev/null
+++ b/flux-umi/src/flux_action/models/dit_time_embed_dedup.py
@@ -0,0 +1,773 @@
+"""Per-(stream, window) timestep-embedding / modulation / adaLN dedup for ``JointSingleSeq`` training.
+
+``JointSingleSeq.forward`` evaluates ``timestep_embedding`` + the fp32 ``time_in`` MLP, ``+ vector_in``,
+the per-stream ``Modulation`` linears (early and single stream, per content modality and for the text
+context) and the ``LastLayer`` adaLN linears on EVERY token, although in packed training every window
+shares one timestep per stream (video and action: ``t_w``; conditioning streams and the context: ``0``, or
+one noise level per window with ``conditioning_noise_max``). This module computes ONE ROW per
+(stream, window) and expands the rows to the per-token tensors the blocks consume with a differentiable
+gather (:class:`ExpandRows`): the forward is one ``index_select`` per tensor, the backward a deterministic
+fp32 segment sum (``view + sum`` for equal runs, ``view + split + sum`` for the periodic window-major joint
+layout, ``index_select + view + sum`` per distinct run length otherwise; no atomics, no one-hot matrices).
+Blocks, checkpoint wrappers and FSDP groups are untouched: only the bound ``forward`` of one instance is
+replaced, and only the packed training call (``seqlens`` given, ``module.training``) takes the new path --
+unpacked calls and inference run the original ``JointSingleSeq.forward``.
+
+Numerics
+--------
+* ``vec`` (``embed_timesteps(t) + vector_emb`` after the ``.to(bf16)`` casts): the row chain keeps
+ bf16-rounded values in fp32 containers (:class:`RoundTo`, identity backward) and applies the same
+ roundings in the same order as the per-token path (fp32 ``time_in`` -> bf16; bf16 add = fp32 add + bf16
+ rounding; bf16 ``silu`` = fp32 formula + bf16 rounding). The only remaining difference is the fp32
+ ``time_in`` SGEMM itself, which cuBLAS runs with M = tokens on one side and M = windows on the other:
+ measured bit-identical (1.000000) for all five production streams (128 windows), while tiny M (6 rows
+ vs 3072 tokens) selects a kernel with another accumulation order and shows 1-ulp bf16 flips in ~0.1 % of
+ the elements (0.9992 bitwise, identical error vs fp64).
+* The modulation / adaLN linears run as fp32 GEMMs on the rows (inputs are bf16-representable, products
+ exact in fp32); after the bf16 cast in :class:`ExpandRows` the per-token values equal the per-token bf16
+ GEMM up to fp32 accumulation order (99.8-99.9 % bit-identical, the rest 1 bf16 ulp).
+* Gradients: the per-token bf16 gradients are segment-summed in fp32 and flow through fp32 row GEMMs into
+ ``time_in`` / the modulation weights (one bf16 rounding at the bf16 weight's ``.float()`` boundary, as the
+ per-token wgrad GEMM has), so they are closer to an fp64 reference than the per-token path, whose chain
+ rounds to bf16 after every per-token op.
+
+Supported configurations (anything else falls back to the original forward)
+---------------------------------------------------------------------------
+* packed call (``seqlens`` given, batch size 1), ``module.training`` True;
+* timesteps constant within every (stream, window) run: the trainer's ``build_forward_kwargs`` layout,
+ including ``separate_timesteps`` (action ``t`` differs from the video ``t`` but is constant per window)
+ and ``conditioning_noise_max > 0`` (one ``video_cond`` ``t`` per window). The invariant is verified on the
+ device: ``check_constant_runs="async"`` (default) is a ``torch._assert_async`` (no host sync; a violation
+ is a loud CUDA assert), ``"sync"`` checks on the host and falls back to the original forward (one sync per
+ call), ``"off"`` trusts the caller;
+* ``Modulation`` modules with ``multiplier == 3`` and no bias, ``LastLayer`` adaLN linears without bias
+ (the architecture ``JointSingleSeq`` builds); ``depth_late_blocks`` supported.
+
+FSDP2: ``install_training_time_embed_dedup`` must run on the un-sharded module or on the ``fully_shard``-ed
+root (it sets ``dit.forward`` on the instance; ``nn.Module.__call__`` and FSDP's hooks resolve ``forward``
+through the instance first). No new parameters or buffers; ``time_in`` keeps its own fp32 group
+(``cast_forward_inputs=False``: the row embedding is computed in the weight dtype under ``autocast``
+disabled exactly as ``embed_timesteps``); the root group's bf16 unsharded modulation weights are upcast
+with ``.float()`` for the row GEMMs (their gradient is cast back to bf16 once, then reduce-scattered in
+``reduce_dtype`` as before).
+
+Use::
+
+ from flux_action.models.dit_time_embed_dedup import install_training_time_embed_dedup
+ info = install_training_time_embed_dedup(policy.dit) # before or after shard_dit
+"""
+
+from __future__ import annotations
+
+import os
+import types
+from collections import defaultdict
+from collections.abc import Sequence
+from itertools import accumulate
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from einops import rearrange
+from torch import Tensor, nn
+
+try: # installed as flux_action.models.dit_time_embed_dedup
+ from .transformer import JointSingleSeq, LastLayer, Modulation, timestep_embedding, window_major_order
+except ImportError:
+ from flux_action.models.transformer import ( # type: ignore[no-redef]
+ JointSingleSeq,
+ LastLayer,
+ Modulation,
+ timestep_embedding,
+ window_major_order,
+ )
+
+__all__ = [
+ "CHECK_MODES",
+ "ExpandRows",
+ "RoundTo",
+ "expand_rows",
+ "forward_dedup",
+ "install_training_time_embed_dedup",
+ "is_installed",
+ "last_layer_forward_dedup",
+ "modulation_rows",
+ "round_to",
+ "run_timesteps",
+ "runtime_info",
+ "segment_sum_fp32",
+ "self_test",
+ "uninstall_time_embed_dedup",
+]
+
+CHECK_MODES = ("async", "sync", "off")
+_REQUIRE = os.environ.get("FLUX_ACTION_TIME_EMBED_DEDUP_REQUIRE") == "1"
+_SETTINGS_ATTR = "_time_embed_dedup_settings"
+_ORIGINAL_FORWARD = JointSingleSeq.forward # the class function at import; the fallback target
+_index_cache: dict[tuple, Tensor] = {}
+_INDEX_CACHE_LIMIT = 256
+
+
+# ------------------------------------------------------------------------------------------ run indices
+def _cached(key: tuple, build) -> Tensor:
+ hit = _index_cache.get(key)
+ if hit is None:
+ if len(_index_cache) >= _INDEX_CACHE_LIMIT:
+ _index_cache.clear()
+ hit = _index_cache[key] = build()
+ return hit
+
+
+def _counts(counts: Sequence[int]) -> tuple[int, ...]:
+ out = tuple(int(c) for c in counts)
+ if any(c < 0 for c in out):
+ raise ValueError(f"negative run length in {out}")
+ return out
+
+
+def run_starts(counts: Sequence[int], device: torch.device) -> Tensor:
+ """First-token offset of every run (``[R]`` int64), cached per ``(counts, device)``."""
+ counts = _counts(counts)
+
+ def build() -> Tensor:
+ starts = torch.zeros(len(counts), dtype=torch.int64)
+ if len(counts) > 1:
+ torch.cumsum(torch.as_tensor(counts[:-1], dtype=torch.int64), 0, out=starts[1:])
+ return starts.to(device)
+
+ return _cached(("starts", counts, str(device)), build)
+
+
+def token_rows(counts: Sequence[int], device: torch.device) -> Tensor:
+ """Row index of every token (``[sum(counts)]`` int64): row ``r`` repeated ``counts[r]`` times, cached."""
+ counts = _counts(counts)
+ return _cached(
+ ("rows", counts, str(device)),
+ lambda: torch.repeat_interleave(
+ torch.arange(len(counts), dtype=torch.int64), torch.as_tensor(counts, dtype=torch.int64)
+ ).to(device),
+ )
+
+
+def _run_groups(counts: tuple[int, ...]) -> dict[int, list[int]]:
+ """``{run length: [run indices]}`` in order of first appearance."""
+ groups: dict[int, list[int]] = defaultdict(list)
+ for r, c in enumerate(counts):
+ groups[c].append(r)
+ return groups
+
+
+def group_token_index(counts: Sequence[int], length: int, device: torch.device) -> tuple[Tensor, Tensor]:
+ """``(tokens, runs)`` for every run of ``length`` tokens: ``tokens`` lists their token offsets run by run
+ (``[n_runs * length]`` int64), ``runs`` the run indices (``[n_runs]`` int64); cached."""
+ counts = _counts(counts)
+ length = int(length)
+ runs = _run_groups(counts)[length]
+ n_runs = len(runs)
+
+ def build() -> Tensor:
+ starts = [0, *accumulate(counts)]
+ tokens = [torch.arange(starts[r], starts[r] + length, dtype=torch.int64) for r in runs]
+ flat_tokens = torch.cat(tokens) if tokens else torch.zeros(0, dtype=torch.int64)
+ return torch.cat([flat_tokens, torch.as_tensor(runs, dtype=torch.int64)]).to(device)
+
+ flat = _cached(("group", counts, length, str(device)), build)
+ return flat[: n_runs * length], flat[n_runs * length :]
+
+
+def _period(counts: tuple[int, ...]) -> int | None:
+ """Segment count ``S`` if ``counts`` is ``counts[:S]`` repeated (the window-major joint layout), else ``None``."""
+ n = len(counts)
+ for s in range(1, n // 2 + 1):
+ if n % s == 0 and counts == counts[:s] * (n // s):
+ return s
+ return None
+
+
+# ------------------------------------------------------------------------------------- expand / reduce
+def expand_rows_nograd(
+ rows: Tensor, counts: Sequence[int], out_dtype: torch.dtype, out_shape: Sequence[int] | None = None
+) -> Tensor:
+ """Fresh tensor (default ``[sum(counts), D]``) with row ``r`` of ``rows [R, D]`` filling run ``r``; one gather."""
+ counts = _counts(counts)
+ r, d = rows.shape
+ if r != len(counts):
+ raise ValueError(f"{r} rows for {len(counts)} runs")
+ n = sum(counts)
+ shape = (n, d) if out_shape is None else tuple(int(s) for s in out_shape)
+ with torch.no_grad(): # a no-grad primitive (ExpandRows supplies the autograd); ``out=`` refuses grad-requiring inputs
+ out = torch.empty(shape, dtype=out_dtype, device=rows.device)
+ # a gather with the cached per-token row index writes at ~2.7-3 TB/s; a stride-0 expand copy only ~1.2 TB/s
+ torch.index_select(rows.to(out_dtype), 0, token_rows(counts, rows.device), out=out.view(n, d))
+ return out
+
+
+def segment_sum_fp32(grad: Tensor, counts: Sequence[int]) -> Tensor:
+ """fp32 sum of ``grad [sum(counts), D]`` over every run -> ``[R, D]`` fp32; deterministic, no atomics.
+
+ Equal runs: ``view + sum``. Periodic runs (window-major joint layout ``[c_0..c_{S-1}] * W``): ``view +
+ split + sum``. Otherwise one ``index_select + view + sum`` per distinct run length (no ``[R, L]`` one-hot).
+ """
+ counts = _counts(counts)
+ r, d = len(counts), grad.shape[-1]
+ grad = grad.reshape(sum(counts), d)
+ if r == 0:
+ return grad.new_zeros((0, d), dtype=torch.float32)
+ if len(set(counts)) == 1:
+ if counts[0] == 0:
+ return grad.new_zeros((r, d), dtype=torch.float32)
+ return grad.view(r, counts[0], d).sum(1, dtype=torch.float32)
+ s = _period(counts)
+ if s is not None:
+ w = r // s
+ pieces = grad.view(w, sum(counts[:s]), d).split(list(counts[:s]), dim=1)
+ sums = [p.sum(1, dtype=torch.float32) for p in pieces] # S x [W, D]
+ return torch.stack(sums, dim=1).reshape(r, d)
+ out = grad.new_zeros((r, d), dtype=torch.float32)
+ for length in _run_groups(counts):
+ if length == 0:
+ continue
+ tokens, runs = group_token_index(counts, length, grad.device)
+ part = grad.index_select(0, tokens).view(runs.numel(), length, d)
+ out.index_copy_(0, runs, part.sum(1, dtype=torch.float32) if length > 1 else part[:, 0].float())
+ return out
+
+
+class ExpandRows(torch.autograd.Function):
+ """``rows [R, D]`` -> per-token ``[sum(counts), D]`` (or ``out_shape``) in ``out_dtype``; row ``r`` fills run ``r``.
+
+ Backward: :func:`segment_sum_fp32` of the incoming gradient, returned in ``rows``' dtype (fp32 rows keep
+ the full-precision sum).
+ """
+
+ @staticmethod
+ def forward(ctx, rows: Tensor, counts: tuple[int, ...], out_dtype: torch.dtype, out_shape=None) -> Tensor:
+ ctx.counts = counts
+ ctx.in_dtype = rows.dtype
+ return expand_rows_nograd(rows, counts, out_dtype, out_shape)
+
+ @staticmethod
+ def backward(ctx, grad: Tensor): # type: ignore[override]
+ return segment_sum_fp32(grad, ctx.counts).to(ctx.in_dtype), None, None, None
+
+
+def expand_rows(
+ rows: Tensor, counts: Sequence[int], out_dtype: torch.dtype, out_shape: Sequence[int] | None = None
+) -> Tensor:
+ """Autograd-friendly :class:`ExpandRows`; the result is a fresh tensor (callers may modify it in place)."""
+ shape = None if out_shape is None else tuple(int(n) for n in out_shape)
+ return ExpandRows.apply(rows, _counts(counts), out_dtype, shape)
+
+
+class RoundTo(torch.autograd.Function):
+ """``x`` rounded to ``dtype`` and returned in ``x.dtype`` (the values the low-precision path sees); identity backward.
+
+ Keeps the row chain (``vec`` -> ``+ vector_emb`` -> ``silu`` -> linears) numerically identical to the bf16
+ per-token path in the forward while its gradients stay fp32: the per-token path sums per-token bf16
+ gradients inside fp32-accumulating GEMMs, so the fp32 segment sums must not be re-rounded to bf16.
+ """
+
+ @staticmethod
+ def forward(ctx, x: Tensor, dtype: torch.dtype) -> Tensor:
+ return x.to(dtype).to(x.dtype)
+
+ @staticmethod
+ def backward(ctx, grad: Tensor): # type: ignore[override]
+ return grad, None
+
+
+def round_to(x: Tensor, dtype: torch.dtype) -> Tensor:
+ return x if x.dtype == dtype else RoundTo.apply(x, dtype)
+
+
+# ------------------------------------------------------------------------------------------- row maths
+def run_timesteps(ts: Tensor, counts: Sequence[int], check: bool = True) -> tuple[Tensor, Tensor | None]:
+ """``(t_rows [R], ok)``: the timestep of each run's first token and, with ``check``, a device-side bool
+ tensor that is True iff every token of every run carries its run's timestep (``None`` otherwise)."""
+ counts = _counts(counts)
+ if ts.ndim != 1 or ts.numel() != sum(counts):
+ raise ValueError(f"timesteps {tuple(ts.shape)} do not match runs of {sum(counts)} tokens")
+ t_rows = ts.index_select(0, run_starts(counts, ts.device))
+ if not check:
+ return t_rows, None
+ return t_rows, torch.eq(t_rows.index_select(0, token_rows(counts, ts.device)), ts).all()
+
+
+def _fp32_weight(w: Tensor) -> Tensor:
+ return w if w.dtype == torch.float32 else w.float()
+
+
+def modulation_rows(mod: Modulation, vec_rows: Tensor, vec_dtype: torch.dtype) -> tuple[Tensor, ...]:
+ """``Modulation.forward`` on per-row ``vec`` with the linear in fp32: ``multiplier`` chunks of ``[R, dim]`` fp32.
+
+ ``vec_rows`` holds ``vec_dtype``-representable values in an fp32 container (see :class:`RoundTo`); ``silu``
+ uses the fp32 formula and is rounded to ``vec_dtype`` exactly like ``F.silu`` on a ``vec_dtype`` tensor, so
+ the GEMM sees the values ``Modulation.forward`` sees; its fp32 result equals the per-token GEMM's up to
+ accumulation order once rounded to ``vec_dtype`` in :class:`ExpandRows`.
+ """
+ with torch.autocast(device_type=vec_rows.device.type, enabled=False):
+ s = round_to(F.silu(vec_rows), vec_dtype)
+ bias = mod.lin.bias
+ out = F.linear(s, _fp32_weight(mod.lin.weight), None if bias is None else _fp32_weight(bias))
+ return out.chunk(mod.multiplier, dim=-1)
+
+
+def last_layer_forward_dedup(
+ layer: LastLayer, x: Tensor, vec_rows: Tensor, counts: Sequence[int], vec_dtype: torch.dtype
+) -> Tensor:
+ """``LastLayer.forward`` with the adaLN linears on per-row ``vec`` (``[R, hidden]``) expanded per token.
+
+ Same in-place sequence as the original: the (fp32-row) linear is rounded to ``vec_dtype`` once in the
+ expansion, then ``+ 1`` in ``vec_dtype``, then the multiply and the add.
+ """
+ lin = layer.adaLN_modulation[1]
+ shift_w, scale_w = lin.weight.chunk(2) # type: ignore[union-attr]
+ with torch.autocast(device_type=x.device.type, enabled=False):
+ s = round_to(F.silu(vec_rows), vec_dtype)
+ scale_rows = F.linear(s, _fp32_weight(scale_w))
+ shift_rows = F.linear(s, _fp32_weight(shift_w))
+ shape = x.shape
+ x = layer.norm_final(x)
+ x.mul_(expand_rows(scale_rows, counts, vec_dtype, shape).add_(1))
+ x.add_(expand_rows(shift_rows, counts, vec_dtype, shape))
+ return layer.linear(x)
+
+
+# ---------------------------------------------------------------------------------------------- forward
+def forward_dedup(
+ self: JointSingleSeq,
+ ctx: Tensor,
+ ctx_ids: Tensor,
+ vector: Tensor,
+ timesteps_ctx: Tensor,
+ pag_single_layers: list[int] | None = None,
+ pag_strength: float = 1.0,
+ seqlens: dict[str, Sequence[int]] | None = None,
+ **kwargs: Tensor,
+) -> dict[str, Tensor]:
+ """``JointSingleSeq.forward`` with time embedding, modulations and adaLN computed once per (stream, window).
+
+ Takes the dedup path only for packed training calls (``seqlens`` given and ``self.training``); every other
+ call -- and, with ``check_constant_runs="sync"``, a call whose timesteps vary inside a window -- runs the
+ original forward unchanged.
+ """
+ if seqlens is None or not self.training:
+ return _ORIGINAL_FORWARD(
+ self, ctx, ctx_ids, vector, timesteps_ctx, pag_single_layers, pag_strength, seqlens, **kwargs
+ )
+ settings = getattr(self, _SETTINGS_ATTR, None) or {"check_constant_runs": "async"}
+ check = settings["check_constant_runs"]
+
+ assert vector.ndim == 2, "invalid vector shape"
+ batch_size = ctx.shape[0]
+
+ # --- stream bookkeeping and validation, as in the original forward --------------------------------
+ x_by_mod: dict[str, list] = defaultdict(list)
+ ids_by_mod: dict[str, list] = defaultdict(list)
+ ts_by_mod: dict[str, list] = defaultdict(list)
+ lens_by_mod: dict[str, list] = defaultdict(list)
+ names_by_mod: dict[str, list] = defaultdict(list)
+ for k, v in self.sequence.items():
+ if k not in kwargs:
+ continue
+ assert k + "_ids" in kwargs and k + "_timesteps" in kwargs, "missing stream metadata"
+ x_by_mod[v].append(kwargs[k])
+ ids_by_mod[v].append(kwargs[k + "_ids"])
+ ts_by_mod[v].append(kwargs[k + "_timesteps"])
+ lens_by_mod[v].append(kwargs[k].shape[1])
+ names_by_mod[v].append(k)
+
+ active = list(x_by_mod.keys())
+ all_mods = sorted(self.in_channels.keys())
+ inactive = [m for m in all_mods if m not in active]
+ dummy_len = 2 # attention kernels need >=2
+ if batch_size != 1:
+ raise ValueError(f"packed windows form one sequence of batch size 1, got {batch_size}")
+ ctx_lens = [int(n) for n in seqlens["ctx"]]
+ if sum(ctx_lens) != ctx.shape[1]:
+ raise ValueError(f"context token counts {ctx_lens} do not add up to {ctx.shape[1]}")
+ mod_lens: dict[str, list[int]] = {}
+ for m in active:
+ if len(names_by_mod[m]) != 1:
+ raise ValueError(f"packed windows need one stream per modality, {m} has {names_by_mod[m]}")
+ lens = [int(n) for n in seqlens[names_by_mod[m][0]]]
+ if len(lens) != len(ctx_lens) or sum(lens) != lens_by_mod[m][0]:
+ raise ValueError(f"{names_by_mod[m][0]}: window token counts {lens} do not match the stream")
+ mod_lens[m] = lens
+
+ device = x_by_mod[active[0]][0].device
+ dtype = x_by_mod[active[0]][0].dtype
+ for k in all_mods:
+ if k in active:
+ x_by_mod[k] = torch.cat(x_by_mod[k], 1)
+ ids_by_mod[k] = torch.cat(ids_by_mod[k], 1)
+ ts_by_mod[k] = torch.cat(ts_by_mod[k], 1)
+ else:
+ x_by_mod[k] = torch.zeros(batch_size, dummy_len, self.in_channels[k], device=device, dtype=dtype)
+ ids_by_mod[k] = torch.zeros(batch_size, dummy_len, 4, device=device, dtype=torch.int64)
+ ts_by_mod[k] = torch.zeros(batch_size, dummy_len, device=device, dtype=dtype)
+
+ # --- one timestep row per (stream, window); inactive dummy streams are one run of two tokens ---------
+ counts_by_mod = {k: (mod_lens[k] if k in active else [dummy_len]) for k in all_mods}
+ counts_ctx = ctx_lens
+ verify = check != "off"
+ t_rows_by_mod: dict[str, Tensor] = {}
+ oks: list[Tensor] = []
+ for k in all_mods:
+ t_rows_by_mod[k], ok = run_timesteps(ts_by_mod[k].reshape(-1), counts_by_mod[k], verify)
+ if ok is not None:
+ oks.append(ok)
+ t_rows_ctx, ok = run_timesteps(timesteps_ctx.reshape(-1), counts_ctx, verify)
+ if ok is not None:
+ oks.append(ok)
+ if oks:
+ all_ok = torch.stack(oks).all()
+ if check == "sync":
+ if not bool(all_ok): # timesteps vary inside a window: exact fallback
+ return _ORIGINAL_FORWARD(
+ self, ctx, ctx_ids, vector, timesteps_ctx, pag_single_layers, pag_strength, seqlens, **kwargs
+ )
+ else:
+ torch._assert_async(all_ok)
+
+ # --- vec rows: the per-token values of ``embed_timesteps(ts, dtype) + vector_emb`` in fp32 containers --
+ vector_emb = self.vector_in(vector) # (1, d) in the root's compute dtype
+ vector_emb_f = vector_emb.float()
+ weight_dtype = self.time_in.in_layer.weight.dtype
+
+ def vec_rows_of(t_rows: Tensor) -> Tensor:
+ with torch.autocast(device_type=device.type, enabled=False):
+ vec = self.time_in(timestep_embedding(t_rows, 256, out_dtype=weight_dtype)).float()
+ vec = round_to(vec, dtype) # embed_timesteps' ``.to(dtype)``
+ vec = round_to(vec + vector_emb_f, dtype) # the ``dtype`` add: fp32 add + one rounding
+ return vec
+
+ vec_rows_by_mod = {k: vec_rows_of(t_rows_by_mod[k]) for k in all_mods}
+ vec_rows_ctx = vec_rows_of(t_rows_ctx)
+
+ def per_token(rows: Tensor, counts: list[int]) -> Tensor:
+ return expand_rows(rows, counts, dtype, (1, sum(counts), rows.shape[-1]))
+
+ early_content_mods: dict[str, tuple] = {}
+ for key in self.early_stream_modulations:
+ if key == "txt":
+ continue
+ chunks = modulation_rows(self.early_stream_modulations[key], vec_rows_by_mod[key], dtype)
+ early_content_mods[key] = tuple(per_token(c, counts_by_mod[key]) for c in chunks[:3])
+ early_txt_mod = tuple(
+ per_token(c, counts_ctx)
+ for c in modulation_rows(self.early_stream_modulations["txt"], vec_rows_ctx, dtype)[:3]
+ )
+
+ single_rows: dict[str, tuple] = {}
+ for key in self.single_stream_modulations:
+ vec = vec_rows_ctx if key == "txt" else vec_rows_by_mod[key]
+ single_rows[key] = modulation_rows(self.single_stream_modulations[key], vec, dtype)[:3]
+
+ if self.depth_late_blocks > 0:
+ late_content_mods: dict[str, tuple] = {}
+ for key in self.late_stream_modulations:
+ if key == "txt":
+ continue
+ chunks = modulation_rows(self.late_stream_modulations[key], vec_rows_by_mod[key], dtype)
+ late_content_mods[key] = tuple(per_token(c, counts_by_mod[key]) for c in chunks[:3])
+ late_txt_mod = tuple(
+ per_token(c, counts_ctx)
+ for c in modulation_rows(self.late_stream_modulations["txt"], vec_rows_ctx, dtype)[:3]
+ )
+
+ content_by_mod = {k: self.emb_in[k](x_by_mod[k]) for k in all_mods}
+ txt = self.txt_in(ctx)
+
+ pe_by_mod = {k: self.pe_embedder(ids_by_mod[k]) for k in all_mods}
+ pe_ctx = self.pe_embedder(ctx_ids)
+
+ for d in range(self.depth):
+ for m in all_mods:
+ content_by_mod[m] = self.content_mode_blocks[m][d](
+ content_by_mod[m], pe_by_mod[m], early_content_mods[m], seqlens=mod_lens.get(m)
+ )
+ txt = self.txt_mode_blocks[d](txt, pe_ctx, early_txt_mod, seqlens=ctx_lens)
+
+ img = torch.cat([content_by_mod[k] for k in active], dim=1)
+ pe_content = torch.cat([pe_by_mod[k] for k in active], dim=2)
+ pe = torch.cat((pe_ctx, pe_content), dim=2)
+
+ # Window-major joint sequence as in the original forward. The per-token modulation is expanded straight
+ # into window-major order from the (window, segment) rows: no segment-major materialisation, no cat and
+ # no gather of three [L, hidden] tensors.
+ order, inverse, window_lens = window_major_order([ctx_lens, *(mod_lens[k] for k in active)], img.device)
+ n_windows = len(ctx_lens)
+ segments = ["txt", *active]
+ counts_wm = [int(n) for w in range(n_windows) for n in (ctx_lens[w], *(mod_lens[k][w] for k in active))]
+ mod = tuple(
+ per_token(torch.stack([single_rows[s][i] for s in segments], dim=1).reshape(n_windows * len(segments), -1), counts_wm)
+ for i in range(3)
+ )
+ seq = torch.cat((txt, img), dim=1)[:, order]
+ pe = pe[:, :, order]
+ for i, block in enumerate(self.single_blocks):
+ layer_pag = pag_strength if (pag_single_layers and i in pag_single_layers) else 0.0
+ _, seq = block(seq, None, pe, mod, None, pag_strength=layer_pag, seqlens=window_lens)
+ txt, img = torch.split(seq[:, inverse], [txt.shape[1], img.shape[1]], dim=1)
+
+ img_by_mod: dict[str, Tensor] = {}
+ pos = 0
+ for k in active:
+ length = sum(lens_by_mod[k])
+ img_by_mod[k] = img[:, pos : pos + length]
+ pos += length
+ for k in inactive:
+ img_by_mod[k] = content_by_mod[k]
+
+ if self.depth_late_blocks > 0:
+ for d in range(self.depth_late_blocks):
+ for m in all_mods:
+ img_by_mod[m] = self.late_content_mode_blocks[m][d](
+ img_by_mod[m], pe_by_mod[m], late_content_mods[m], seqlens=mod_lens.get(m)
+ )
+ txt = self.late_txt_mode_blocks[d](txt, pe_ctx, late_txt_mod, seqlens=ctx_lens)
+
+ final = {
+ k: last_layer_forward_dedup(self.final_layer[k], img_by_mod[k], vec_rows_by_mod[k], counts_by_mod[k], dtype)
+ for k in all_mods
+ }
+ out: dict[str, Tensor] = {}
+ for k in active:
+ pos = 0
+ for name, length in zip(names_by_mod[k], lens_by_mod[k], strict=True):
+ out[name] = final[k][:, pos : pos + length]
+ pos += length
+ return out
+
+
+# ---------------------------------------------------------------------------------------------- install
+def _modulations(dit: JointSingleSeq) -> list[tuple[str, nn.Module]]:
+ out = []
+ for kind in ("early_stream_modulations", "single_stream_modulations", "late_stream_modulations"):
+ for name, m in getattr(dit, kind, nn.ModuleDict()).items():
+ out.append((f"{kind}.{name}", m))
+ return out
+
+
+def _unsupported_reason(dit: nn.Module, compile_model: bool) -> str | None:
+ if not isinstance(dit, JointSingleSeq):
+ return f"expected a JointSingleSeq, got {type(dit).__name__}"
+ if compile_model:
+ return "compiled models keep the original forward"
+ if JointSingleSeq.forward is not _ORIGINAL_FORWARD:
+ return "JointSingleSeq.forward was replaced at class level by other code"
+ own = dit.__dict__.get("forward")
+ if own is not None and getattr(own, "__func__", None) is not forward_dedup:
+ return "the instance forward is already patched by other code"
+ time_in = getattr(dit, "time_in", None)
+ if not isinstance(getattr(time_in, "in_layer", None), nn.Linear):
+ return "time_in is not an MLPEmbedder"
+ if not isinstance(getattr(dit, "vector_in", None), nn.Module):
+ return "vector_in is not a module"
+ mods = _modulations(dit)
+ if not mods:
+ return "no Modulation modules"
+ for name, m in mods:
+ if type(m) is not Modulation or m.multiplier != 3 or m.is_double:
+ return f"{name}: unsupported Modulation (multiplier {getattr(m, 'multiplier', '?')})"
+ if not isinstance(m.lin, nn.Linear) or m.lin.bias is not None:
+ return f"{name}: modulation linear with bias is not supported"
+ for name, layer in dit.final_layer.items():
+ if type(layer) is not LastLayer:
+ return f"final_layer.{name}: unsupported class {type(layer).__name__}"
+ lin = layer.adaLN_modulation[1]
+ if not isinstance(lin, nn.Linear) or lin.bias is not None or lin.weight.shape[0] != 2 * lin.weight.shape[1]:
+ return f"final_layer.{name}: unsupported adaLN linear"
+ if not isinstance(layer.norm_final, nn.LayerNorm):
+ return f"final_layer.{name}: unsupported norm_final"
+ return None
+
+
+def is_installed(dit: nn.Module) -> bool:
+ own = dit.__dict__.get("forward")
+ return own is not None and getattr(own, "__func__", None) is forward_dedup
+
+
+def runtime_info(dit: nn.Module) -> dict:
+ settings = getattr(dit, _SETTINGS_ATTR, None) or {}
+ info = {
+ "installed": is_installed(dit),
+ "require": _REQUIRE,
+ "check_constant_runs": settings.get("check_constant_runs"),
+ "modulation_count": len(_modulations(dit)) if isinstance(dit, JointSingleSeq) else 0,
+ "final_layer_count": len(dit.final_layer) if isinstance(dit, JointSingleSeq) else 0,
+ "parameters_added": 0,
+ "scope": "packed training calls of one JointSingleSeq instance (seqlens given, training mode); "
+ "unpacked calls and inference run the original forward",
+ }
+ if _REQUIRE and not info["installed"]:
+ raise RuntimeError(f"Required time-embedding dedup is not installed: {info}")
+ return info
+
+
+def install_training_time_embed_dedup(
+ dit: nn.Module, *, compile_model: bool = False, check_constant_runs: str = "async"
+) -> dict:
+ """Replace ``dit.forward`` (instance-level) with :func:`forward_dedup`; returns :func:`runtime_info`.
+
+ Structural checks first (architecture contract, no foreign patches); on failure the module is left
+ untouched and ``{"installed": False, "reason": ...}`` is returned, or ``RuntimeError`` is raised when
+ ``FLUX_ACTION_TIME_EMBED_DEDUP_REQUIRE=1``. Idempotent. Works before or after ``fully_shard``.
+ """
+ if check_constant_runs not in CHECK_MODES:
+ raise ValueError(f"check_constant_runs must be one of {CHECK_MODES}, got {check_constant_runs!r}")
+ reason = _unsupported_reason(dit, compile_model)
+ if reason is not None:
+ if _REQUIRE:
+ raise RuntimeError(f"Required time-embedding dedup installation failed: {reason}")
+ return {"installed": False, "reason": reason, "require": False, "parameters_added": 0}
+ object.__setattr__(dit, _SETTINGS_ATTR, {"check_constant_runs": check_constant_runs})
+ dit.__dict__["forward"] = types.MethodType(forward_dedup, dit)
+ return runtime_info(dit)
+
+
+def uninstall_time_embed_dedup(dit: nn.Module) -> bool:
+ """Remove the instance-level forward installed by :func:`install_training_time_embed_dedup`."""
+ if not is_installed(dit):
+ return False
+ del dit.__dict__["forward"]
+ dit.__dict__.pop(_SETTINGS_ATTR, None)
+ return True
+
+
+# -------------------------------------------------------------------------------------------- self-test
+def _tiny_dit(device: torch.device, dtype: torch.dtype, seed: int = 0, depth_late_blocks: int = 0) -> JointSingleSeq:
+ from flux_action.models.transformer import JointSingleSeqParams # local: keeps the module import light
+
+ params = JointSingleSeqParams(
+ in_channels={"video": 8, "video_cond": 8, "act": 4, "act_cond": 4},
+ sequence={"x_video": "video", "x_video_cond": "video_cond", "x_act": "act", "x_act_cond": "act_cond"},
+ vec_in_dim=12,
+ context_in_dim=16,
+ hidden_size=64,
+ num_heads=2,
+ depth=1,
+ depth_single_blocks=2,
+ depth_late_blocks=depth_late_blocks,
+ axes_dim=[8, 8, 8, 8],
+ attn_mode="torch",
+ )
+ torch.manual_seed(seed)
+ dit = JointSingleSeq(params).to(device=device, dtype=dtype)
+ dit.time_in.float() # the fp32 group of shard_dit
+ return dit.train()
+
+
+def _tiny_inputs(
+ device: torch.device,
+ dtype: torch.dtype,
+ ctx_lens: Sequence[int],
+ seed: int = 1,
+ *,
+ lv: int = 6,
+ lvc: int = 3,
+ la: int = 4,
+ lac: int = 1,
+ cond_noise: bool = False,
+ separate_action_t: bool = False,
+ vector_zero: bool = True,
+) -> dict:
+ """Packed kwargs for ``len(ctx_lens)`` windows, timesteps constant per (stream, window) like the trainer's."""
+ g = torch.Generator().manual_seed(seed)
+ w = len(ctx_lens)
+ t = torch.rand(w, generator=g).to(torch.bfloat16).float()
+ t_act = torch.rand(w, generator=g).to(torch.bfloat16).float() if separate_action_t else t
+ t_cond = torch.rand(w, generator=g).mul(0.1).to(torch.bfloat16).float() if cond_noise else torch.zeros(w)
+
+ def stream(name: str, n: int, c: int, tval: Tensor) -> dict:
+ xs = torch.randn(w, n, c, generator=g)
+ ids = torch.randint(0, 20, (w, n, 4), generator=g)
+ ts = tval[:, None] * torch.ones(w, n)
+ return {
+ name: xs.reshape(1, w * n, c).to(device, dtype),
+ f"{name}_ids": ids.reshape(1, w * n, 4).to(device),
+ f"{name}_timesteps": ts.reshape(1, w * n).to(device),
+ }
+
+ kw: dict = {}
+ kw |= stream("x_video", lv, 8, t)
+ kw |= stream("x_video_cond", lvc, 8, t_cond)
+ kw |= stream("x_act", la, 4, t_act)
+ kw |= stream("x_act_cond", lac, 4, torch.zeros(w))
+ ctx = torch.cat([torch.randn(1, n, 16, generator=g) for n in ctx_lens], 1)
+ ctx_ids = torch.cat([torch.randint(0, 20, (1, n, 4), generator=g) for n in ctx_lens], 1)
+ vector = torch.zeros(1, 12) if vector_zero else torch.randn(1, 12, generator=g)
+ kw |= {
+ "ctx": ctx.to(device, dtype),
+ "ctx_ids": ctx_ids.to(device),
+ "timesteps_ctx": torch.zeros(1, ctx.shape[1], device=device),
+ "vector": vector.to(device, dtype),
+ "seqlens": {
+ "ctx": list(ctx_lens),
+ "x_video": [lv] * w,
+ "x_video_cond": [lvc] * w,
+ "x_act": [la] * w,
+ "x_act_cond": [lac] * w,
+ },
+ }
+ return kw
+
+
+def _compare(a: Tensor, b: Tensor) -> dict:
+ a64, b64 = a.detach().double(), b.detach().double()
+ diff = a64 - b64
+ return {
+ "max_abs": diff.abs().max().item() if diff.numel() else 0.0,
+ "ref_absmax": b64.abs().max().item() if diff.numel() else 0.0,
+ "rel_l2": (diff.norm() / b64.norm().clamp_min(1e-30)).item() if diff.numel() else 0.0,
+ "bitwise": (a.detach() == b.detach()).double().mean().item() if diff.numel() else 1.0,
+ }
+
+
+def self_test(device: str | torch.device = "cpu", dtype: torch.dtype = torch.bfloat16, strict: bool = True) -> dict:
+ """Dedup vs original forward on a tiny ``JointSingleSeq`` (fwd + bwd, packed windows with unequal
+ contexts, per-window conditioning noise and separate action timesteps): outputs within bf16 rounding
+ noise, every gradient present on both sides, fallbacks identical. Raises ``AssertionError`` with
+ ``strict``; returns the measured numbers."""
+ device = torch.device(device)
+ dit = _tiny_dit(device, dtype)
+ kw = _tiny_inputs(device, dtype, [5, 3, 4, 5], cond_noise=True, separate_action_t=True, vector_zero=False)
+
+ def run(installed: bool) -> tuple[dict, dict]:
+ if installed:
+ assert install_training_time_embed_dedup(dit)["installed"]
+ else:
+ uninstall_time_embed_dedup(dit)
+ dit.zero_grad(set_to_none=True)
+ pred = dit(**kw)
+ torch.manual_seed(3)
+ loss = sum(
+ (p.float() * torch.randn(p.shape, generator=torch.Generator().manual_seed(i)).to(p.device)).sum()
+ for i, p in enumerate(pred.values())
+ )
+ loss.backward()
+ grads = {n: p.grad.detach().clone() for n, p in dit.named_parameters() if p.grad is not None}
+ return {k: v.detach().clone() for k, v in pred.items()}, grads
+
+ pred_ref, grads_ref = run(False)
+ pred_new, grads_new = run(True)
+ uninstall_time_embed_dedup(dit)
+ report = {"pred": {k: _compare(pred_new[k], pred_ref[k]) for k in pred_ref}}
+ report["grads_missing"] = sorted(set(grads_ref) ^ set(grads_new))
+ report["grads"] = {n: _compare(grads_new[n], grads_ref[n]) for n in grads_ref if n in grads_new}
+ worst_pred = max(v["rel_l2"] for v in report["pred"].values())
+ report["worst_pred_rel_l2"] = worst_pred
+ if strict:
+ assert not report["grads_missing"], report["grads_missing"]
+ rtol, atol = (0.03, 1e-3) if dtype == torch.bfloat16 else (1e-4, 1e-6)
+ assert worst_pred < rtol, report["pred"]
+ bad = {n: v for n, v in report["grads"].items() if v["max_abs"] > rtol * v["ref_absmax"] + atol}
+ assert not bad, bad
+ return report
+
+
+if __name__ == "__main__": # pragma: no cover
+ import json
+
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
+ print(json.dumps(self_test(dev), indent=1, default=str)[:4000])
diff --git a/flux-umi/src/flux_action/models/positional.py b/flux-umi/src/flux_action/models/positional.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba081411eee4cda06b04024a64baf5f6001ac167
--- /dev/null
+++ b/flux-umi/src/flux_action/models/positional.py
@@ -0,0 +1,126 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Position-id packers and scatter helpers."""
+
+from collections.abc import Callable
+
+import torch
+from einops import rearrange
+from torch import Tensor
+
+
+def prc_vid(x: Tensor, t_coord: Tensor | None = None, l_coord: Tensor | None = None) -> tuple[Tensor, Tensor]:
+ _, t, h, w = x.shape
+ dev = x.device
+ if t_coord is None:
+ t_coord = torch.arange(t, device=dev)
+ coords = {
+ "t": t_coord.to(dev),
+ "h": torch.arange(h, device=dev),
+ "w": torch.arange(w, device=dev),
+ "l": torch.arange(1, device=dev) if l_coord is None else l_coord.to(dev),
+ }
+ x_ids = torch.cartesian_prod(coords["t"], coords["h"], coords["w"], coords["l"])
+ x = rearrange(x, "c t h w -> (t h w) c")
+ return x, x_ids
+
+
+def prc_action(
+ x: Tensor, t_coord: Tensor | None = None, l_coord: Tensor | None = None
+) -> tuple[Tensor, Tensor]:
+ _, t = x.shape
+ dev = x.device
+ t_coord = torch.arange(t, device=dev) if t_coord is None else t_coord.to(dev)
+ coords = {
+ "t": t_coord,
+ "h": torch.arange(1, device=dev),
+ "w": torch.arange(1, device=dev),
+ "l": torch.arange(1, device=dev) if l_coord is None else l_coord.to(dev),
+ }
+ x_ids = torch.cartesian_prod(coords["t"], coords["h"], coords["w"], coords["l"])
+ x = rearrange(x, "c t -> t c")
+ return x, x_ids
+
+
+def prc_txt(x: Tensor, t_coord: Tensor | None = None, l_coord: Tensor | None = None) -> tuple[Tensor, Tensor]:
+ assert l_coord is None, "l_coord not supported for txt"
+ length, _ = x.shape
+ dev = x.device
+ coords = {
+ "t": torch.arange(1, device=dev) if t_coord is None else t_coord.to(dev),
+ "h": torch.arange(1, device=dev),
+ "w": torch.arange(1, device=dev),
+ "l": torch.arange(length, device=dev),
+ }
+ x_ids = torch.cartesian_prod(coords["t"], coords["h"], coords["w"], coords["l"])
+ return x, x_ids
+
+
+def _batched(fn: Callable) -> Callable:
+ def wrapped(
+ x: Tensor, t_coord: Tensor | None = None, l_coord: Tensor | None = None
+ ) -> tuple[Tensor, Tensor]:
+ pairs = [
+ fn(
+ x[i],
+ t_coord[i] if t_coord is not None else None,
+ l_coord[i] if l_coord is not None else None,
+ )
+ for i in range(len(x))
+ ]
+ xs, ids = zip(*pairs, strict=True)
+ return torch.stack(xs), torch.stack(ids)
+
+ return wrapped
+
+
+batched_prc_vid = _batched(prc_vid)
+batched_prc_action = _batched(prc_action)
+batched_prc_txt = _batched(prc_txt)
+
+
+def _compress_time(t_ids: Tensor) -> Tensor:
+ t_max = torch.max(t_ids)
+ remap = torch.zeros((t_max + 1,), device=t_ids.device, dtype=t_ids.dtype)
+ uniq = torch.unique(t_ids, sorted=True)
+ remap[uniq] = torch.arange(len(uniq), device=t_ids.device, dtype=t_ids.dtype)
+ return remap[t_ids]
+
+
+def scatter_ids(x: Tensor, x_ids: Tensor) -> list[Tensor]:
+ out_list = []
+ for data, pos in zip(x, x_ids, strict=True):
+ _, ch = data.shape
+ t_ids = pos[:, 0].to(torch.int64)
+ h_ids = pos[:, 1].to(torch.int64)
+ w_ids = pos[:, 2].to(torch.int64)
+
+ t_ids_c = _compress_time(t_ids)
+ t = int(torch.max(t_ids_c)) + 1
+ h = int(torch.max(h_ids)) + 1
+ w = int(torch.max(w_ids)) + 1
+
+ flat_ids = t_ids_c * w * h + h_ids * w + w_ids
+ out = torch.zeros((t * h * w, ch), device=data.device, dtype=data.dtype)
+ out.scatter_(0, flat_ids.unsqueeze(1).expand(-1, ch), data)
+ out_list.append(rearrange(out, "(t h w) c -> 1 c t h w", t=t, h=h, w=w))
+ return out_list
+
+
+def times_to_ids(time: Tensor) -> Tensor:
+ return (time * 1000 // 10).to(dtype=torch.int64)
+
+
+def times_to_ids_round(time: Tensor) -> Tensor:
+ return torch.round(time * 100).to(dtype=torch.int64)
diff --git a/flux-umi/src/flux_action/models/runtime.py b/flux-umi/src/flux_action/models/runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..4156f8d7f890bf6af84200cb5630cf77da4356a2
--- /dev/null
+++ b/flux-umi/src/flux_action/models/runtime.py
@@ -0,0 +1,72 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Small runtime helpers shared by the flux3 model components."""
+
+import os
+
+import torch
+
+MOCK_INIT_SEED = 0
+TRUNK_WEIGHTS_FILENAME = "dit.safetensors"
+
+
+def parse_weight_spec(spec: str) -> tuple[str, str | None, str | None]:
+ """``repo_id[:filename][@revision]`` -> ``(repo_id, filename, revision)``.
+
+ ``@revision`` pins a commit sha, branch or tag so a recipe keeps loading the same bytes after the file
+ is replaced on the repository head. Local paths are not parsed; check :func:`os.path.exists` first.
+ """
+ body, _, revision = spec.partition("@")
+ repo_id, _, filename = body.partition(":")
+ if not repo_id:
+ raise ValueError(f"weight spec must be a local path or repo_id[:filename][@revision], got {spec!r}")
+ return repo_id, filename or None, revision or None
+
+
+def _looks_like_local_path(repo_id: str) -> bool:
+ """Whether a spec's repo_id reads as a filesystem path rather than a Hub ``namespace/name``."""
+ return (
+ repo_id.startswith((os.sep, "." + os.sep, ".." + os.sep, "~"))
+ or repo_id.endswith((".safetensors", ".pt", ".bin"))
+ or repo_id.count("/") > 1
+ )
+
+
+def resolve_weights(spec: str, default_filename: str) -> str:
+ """A local file or directory is returned as is; anything else is downloaded from the Hub."""
+ if os.path.exists(spec):
+ return spec
+ repo_id, filename, revision = parse_weight_spec(spec)
+ if _looks_like_local_path(repo_id):
+ raise FileNotFoundError(
+ f"no such file or directory: {spec!r}. Configured weight paths are relative to the working "
+ f"directory; download the weights first (see docs/setup.md). Pass a Hub spec as "
+ f"repo_id[:filename][@revision] to download instead."
+ )
+ from huggingface_hub import hf_hub_download
+
+ return hf_hub_download(repo_id, filename or default_filename, revision=revision)
+
+
+def random_init_(model: torch.nn.Module, dtype: torch.dtype = torch.bfloat16) -> None:
+ """Fill a model with small random values and cast to ``dtype`` (weightless wiring/smoke runs).
+
+ Seeded so repeated builds are identical.
+ """
+ torch.manual_seed(MOCK_INIT_SEED)
+ with torch.no_grad():
+ for p in model.parameters():
+ if not p.is_meta:
+ p.normal_(0, 0.02)
+ model.to(dtype=dtype)
diff --git a/flux-umi/src/flux_action/models/swiglu_native_out.py b/flux-umi/src/flux_action/models/swiglu_native_out.py
new file mode 100644
index 0000000000000000000000000000000000000000..65254e462157a5b5e89aba6b4d3349ed93ad6d7f
--- /dev/null
+++ b/flux-umi/src/flux_action/models/swiglu_native_out.py
@@ -0,0 +1,122 @@
+"""Isolated SwiGLU candidate A: original ATen math, no gradient concatenation.
+
+No production module imports this file. CUDA support is deliberately limited to
+the audited Torch 2.10 BF16 environment until the independent GPU screen runs.
+CPU BF16/FP32/FP64 support exists for interface and numerical-gradient testing.
+"""
+
+import torch
+from torch import Tensor, nn
+from torch.nn import functional as F
+
+AUDITED_TORCH_GIT = "449b1768410104d3ed79d3bcfe4ba1d65c7f22c0"
+
+
+def swiglu_reference(x: Tensor) -> Tensor:
+ """The unchanged SiLUActivation expression, including its BF16 intermediate."""
+ left, right = x.chunk(2, dim=-1)
+ return F.silu(left) * right
+
+
+def unsupported_reason(x: Tensor):
+ """Metadata-only dispatch decision; no values, copies, or GPU initialization."""
+ if torch.compiler.is_compiling():
+ return "torch.compile uses the original graph"
+ if torch._C._are_functorch_transforms_active():
+ return "torch.func transforms use the original graph"
+ if torch.autograd.forward_ad._current_level >= 0:
+ return "forward-mode AD uses the original graph"
+ if type(x) is not Tensor or x.layout != torch.strided:
+ return "Tensor subclasses and non-strided layouts use the original graph"
+ if x.ndim < 1 or x.shape[-1] < 2 or x.shape[-1] % 2 or x.numel() == 0:
+ return "a nonempty even last dimension is required"
+ if not x.is_contiguous():
+ return "only contiguous full inputs are supported"
+ if x.device.type == "cpu":
+ if x.dtype not in (torch.bfloat16, torch.float32, torch.float64):
+ return "CPU validation supports BF16, FP32 and FP64"
+ elif x.device.type == "cuda":
+ if x.dtype != torch.bfloat16:
+ return "the CUDA candidate currently supports only BF16"
+ if (str(torch.__version__).split("+")[0] != "2.10.0"
+ or torch.version.git_version != AUDITED_TORCH_GIT
+ or torch.version.cuda != "13.0"):
+ return "CUDA support is limited to the audited Torch 2.10/CUDA 13.0"
+ else:
+ return "this device uses the original graph"
+ return None
+
+
+def _reference_vjp(x: Tensor, grad: Tensor, *, create_graph: bool) -> Tensor:
+ # Recompute from saved x, not the detached gate saved by Function.forward.
+ # This exactly delegates higher derivatives to the original autograd graph.
+ with torch.enable_grad():
+ result, = torch.autograd.grad(
+ swiglu_reference(x), x, grad, create_graph=create_graph,
+ )
+ return result
+
+
+def _direct_backward(x: Tensor, rounded_gate: Tensor, grad: Tensor) -> Tensor:
+ left, right = x.chunk(2, dim=-1)
+ dgate = grad * right # Mandatory original dtype rounding, BF16 in training.
+ # Original chunk backward concatenates into a fresh canonical contiguous dx.
+ # ATen TensorIterator keeps its 64-bit partitioning for production-sized inputs.
+ dx = torch.empty(x.shape, dtype=x.dtype, device=x.device)
+ width = x.shape[-1] // 2
+ torch.ops.aten.silu_backward.grad_input(dgate, left, grad_input=dx[..., :width])
+ torch.mul(grad, rounded_gate, out=dx[..., width:])
+ return dx
+
+
+class _NativeOutSwiGLU(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x):
+ left, right = x.chunk(2, dim=-1)
+ rounded_gate = F.silu(left)
+ output = rounded_gate * right
+ ctx.set_materialize_grads(False)
+ ctx.save_for_backward(x, rounded_gate)
+ return output
+
+ @staticmethod
+ def backward(ctx, grad):
+ if grad is None:
+ return None
+ x, rounded_gate = ctx.saved_tensors
+ create_graph = torch.is_grad_enabled()
+ if (create_graph or type(grad) is not Tensor or grad.layout != torch.strided
+ or grad.dtype != x.dtype or grad.device != x.device):
+ return _reference_vjp(x, grad, create_graph=create_graph)
+ return _direct_backward(x, rounded_gate, grad)
+
+
+def swiglu_native_out(x: Tensor, *, require_candidate: bool = False) -> Tensor:
+ reason = unsupported_reason(x)
+ if reason is not None:
+ if require_candidate:
+ raise ValueError(reason)
+ return swiglu_reference(x)
+ if not torch.is_grad_enabled() or not x.requires_grad:
+ # Forward is unchanged and has no benefit from constructing custom state.
+ return swiglu_reference(x)
+ return _NativeOutSwiGLU.apply(x)
+
+
+class NativeOutSiLUActivation(nn.Module):
+ """Test-only replacement with the original empty module/state-dict structure."""
+
+ def __init__(self, *, require_candidate: bool = False):
+ super().__init__()
+ self.gate_fn = nn.SiLU()
+ self.require_candidate = require_candidate
+
+ def forward(self, x: Tensor) -> Tensor:
+ if (type(self.gate_fn) is not nn.SiLU or self.gate_fn.inplace
+ or self.gate_fn._forward_hooks or self.gate_fn._forward_pre_hooks
+ or self.gate_fn._backward_hooks):
+ if self.require_candidate:
+ raise ValueError("a modified or hooked gate module uses the original module graph")
+ left, right = x.chunk(2, dim=-1)
+ return self.gate_fn(left) * right
+ return swiglu_native_out(x, require_candidate=self.require_candidate)
diff --git a/flux-umi/src/flux_action/models/swiglu_native_out_adapter.py b/flux-umi/src/flux_action/models/swiglu_native_out_adapter.py
new file mode 100644
index 0000000000000000000000000000000000000000..501116b367fe3535d3156b0eb28101231af8c033
--- /dev/null
+++ b/flux-umi/src/flux_action/models/swiglu_native_out_adapter.py
@@ -0,0 +1,181 @@
+"""Opt-in training adapter for the byte-identical screened SwiGLU helper.
+
+Installation adds ordinary Python flags to existing activation modules. Module,
+parameter and buffer ownership/state keys are unchanged. CUDA work is never
+performed during installation; the explicit CPU oracle is only for tests.
+"""
+from functools import lru_cache
+import hashlib
+import os
+from pathlib import Path
+
+import torch
+from torch import nn
+from torch.nn.modules import module as module_api
+
+from . import swiglu_native_out as _core
+from .swiglu_native_out import AUDITED_TORCH_GIT, swiglu_native_out, unsupported_reason
+
+CORE_SHA256 = "0b0f736c8b5b92c4354a4733f0d9aef885d871e0057aa7650dcb76b9c4ce6b36"
+_ORIGINAL_SILU_FORWARD = nn.SiLU.forward
+_PACKED_LENGTHS = frozenset((128, 4096, 10240, 32768, 262144, 309376))
+
+
+def backend_reason():
+ if (str(torch.__version__) != "2.10.0+cu130" or torch.version.cuda != "13.0"
+ or torch.version.git_version != AUDITED_TORCH_GIT):
+ return "unvalidated Torch/CUDA arithmetic environment"
+ return None
+
+
+def gate_reason(activation):
+ if "forward" in activation.__dict__:
+ return "modified activation forward"
+ gate = activation.gate_fn
+ if (type(gate) is not nn.SiLU or gate.inplace or "forward" in gate.__dict__
+ or nn.SiLU.forward is not _ORIGINAL_SILU_FORWARD):
+ return "modified or replaced SiLU gate"
+ if any(getattr(gate, name) for name in (
+ "_forward_hooks", "_forward_pre_hooks", "_backward_hooks", "_backward_pre_hooks"
+ )):
+ return "hooked SiLU gate"
+ if any(getattr(module_api, name) for name in (
+ "_global_forward_hooks", "_global_forward_pre_hooks",
+ "_global_backward_hooks", "_global_backward_pre_hooks"
+ )):
+ return "global module hooks observe the SiLU gate"
+ return None
+
+
+def core_source_sha256():
+ return hashlib.sha256(Path(_core.__file__).read_bytes()).hexdigest()
+
+
+def install_training_swiglu(dit, *, compile_model=False, cpu_oracle=False):
+ """Validate all modules before atomically marking the original activations."""
+ from .transformer import JointSingleSeq, ModeBlock, SiLUActivation, SingleStreamBlock
+
+ require = os.environ.get("FLUX_ACTION_SWIGLU_NATIVE_OUT_REQUIRE_KERNEL") == "1"
+ expected = 53
+
+ def unsupported(reason):
+ if require:
+ raise RuntimeError(f"Required native-out SwiGLU installation failed: {reason}")
+ return {"enabled": False, "configured": False, "actual_activation_count": 0,
+ "expected_activation_count": expected, "require_kernel": False, "reason": reason}
+
+ if type(dit) is not JointSingleSeq:
+ return unsupported("unrecognized DiT class")
+ if compile_model:
+ return unsupported("compiled model is outside the validated training path")
+ if cpu_oracle:
+ expected = ((len(dit.in_channels) + 1) * (dit.depth + dit.depth_late_blocks)
+ + dit.depth_single_blocks)
+ elif (dit.hidden_size != 3072 or dit.num_heads != 24 or dit.mlp_ratio != 3.0
+ or dit.depth != 5 or dit.depth_single_blocks != 28 or dit.depth_late_blocks != 0
+ or len(dit.in_channels) != 4):
+ return unsupported("DiT configuration differs from the audited 53-block G2 model")
+ reason = None if cpu_oracle else backend_reason()
+ if reason is not None:
+ return unsupported(reason)
+ if core_source_sha256() != CORE_SHA256:
+ return unsupported("core source differs from the GPU-screened implementation")
+ blocks = [(name, layer) for name, layer in dit.named_modules()
+ if isinstance(layer, (ModeBlock, SingleStreamBlock))]
+ if len(blocks) != expected:
+ return unsupported("unexpected transformer-block inventory")
+ activations = []
+ for name, block in blocks:
+ if (type(block) not in (ModeBlock, SingleStreamBlock)
+ or type(block.mlp_act) is not SiLUActivation or block.mlp_mult_factor != 2
+ or block.mlp_hidden_dim != int(dit.hidden_size * dit.mlp_ratio)
+ or gate_reason(block.mlp_act) is not None):
+ return unsupported(f"modified activation/block at {name}")
+ activations.append((name + ".mlp_act", block.mlp_act))
+ if (len({id(layer) for _, layer in activations}) != expected
+ or sum(type(layer) is SiLUActivation for layer in dit.modules()) != expected):
+ return unsupported("shared or unexpected activation modules")
+ for _, layer in activations:
+ layer._swiglu_native_out_enabled = True
+ layer._swiglu_native_out_require_kernel = require
+ layer._swiglu_native_out_cpu_oracle = cpu_oracle
+ dit._swiglu_native_out_spec = {
+ "enabled": True, "configured": True, "expected_activation_count": expected,
+ "require_kernel": require, "cpu_oracle": cpu_oracle,
+ "module_names": [name for name, _ in activations],
+ "torch": str(torch.__version__), "torch_git": torch.version.git_version,
+ "cuda": torch.version.cuda, "backend_supported": True,
+ "validated_device_capability": [10, 3], "core_sha256": CORE_SHA256,
+ "scope": "original DiT activations, training/eager/grad-enabled input requiring grad",
+ "intentional_reference_paths": ["eval", "no_grad", "input without gradient", "compiler/transforms/forward AD"],
+ "modules_parameters_buffers_and_state_keys_unchanged": True,
+ }
+ return inspect_training_swiglu(dit)
+
+
+def inspect_training_swiglu(dit):
+ """Re-read actual installed flags; this does not claim kernel execution."""
+ from .transformer import SiLUActivation
+
+ spec = getattr(dit, "_swiglu_native_out_spec", None)
+ if spec is None:
+ return None
+ marked = [(name, layer) for name, layer in dit.named_modules()
+ if getattr(layer, "_swiglu_native_out_enabled", False)]
+ valid = [".".join(part for part in name.split(".") if part != "_checkpoint_wrapped_module")
+ for name, layer in marked if type(layer) is SiLUActivation
+ and getattr(layer, "_swiglu_native_out_require_kernel", None) == spec["require_kernel"]
+ and getattr(layer, "_swiglu_native_out_cpu_oracle", None) == spec["cpu_oracle"]
+ and gate_reason(layer) is None]
+ matches = valid == spec["module_names"] and len(marked) == spec["expected_activation_count"]
+ result = {**spec, "actual_activation_count": len(valid), "actual_inventory_matches": matches,
+ "actual_module_names": [name for name, _ in marked], "core_sha256": core_source_sha256()}
+ if spec["require_kernel"] and (not matches or result["core_sha256"] != CORE_SHA256):
+ raise RuntimeError(f"Required native-out SwiGLU actual inventory changed: {result}")
+ return result
+
+
+def runtime_optimization_info(policy):
+ """Build-time runner hook: verify actual modules after checkpoint/FSDP wrapping."""
+ require = os.environ.get("FLUX_ACTION_SWIGLU_NATIVE_OUT_REQUIRE_KERNEL") == "1"
+ info = inspect_training_swiglu(policy.dit)
+ if require:
+ expected = {"enabled": True, "configured": True, "expected_activation_count": 53,
+ "actual_activation_count": 53, "actual_inventory_matches": True,
+ "require_kernel": True, "cpu_oracle": False, "backend_supported": True}
+ if (not getattr(policy.config, "dit_swiglu_native_out", False) or info is None
+ or any(info.get(key) != value for key, value in expected.items())):
+ raise RuntimeError(f"Required native-out SwiGLU runtime installation was not verified: {info}")
+ return info
+
+
+@lru_cache(maxsize=16)
+def _device_supported(index):
+ return torch.cuda.get_device_capability(index) == (10, 3)
+
+
+def dispatch_training_swiglu(activation, x):
+ """Return None to execute the original gate-module expression."""
+ if torch.compiler.is_compiling():
+ return None
+ if torch._C._are_functorch_transforms_active() or torch.autograd.forward_ad._current_level >= 0:
+ return None
+ if (not activation.training or not torch.is_grad_enabled() or not x.requires_grad
+ or not getattr(activation, "_swiglu_native_out_enabled", False)):
+ return None
+ oracle = activation._swiglu_native_out_cpu_oracle
+ reason = gate_reason(activation) or unsupported_reason(x)
+ if reason is None and not oracle:
+ reason = backend_reason()
+ if reason is None and (x.device.type != "cuda" or x.dtype != torch.bfloat16):
+ reason = "production dispatch requires a BF16 CUDA tensor"
+ if reason is None and (x.ndim != 3 or x.shape[0] != 1 or x.shape[-1] != 18432
+ or x.shape[1] not in _PACKED_LENGTHS):
+ reason = "input differs from the audited packed G2 SwiGLU shapes"
+ if reason is None and not _device_supported(x.device.index):
+ reason = "native-out SwiGLU was numerically screened only on SM103"
+ if reason is not None:
+ if activation._swiglu_native_out_require_kernel:
+ raise RuntimeError(f"Required native-out SwiGLU dispatch failed: {reason}")
+ return None
+ return swiglu_native_out(x, require_candidate=True)
diff --git a/flux-umi/src/flux_action/models/text_encoder.py b/flux-umi/src/flux_action/models/text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..da868e1bce492206e44aae1234f76580461736f5
--- /dev/null
+++ b/flux-umi/src/flux_action/models/text_encoder.py
@@ -0,0 +1,237 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Qwen3-VL text encoder: stacks hidden states from selected layers along the
+channel dim to form the DiT text context. Uses Qwen3-VL-4B: `ctx` = selected hidden layers stacked along the channel dim
+(width = len(output_layer) * qwen_hidden = 8 * 2560 = 20480). Needs `transformers`.
+
+Prompts are encoded one at a time, right-padded to the next multiple of
+``TEXT_PAD_MULTIPLE`` (capped at ``TEXT_PAD_MAX_LENGTH``). Prompt and negative
+bucket to independent lengths, so CFG runs as two bs=1 forward passes (see
+``flux_action.inference.sampling``).
+"""
+
+import math
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import torch
+from einops import rearrange
+from torch import Tensor, nn
+
+TEXT_PAD_MULTIPLE = 80
+TEXT_PAD_MAX_LENGTH = 8192
+
+
+def padded_text_token_count(
+ real_len: int,
+ pad_multiple: int,
+ pad_max_length: int,
+) -> int:
+ return min(math.ceil(real_len / pad_multiple) * pad_multiple, pad_max_length)
+
+
+@dataclass
+class Qwen3VLEmbedderParams:
+ output_layer: list[int] = field(default_factory=lambda: [4, 8, 12, 16, 20, 24, 28, 32])
+ torch_dtype: str = "bfloat16"
+ stack_channels: bool = True
+ use_compile: bool = False
+ compile_config: dict | None = field(default_factory=lambda: {"dynamic_compile": True})
+
+
+class Qwen3VLEmbedder(nn.Module):
+ is_mock = False # marker for tools and tests; the policy calls ``forward_bucketed`` on either encoder
+
+ def __init__(self, model_spec: str, params: Qwen3VLEmbedderParams = Qwen3VLEmbedderParams()):
+ super().__init__()
+ from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
+
+ self.params = params
+ self.dtype = getattr(torch, params.torch_dtype)
+ self.output_layer = list(params.output_layer)
+ self.stack_channels = params.stack_channels
+
+ # ``repo_id[:subfolder][@revision]`` also supports shared frozen encoders.
+ hub_kwargs = {}
+ if not os.path.exists(model_spec):
+ from .runtime import parse_weight_spec
+
+ model_spec, subfolder, revision = parse_weight_spec(model_spec)
+ hub_kwargs = {"revision": revision, "subfolder": subfolder or ""}
+ self.model = Qwen3VLForConditionalGeneration.from_pretrained(
+ model_spec, torch_dtype=self.dtype, **hub_kwargs
+ )
+ self.processor = AutoProcessor.from_pretrained(model_spec, **hub_kwargs)
+ if self.processor.tokenizer.padding_side != "right":
+ raise ValueError("the text encoder requires a right-padding tokenizer")
+
+ if params.use_compile:
+ cc = params.compile_config or {}
+ for layer in self.model.model.language_model.layers:
+ layer.forward = torch.compile(
+ layer.forward,
+ mode=cc.get("compile_mode", "default"),
+ fullgraph=cc.get("fullgraph", False),
+ dynamic=cc.get("dynamic_compile", False),
+ backend=cc.get("backend", "inductor"),
+ )
+
+ @torch.no_grad()
+ def forward_bucketed(self, text: str, *, fixed_length: int | None = None) -> Tensor:
+ """Single-string encode -> ``(1, L, len(output_layer) * qwen_hidden)``,
+ right-padded to the bucketed length. The DiT's ``vector`` and
+ ``timesteps_ctx`` are zeros, F3 does not condition on a pooled text
+ vector."""
+ return self.forward_bucketed_batch([text], fixed_length=fixed_length)[0]
+
+ @torch.no_grad()
+ def forward_bucketed_batch(self, texts: list[str], *, fixed_length: int | None = None) -> list[Tensor]:
+ """Encode many strings: one forward per padded length bucket, ``[(1, L_i, ...)]`` in input order.
+
+ Every string is right-padded to its own bucket (the next multiple of ``TEXT_PAD_MULTIPLE``), as
+ in :meth:`forward_bucketed`; strings of one bucket share a forward. The attention mask hides the
+ padding, so a string's context does not depend on what it is batched with.
+ """
+ if fixed_length is not None and not 1 <= fixed_length <= TEXT_PAD_MAX_LENGTH:
+ raise ValueError(f"fixed_length must be between 1 and {TEXT_PAD_MAX_LENGTH}")
+ tokenizer = self.processor.tokenizer
+ formatted = [
+ self.processor.apply_chat_template(
+ [{"role": "user", "content": text}], tokenize=False, add_generation_prompt=True
+ )
+ for text in texts
+ ]
+ buckets: dict[int, list[int]] = {}
+ for i, prompt in enumerate(formatted):
+ if fixed_length is not None:
+ buckets.setdefault(fixed_length, []).append(i)
+ continue
+ real_len = tokenizer(
+ prompt, return_tensors="pt", padding=False, truncation=True, max_length=TEXT_PAD_MAX_LENGTH
+ )["input_ids"].shape[1]
+ target = padded_text_token_count(real_len, TEXT_PAD_MULTIPLE, TEXT_PAD_MAX_LENGTH)
+ buckets.setdefault(target, []).append(i)
+ results: list[Tensor | None] = [None] * len(texts)
+ for target_length, members in sorted(buckets.items()):
+ toks = tokenizer(
+ [formatted[i] for i in members],
+ return_tensors="pt",
+ padding="max_length",
+ truncation=True,
+ max_length=target_length,
+ padding_side="right",
+ )
+ out = self.model.model(
+ input_ids=toks["input_ids"].to(self.model.device, non_blocking=True),
+ attention_mask=toks["attention_mask"].to(self.model.device, non_blocking=True),
+ output_hidden_states=True,
+ use_cache=False,
+ )
+ if len(self.output_layer) == 1:
+ result = out.hidden_states[self.output_layer[0]]
+ else:
+ stacked = torch.stack([out.hidden_states[k] for k in self.output_layer], dim=1)
+ result = rearrange(stacked, "b c l d -> b l (c d)") if self.stack_channels else stacked
+ result = result.to(self.dtype)
+ for j, i in enumerate(members):
+ results[i] = result[j : j + 1]
+ return results
+
+
+# ---------------------------------------------------------------------------------------------
+# Policy-side stand-in and loader.
+# ---------------------------------------------------------------------------------------------
+DEFAULT_TEXT_TOKENS = TEXT_PAD_MULTIPLE
+CTX_DIM = 20480 # 8 Qwen3-VL-4B layers x 2560 hidden
+VEC_DIM = 768 # pooled vector width; FLUX Action feeds zeros
+
+
+class MockTextEncoder(nn.Module):
+ """Shape-only stand-in: deterministic pseudo-random context per caption, no weights needed."""
+
+ is_mock = True
+
+ def __init__(self, context_in_dim: int = CTX_DIM, device: str | torch.device = "cpu"):
+ super().__init__()
+ self.context_in_dim = context_in_dim
+ del device # contexts are produced on the CPU; the caller moves them (see ``text_context``)
+
+ @torch.inference_mode()
+ def encode(self, batch: int, n_tokens: int = DEFAULT_TEXT_TOKENS, seed: int = 0) -> tuple[Tensor, Tensor]:
+ gen = torch.Generator().manual_seed(seed)
+ ctx = torch.randn(batch, n_tokens, self.context_in_dim, generator=gen).to(torch.bfloat16)
+ vector = torch.zeros(batch, VEC_DIM, dtype=torch.bfloat16)
+ return ctx, vector
+
+ @torch.inference_mode()
+ def forward_bucketed(self, text: str, *, fixed_length: int | None = None) -> Tensor:
+ # different captions -> different (but reproducible) contexts, so CFG has something to guide on
+ seed = sum(ord(c) * (i + 1) for i, c in enumerate(text)) % (2**31)
+ return self.encode(1, n_tokens=fixed_length or DEFAULT_TEXT_TOKENS, seed=seed)[0]
+
+ def forward_bucketed_batch(self, texts: list[str], *, fixed_length: int | None = None) -> list[Tensor]:
+ kwargs = {} if fixed_length is None else {"fixed_length": fixed_length}
+ return [self.forward_bucketed(text, **kwargs) for text in texts]
+
+
+def load_text_encoder(
+ spec: str | None,
+ device: str | torch.device = "cpu",
+ *,
+ compile_model: bool = False,
+ context_in_dim: int = CTX_DIM,
+) -> nn.Module:
+ """``spec`` = Hub id or local path of Qwen3-VL-4B (needs ``transformers``); ``None`` -> mock."""
+ if spec:
+ from ..hub import looks_like_local_path
+
+ if looks_like_local_path(str(spec)) and not Path(spec).expanduser().exists():
+ raise FileNotFoundError(
+ f"no such text encoder directory: {spec}. Paths are relative to the working directory; "
+ f"download the shared encoders first (docs/setup.md), or pass a Hub id to download them."
+ )
+ enc = Qwen3VLEmbedder(spec, Qwen3VLEmbedderParams(use_compile=compile_model))
+ enc.eval()
+ for p in enc.parameters():
+ p.requires_grad_(False)
+ return enc.to(device)
+ return MockTextEncoder(context_in_dim, device)
+
+
+@torch.no_grad()
+def text_context(text_encoder: nn.Module, caption: str, device: str | torch.device) -> Tensor:
+ """Caption -> ctx ``(1, L, 20480)`` bf16, ``L`` a multiple of 80. The empty caption is the CFG null."""
+ return text_contexts(text_encoder, [caption], device)[0]
+
+
+@torch.no_grad()
+def text_contexts(
+ text_encoder: nn.Module,
+ captions: list[str],
+ device: str | torch.device,
+ *,
+ fixed_length: int | None = None,
+) -> list[Tensor]:
+ """Captions -> contexts ``(1, L_i, 20480)`` bf16 in order; one encoder call per length bucket when the
+ encoder offers ``forward_bucketed_batch``, otherwise one call per caption."""
+ encode = getattr(text_encoder, "forward_bucketed_batch", None)
+ kwargs = {} if fixed_length is None else {"fixed_length": fixed_length}
+ ctxs = (
+ encode(captions, **kwargs)
+ if encode is not None
+ else [text_encoder.forward_bucketed(c, **kwargs) for c in captions]
+ )
+ # produced under inference_mode: clone so autograd may consume it downstream
+ return [ctx.to(device=device, dtype=torch.bfloat16).clone() for ctx in ctxs]
diff --git a/flux-umi/src/flux_action/models/transformer.py b/flux-umi/src/flux_action/models/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecff8c31a85747104c40407ae9281b79fe616ffb
--- /dev/null
+++ b/flux-umi/src/flux_action/models/transformer.py
@@ -0,0 +1,931 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""JointSingleSeq DiT. Module tree matches the production checkpoint layout so safetensors keys load without renaming."""
+
+import importlib
+import math
+import os
+from collections import defaultdict
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from einops import rearrange
+from torch import Tensor, nn
+from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ATTN_MODES = ("torch", "cudnn", "flash")
+# Fixed at import so checkpoint recomputation cannot change paths mid-step.
+_CUTE_ROPE_ENABLED = os.environ.get("FLUX_ACTION_CUTE_ROPE") == "1"
+_CUTE_ROPE_REQUIRE_KERNEL = os.environ.get("FLUX_ACTION_CUTE_ROPE_REQUIRE_KERNEL") == "1"
+# ``cudnn``: the cuDNN fused kernel first (the reference trainer forces it), torch's own kernels for
+# the shapes cuDNN declines (very short sequences such as the two-token dummy streams).
+_CUDNN_FIRST = [
+ SDPBackend.CUDNN_ATTENTION,
+ SDPBackend.FLASH_ATTENTION,
+ SDPBackend.EFFICIENT_ATTENTION,
+ SDPBackend.MATH,
+]
+_FLASH_CANDIDATES = (
+ (
+ "flash_attn.cute.interface",
+ "flash-attn 4",
+ ), # CuTe DSL kernels (Blackwell), the reference's varlen kernel
+ ("flash_attn_interface", "flash-attn 3"), # Hopper
+ ("flash_attn", "flash-attn 2"),
+)
+_flash: tuple | None = None
+_cu_seqlens_cache: dict[tuple, Tensor] = {}
+_order_cache: dict[tuple, tuple[Tensor, Tensor, list[int]]] = {}
+
+
+def _default_attn_mode() -> str:
+ """Default attention backend.
+
+ Plain torch SDPA everywhere; ``cudnn`` (cuDNN fused attention with torch fallbacks) and ``flash``
+ (flash-attn 4 / 3 / 2, dense and variable-length kernels) are opt-in speed-ups.
+ """
+ return "torch"
+
+
+def flash_kernels() -> tuple:
+ """``(flash_attn_func, flash_attn_varlen_func, name)`` of the first flash-attn generation that imports.
+
+ Resolved on first use so that importing this module never pulls in the CuTe DSL.
+ """
+ global _flash
+ if _flash is None:
+ errors = []
+ for module_name, label in _FLASH_CANDIDATES:
+ try:
+ module = importlib.import_module(module_name)
+ _flash = (module.flash_attn_func, module.flash_attn_varlen_func, label)
+ break
+ except Exception as e: # ImportError, or a DSL that fails to initialise on this machine
+ errors.append(f"{module_name}: {e!r}")
+ else:
+ raise RuntimeError("attn_mode='flash' needs flash-attn 4, 3 or 2; " + "; ".join(errors))
+ return _flash
+
+
+def cu_seqlens(lens: Sequence[int], device: torch.device) -> Tensor:
+ """``[0, l0, l0 + l1, ...]`` as int32 on ``device``; cached, the same window layout recurs every block."""
+ key = (tuple(lens), str(device))
+ hit = _cu_seqlens_cache.get(key)
+ if hit is None:
+ if len(_cu_seqlens_cache) > 64:
+ _cu_seqlens_cache.clear()
+ cu = torch.zeros(len(lens) + 1, dtype=torch.int32)
+ torch.cumsum(torch.as_tensor(list(lens), dtype=torch.int32), 0, out=cu[1:])
+ hit = _cu_seqlens_cache[key] = cu.to(device)
+ return hit
+
+
+def window_major_order(
+ segments: Sequence[Sequence[int]], device: torch.device
+) -> tuple[Tensor, Tensor, list[int]]:
+ """Reorder a sequence laid out segment-major into window-major.
+
+ ``segments[s][i]`` is the token count of window ``i`` in segment ``s`` (context, then each content
+ stream); the sequence holds segment 0 for all windows, then segment 1, ... Returns ``(order,
+ inverse, window_lens)``: ``x[:, order]`` puts every window's tokens together (segment 0 of window 0,
+ segment 1 of window 0, ..., then window 1), ``y[:, inverse]`` undoes it, ``window_lens[i]`` counts
+ the tokens of window ``i``.
+ """
+ key = (tuple(tuple(int(n) for n in seg) for seg in segments), str(device))
+ hit = _order_cache.get(key)
+ if hit is None:
+ if len(_order_cache) > 16:
+ _order_cache.clear()
+ n_windows = len(segments[0])
+ if any(len(seg) != n_windows for seg in segments):
+ raise ValueError("every segment must list one token count per window")
+ starts, base = [], 0
+ for seg in segments:
+ offsets = [base]
+ for n in seg[:-1]:
+ offsets.append(offsets[-1] + int(n))
+ starts.append(offsets)
+ base += int(sum(seg))
+ pieces = [
+ torch.arange(starts[s][i], starts[s][i] + int(segments[s][i]))
+ for i in range(n_windows)
+ for s in range(len(segments))
+ ]
+ order = torch.cat(pieces)
+ inverse = torch.empty_like(order)
+ inverse[order] = torch.arange(order.numel())
+ window_lens = [int(sum(seg[i] for seg in segments)) for i in range(n_windows)]
+ hit = _order_cache[key] = (order.to(device), inverse.to(device), window_lens)
+ return hit
+
+
+@dataclass
+class JointSingleSeqParams:
+ in_channels: dict = field(
+ default_factory=lambda: {
+ "video": 96,
+ "video_cond": 96,
+ }
+ )
+ sequence: dict = field(
+ default_factory=lambda: {
+ "x_video": "video",
+ "x_video_cond": "video_cond",
+ }
+ )
+ vec_in_dim: int | None = 768
+ context_in_dim: int = 20480
+ hidden_size: int = 3072
+ num_heads: int = 24
+ depth: int = 5
+ depth_single_blocks: int = 28
+ depth_late_blocks: int = 0
+ axes_dim: list[int] = field(default_factory=lambda: [32, 32, 32, 32])
+ theta: int = 10000
+ mlp_ratio: float = 3.0
+ qkv_bias: bool = False
+ gate_type: str | None = None
+ attn_mode: str = field(default_factory=_default_attn_mode)
+
+
+def rope(pos: Tensor, dim: int, theta: int) -> Tensor:
+ assert dim % 2 == 0, "RoPE dimension must be even"
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
+ omega = 1.0 / (theta**scale)
+ out = torch.einsum("...n,d->...nd", pos, omega)
+ out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1)
+ out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
+ return out.float()
+
+
+def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
+ if _CUTE_ROPE_ENABLED:
+ # Optional dependencies remain unloaded until an eligible CUDA call.
+ # Unsupported inputs retain eager autograd; compile/launch errors propagate.
+ from .cute_rope import apply_rope_cute
+
+ return apply_rope_cute(xq, xk, freqs_cis, require_kernel=_CUTE_ROPE_REQUIRE_KERNEL)
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
+
+
+def qk_norm_rope(norm: nn.Module, q: Tensor, k: Tensor, v: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
+ """The blocks' Q/K RMSNorm + RoPE seam (``norm`` is the block's ``QKNorm``); looked up on this module at call time
+ so ``dit_qknorm_rope_fused.install`` can route it to one fused kernel."""
+ q, k = norm(q, k, v)
+ return apply_rope(q, k, pe)
+
+
+def dense_attention(q: Tensor, k: Tensor, v: Tensor, attn_mode: str) -> Tensor:
+ """Full attention within each batch entry: ``(B, H, L, D)`` -> ``(B, L, H * D)``."""
+ if attn_mode == "flash":
+ flash_attn_func, _, _ = flash_kernels()
+ x = flash_attn_func(*(t.transpose(1, 2) for t in (q, k, v))) # (B, L, H, D)
+ x = x[0] if isinstance(x, tuple) else x
+ return x.flatten(2)
+ if attn_mode == "cudnn":
+ if q.shape[-2] == 1:
+ # the single-token state stream: cuDNN declines length-1 sequences; PyTorch's own kernels keep
+ # the (zero) gradients flowing to the query and key projections like every other mode
+ x = F.scaled_dot_product_attention(q, k, v)
+ else:
+ with sdpa_kernel(_CUDNN_FIRST, set_priority=True):
+ x = F.scaled_dot_product_attention(q, k, v)
+ elif attn_mode == "torch":
+ x = F.scaled_dot_product_attention(q, k, v)
+ else:
+ raise NotImplementedError(f"attn_mode={attn_mode!r} not supported")
+ return rearrange(x, "b h n d -> b n (h d)")
+
+
+def packed_attention(q: Tensor, k: Tensor, v: Tensor, attn_mode: str, seqlens: Sequence[int]) -> Tensor:
+ """Attention within each of the windows packed along ``L``: ``(1, H, L, D)`` -> ``(1, L, H * D)``.
+
+ ``seqlens`` are the windows' token counts in order (``sum == L``); a token attends to its own
+ window only. ``flash`` runs the variable-length kernel over the whole sequence. ``torch`` and
+ ``cudnn`` batch windows of equal length into one dense call (a reshape when all windows match,
+ the usual case: equal canvases and, mostly, equal caption buckets) and run one call per distinct
+ length otherwise; the maths is that of separate per-window forwards.
+ """
+ if q.shape[0] != 1:
+ raise ValueError(f"packed windows form one sequence of batch size 1, got {q.shape[0]}")
+ lens = [int(n) for n in seqlens]
+ _, heads, total, dim = q.shape
+ if sum(lens) != total or any(n < 1 for n in lens):
+ raise ValueError(f"window token counts {lens} do not add up to the sequence length {total}")
+ if attn_mode == "flash":
+ _, flash_attn_varlen_func, _ = flash_kernels()
+ cu = cu_seqlens(lens, q.device)
+ longest = max(lens)
+ x = flash_attn_varlen_func(
+ *(t[0].transpose(0, 1) for t in (q, k, v)), # (L, H, D)
+ cu_seqlens_q=cu,
+ cu_seqlens_k=cu,
+ max_seqlen_q=longest,
+ max_seqlen_k=longest,
+ )
+ x = x[0] if isinstance(x, tuple) else x
+ return x.reshape(1, total, heads * dim)
+ if attn_mode not in ("torch", "cudnn"):
+ raise NotImplementedError(f"attn_mode={attn_mode!r} not supported")
+ n_windows = len(lens)
+ if len(set(lens)) == 1:
+ per = total // n_windows
+ qw, kw, vw = (t.reshape(heads, n_windows, per, dim).transpose(0, 1) for t in (q, k, v))
+ return dense_attention(qw, kw, vw, attn_mode).reshape(1, total, heads * dim)
+ offsets = [0]
+ for n in lens:
+ offsets.append(offsets[-1] + n)
+ by_length: dict[int, list[int]] = defaultdict(list)
+ for i, n in enumerate(lens):
+ by_length[n].append(i)
+ out = q.new_empty(1, total, heads * dim)
+ for n, windows in by_length.items():
+ group = [
+ torch.stack([t[0, :, offsets[i] : offsets[i] + n] for i in windows]) for t in (q, k, v)
+ ] # (n_group, H, n, D)
+ result = dense_attention(*group, attn_mode)
+ for j, i in enumerate(windows):
+ out[:, offsets[i] : offsets[i] + n] = result[j]
+ return out
+
+
+class Attention(nn.Module):
+ def forward(
+ self, q: Tensor, k: Tensor, v: Tensor, attn_mode: str = "cudnn", seqlens: Sequence[int] | None = None
+ ) -> Tensor:
+ """``(B, H, L, D)`` -> ``(B, L, H * D)``; with ``seqlens`` the windows packed along ``L`` attend separately."""
+ if seqlens is not None:
+ return packed_attention(q, k, v, attn_mode, seqlens)
+ return dense_attention(q, k, v, attn_mode)
+
+
+# Perturbs the whole call; the two-pass CFG denoise loops enable PAG on the
+# uncond forward only, so the CFG combine guides against the perturbed
+# prediction.
+def apply_pag(attn: Tensor, v: Tensor, pag_strength: float) -> Tensor:
+ if pag_strength <= 0.0:
+ return attn
+
+ v_passthrough = rearrange(v, "b h n d -> b n (h d)")
+ if pag_strength >= 1.0:
+ return v_passthrough
+ return (1 - pag_strength) * attn + pag_strength * v_passthrough
+
+
+def _bf16_if_required(module: nn.Module, x: Tensor) -> Tensor:
+ if getattr(module, "_requires_bf16_input", False) and x.dtype != torch.bfloat16:
+ return x.to(torch.bfloat16)
+ return x
+
+
+class EmbedND(nn.Module):
+ def __init__(self, dim: int, theta: int, axes_dim: list[int]):
+ super().__init__()
+ self.dim = dim
+ self.theta = theta
+ self.axes_dim = axes_dim
+
+ def forward(self, ids: Tensor) -> Tensor:
+ emb = torch.cat(
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(len(self.axes_dim))],
+ dim=-3,
+ )
+ return emb.unsqueeze(1)
+
+
+def timestep_embedding(
+ t: Tensor,
+ dim: int,
+ max_period: int = 10000,
+ time_factor: float = 1000.0,
+ out_dtype: torch.dtype | None = None,
+) -> Tensor:
+ t = time_factor * t
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period) * torch.arange(0, half, device=t.device, dtype=torch.float32) / half
+ )
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ if torch.is_floating_point(t):
+ embedding = embedding.to(out_dtype if out_dtype is not None else t.dtype)
+ return embedding
+
+
+class MLPEmbedder(nn.Module):
+ def __init__(self, in_dim: int, hidden_dim: int, disable_bias: bool = False):
+ super().__init__()
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=not disable_bias)
+ self.silu = nn.SiLU()
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=not disable_bias)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.out_layer(self.silu(self.in_layer(x)))
+
+
+class RMSNorm(nn.Module):
+ def __init__(self, dim: int):
+ super().__init__()
+ self.scale = nn.Parameter(torch.ones(dim))
+
+ def forward(self, x: Tensor) -> Tensor:
+ if getattr(self, "_cute_qknorm_enabled", False) and self.training:
+ from .dit_cute_qknorm import dispatch
+
+ return dispatch(self, x)
+ dtype = x.dtype
+ x = x.float()
+ rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)
+ return (x * rrms).to(dtype=dtype) * self.scale
+
+
+class QKNorm(nn.Module):
+ def __init__(self, dim: int):
+ super().__init__()
+ self.query_norm = RMSNorm(dim)
+ self.key_norm = RMSNorm(dim)
+
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
+ return self.query_norm(q).to(v), self.key_norm(k).to(v)
+
+
+class SiLUActivation(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.gate_fn = nn.SiLU()
+
+ def forward(self, x: Tensor) -> Tensor:
+ if self.training and getattr(self, "_swiglu_native_out_enabled", False):
+ from .swiglu_native_out_adapter import dispatch_training_swiglu
+
+ result = dispatch_training_swiglu(self, x)
+ if result is not None:
+ return result
+ x1, x2 = x.chunk(2, dim=-1)
+ return self.gate_fn(x1) * x2
+
+
+class Modulation(nn.Module):
+ def __init__(self, dim: int, double: bool, disable_bias: bool = False):
+ super().__init__()
+ self.is_double = double
+ self.multiplier = 6 if double else 3
+ self.lin = nn.Linear(dim, self.multiplier * dim, bias=not disable_bias)
+
+ def forward(self, vec: Tensor):
+ out = self.lin(F.silu(vec))
+ if out.ndim == 2:
+ out = out[:, None, :]
+ out = out.chunk(self.multiplier, dim=-1)
+ return out[:3], out[3:] if self.is_double else None
+
+
+class LastLayer(nn.Module):
+ def __init__(self, hidden_size: int, out_channels: int):
+ super().__init__()
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.linear = nn.Linear(hidden_size, out_channels, bias=False)
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=False))
+
+ def forward(self, x: Tensor, vec: Tensor) -> Tensor:
+ if vec.ndim == 2:
+ vec = vec[:, None, :]
+ s = self.adaLN_modulation[0](vec) # type: ignore
+ shift_w, scale_w = self.adaLN_modulation[1].weight.chunk(2)
+
+ # x = (1 + scale) * self.norm_final(x) + shift
+ # using in place ops and avoid materializing full (seq, 2*hidden) projection to reduce memory
+ x = self.norm_final(x)
+ x.mul_(F.linear(s, scale_w).add_(1))
+ x.add_(F.linear(s, shift_w))
+ return self.linear(x)
+
+
+class ModeBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int,
+ num_heads: int,
+ mlp_ratio: float = 3.0,
+ qkv_bias: bool = False,
+ gate_type: str | None = None,
+ use_gated_mlp: bool = True,
+ ):
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = hidden_size // num_heads
+ self.hidden_size = hidden_size
+ self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ self.mlp_mult_factor = 2 if use_gated_mlp else 1
+ self.gate_type = gate_type
+
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias)
+ self.mlp_in = nn.Linear(hidden_size, self.mlp_hidden_dim * self.mlp_mult_factor, bias=False)
+ if gate_type is not None:
+ self.gate_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+
+ self.attn_out = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_out = nn.Linear(self.mlp_hidden_dim, hidden_size, bias=False)
+
+ self.norm = QKNorm(head_dim)
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.mlp_act = SiLUActivation() if use_gated_mlp else nn.GELU(approximate="tanh")
+ self.attention = Attention()
+ self.attn_mode = "torch"
+
+ def forward(
+ self, x: Tensor, pe: Tensor, mod: tuple[Tensor, ...], seqlens: Sequence[int] | None = None
+ ) -> Tensor:
+ mod_shift, mod_scale, mod_gate = mod
+ x_mod = (1 + mod_scale) * self.pre_norm(x) + mod_shift
+
+ q = rearrange(
+ self.q_proj(_bf16_if_required(self.q_proj, x_mod)),
+ "B L (H D) -> B H L D",
+ H=self.num_heads,
+ )
+ k = rearrange(
+ self.k_proj(_bf16_if_required(self.k_proj, x_mod)),
+ "B L (H D) -> B H L D",
+ H=self.num_heads,
+ )
+ v = rearrange(
+ self.v_proj(_bf16_if_required(self.v_proj, x_mod)),
+ "B L (H D) -> B H L D",
+ H=self.num_heads,
+ )
+ mlp = self.mlp_in(_bf16_if_required(self.mlp_in, x_mod))
+
+ q, k = qk_norm_rope(self.norm, q, k, v, pe)
+ attn = self.attention(q, k, v, self.attn_mode, seqlens)
+
+ output = self.attn_out(_bf16_if_required(self.attn_out, attn)) + self.mlp_out(
+ _bf16_if_required(self.mlp_out, self.mlp_act(mlp))
+ )
+ if self.gate_type is not None:
+ output = output * F.silu(self.gate_proj(x_mod))
+ return x + mod_gate * output
+
+
+class SingleStreamBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int,
+ num_heads: int,
+ mlp_ratio: float = 3.0,
+ gate_type: str | None = None,
+ use_gated_mlp: bool = True,
+ ):
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = hidden_size // num_heads
+ self.hidden_size = hidden_size
+ self.mlp_hidden_dim = int(hidden_size * mlp_ratio)
+ self.mlp_mult_factor = 2 if use_gated_mlp else 1
+ self.gate_type = gate_type
+
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_in = nn.Linear(hidden_size, self.mlp_hidden_dim * self.mlp_mult_factor, bias=False)
+ self.attn_out = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_out = nn.Linear(self.mlp_hidden_dim, hidden_size, bias=False)
+ if gate_type is not None:
+ self.gate_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+
+ self.norm = QKNorm(head_dim)
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.mlp_act = SiLUActivation() if use_gated_mlp else nn.GELU(approximate="tanh")
+ self.attention = Attention()
+ self.attn_mode = "torch"
+
+ def forward(
+ self,
+ x: Tensor,
+ ctx: Tensor | None,
+ pe: Tensor,
+ mod_x: tuple[Tensor, ...],
+ mod_ctx: tuple[Tensor, ...] | None,
+ pag_strength: float = 0.0,
+ seqlens: Sequence[int] | None = None,
+ ) -> tuple[Tensor | None, Tensor]:
+ """``ctx is None``: ``x`` already holds the whole sequence (context and content of every window,
+ window-major, see ``JointSingleSeq.forward``) with its per-token modulation ``mod_x``; the block
+ then returns ``(None, x_out)``. ``seqlens`` keeps attention within each packed window."""
+ mod_shift_x, mod_scale_x, mod_gate_x = mod_x
+ if ctx is None:
+ combined = (1 + mod_scale_x) * self.pre_norm(x) + mod_shift_x
+ else:
+ mod_shift_ctx, mod_scale_ctx, mod_gate_ctx = mod_ctx
+ x_mod = (1 + mod_scale_x) * self.pre_norm(x) + mod_shift_x
+ ctx_mod = (1 + mod_scale_ctx) * self.pre_norm(ctx) + mod_shift_ctx
+ combined = torch.cat((ctx_mod, x_mod), dim=1)
+
+ q = rearrange(
+ self.q_proj(_bf16_if_required(self.q_proj, combined)),
+ "B L (H D) -> B H L D",
+ H=self.num_heads,
+ )
+ k = rearrange(
+ self.k_proj(_bf16_if_required(self.k_proj, combined)),
+ "B L (H D) -> B H L D",
+ H=self.num_heads,
+ )
+ v = rearrange(
+ self.v_proj(_bf16_if_required(self.v_proj, combined)),
+ "B L (H D) -> B H L D",
+ H=self.num_heads,
+ )
+ mlp = self.mlp_in(_bf16_if_required(self.mlp_in, combined))
+
+ q, k = qk_norm_rope(self.norm, q, k, v, pe)
+ attn = self.attention(q, k, v, self.attn_mode, seqlens)
+ attn = apply_pag(attn, v, pag_strength)
+
+ output = self.attn_out(_bf16_if_required(self.attn_out, attn)) + self.mlp_out(
+ _bf16_if_required(self.mlp_out, self.mlp_act(mlp))
+ )
+ if self.gate_type is not None:
+ output = output * F.silu(self.gate_proj(combined))
+
+ if ctx is None:
+ return None, x + mod_gate_x * output
+ ctx_out, x_out = torch.split(output, [ctx.shape[1], x.shape[1]], dim=1)
+ return ctx + mod_gate_ctx * ctx_out, x + mod_gate_x * x_out
+
+
+class JointSingleSeq(nn.Module):
+ def __init__(self, params: JointSingleSeqParams = JointSingleSeqParams()):
+ super().__init__()
+ self.params = params
+
+ self.sequence = params.sequence
+ for _, v in params.sequence.items():
+ assert v in params.in_channels, (params.sequence, params.in_channels)
+
+ self.in_channels = params.in_channels
+ self.hidden_size = params.hidden_size
+ self.num_heads = params.num_heads
+ self.depth = params.depth
+ self.depth_single_blocks = params.depth_single_blocks
+ self.depth_late_blocks = params.depth_late_blocks
+ self.mlp_ratio = params.mlp_ratio
+ self.qkv_bias = params.qkv_bias
+ self.gate_type = params.gate_type
+ self.attn_mode = params.attn_mode
+
+ if params.hidden_size % params.num_heads != 0:
+ raise ValueError(
+ f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
+ )
+ pe_dim = params.hidden_size // params.num_heads
+ if sum(params.axes_dim) != pe_dim:
+ raise ValueError(f"Got {params.axes_dim} but expected positional dim {pe_dim}")
+
+ self.pe_embedder = EmbedND(dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim)
+
+ self.emb_in = nn.ModuleDict(
+ {m: nn.Linear(c, params.hidden_size, bias=False) for m, c in params.in_channels.items()}
+ )
+ self.txt_in = nn.Linear(params.context_in_dim, params.hidden_size, bias=False)
+
+ self.time_in = MLPEmbedder(in_dim=256, hidden_dim=params.hidden_size, disable_bias=True)
+ self.vector_in: nn.Module = (
+ MLPEmbedder(params.vec_in_dim, params.hidden_size, disable_bias=True)
+ if params.vec_in_dim is not None
+ else nn.Identity()
+ )
+
+ content_modalities = sorted(params.in_channels.keys())
+ self.early_stream_modulations = nn.ModuleDict(
+ {
+ **{
+ m: Modulation(params.hidden_size, double=False, disable_bias=True)
+ for m in content_modalities
+ },
+ "txt": Modulation(params.hidden_size, double=False, disable_bias=True),
+ }
+ )
+ self.single_stream_modulations = nn.ModuleDict(
+ {
+ **{
+ m: Modulation(params.hidden_size, double=False, disable_bias=True)
+ for m in content_modalities
+ },
+ "txt": Modulation(params.hidden_size, double=False, disable_bias=True),
+ }
+ )
+ if params.depth_late_blocks > 0:
+ self.late_stream_modulations = nn.ModuleDict(
+ {
+ **{
+ m: Modulation(params.hidden_size, double=False, disable_bias=True)
+ for m in content_modalities
+ },
+ "txt": Modulation(params.hidden_size, double=False, disable_bias=True),
+ }
+ )
+
+ self.content_mode_blocks = nn.ModuleDict(
+ {
+ m: nn.ModuleList(
+ [
+ ModeBlock(
+ params.hidden_size,
+ params.num_heads,
+ mlp_ratio=params.mlp_ratio,
+ qkv_bias=params.qkv_bias,
+ gate_type=params.gate_type,
+ )
+ for _ in range(params.depth)
+ ]
+ )
+ for m in content_modalities
+ }
+ )
+ self.txt_mode_blocks = nn.ModuleList(
+ [
+ ModeBlock(
+ params.hidden_size,
+ params.num_heads,
+ mlp_ratio=params.mlp_ratio,
+ qkv_bias=params.qkv_bias,
+ gate_type=params.gate_type,
+ )
+ for _ in range(params.depth)
+ ]
+ )
+
+ self.single_blocks = nn.ModuleList(
+ [
+ SingleStreamBlock(
+ params.hidden_size,
+ params.num_heads,
+ mlp_ratio=params.mlp_ratio,
+ gate_type=params.gate_type,
+ )
+ for _ in range(params.depth_single_blocks)
+ ]
+ )
+
+ if params.depth_late_blocks > 0:
+ self.late_content_mode_blocks = nn.ModuleDict(
+ {
+ m: nn.ModuleList(
+ [
+ ModeBlock(
+ params.hidden_size,
+ params.num_heads,
+ mlp_ratio=params.mlp_ratio,
+ qkv_bias=params.qkv_bias,
+ gate_type=params.gate_type,
+ )
+ for _ in range(params.depth_late_blocks)
+ ]
+ )
+ for m in content_modalities
+ }
+ )
+ self.late_txt_mode_blocks = nn.ModuleList(
+ [
+ ModeBlock(
+ params.hidden_size,
+ params.num_heads,
+ mlp_ratio=params.mlp_ratio,
+ qkv_bias=params.qkv_bias,
+ gate_type=params.gate_type,
+ )
+ for _ in range(params.depth_late_blocks)
+ ]
+ )
+
+ self.final_layer = nn.ModuleDict(
+ {m: LastLayer(params.hidden_size, c) for m, c in params.in_channels.items()}
+ )
+
+ # Propagate the selected attention backend to every block (default: torch SDPA,
+ # see _default_attn_mode; "flash" and "cudnn" are opt-in).
+ for module in self.modules():
+ if hasattr(module, "attn_mode"):
+ module.attn_mode = params.attn_mode
+
+ def embed_timesteps(self, ts: Tensor, out_dtype: torch.dtype) -> Tensor:
+ """Sinusoid + ``time_in`` in the precision of ``time_in``'s own weights, outside autocast.
+
+ The reference trainer keeps this MLP in fp32 under bf16 mixed precision (its own FSDP group)
+ and casts the result where the modulations consume it; :func:`shard_dit` does the same, and a
+ bf16 inference model computes it in bf16 as before.
+ """
+ weight_dtype = self.time_in.in_layer.weight.dtype
+ with torch.autocast(device_type=ts.device.type, enabled=False):
+ vec = self.time_in(timestep_embedding(ts, 256, out_dtype=weight_dtype))
+ return vec.to(out_dtype)
+
+ def forward(
+ self,
+ ctx: Tensor,
+ ctx_ids: Tensor,
+ vector: Tensor,
+ timesteps_ctx: Tensor,
+ pag_single_layers: list[int] | None = None,
+ pag_strength: float = 1.0,
+ seqlens: dict[str, Sequence[int]] | None = None,
+ **kwargs: Tensor,
+ ) -> dict[str, Tensor]:
+ """Denoise every stream given in ``kwargs`` (``x_``, ``x__ids``, ``x__timesteps``).
+
+ ``seqlens`` packs several windows into one call of batch size 1: ``seqlens["ctx"]`` and
+ ``seqlens["x_"]`` list the token counts of each window in order, and every stream and the
+ context hold the windows' tokens concatenated in that order. Attention then stays within each
+ window (mode blocks per stream, the joint blocks over context plus content of a window), so the
+ result equals separate per-window forwards while the whole micro-batch runs in one pass: one set of
+ FSDP gathers, large matmuls, and captions of different lengths without padding.
+ """
+ assert vector.ndim == 2, "invalid vector shape"
+ batch_size = ctx.shape[0]
+
+ x_by_mod: dict[str, list] = defaultdict(list)
+ ids_by_mod: dict[str, list] = defaultdict(list)
+ ts_by_mod: dict[str, list] = defaultdict(list)
+ lens_by_mod: dict[str, list] = defaultdict(list)
+ names_by_mod: dict[str, list] = defaultdict(list)
+ for k, v in self.sequence.items():
+ if k not in kwargs:
+ continue
+ assert k + "_ids" in kwargs and k + "_timesteps" in kwargs, "missing stream metadata"
+ x_by_mod[v].append(kwargs[k])
+ ids_by_mod[v].append(kwargs[k + "_ids"])
+ ts_by_mod[v].append(kwargs[k + "_timesteps"])
+ lens_by_mod[v].append(kwargs[k].shape[1])
+ names_by_mod[v].append(k)
+
+ active = list(x_by_mod.keys())
+ all_mods = sorted(self.in_channels.keys())
+ inactive = [m for m in all_mods if m not in active]
+ dummy_len = 2 # attention kernels need >=2
+ packed = seqlens is not None
+ mod_lens: dict[str, list[int]] = {}
+ ctx_lens: list[int] | None = None
+ if packed:
+ if batch_size != 1:
+ raise ValueError(f"packed windows form one sequence of batch size 1, got {batch_size}")
+ ctx_lens = [int(n) for n in seqlens["ctx"]]
+ if sum(ctx_lens) != ctx.shape[1]:
+ raise ValueError(f"context token counts {ctx_lens} do not add up to {ctx.shape[1]}")
+ for m in active:
+ if len(names_by_mod[m]) != 1:
+ raise ValueError(
+ f"packed windows need one stream per modality, {m} has {names_by_mod[m]}"
+ )
+ lens = [int(n) for n in seqlens[names_by_mod[m][0]]]
+ if len(lens) != len(ctx_lens) or sum(lens) != lens_by_mod[m][0]:
+ raise ValueError(
+ f"{names_by_mod[m][0]}: window token counts {lens} do not match the stream"
+ )
+ mod_lens[m] = lens
+
+ device = x_by_mod[active[0]][0].device
+ dtype = x_by_mod[active[0]][0].dtype
+ for k in all_mods:
+ if k in active:
+ x_by_mod[k] = torch.cat(x_by_mod[k], 1)
+ ids_by_mod[k] = torch.cat(ids_by_mod[k], 1)
+ ts_by_mod[k] = torch.cat(ts_by_mod[k], 1)
+ else:
+ x_by_mod[k] = torch.zeros(
+ batch_size,
+ dummy_len,
+ self.in_channels[k],
+ device=device,
+ dtype=dtype,
+ )
+ ids_by_mod[k] = torch.zeros(batch_size, dummy_len, 4, device=device, dtype=torch.int64)
+ ts_by_mod[k] = torch.zeros(batch_size, dummy_len, device=device, dtype=dtype)
+
+ vec_by_mod: dict[str, Tensor] = {}
+ for k in all_mods:
+ ts = rearrange(ts_by_mod[k], "b t -> (b t)")
+ vec_by_mod[k] = rearrange(self.embed_timesteps(ts, dtype), "(b t) d -> b t d", b=batch_size)
+ ts_ctx = rearrange(timesteps_ctx, "b t -> (b t)")
+ vec_ctx = rearrange(self.embed_timesteps(ts_ctx, dtype), "(b t) d -> b t d", b=batch_size)
+
+ vector_emb = self.vector_in(vector)
+ for k in all_mods:
+ vec_by_mod[k] = vec_by_mod[k] + vector_emb[:, None, :]
+ vec_ctx = vec_ctx + vector_emb[:, None, :]
+
+ early_content_mods: dict[str, tuple] = {}
+ for key in self.early_stream_modulations:
+ if key == "txt":
+ continue
+ mod, _ = self.early_stream_modulations[key](vec_by_mod[key])
+ early_content_mods[key] = mod
+ early_txt_mod, _ = self.early_stream_modulations["txt"](vec_ctx)
+
+ single_content_mods: dict[str, list] = {}
+ for key in self.single_stream_modulations:
+ if key == "txt":
+ continue
+ mod, _ = self.single_stream_modulations[key](vec_by_mod[key])
+ single_content_mods[key] = list(mod)
+ single_txt_mod, _ = self.single_stream_modulations["txt"](vec_ctx)
+
+ if self.depth_late_blocks > 0:
+ late_content_mods: dict[str, tuple] = {}
+ for key in self.late_stream_modulations:
+ if key == "txt":
+ continue
+ mod, _ = self.late_stream_modulations[key](vec_by_mod[key])
+ late_content_mods[key] = mod
+ late_txt_mod, _ = self.late_stream_modulations["txt"](vec_ctx)
+
+ content_by_mod = {k: self.emb_in[k](x_by_mod[k]) for k in all_mods}
+ txt = self.txt_in(ctx)
+
+ pe_by_mod = {k: self.pe_embedder(ids_by_mod[k]) for k in all_mods}
+ pe_ctx = self.pe_embedder(ctx_ids)
+
+ for d in range(self.depth):
+ for m in all_mods:
+ content_by_mod[m] = self.content_mode_blocks[m][d](
+ content_by_mod[m], pe_by_mod[m], early_content_mods[m], seqlens=mod_lens.get(m)
+ )
+ txt = self.txt_mode_blocks[d](txt, pe_ctx, early_txt_mod, seqlens=ctx_lens)
+
+ img = torch.cat([content_by_mod[k] for k in active], dim=1)
+ content_mod = tuple(torch.cat([single_content_mods[k][i] for k in active], dim=1) for i in range(3))
+ pe_content = torch.cat([pe_by_mod[k] for k in active], dim=2)
+ pe = torch.cat((pe_ctx, pe_content), dim=2)
+
+ if not packed:
+ for i, block in enumerate(self.single_blocks):
+ layer_pag = pag_strength if (pag_single_layers and i in pag_single_layers) else 0.0
+ txt, img = block(
+ img,
+ txt,
+ pe,
+ content_mod,
+ single_txt_mod,
+ pag_strength=layer_pag,
+ )
+ else:
+ # The joint sequence is laid out context-then-content; gather it window-major once so each
+ # window is one contiguous segment for attention, run the blocks on that single sequence with
+ # its per-token modulation, and scatter back for the per-stream heads.
+ order, inverse, window_lens = window_major_order(
+ [ctx_lens, *(mod_lens[k] for k in active)], img.device
+ )
+ seq = torch.cat((txt, img), dim=1)[:, order]
+ mod = tuple(torch.cat((single_txt_mod[i], content_mod[i]), dim=1)[:, order] for i in range(3))
+ pe = pe[:, :, order]
+ for i, block in enumerate(self.single_blocks):
+ layer_pag = pag_strength if (pag_single_layers and i in pag_single_layers) else 0.0
+ _, seq = block(seq, None, pe, mod, None, pag_strength=layer_pag, seqlens=window_lens)
+ txt, img = torch.split(seq[:, inverse], [txt.shape[1], img.shape[1]], dim=1)
+
+ img_by_mod: dict[str, Tensor] = {}
+ pos = 0
+ for k in active:
+ length = sum(lens_by_mod[k])
+ img_by_mod[k] = img[:, pos : pos + length]
+ pos += length
+ for k in inactive:
+ img_by_mod[k] = content_by_mod[k]
+
+ if self.depth_late_blocks > 0:
+ for d in range(self.depth_late_blocks):
+ for m in all_mods:
+ img_by_mod[m] = self.late_content_mode_blocks[m][d](
+ img_by_mod[m], pe_by_mod[m], late_content_mods[m], seqlens=mod_lens.get(m)
+ )
+ txt = self.late_txt_mode_blocks[d](txt, pe_ctx, late_txt_mod, seqlens=ctx_lens)
+
+ final = {k: self.final_layer[k](img_by_mod[k], vec_by_mod[k]) for k in all_mods}
+ out: dict[str, Tensor] = {}
+ for k in active:
+ pos = 0
+ for name, length in zip(names_by_mod[k], lens_by_mod[k], strict=True):
+ out[name] = final[k][:, pos : pos + length]
+ pos += length
+ return out
diff --git a/flux-umi/src/flux_action/models/transformer_inf_bf16.py b/flux-umi/src/flux_action/models/transformer_inf_bf16.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d857e6823f978539a836d982957f8ceede4ba1f
--- /dev/null
+++ b/flux-umi/src/flux_action/models/transformer_inf_bf16.py
@@ -0,0 +1,713 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Self-contained BF16 inference transformer for the released DROID policy.
+
+This module deliberately owns its attention, transformer blocks, prepared
+state, and RoPE layout. It shares checkpoint names with the training model,
+but never calls training/reference blocks at runtime.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from torch import Tensor, nn
+
+VIDEO = "video"
+VIDEO_COND = "video_cond"
+ACTION = "action_prediction_droid"
+ACTION_COND = "action_prediction_droid_cond"
+STREAM_ORDER = (VIDEO, VIDEO_COND, ACTION, ACTION_COND)
+CHANNELS = {VIDEO: 96, VIDEO_COND: 96, ACTION: 8, ACTION_COND: 8}
+HIDDEN_SIZE = 3072
+NUM_HEADS = 24
+MLP_SIZE = 9216
+EARLY_DEPTH = 5
+JOINT_DEPTH = 28
+CONTEXT_DIM = 20480
+VECTOR_DIM = 768
+AXES_DIM = (32, 32, 32, 32)
+THETA = 10000
+
+ModulationTuple = tuple[Tensor, Tensor, Tensor]
+
+
+@dataclass(frozen=True)
+class _PreparedText:
+ batch_size: int
+ dtype: torch.dtype
+ device: torch.device
+ txt_len: int
+ txt: Tensor
+ rope: Tensor
+ early_video_cond: ModulationTuple
+ early_action_cond: ModulationTuple
+ single_txt: ModulationTuple
+ single_video_cond: ModulationTuple
+ single_action_cond: ModulationTuple
+ vector_embedding: Tensor
+
+
+@dataclass(frozen=True)
+class _PreparedRequest:
+ batch_size: int
+ dtype: torch.dtype
+ device: torch.device
+ txt_len: int
+ video_len: int
+ video_cond_len: int
+ action_len: int
+ action_cond_len: int
+ txt: Tensor
+ video_cond: Tensor
+ action_cond: Tensor
+ rope: Tensor
+ single_txt: ModulationTuple
+ single_video_cond: ModulationTuple
+ single_action_cond: ModulationTuple
+ vector_embedding: Tensor
+
+
+@dataclass(frozen=True)
+class _PreparedStep:
+ early_video: ModulationTuple
+ early_action: ModulationTuple
+ single_video: ModulationTuple
+ single_action: ModulationTuple
+ final_video_shift: Tensor
+ final_video_scale: Tensor
+ final_action_shift: Tensor
+ final_action_scale: Tensor
+
+
+@dataclass(frozen=True)
+class DroidPrediction:
+ video: Tensor
+ action: Tensor
+
+ def as_dict(self) -> dict[str, Tensor]:
+ return {"x_video": self.video, "x_action_prediction_droid": self.action}
+
+
+def _rope(pos: Tensor, dim: int, theta: int) -> Tensor:
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
+ omega = 1.0 / (theta**scale)
+ angles = torch.einsum("...n,d->...nd", pos, omega)
+ matrix = torch.stack(
+ (torch.cos(angles), -torch.sin(angles), torch.sin(angles), torch.cos(angles)), dim=-1
+ )
+ return matrix.reshape(*matrix.shape[:-1], 2, 2).float()
+
+
+def _apply_rope(q: Tensor, k: Tensor, rope: Tensor) -> tuple[Tensor, Tensor]:
+ q_pairs = q.float().reshape(*q.shape[:-1], -1, 1, 2)
+ k_pairs = k.float().reshape(*k.shape[:-1], -1, 1, 2)
+ q_out = rope[..., 0] * q_pairs[..., 0] + rope[..., 1] * q_pairs[..., 1]
+ k_out = rope[..., 0] * k_pairs[..., 0] + rope[..., 1] * k_pairs[..., 1]
+ return q_out.reshape_as(q).to(q.dtype), k_out.reshape_as(k).to(k.dtype)
+
+
+def _timestep_embedding(timestep: Tensor, dim: int = 256) -> Tensor:
+ scaled = timestep * 1000.0
+ half = dim // 2
+ frequencies = torch.exp(
+ -math.log(10000) * torch.arange(half, device=timestep.device, dtype=torch.float32) / half
+ )
+ angles = scaled[:, None].float() * frequencies[None]
+ return torch.cat((torch.cos(angles), torch.sin(angles)), dim=-1)
+
+
+class _RopeEmbedder(nn.Module):
+ def __init__(self, head_dim: int, theta: int, axes_dim: tuple[int, int, int, int]):
+ super().__init__()
+ self.dim = head_dim
+ self.theta = theta
+ self.axes_dim = axes_dim
+
+ def forward(self, ids: Tensor) -> Tensor:
+ embeddings = torch.cat(
+ tuple(_rope(ids[..., axis], dim, self.theta) for axis, dim in enumerate(self.axes_dim)),
+ dim=-3,
+ )
+ return embeddings.unsqueeze(1)
+
+
+class _MLPEmbedder(nn.Module):
+ def __init__(self, in_dim: int, hidden_dim: int):
+ super().__init__()
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=False)
+ self.silu = nn.SiLU()
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.out_layer(self.silu(self.in_layer(x)))
+
+
+class _RMSNorm(nn.Module):
+ def __init__(self, dim: int):
+ super().__init__()
+ self.scale = nn.Parameter(torch.ones(dim))
+
+ def forward(self, x: Tensor) -> Tensor:
+ dtype = x.dtype
+ x_float = x.float()
+ normalized = x_float * torch.rsqrt(torch.mean(x_float**2, dim=-1, keepdim=True) + 1e-6)
+ return normalized.to(dtype) * self.scale
+
+
+class _QKNorm(nn.Module):
+ def __init__(self, dim: int):
+ super().__init__()
+ self.query_norm = _RMSNorm(dim)
+ self.key_norm = _RMSNorm(dim)
+
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:
+ return self.query_norm(q).to(v), self.key_norm(k).to(v)
+
+
+class _SwiGLU(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.gate_fn = nn.SiLU()
+
+ def forward(self, x: Tensor) -> Tensor:
+ gate, value = x.chunk(2, dim=-1)
+ return self.gate_fn(gate) * value
+
+
+class _Modulation(nn.Module):
+ def __init__(self, hidden_size: int):
+ super().__init__()
+ self.lin = nn.Linear(hidden_size, 3 * hidden_size, bias=False)
+
+ def forward(self, vector: Tensor) -> ModulationTuple:
+ output = self.lin(F.silu(vector))
+ if output.ndim == 2:
+ output = output[:, None, :]
+ shift, scale, gate = output.chunk(3, dim=-1)
+ return shift, scale, gate
+
+
+class _LastLayer(nn.Module):
+ def __init__(self, hidden_size: int, out_channels: int):
+ super().__init__()
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.linear = nn.Linear(hidden_size, out_channels, bias=False)
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=False))
+
+
+class _Attention(nn.Module):
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
+ attended = F.scaled_dot_product_attention(q, k, v)
+ return attended.transpose(1, 2).flatten(2)
+
+
+class _ModeBlock(nn.Module):
+ def __init__(self):
+ super().__init__()
+ hidden_size = HIDDEN_SIZE
+ self.num_heads = NUM_HEADS
+ self.hidden_size = hidden_size
+ self.mlp_hidden_dim = MLP_SIZE
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_in = nn.Linear(hidden_size, 2 * MLP_SIZE, bias=False)
+ self.attn_out = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_out = nn.Linear(MLP_SIZE, hidden_size, bias=False)
+ self.norm = _QKNorm(hidden_size // NUM_HEADS)
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.mlp_act = _SwiGLU()
+ self.attention = _Attention()
+ self.register_parameter("in_proj_weight", None)
+
+ def pack_input_projection(self) -> None:
+ assert self.in_proj_weight is None, "input projection already packed"
+ packed = torch.cat(
+ (self.q_proj.weight, self.k_proj.weight, self.v_proj.weight, self.mlp_in.weight), dim=0
+ )
+ self.in_proj_weight = nn.Parameter(packed, requires_grad=False)
+ del self.q_proj, self.k_proj, self.v_proj, self.mlp_in
+
+ def forward(self, x: Tensor, rope: Tensor, modulation: ModulationTuple) -> Tensor:
+ shift, scale, gate = modulation
+ modulated = (1 + scale) * self.pre_norm(x) + shift
+ batch, length, _ = modulated.shape
+ assert self.in_proj_weight is not None, "input projection is not packed"
+ q, k, v, mlp = F.linear(modulated, self.in_proj_weight).split(
+ (self.hidden_size, self.hidden_size, self.hidden_size, 2 * self.mlp_hidden_dim), dim=-1
+ )
+ q = q.reshape(batch, length, self.num_heads, -1).transpose(1, 2)
+ k = k.reshape(batch, length, self.num_heads, -1).transpose(1, 2)
+ v = v.reshape(batch, length, self.num_heads, -1).transpose(1, 2)
+ q, k = self.norm(q, k, v)
+ q, k = _apply_rope(q, k, rope)
+ output = self.attn_out(self.attention(q, k, v)) + self.mlp_out(self.mlp_act(mlp))
+ return x + gate * output
+
+
+def _modulate_segments(
+ normalized: Tensor,
+ lengths: tuple[int, int, int, int, int],
+ modulations: tuple[ModulationTuple, ModulationTuple, ModulationTuple, ModulationTuple, ModulationTuple],
+) -> Tensor:
+ segments = torch.split(normalized, lengths, dim=1)
+ return torch.cat(
+ tuple(
+ (1 + modulation[1]) * segment + modulation[0]
+ for segment, modulation in zip(segments, modulations)
+ ),
+ dim=1,
+ )
+
+
+def _gate_segments(
+ output: Tensor,
+ lengths: tuple[int, int, int, int, int],
+ modulations: tuple[ModulationTuple, ModulationTuple, ModulationTuple, ModulationTuple, ModulationTuple],
+) -> Tensor:
+ segments = torch.split(output, lengths, dim=1)
+ return torch.cat(
+ tuple(modulation[2] * segment for segment, modulation in zip(segments, modulations)), dim=1
+ )
+
+
+class _JointBlock(nn.Module):
+ def __init__(self):
+ super().__init__()
+ hidden_size = HIDDEN_SIZE
+ self.num_heads = NUM_HEADS
+ self.hidden_size = hidden_size
+ self.mlp_hidden_dim = MLP_SIZE
+ self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_in = nn.Linear(hidden_size, 2 * MLP_SIZE, bias=False)
+ self.attn_out = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.mlp_out = nn.Linear(MLP_SIZE, hidden_size, bias=False)
+ self.norm = _QKNorm(hidden_size // NUM_HEADS)
+ self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.mlp_act = _SwiGLU()
+ self.attention = _Attention()
+ self.register_parameter("in_proj_weight", None)
+
+ def pack_input_projection(self) -> None:
+ assert self.in_proj_weight is None, "input projection already packed"
+ packed = torch.cat(
+ (self.q_proj.weight, self.k_proj.weight, self.v_proj.weight, self.mlp_in.weight), dim=0
+ )
+ self.in_proj_weight = nn.Parameter(packed, requires_grad=False)
+ del self.q_proj, self.k_proj, self.v_proj, self.mlp_in
+
+ def forward(
+ self,
+ sequence: Tensor,
+ rope: Tensor,
+ lengths: tuple[int, int, int, int, int],
+ modulations: tuple[
+ ModulationTuple,
+ ModulationTuple,
+ ModulationTuple,
+ ModulationTuple,
+ ModulationTuple,
+ ],
+ ) -> Tensor:
+ modulated = _modulate_segments(self.pre_norm(sequence), lengths, modulations)
+ batch, length, _ = modulated.shape
+ assert self.in_proj_weight is not None, "input projection is not packed"
+ q, k, v, mlp = F.linear(modulated, self.in_proj_weight).split(
+ (self.hidden_size, self.hidden_size, self.hidden_size, 2 * self.mlp_hidden_dim), dim=-1
+ )
+ q = q.reshape(batch, length, self.num_heads, -1).transpose(1, 2)
+ k = k.reshape(batch, length, self.num_heads, -1).transpose(1, 2)
+ v = v.reshape(batch, length, self.num_heads, -1).transpose(1, 2)
+ q, k = self.norm(q, k, v)
+ q, k = _apply_rope(q, k, rope)
+ output = self.attn_out(self.attention(q, k, v)) + self.mlp_out(self.mlp_act(mlp))
+ return sequence + _gate_segments(output, lengths, modulations)
+
+
+class BF16InferenceDiT(nn.Module):
+ """Released DROID BF16 DiT with opaque, explicitly owned prepared state."""
+
+ def __init__(self):
+ super().__init__()
+ in_channels = CHANNELS
+ self.depth = EARLY_DEPTH
+
+ head_dim = HIDDEN_SIZE // NUM_HEADS
+ self.pe_embedder = _RopeEmbedder(head_dim, THETA, AXES_DIM)
+ self.emb_in = nn.ModuleDict(
+ {name: nn.Linear(channels, HIDDEN_SIZE, bias=False) for name, channels in in_channels.items()}
+ )
+ self.txt_in = nn.Linear(CONTEXT_DIM, HIDDEN_SIZE, bias=False)
+ self.time_in = _MLPEmbedder(256, HIDDEN_SIZE)
+ self.vector_in = _MLPEmbedder(VECTOR_DIM, HIDDEN_SIZE)
+
+ sorted_modalities = sorted(in_channels)
+ self.early_stream_modulations = nn.ModuleDict(
+ {
+ **{name: _Modulation(HIDDEN_SIZE) for name in sorted_modalities},
+ "txt": _Modulation(HIDDEN_SIZE),
+ }
+ )
+ self.single_stream_modulations = nn.ModuleDict(
+ {
+ **{name: _Modulation(HIDDEN_SIZE) for name in sorted_modalities},
+ "txt": _Modulation(HIDDEN_SIZE),
+ }
+ )
+ self.content_mode_blocks = nn.ModuleDict(
+ {name: nn.ModuleList(_ModeBlock() for _ in range(EARLY_DEPTH)) for name in sorted_modalities}
+ )
+ self.txt_mode_blocks = nn.ModuleList(_ModeBlock() for _ in range(EARLY_DEPTH))
+ self.single_blocks = nn.ModuleList(_JointBlock() for _ in range(JOINT_DEPTH))
+ self.final_layer = nn.ModuleDict(
+ {name: _LastLayer(HIDDEN_SIZE, channels) for name, channels in in_channels.items()}
+ )
+
+ self._compiled_text = None
+ self._compiled_observation = None
+ self._compiled_step = None
+ self._compiled_hot = None
+ self._packed = False
+
+ @classmethod
+ def from_state_dict(
+ cls,
+ state_dict: Mapping[str, Tensor],
+ ) -> BF16InferenceDiT:
+ """Strictly load materialized BF16 tensors."""
+ with torch.device("meta"):
+ model = cls()
+ devices = {tensor.device for tensor in state_dict.values()}
+ dtypes = {tensor.dtype for tensor in state_dict.values()}
+ assert len(devices) == 1 and next(iter(devices)).type != "meta", "weights need one real device"
+ assert dtypes == {torch.bfloat16}, "expected BF16 weights"
+ model.load_state_dict(state_dict, strict=True, assign=True)
+ model._pack_for_inference()
+ model.eval()
+ return model
+
+ def _pack_for_inference(self) -> None:
+ assert not self._packed, "model already packed"
+ for collection in (self.content_mode_blocks.values(), (self.txt_mode_blocks,), (self.single_blocks,)):
+ for group in collection:
+ for block in group:
+ block.pack_input_projection()
+ del self.final_layer[VIDEO_COND]
+ del self.final_layer[ACTION_COND]
+ self._packed = True
+
+ def train(self, mode: bool = True) -> BF16InferenceDiT:
+ assert not mode, "BF16InferenceDiT is inference-only"
+ super().train(False)
+ return self
+
+ def _apply(self, fn, recurse: bool = True):
+ assert not self._packed, "prepare inference after device placement"
+ return super()._apply(fn, recurse=recurse)
+
+ def compile_static(self) -> None:
+ assert not any(
+ compiled is not None
+ for compiled in (self._compiled_text, self._compiled_observation, self._compiled_step)
+ ), "static path already compiled"
+ options = {"dynamic": False, "fullgraph": True, "mode": "reduce-overhead"}
+ self._compiled_text = torch.compile(self._prepare_text_math, **options)
+ self._compiled_observation = torch.compile(self._prepare_observation_math, **options)
+ self._compiled_step = torch.compile(self._prepare_step_math, **options)
+
+ def compile_hot(self) -> None:
+ assert self._compiled_hot is None, "hot path already compiled"
+ self._compiled_hot = torch.compile(
+ self._forward_math, dynamic=False, fullgraph=True, mode="reduce-overhead"
+ )
+
+ def _weight_spec(self) -> tuple[torch.device, torch.dtype]:
+ weight = self.txt_in.weight
+ assert weight.dtype == torch.bfloat16 and weight.device.type != "meta", "expected BF16 weights"
+ return weight.device, weight.dtype
+
+ def validate_runtime_device(self) -> None:
+ device, _ = self._weight_spec()
+ assert device.type == "cuda", "prepare after CUDA placement"
+
+ def _embed_timestep(self, timestep: Tensor) -> Tensor:
+ with torch.autocast(device_type=timestep.device.type, enabled=False):
+ return self.time_in(_timestep_embedding(timestep).to(self.time_in.in_layer.weight.dtype))
+
+ def _prepare_text_math(self, ctx: Tensor, ctx_ids: Tensor, vector: Tensor) -> tuple[Tensor, ...]:
+ vector_embedding = self.vector_in(vector)
+ zero = torch.zeros(ctx.shape[0], dtype=torch.float32, device=ctx.device)
+ static_vector = self._embed_timestep(zero).to(ctx.dtype) + vector_embedding
+ early_txt = self.early_stream_modulations["txt"](static_vector)
+ early_video_cond = self.early_stream_modulations[VIDEO_COND](static_vector)
+ early_action_cond = self.early_stream_modulations[ACTION_COND](static_vector)
+ single_txt = self.single_stream_modulations["txt"](static_vector)
+ single_video_cond = self.single_stream_modulations[VIDEO_COND](static_vector)
+ single_action_cond = self.single_stream_modulations[ACTION_COND](static_vector)
+ text_rope = self.pe_embedder(ctx_ids)
+ txt = self.txt_in(ctx)
+ for depth in range(self.depth):
+ txt = self.txt_mode_blocks[depth](txt, text_rope, early_txt)
+ return (
+ txt,
+ text_rope,
+ *early_video_cond,
+ *early_action_cond,
+ *single_txt,
+ *single_video_cond,
+ *single_action_cond,
+ vector_embedding,
+ )
+
+ def _prepare_observation_math(
+ self,
+ text_rope: Tensor,
+ video_ids: Tensor,
+ video_cond: Tensor,
+ video_cond_ids: Tensor,
+ action_ids: Tensor,
+ action_cond: Tensor,
+ action_cond_ids: Tensor,
+ early_video_cond: ModulationTuple,
+ early_action_cond: ModulationTuple,
+ ) -> tuple[Tensor, Tensor, Tensor]:
+ video_rope = self.pe_embedder(video_ids)
+ video_cond_rope = self.pe_embedder(video_cond_ids)
+ action_rope = self.pe_embedder(action_ids)
+ action_cond_rope = self.pe_embedder(action_cond_ids)
+ encoded_video_cond = self.emb_in[VIDEO_COND](video_cond)
+ encoded_action_cond = self.emb_in[ACTION_COND](action_cond)
+ for depth in range(self.depth):
+ encoded_video_cond = self.content_mode_blocks[VIDEO_COND][depth](
+ encoded_video_cond, video_cond_rope, early_video_cond
+ )
+ encoded_action_cond = self.content_mode_blocks[ACTION_COND][depth](
+ encoded_action_cond, action_cond_rope, early_action_cond
+ )
+ joint_rope = torch.cat((text_rope, video_rope, video_cond_rope, action_rope, action_cond_rope), dim=2)
+ return encoded_video_cond, encoded_action_cond, joint_rope
+
+ def _prepare_step_math(
+ self,
+ vector_embedding: Tensor,
+ video_timestep: Tensor,
+ action_timestep: Tensor,
+ ) -> tuple[Tensor, ...]:
+ video_vector = self._embed_timestep(video_timestep).to(vector_embedding.dtype) + vector_embedding
+ action_vector = self._embed_timestep(action_timestep).to(vector_embedding.dtype) + vector_embedding
+ early_video = self.early_stream_modulations[VIDEO](video_vector)
+ early_action = self.early_stream_modulations[ACTION](action_vector)
+ single_video = self.single_stream_modulations[VIDEO](video_vector)
+ single_action = self.single_stream_modulations[ACTION](action_vector)
+ final_values = []
+ for name, vector in ((VIDEO, video_vector), (ACTION, action_vector)):
+ head = self.final_layer[name]
+ activated = head.adaLN_modulation[0](vector)
+ shift_weight, scale_weight = head.adaLN_modulation[1].weight.chunk(2)
+ final_values.extend(
+ (
+ F.linear(activated, shift_weight).unsqueeze(1),
+ F.linear(activated, scale_weight).add_(1).unsqueeze(1),
+ )
+ )
+ return (*early_video, *early_action, *single_video, *single_action, *final_values)
+
+ @torch.no_grad()
+ def prepare_text(self, ctx: Tensor, ctx_ids: Tensor, vector: Tensor) -> _PreparedText:
+ device, dtype = self._weight_spec()
+ batch = ctx.shape[0]
+ core = self._compiled_text if self._compiled_text is not None else self._prepare_text_math
+ txt, rope, *values = core(ctx, ctx_ids, vector)
+ return _PreparedText(
+ batch_size=batch,
+ dtype=dtype,
+ device=device,
+ txt_len=ctx.shape[1],
+ txt=txt.detach().clone(),
+ rope=rope.detach().clone(),
+ early_video_cond=tuple(x.detach().clone() for x in values[0:3]), # type: ignore[arg-type]
+ early_action_cond=tuple(x.detach().clone() for x in values[3:6]), # type: ignore[arg-type]
+ single_txt=tuple(x.detach().clone() for x in values[6:9]), # type: ignore[arg-type]
+ single_video_cond=tuple(x.detach().clone() for x in values[9:12]), # type: ignore[arg-type]
+ single_action_cond=tuple(x.detach().clone() for x in values[12:15]), # type: ignore[arg-type]
+ vector_embedding=values[15].detach().clone(),
+ )
+
+ @torch.no_grad()
+ def prepare_observation(
+ self,
+ text: _PreparedText,
+ *,
+ video_ids: Tensor,
+ video_cond: Tensor,
+ video_cond_ids: Tensor,
+ action_ids: Tensor,
+ action_cond: Tensor,
+ action_cond_ids: Tensor,
+ ) -> _PreparedRequest:
+ batch, device, dtype = text.batch_size, text.device, text.dtype
+ core = (
+ self._compiled_observation
+ if self._compiled_observation is not None
+ else self._prepare_observation_math
+ )
+ encoded_video_cond, encoded_action_cond, rope = core(
+ text.rope,
+ video_ids,
+ video_cond,
+ video_cond_ids,
+ action_ids,
+ action_cond,
+ action_cond_ids,
+ text.early_video_cond,
+ text.early_action_cond,
+ )
+ return _PreparedRequest(
+ batch_size=batch,
+ dtype=dtype,
+ device=device,
+ txt_len=text.txt_len,
+ video_len=video_ids.shape[1],
+ video_cond_len=video_cond.shape[1],
+ action_len=action_ids.shape[1],
+ action_cond_len=action_cond.shape[1],
+ txt=text.txt,
+ video_cond=encoded_video_cond.detach().clone(),
+ action_cond=encoded_action_cond.detach().clone(),
+ rope=rope.detach().clone(),
+ single_txt=text.single_txt,
+ single_video_cond=text.single_video_cond,
+ single_action_cond=text.single_action_cond,
+ vector_embedding=text.vector_embedding,
+ )
+
+ def _normalize_timestep(self, timestep: Tensor, request: _PreparedRequest) -> Tensor:
+ if timestep.ndim == 0:
+ timestep = timestep.expand(request.batch_size)
+ elif timestep.shape == (request.batch_size, 1):
+ timestep = timestep[:, 0]
+ else:
+ assert timestep.shape == (request.batch_size,), "invalid timestep shape"
+ assert timestep.dtype == torch.float32 and timestep.device == request.device, (
+ "invalid timestep placement"
+ )
+ return timestep
+
+ @torch.no_grad()
+ def prepare_step(
+ self,
+ request: _PreparedRequest,
+ video_timestep: Tensor,
+ action_timestep: Tensor,
+ ) -> _PreparedStep:
+ video_timestep = self._normalize_timestep(video_timestep, request)
+ action_timestep = self._normalize_timestep(action_timestep, request)
+ core = self._compiled_step if self._compiled_step is not None else self._prepare_step_math
+ values = core(request.vector_embedding, video_timestep, action_timestep)
+ return _PreparedStep(
+ early_video=tuple(x.detach().clone() for x in values[0:3]), # type: ignore[arg-type]
+ early_action=tuple(x.detach().clone() for x in values[3:6]), # type: ignore[arg-type]
+ single_video=tuple(x.detach().clone() for x in values[6:9]), # type: ignore[arg-type]
+ single_action=tuple(x.detach().clone() for x in values[9:12]), # type: ignore[arg-type]
+ final_video_shift=values[12].detach().clone(),
+ final_video_scale=values[13].detach().clone(),
+ final_action_shift=values[14].detach().clone(),
+ final_action_scale=values[15].detach().clone(),
+ )
+
+ def prepare_steps(
+ self,
+ request: _PreparedRequest,
+ video_timesteps: Tensor,
+ action_timesteps: Tensor,
+ ) -> tuple[_PreparedStep, ...]:
+ assert video_timesteps.ndim == action_timesteps.ndim == 1, "invalid timestep rank"
+ assert video_timesteps.shape == action_timesteps.shape, "timestep shape mismatch"
+ return tuple(
+ self.prepare_step(request, video_timesteps[index], action_timesteps[index])
+ for index in range(video_timesteps.numel())
+ )
+
+ def _forward_math(
+ self,
+ request: _PreparedRequest,
+ step: _PreparedStep,
+ video: Tensor,
+ action: Tensor,
+ ) -> tuple[Tensor, Tensor]:
+ video_start = request.txt_len
+ video_cond_start = video_start + request.video_len
+ action_start = video_cond_start + request.video_cond_len
+ action_cond_start = action_start + request.action_len
+ video_rope = request.rope[:, :, video_start:video_cond_start]
+ action_rope = request.rope[:, :, action_start:action_cond_start]
+ encoded_video = self.emb_in[VIDEO](video)
+ encoded_action = self.emb_in[ACTION](action)
+ for depth in range(self.depth):
+ encoded_video = self.content_mode_blocks[VIDEO][depth](
+ encoded_video, video_rope, step.early_video
+ )
+ encoded_action = self.content_mode_blocks[ACTION][depth](
+ encoded_action, action_rope, step.early_action
+ )
+ sequence = torch.cat(
+ (request.txt, encoded_video, request.video_cond, encoded_action, request.action_cond), dim=1
+ )
+ lengths = (
+ request.txt_len,
+ request.video_len,
+ request.video_cond_len,
+ request.action_len,
+ request.action_cond_len,
+ )
+ modulations = (
+ request.single_txt,
+ step.single_video,
+ request.single_video_cond,
+ step.single_action,
+ request.single_action_cond,
+ )
+ for block in self.single_blocks:
+ sequence = block(sequence, request.rope, lengths, modulations)
+ video_hidden = sequence[:, video_start:video_cond_start]
+ action_hidden = sequence[:, action_start:action_cond_start]
+ video_hidden = self.final_layer[VIDEO].norm_final(video_hidden)
+ video_hidden.mul_(step.final_video_scale).add_(step.final_video_shift)
+ action_hidden = self.final_layer[ACTION].norm_final(action_hidden)
+ action_hidden.mul_(step.final_action_scale).add_(step.final_action_shift)
+ return self.final_layer[VIDEO].linear(video_hidden), self.final_layer[ACTION].linear(action_hidden)
+
+ @torch.no_grad()
+ def forward_prepared(
+ self,
+ request: _PreparedRequest,
+ step: _PreparedStep,
+ *,
+ video: Tensor,
+ action: Tensor,
+ ) -> DroidPrediction:
+ core = self._compiled_hot if self._compiled_hot is not None else self._forward_math
+ video_output, action_output = core(request, step, video, action)
+ return DroidPrediction(video_output, action_output)
+
+ def forward(self, *_args: Any, **_kwargs: Any):
+ raise RuntimeError("use prepare_text/prepare_observation/prepare_steps/forward_prepared")
diff --git a/flux-umi/src/flux_action/models/transformer_inf_fp8r.py b/flux-umi/src/flux_action/models/transformer_inf_fp8r.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd5275ab909412c79a1e0c4371785e3894489327
--- /dev/null
+++ b/flux-umi/src/flux_action/models/transformer_inf_fp8r.py
@@ -0,0 +1,1006 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Native rowwise-FP8 inference for the released DROID DiT.
+
+Every transformer-block linear is loaded from an E4M3 weight and an FP32
+per-row scale. The published checkpoint also quantizes video/text boundaries,
+time/vector embedders, and non-action modulations; action boundaries and
+modulations plus RMSNorm weights remain BF16. Runtime activation quantization,
+Q/K RMSNorm plus RoPE, and SwiGLU are ordinary Torch expressions; matrix
+multiplication uses :func:`torch._scaled_mm`.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from torch import Tensor, nn
+
+VIDEO = "video"
+VIDEO_COND = "video_cond"
+ACTION = "action_prediction_droid"
+ACTION_COND = "action_prediction_droid_cond"
+_STREAMS = (VIDEO, VIDEO_COND, ACTION, ACTION_COND)
+_JOINT_STREAMS = ("txt", VIDEO, VIDEO_COND, ACTION, ACTION_COND)
+_CHANNELS = {VIDEO: 96, VIDEO_COND: 96, ACTION: 8, ACTION_COND: 8}
+CONTEXT_DIM = 20480
+VECTOR_DIM = 768
+HIDDEN = 3072
+HEADS = 24
+DEPTH = 5
+JOINT_DEPTH = 28
+AXES = (32, 32, 32, 32)
+THETA = 10000
+MLP = 9216
+GEMM_ALIGNMENT = 256
+ROW_ALIGNMENT = 128
+
+_BF16_LINEAR_PREFIXES = (
+ f"emb_in.{ACTION}",
+ f"emb_in.{ACTION_COND}",
+ f"early_stream_modulations.{ACTION}",
+ f"early_stream_modulations.{ACTION_COND}",
+ f"single_stream_modulations.{ACTION}",
+ f"single_stream_modulations.{ACTION_COND}",
+ f"final_layer.{ACTION}",
+ f"final_layer.{ACTION_COND}",
+)
+
+ModulationTuple = tuple[Tensor, Tensor, Tensor]
+
+
+def _is_native_fp8r_weight(name: str) -> bool:
+ return name.endswith(".weight") and not name.startswith(_BF16_LINEAR_PREFIXES)
+
+
+def _quantize_fp8r(value: Tensor) -> tuple[Tensor, Tensor]:
+ assert value.dtype == torch.bfloat16 and value.is_contiguous() and value.ndim >= 1, (
+ "expected contiguous BF16 weight"
+ )
+ rows = value.reshape(-1, value.shape[-1]).float()
+ scale = (rows.abs().amax(dim=1) / 448.0).clamp(min=1e-12)
+ quantized = (rows / scale[:, None]).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)
+ return quantized.reshape_as(value), scale
+
+
+def _scaled_mm(
+ activation_q: Tensor,
+ weight_q_nk: Tensor,
+ activation_scale: Tensor,
+ weight_scale: Tensor,
+) -> Tensor:
+ return torch._scaled_mm(
+ activation_q,
+ weight_q_nk.T,
+ activation_scale[:, None].contiguous(),
+ weight_scale[None, :].contiguous(),
+ out_dtype=torch.bfloat16,
+ use_fast_accum=True,
+ )
+
+
+def _rmsnorm_rope(value: Tensor, weight: Tensor, rope: Tensor, eps: float) -> Tensor:
+ normalized = value.float() * torch.rsqrt(value.float().square().mean(dim=-1, keepdim=True) + eps)
+ normalized = normalized.to(torch.bfloat16) * weight
+ pairs = normalized.float().reshape(*normalized.shape[:-1], -1, 2)
+ cosine = rope[:, :, None, :, 0]
+ sine = rope[:, :, None, :, 1]
+ even = cosine * pairs[..., 0] - sine * pairs[..., 1]
+ odd = sine * pairs[..., 0] + cosine * pairs[..., 1]
+ return torch.stack((even, odd), dim=-1).reshape_as(value).to(torch.bfloat16)
+
+
+def _qk_norm_rope(
+ q: Tensor,
+ k: Tensor,
+ q_weight: Tensor,
+ k_weight: Tensor,
+ q_rope: Tensor,
+ k_rope: Tensor,
+ eps: float,
+) -> tuple[Tensor, Tensor]:
+ return (
+ _rmsnorm_rope(q, q_weight, q_rope, eps),
+ _rmsnorm_rope(k, k_weight, k_rope, eps),
+ )
+
+
+def _swiglu(value: Tensor) -> Tensor:
+ gate, up = value.chunk(2, dim=-1)
+ return (F.silu(gate.float()) * up.float()).to(torch.bfloat16)
+
+
+@dataclass(frozen=True)
+class _PreparedText:
+ batch: int
+ dtype: torch.dtype
+ device: torch.device
+ text_len: int
+ text: Tensor
+ rope: Tensor
+ condition_early: tuple[ModulationTuple, ModulationTuple]
+ static_joint: tuple[ModulationTuple, ModulationTuple, ModulationTuple]
+ vector: Tensor
+
+
+@dataclass(frozen=True)
+class _PreparedRequest:
+ batch: int
+ dtype: torch.dtype
+ device: torch.device
+ lengths: tuple[int, int, int, int, int]
+ text: Tensor
+ video_cond: Tensor
+ action_cond: Tensor
+ rope: Tensor
+ static_joint: tuple[ModulationTuple, ModulationTuple, ModulationTuple]
+ vector: Tensor
+
+
+@dataclass(frozen=True)
+class _PreparedStep:
+ video_early: ModulationTuple
+ action_early: ModulationTuple
+ dynamic_joint: tuple[ModulationTuple, ModulationTuple]
+ final_video: tuple[Tensor, Tensor]
+ final_action: tuple[Tensor, Tensor]
+
+
+@dataclass(frozen=True)
+class DroidPrediction:
+ video: Tensor
+ action: Tensor
+
+ def as_dict(self) -> dict[str, Tensor]:
+ return {"x_video": self.video, "x_action_prediction_droid": self.action}
+
+
+def _ceil(value: int, alignment: int) -> int:
+ return (value + alignment - 1) // alignment * alignment
+
+
+def _pad_sequence(value: Tensor, alignment: int) -> Tensor:
+ padded = _ceil(value.shape[1], alignment)
+ if padded == value.shape[1]:
+ return value.contiguous()
+ return F.pad(value, (0, 0, 0, padded - value.shape[1]))
+
+
+def _pad_to_tokens(value: Tensor, tokens: int) -> Tensor:
+ if value.shape[1] == tokens:
+ return value
+ return F.pad(value, (0, 0, 0, tokens - value.shape[1]))
+
+
+def _rope(pos: Tensor, dim: int, theta: int) -> Tensor:
+ assert dim % 2 == 0, "RoPE dimension must be even"
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
+ phase = torch.einsum("...n,d->...nd", pos, 1.0 / (theta**scale))
+ return torch.stack((phase.cos(), phase.sin()), dim=-1).float()
+
+
+def _timestep_embedding(t: Tensor, dim: int = 256) -> Tensor:
+ half = dim // 2
+ frequencies = torch.exp(
+ -math.log(10000) * torch.arange(half, device=t.device, dtype=torch.float32) / half
+ )
+ angles = (1000.0 * t.float())[:, None] * frequencies[None]
+ return torch.cat((angles.cos(), angles.sin()), dim=-1)
+
+
+class _EmbedND(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.axes = AXES
+ self.theta = THETA
+
+ def forward(self, ids: Tensor) -> Tensor:
+ pieces = [_rope(ids[..., axis], dim, self.theta) for axis, dim in enumerate(self.axes)]
+ return torch.cat(pieces, dim=-2).contiguous()
+
+
+class _FP8RLinear(nn.Module):
+ """One packed rowwise-FP8 weight with explicit GEMM padding."""
+
+ def __init__(
+ self,
+ weight_q: Tensor,
+ weight_scale: Tensor,
+ in_features: int,
+ out_features: int,
+ row_alignment: int,
+ ):
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.row_alignment = row_alignment
+ self.register_buffer("weight_q", weight_q)
+ self.register_buffer("weight_scale", weight_scale)
+
+ @classmethod
+ @torch.no_grad()
+ def pack(
+ cls,
+ linear: nn.Linear,
+ native_scale: Tensor,
+ ) -> _FP8RLinear:
+ weight = linear.weight
+ padded_n = _ceil(linear.out_features, GEMM_ALIGNMENT)
+ padded_k = _ceil(linear.in_features, GEMM_ALIGNMENT)
+ padding = (0, padded_k - linear.in_features, 0, padded_n - linear.out_features)
+ assert weight.dtype == torch.float8_e4m3fn, "expected E4M3 weight"
+ weight_q = F.pad(weight, padding).contiguous()
+ weight_scale = F.pad(native_scale, (0, padded_n - linear.out_features), value=1.0).contiguous()
+ assert linear.bias is None, "FP8r linear cannot have bias"
+ return cls(
+ weight_q,
+ weight_scale,
+ linear.in_features,
+ linear.out_features,
+ ROW_ALIGNMENT,
+ )
+
+ def quantize_input(self, x: Tensor) -> tuple[Tensor, Tensor, int, tuple[int, ...]]:
+ assert x.dtype == torch.bfloat16, "expected BF16 activations"
+ assert x.shape[-1] == self.in_features, "invalid linear input width"
+ leading = x.shape[:-1]
+ rows = math.prod(leading)
+ assert rows >= 1, "empty linear input"
+ padded_rows = _ceil(rows, self.row_alignment)
+ flat = x.reshape(rows, self.in_features)
+ pad_k = self.weight_q.shape[1] - self.in_features
+ pad_m = padded_rows - rows
+ flat = F.pad(flat, (0, pad_k, 0, pad_m)) if pad_k or pad_m else flat.contiguous()
+ activation_q, activation_scale = _quantize_fp8r(flat)
+ return activation_q, activation_scale, rows, leading
+
+ def forward_quantized(
+ self,
+ activation_q: Tensor,
+ activation_scale: Tensor,
+ rows: int,
+ leading: tuple[int, ...],
+ ) -> Tensor:
+ result = _scaled_mm(
+ activation_q,
+ self.weight_q,
+ activation_scale,
+ self.weight_scale,
+ )[:rows, : self.out_features]
+ return result.reshape(*leading, self.out_features)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.forward_quantized(*self.quantize_input(x))
+
+
+def _standalone_qkv_epilogue(
+ q_value: Tensor,
+ k_value: Tensor,
+ v_value: Tensor,
+ *,
+ batch: int,
+ tokens: int,
+ valid_length: int,
+ heads: int,
+ norm: _QKNorm,
+ rope: Tensor,
+) -> tuple[Tensor, Tensor, Tensor]:
+ # Independent scaled-mm outputs become exact contiguous BLHD views before
+ # Torch RMSNorm and RoPE.
+ q_blhd = q_value.reshape(batch, tokens, heads, -1).contiguous()
+ k_blhd = k_value.reshape(batch, tokens, heads, -1).contiguous()
+ valid_rope = rope[:, :valid_length].contiguous()
+ q, k = _qk_norm_rope(
+ q_blhd[:, :valid_length].contiguous(),
+ k_blhd[:, :valid_length].contiguous(),
+ norm.query_norm.scale,
+ norm.key_norm.scale,
+ valid_rope,
+ valid_rope,
+ 1e-6,
+ )
+ q = q.transpose(1, 2)
+ k = k.transpose(1, 2)
+ v = v_value.reshape(batch, tokens, heads, -1)[:, :valid_length].transpose(1, 2)
+ return q, k, v
+
+
+class _BlockProjections(nn.Module):
+ """One canonical quantization of QKV and W13 for an FP8 block."""
+
+ def __init__(
+ self,
+ qkv_q: Tensor,
+ qkv_scale: Tensor,
+ mlp_q: Tensor,
+ mlp_scale: Tensor,
+ *,
+ hidden: int,
+ mlp: int,
+ row_alignment: int,
+ ):
+ super().__init__()
+ self.hidden = hidden
+ self.mlp = mlp
+ self.row_alignment = row_alignment
+ self.register_buffer("qkv_q", qkv_q)
+ self.register_buffer("qkv_scale", qkv_scale)
+ self.register_buffer("mlp_q", mlp_q)
+ self.register_buffer("mlp_scale", mlp_scale)
+
+ @classmethod
+ @torch.no_grad()
+ def pack(
+ cls,
+ q_proj: nn.Linear,
+ k_proj: nn.Linear,
+ v_proj: nn.Linear,
+ mlp_in: nn.Linear,
+ *,
+ native_scales: tuple[Tensor, Tensor, Tensor, Tensor],
+ ) -> _BlockProjections:
+ qkv_weights = (q_proj.weight, k_proj.weight, v_proj.weight)
+ qkv_scales = native_scales[:3]
+ assert all(weight.dtype == torch.float8_e4m3fn for weight in qkv_weights), "expected E4M3 QKV"
+ qkv_q = torch.cat(qkv_weights, dim=0).contiguous()
+ qkv_scale = torch.cat(qkv_scales, dim=0).contiguous()
+
+ mlp_scale = native_scales[3]
+ assert mlp_in.weight.dtype == torch.float8_e4m3fn, "expected E4M3 MLP weight"
+ mlp_q = mlp_in.weight.contiguous()
+ return cls(
+ qkv_q,
+ qkv_scale,
+ mlp_q,
+ mlp_scale,
+ hidden=q_proj.out_features,
+ mlp=mlp_in.out_features // 2,
+ row_alignment=ROW_ALIGNMENT,
+ )
+
+ def quantize_input(self, active: Tensor) -> tuple[Tensor, Tensor]:
+ flat = active.reshape(-1, active.shape[-1]).contiguous()
+ assert flat.shape[0] % self.row_alignment == 0, "invalid packed row alignment"
+ return _quantize_fp8r(flat)
+
+ def qkv(
+ self,
+ active_q: Tensor,
+ active_scale: Tensor,
+ *,
+ batch: int,
+ tokens: int,
+ valid_length: int,
+ heads: int,
+ norm: _QKNorm,
+ rope: Tensor,
+ ) -> tuple[Tensor, Tensor, Tensor]:
+ weights = self.qkv_q.split(self.hidden, dim=0)
+ scales = self.qkv_scale.split(self.hidden, dim=0)
+ q_value, k_value, v_value = (
+ _scaled_mm(active_q, weight, active_scale, scale)
+ for weight, scale in zip(weights, scales, strict=True)
+ )
+ return _standalone_qkv_epilogue(
+ q_value,
+ k_value,
+ v_value,
+ batch=batch,
+ tokens=tokens,
+ valid_length=valid_length,
+ heads=heads,
+ norm=norm,
+ rope=rope,
+ )
+
+ def mlp_value(self, active_q: Tensor, active_scale: Tensor, *, batch: int, tokens: int) -> Tensor:
+ packed = _scaled_mm(active_q, self.mlp_q, active_scale, self.mlp_scale)
+ return _swiglu(packed.reshape(batch, tokens, 2 * self.mlp).contiguous())
+
+
+class _MLPEmbedder(nn.Module):
+ def __init__(self, in_dim: int, hidden: int):
+ super().__init__()
+ self.in_layer = nn.Linear(in_dim, hidden, bias=False)
+ self.out_layer = nn.Linear(hidden, hidden, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.out_layer(F.silu(self.in_layer(x)))
+
+
+class _RMSNorm(nn.Module):
+ def __init__(self, dim: int):
+ super().__init__()
+ self.scale = nn.Parameter(torch.ones(dim))
+
+
+class _QKNorm(nn.Module):
+ def __init__(self, dim: int):
+ super().__init__()
+ self.query_norm = _RMSNorm(dim)
+ self.key_norm = _RMSNorm(dim)
+
+
+class _Modulation(nn.Module):
+ def __init__(self, hidden: int):
+ super().__init__()
+ self.lin = nn.Linear(hidden, 3 * hidden, bias=False)
+
+ def forward(self, vector: Tensor) -> ModulationTuple:
+ values = self.lin(F.silu(vector))[:, None].chunk(3, dim=-1)
+ return values # type: ignore[return-value]
+
+
+class _ModeBlock(nn.Module):
+ def __init__(self):
+ super().__init__()
+ hidden = HIDDEN
+ mlp = MLP
+ self.heads = HEADS
+ self.q_proj = nn.Linear(hidden, hidden, bias=False)
+ self.k_proj = nn.Linear(hidden, hidden, bias=False)
+ self.v_proj = nn.Linear(hidden, hidden, bias=False)
+ self.mlp_in = nn.Linear(hidden, 2 * mlp, bias=False)
+ self.attn_out = nn.Linear(hidden, hidden, bias=False)
+ self.mlp_out = nn.Linear(mlp, hidden, bias=False)
+ self.norm = _QKNorm(hidden // HEADS)
+ self.pre_norm = nn.LayerNorm(hidden, elementwise_affine=False, eps=1e-6)
+ self.projections: _BlockProjections | None = None
+
+ @torch.no_grad()
+ def pack_fp8r(
+ self,
+ native_scales: tuple[Tensor, Tensor, Tensor, Tensor],
+ ) -> None:
+ self.projections = _BlockProjections.pack(
+ self.q_proj,
+ self.k_proj,
+ self.v_proj,
+ self.mlp_in,
+ native_scales=native_scales,
+ )
+ del self.q_proj, self.k_proj, self.v_proj, self.mlp_in
+
+ def forward(self, x: Tensor, pe: Tensor, modulation: ModulationTuple, valid_length: int) -> Tensor:
+ shift, scale, gate = modulation
+ active = (1 + scale) * self.pre_norm(x) + shift
+ batch, tokens = active.shape[:2]
+ assert self.projections is not None, "mode projections are not packed"
+ active_q, active_scale = self.projections.quantize_input(active)
+ q, k, v = self.projections.qkv(
+ active_q,
+ active_scale,
+ batch=batch,
+ tokens=tokens,
+ valid_length=valid_length,
+ heads=self.heads,
+ norm=self.norm,
+ rope=pe,
+ )
+ mlp = self.projections.mlp_value(active_q, active_scale, batch=batch, tokens=tokens)
+ attention = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).flatten(2)
+ attention = _pad_to_tokens(attention, x.shape[1])
+ branch = self.attn_out(attention) + self.mlp_out(mlp)
+ updated = x[:, :valid_length] + gate * branch[:, :valid_length]
+ return _pad_to_tokens(updated, x.shape[1])
+
+
+class _JointBlock(nn.Module):
+ def __init__(self):
+ super().__init__()
+ hidden = HIDDEN
+ mlp = MLP
+ self.heads = HEADS
+ self.q_proj = nn.Linear(hidden, hidden, bias=False)
+ self.k_proj = nn.Linear(hidden, hidden, bias=False)
+ self.v_proj = nn.Linear(hidden, hidden, bias=False)
+ self.mlp_in = nn.Linear(hidden, 2 * mlp, bias=False)
+ self.attn_out = nn.Linear(hidden, hidden, bias=False)
+ self.mlp_out = nn.Linear(mlp, hidden, bias=False)
+ self.norm = _QKNorm(hidden // HEADS)
+ self.pre_norm = nn.LayerNorm(hidden, elementwise_affine=False, eps=1e-6)
+ self.projections: _BlockProjections | None = None
+
+ @torch.no_grad()
+ def pack_fp8r(
+ self,
+ native_scales: tuple[Tensor, Tensor, Tensor, Tensor],
+ ) -> None:
+ self.projections = _BlockProjections.pack(
+ self.q_proj,
+ self.k_proj,
+ self.v_proj,
+ self.mlp_in,
+ native_scales=native_scales,
+ )
+ del self.q_proj, self.k_proj, self.v_proj, self.mlp_in
+
+ def forward(
+ self,
+ sequence: Tensor,
+ lengths: tuple[int, int, int, int, int],
+ pe: Tensor,
+ modulations: tuple[
+ ModulationTuple, ModulationTuple, ModulationTuple, ModulationTuple, ModulationTuple
+ ],
+ ) -> Tensor:
+ valid_length = sum(lengths)
+ normalized = self.pre_norm(sequence[:, :valid_length])
+ pieces = normalized.split(lengths, dim=1)
+ active_valid = torch.cat(
+ [(1 + modulation[1]) * piece + modulation[0] for piece, modulation in zip(pieces, modulations)],
+ dim=1,
+ )
+ active = _pad_to_tokens(active_valid, sequence.shape[1])
+ assert self.projections is not None, "joint projections are not packed"
+ batch, tokens = active.shape[:2]
+ active_q, active_scale = self.projections.quantize_input(active)
+ q, k, v = self.projections.qkv(
+ active_q,
+ active_scale,
+ batch=batch,
+ tokens=tokens,
+ valid_length=valid_length,
+ heads=self.heads,
+ norm=self.norm,
+ rope=pe,
+ )
+ attention = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).flatten(2)
+ attention = _pad_to_tokens(attention, sequence.shape[1])
+ mlp = self.projections.mlp_value(active_q, active_scale, batch=batch, tokens=tokens)
+ branch = self.attn_out(attention) + self.mlp_out(mlp)
+ branch_pieces = branch[:, :valid_length].split(lengths, dim=1)
+ sequence_pieces = sequence[:, :valid_length].split(lengths, dim=1)
+ updated = torch.cat(
+ [
+ value + modulation[2] * update
+ for value, modulation, update in zip(sequence_pieces, modulations, branch_pieces)
+ ],
+ dim=1,
+ )
+ return _pad_to_tokens(updated, sequence.shape[1])
+
+
+class _LastLayer(nn.Module):
+ def __init__(self, hidden: int, channels: int):
+ super().__init__()
+ self.norm_final = nn.LayerNorm(hidden, elementwise_affine=False, eps=1e-6)
+ self.linear = nn.Linear(hidden, channels, bias=False)
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden, 2 * hidden, bias=False))
+
+
+class FP8RInferenceDiT(nn.Module):
+ """Released DROID architecture with owned packed FP8 weights and prepared state."""
+
+ def __init__(self):
+ super().__init__()
+ self._packed = False
+ self._compiled_text = None
+ self._compiled_observation = None
+ self._compiled_step = None
+ self._compiled_hot = None
+ self.pe_embedder = _EmbedND()
+ self.emb_in = nn.ModuleDict(
+ {name: nn.Linear(width, HIDDEN, bias=False) for name, width in _CHANNELS.items()}
+ )
+ self.txt_in = nn.Linear(CONTEXT_DIM, HIDDEN, bias=False)
+ self.time_in = _MLPEmbedder(256, HIDDEN)
+ self.vector_in = _MLPEmbedder(VECTOR_DIM, HIDDEN)
+ self.early_stream_modulations = nn.ModuleDict(
+ {name: _Modulation(HIDDEN) for name in (*_STREAMS, "txt")}
+ )
+ self.single_stream_modulations = nn.ModuleDict(
+ {name: _Modulation(HIDDEN) for name in (*_STREAMS, "txt")}
+ )
+ self.content_mode_blocks = nn.ModuleDict(
+ {name: nn.ModuleList([_ModeBlock() for _ in range(DEPTH)]) for name in _STREAMS}
+ )
+ self.txt_mode_blocks = nn.ModuleList([_ModeBlock() for _ in range(DEPTH)])
+ self.single_blocks = nn.ModuleList([_JointBlock() for _ in range(JOINT_DEPTH)])
+ self.final_layer = nn.ModuleDict(
+ {name: _LastLayer(HIDDEN, width) for name, width in _CHANNELS.items()}
+ )
+
+ @staticmethod
+ def _check_runtime_device(device: torch.device) -> None:
+ assert device.type == "cuda", "native FP8r inference requires CUDA"
+ capability = torch.cuda.get_device_capability(device)
+ supported = {(8, 9), (9, 0), (10, 0), (10, 3), (12, 0)}
+ # TODO: REMOVE ME after SM89 rowwise FP8 runtime validation.
+ if capability not in supported:
+ raise RuntimeError(
+ "FP8r inference requires SM89/SM90/SM100/SM103/SM120 native FP8 support, "
+ f"got SM{capability[0]}{capability[1]}"
+ )
+
+ @classmethod
+ def from_quantized_state_dict(cls, state_dict: Mapping[str, Tensor]) -> FP8RInferenceDiT:
+ """Strictly load the released native-FP8r checkpoint without changing its payloads."""
+ devices = {value.device for value in state_dict.values()}
+ assert len(devices) == 1, "weights need one device"
+ base = {key: value for key, value in state_dict.items() if not key.endswith(".weight_scale")}
+ scales = {key: value for key, value in state_dict.items() if key.endswith(".weight_scale")}
+ expected_scales: set[str] = set()
+ for key, value in base.items():
+ if not _is_native_fp8r_weight(key):
+ assert value.dtype == torch.bfloat16, "expected BF16 boundary weight"
+ else:
+ assert value.dtype == torch.float8_e4m3fn, "expected E4M3 weight"
+ scale_key = f"{key.removesuffix('.weight')}.weight_scale"
+ expected_scales.add(scale_key)
+ scale = scales[scale_key]
+ assert scale.dtype == torch.float32 and scale.shape == (value.shape[0],), "invalid FP8r scale"
+ assert value.is_contiguous() and scale.is_contiguous(), "FP8r payload must be contiguous"
+ assert set(scales) == expected_scales, "FP8r scale set mismatch"
+
+ with torch.device("meta"):
+ model = cls()
+ model.load_state_dict(base, strict=True, assign=True)
+ del model.final_layer[VIDEO_COND]
+ del model.final_layer[ACTION_COND]
+ model._pack_linears(scales)
+ model.eval()
+ return model
+
+ def _pack_linears(self, native_scales: Mapping[str, Tensor]) -> None:
+ assert not self._packed, "model already packed"
+
+ def scale_for(path: str) -> Tensor:
+ scale_path = f"{path.removesuffix('.weight')}.weight_scale"
+ return native_scales[scale_path]
+
+ def convert(module: nn.Module, path: str) -> None:
+ for name, child in list(module.named_children()):
+ child_path = f"{path}.{name}" if path else name
+ weight_path = f"{child_path}.weight"
+ if isinstance(child, nn.Linear) and _is_native_fp8r_weight(weight_path):
+ setattr(
+ module,
+ name,
+ _FP8RLinear.pack(child, scale_for(weight_path)),
+ )
+ else:
+ convert(child, child_path)
+
+ # Each block shares one activation quantization across Q/K/V and W13.
+ for stream, blocks in self.content_mode_blocks.items():
+ for index, block in enumerate(blocks):
+ prefix = f"content_mode_blocks.{stream}.{index}"
+ block.pack_fp8r(
+ tuple(
+ scale_for(f"{prefix}.{name}.weight")
+ for name in ("q_proj", "k_proj", "v_proj", "mlp_in")
+ ),
+ )
+ for index, block in enumerate(self.txt_mode_blocks):
+ prefix = f"txt_mode_blocks.{index}"
+ block.pack_fp8r(
+ tuple(
+ scale_for(f"{prefix}.{name}.weight") for name in ("q_proj", "k_proj", "v_proj", "mlp_in")
+ ),
+ )
+ for index, block in enumerate(self.single_blocks):
+ prefix = f"single_blocks.{index}"
+ block.pack_fp8r(
+ tuple(
+ scale_for(f"{prefix}.{name}.weight") for name in ("q_proj", "k_proj", "v_proj", "mlp_in")
+ ),
+ )
+
+ for name, child in list(self.named_children()):
+ if name in ("content_mode_blocks", "txt_mode_blocks", "single_blocks"):
+ convert(child, name)
+ elif isinstance(child, nn.Linear):
+ weight_path = f"{name}.weight"
+ if _is_native_fp8r_weight(weight_path):
+ setattr(self, name, _FP8RLinear.pack(child, scale_for(weight_path)))
+ else:
+ convert(child, name)
+ self._packed = True
+
+ def train(self, mode: bool = True) -> FP8RInferenceDiT:
+ assert not mode, "FP8RInferenceDiT is inference-only"
+ super().train(False)
+ return self
+
+ def _weight_spec(self) -> tuple[torch.device, torch.dtype]:
+ action_input = self.emb_in[ACTION]
+ assert self._packed and isinstance(action_input, nn.Linear), "native model is not packed"
+ assert action_input.weight.dtype == torch.bfloat16, "expected BF16 action input"
+ return action_input.weight.device, torch.bfloat16
+
+ def validate_runtime_device(self) -> None:
+ """Require native-FP8 hardware only when the restored model is used for inference."""
+ device, _ = self._weight_spec()
+ self._check_runtime_device(device)
+ for module in self.modules():
+ if isinstance(module, _FP8RLinear):
+ assert module.weight_q.dtype == torch.float8_e4m3fn, "expected E4M3 weight"
+ assert module.weight_scale.dtype == torch.float32, "expected FP32 scale"
+ elif isinstance(module, _BlockProjections):
+ assert module.qkv_q.dtype == module.mlp_q.dtype == torch.float8_e4m3fn, (
+ "expected E4M3 block weights"
+ )
+ assert module.qkv_scale.dtype == module.mlp_scale.dtype == torch.float32, (
+ "expected FP32 block scales"
+ )
+
+ def compile_static(self) -> None:
+ assert not any(
+ value is not None
+ for value in (self._compiled_text, self._compiled_observation, self._compiled_step)
+ ), "static path already compiled"
+ options = dict(dynamic=False, fullgraph=True, mode="reduce-overhead")
+ self._compiled_text = torch.compile(self._prepare_text_math, **options)
+ self._compiled_observation = torch.compile(self._prepare_observation_math, **options)
+ self._compiled_step = torch.compile(self._prepare_step_math, **options)
+
+ def compile_hot(self) -> None:
+ assert self._compiled_hot is None, "hot path already compiled"
+ self._compiled_hot = torch.compile(
+ self._forward_math, dynamic=False, fullgraph=True, mode="reduce-overhead"
+ )
+
+ def _embed_time(self, timestep: Tensor) -> Tensor:
+ return self.time_in(_timestep_embedding(timestep).to(torch.bfloat16))
+
+ def _zero_vector(self, vector: Tensor) -> Tensor:
+ zero = torch.zeros(vector.shape[0], device=vector.device, dtype=torch.float32)
+ return self._embed_time(zero) + vector
+
+ def _prepare_text_math(self, ctx: Tensor, ctx_ids: Tensor, vector: Tensor) -> tuple[Tensor, ...]:
+ vector_embedding = self.vector_in(vector)
+ static = self._zero_vector(vector_embedding)
+ text_early = self.early_stream_modulations["txt"](static)
+ condition_early = (
+ self.early_stream_modulations[VIDEO_COND](static),
+ self.early_stream_modulations[ACTION_COND](static),
+ )
+ static_joint = tuple(
+ self.single_stream_modulations[name](static) for name in ("txt", VIDEO_COND, ACTION_COND)
+ )
+ pe = self.pe_embedder(ctx_ids)
+ text = _pad_sequence(self.txt_in(ctx), ROW_ALIGNMENT)
+ for block in self.txt_mode_blocks:
+ text = block(text, pe, text_early, ctx.shape[1])
+ return (
+ text,
+ pe,
+ *condition_early[0],
+ *condition_early[1],
+ *static_joint[0],
+ *static_joint[1],
+ *static_joint[2],
+ vector_embedding,
+ )
+
+ @torch.no_grad()
+ def prepare_text(self, ctx: Tensor, ctx_ids: Tensor, vector: Tensor) -> _PreparedText:
+ device, dtype = self._weight_spec()
+ batch = ctx.shape[0]
+ core = self._compiled_text or self._prepare_text_math
+ text, pe, *values = core(ctx, ctx_ids, vector)
+ return _PreparedText(
+ batch,
+ dtype,
+ device,
+ ctx.shape[1],
+ text.detach().clone(),
+ pe.detach().clone(),
+ (tuple(x.detach().clone() for x in values[0:3]), tuple(x.detach().clone() for x in values[3:6])), # type: ignore[arg-type]
+ tuple(tuple(x.detach().clone() for x in values[start : start + 3]) for start in (6, 9, 12)), # type: ignore[arg-type]
+ values[15].detach().clone(),
+ )
+
+ def _prepare_observation_math(
+ self,
+ text_rope: Tensor,
+ video_ids: Tensor,
+ video_cond: Tensor,
+ video_cond_ids: Tensor,
+ action_ids: Tensor,
+ action_cond: Tensor,
+ action_cond_ids: Tensor,
+ video_shift: Tensor,
+ video_scale: Tensor,
+ video_gate: Tensor,
+ action_shift: Tensor,
+ action_scale: Tensor,
+ action_gate: Tensor,
+ ) -> tuple[Tensor, Tensor, Tensor]:
+ ropes = tuple(
+ self.pe_embedder(ids) for ids in (video_ids, video_cond_ids, action_ids, action_cond_ids)
+ )
+ video_value = _pad_sequence(self.emb_in[VIDEO_COND](video_cond), ROW_ALIGNMENT)
+ action_value = _pad_sequence(self.emb_in[ACTION_COND](action_cond), ROW_ALIGNMENT)
+ for block in self.content_mode_blocks[VIDEO_COND]:
+ video_value = block(
+ video_value,
+ ropes[1],
+ (video_shift, video_scale, video_gate),
+ video_cond.shape[1],
+ )
+ for block in self.content_mode_blocks[ACTION_COND]:
+ action_value = block(
+ action_value,
+ ropes[3],
+ (action_shift, action_scale, action_gate),
+ action_cond.shape[1],
+ )
+ return video_value, action_value, torch.cat((text_rope, *ropes), dim=1)
+
+ @torch.no_grad()
+ def prepare_observation(
+ self,
+ text: _PreparedText,
+ *,
+ video_ids: Tensor,
+ video_cond: Tensor,
+ video_cond_ids: Tensor,
+ action_ids: Tensor,
+ action_cond: Tensor,
+ action_cond_ids: Tensor,
+ ) -> _PreparedRequest:
+ core = self._compiled_observation or self._prepare_observation_math
+ video_value, action_value, pe = core(
+ text.rope,
+ video_ids,
+ video_cond,
+ video_cond_ids,
+ action_ids,
+ action_cond,
+ action_cond_ids,
+ *text.condition_early[0],
+ *text.condition_early[1],
+ )
+ return _PreparedRequest(
+ text.batch,
+ text.dtype,
+ text.device,
+ (
+ text.text_len,
+ video_ids.shape[1],
+ video_cond.shape[1],
+ action_ids.shape[1],
+ action_cond.shape[1],
+ ),
+ text.text,
+ video_value.detach().clone(),
+ action_value.detach().clone(),
+ pe.detach().clone(),
+ text.static_joint,
+ text.vector,
+ )
+
+ def _prepare_step_math(
+ self, vector: Tensor, video_timestep: Tensor, action_timestep: Tensor
+ ) -> tuple[Tensor, ...]:
+ video_vector = self._embed_time(video_timestep) + vector
+ action_vector = self._embed_time(action_timestep) + vector
+ video_early = self.early_stream_modulations[VIDEO](video_vector)
+ action_early = self.early_stream_modulations[ACTION](action_vector)
+ dynamic_joint = (
+ self.single_stream_modulations[VIDEO](video_vector),
+ self.single_stream_modulations[ACTION](action_vector),
+ )
+ video_final = self.final_layer[VIDEO].adaLN_modulation(video_vector)[:, None].chunk(2, dim=-1)
+ action_final = self.final_layer[ACTION].adaLN_modulation(action_vector)[:, None].chunk(2, dim=-1)
+ return (
+ *video_early,
+ *action_early,
+ *dynamic_joint[0],
+ *dynamic_joint[1],
+ video_final[0],
+ video_final[1] + 1,
+ action_final[0],
+ action_final[1] + 1,
+ )
+
+ def _scalar_timestep(self, value: Tensor, request: _PreparedRequest) -> Tensor:
+ if value.ndim == 0:
+ value = value.expand(request.batch)
+ elif value.shape == (request.batch, 1):
+ value = value[:, 0]
+ else:
+ assert value.shape == (request.batch,), "invalid timestep shape"
+ assert value.dtype == torch.float32 and value.device == request.device, "invalid timestep placement"
+ return value
+
+ def _prepare_step(
+ self, request: _PreparedRequest, video_timestep: Tensor, action_timestep: Tensor
+ ) -> _PreparedStep:
+ video_timestep = self._scalar_timestep(video_timestep, request)
+ action_timestep = self._scalar_timestep(action_timestep, request)
+ core = self._compiled_step or self._prepare_step_math
+ values = core(request.vector, video_timestep, action_timestep)
+ values = tuple(value.detach().clone() for value in values)
+ return _PreparedStep(
+ tuple(values[0:3]), # type: ignore[arg-type]
+ tuple(values[3:6]), # type: ignore[arg-type]
+ (tuple(values[6:9]), tuple(values[9:12])), # type: ignore[arg-type]
+ (values[12], values[13]),
+ (values[14], values[15]),
+ )
+
+ @torch.no_grad()
+ def prepare_steps(
+ self, request: _PreparedRequest, video_timesteps: Tensor, action_timesteps: Tensor
+ ) -> tuple[_PreparedStep, ...]:
+ assert video_timesteps.ndim == action_timesteps.ndim == 1, "invalid timestep rank"
+ assert video_timesteps.shape == action_timesteps.shape, "timestep shape mismatch"
+ return tuple(
+ self._prepare_step(request, video_timesteps[index], action_timesteps[index])
+ for index in range(video_timesteps.numel())
+ )
+
+ def _forward_math(
+ self, request: _PreparedRequest, step: _PreparedStep, video: Tensor, action: Tensor
+ ) -> tuple[Tensor, Tensor]:
+ video_value = _pad_sequence(self.emb_in[VIDEO](video), ROW_ALIGNMENT)
+ action_value = _pad_sequence(self.emb_in[ACTION](action), ROW_ALIGNMENT)
+ text_len, video_len, video_cond_len, action_len, _ = request.lengths
+ video_pe = request.rope[:, text_len : text_len + video_len]
+ action_start = text_len + video_len + video_cond_len
+ action_pe = request.rope[:, action_start : action_start + action_len]
+ for block in self.content_mode_blocks[VIDEO]:
+ video_value = block(video_value, video_pe, step.video_early, video_len)
+ for block in self.content_mode_blocks[ACTION]:
+ action_value = block(action_value, action_pe, step.action_early, action_len)
+ valid_streams = (
+ request.text[:, :text_len],
+ video_value[:, :video_len],
+ request.video_cond[:, :video_cond_len],
+ action_value[:, :action_len],
+ request.action_cond[:, : request.lengths[4]],
+ )
+ sequence = _pad_sequence(torch.cat(valid_streams, dim=1), ROW_ALIGNMENT)
+ mods = (
+ request.static_joint[0],
+ step.dynamic_joint[0],
+ request.static_joint[1],
+ step.dynamic_joint[1],
+ request.static_joint[2],
+ )
+ for block in self.single_blocks:
+ sequence = block(sequence, request.lengths, request.rope, mods)
+ offsets = (text_len, text_len + video_len + video_cond_len)
+ video_hidden = self.final_layer[VIDEO].norm_final(sequence[:, offsets[0] : offsets[0] + video_len])
+ video_hidden = video_hidden * step.final_video[1] + step.final_video[0]
+ action_hidden = self.final_layer[ACTION].norm_final(sequence[:, offsets[1] : offsets[1] + action_len])
+ action_hidden = action_hidden * step.final_action[1] + step.final_action[0]
+ return self.final_layer[VIDEO].linear(video_hidden), self.final_layer[ACTION].linear(action_hidden)
+
+ @torch.no_grad()
+ def forward_prepared(
+ self,
+ request: _PreparedRequest,
+ step: _PreparedStep,
+ *,
+ video: Tensor,
+ action: Tensor,
+ ) -> DroidPrediction:
+ core = self._compiled_hot or self._forward_math
+ video_output, action_output = core(request, step, video, action)
+ return DroidPrediction(video_output, action_output)
+
+ def forward(self, *args: Any, **kwargs: Any) -> None:
+ raise RuntimeError("use prepare_text/prepare_observation/prepare_steps/forward_prepared")
+
+
+__all__ = ["DroidPrediction", "FP8RInferenceDiT"]
diff --git a/flux-umi/src/flux_action/models/vae_cute_rmsnorm.py b/flux-umi/src/flux_action/models/vae_cute_rmsnorm.py
new file mode 100644
index 0000000000000000000000000000000000000000..16b691c0ea9919ae054785950a5d35eada603e34
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_cute_rmsnorm.py
@@ -0,0 +1,106 @@
+"""Staging adapter for an explicitly enabled frozen training VAE RMSNorm.
+
+This file is copied into the isolated integration snapshot only after its base
+snapshot is frozen. Decoder modules are never changed. Outside the training
+encoding context the original nn.RMSNorm forward remains active.
+"""
+
+import os
+from contextlib import contextmanager
+from contextvars import ContextVar
+from functools import lru_cache
+from importlib.metadata import PackageNotFoundError, version
+
+import torch
+from torch import nn
+
+from .cute_rmsnorm_kernel import rms_norm_cute
+
+_TRAINING_ENCODING = ContextVar("flux_action_cute_rmsnorm_training_encoding", default=False)
+_REQUIRE_KERNEL = os.environ.get("FLUX_ACTION_CUTE_RMSNORM_REQUIRE_KERNEL") == "1"
+
+
+@lru_cache(maxsize=1)
+def dependency_versions():
+ packages = {}
+ for name in ("nvidia-cutlass-dsl", "apache-tvm-ffi"):
+ try:
+ packages[name] = version(name)
+ except PackageNotFoundError:
+ packages[name] = None
+ return packages
+
+
+def dependencies_supported():
+ # Exact versions used by the successful GPU correctness and real-VAE tests.
+ return dependency_versions() == {
+ "nvidia-cutlass-dsl": "4.8.0", "apache-tvm-ffi": "0.1.14.post1"}
+
+
+@contextmanager
+def training_rmsnorm_context(enabled):
+ token = _TRAINING_ENCODING.set(bool(enabled))
+ try:
+ yield
+ finally:
+ _TRAINING_ENCODING.reset(token)
+
+
+class FrozenTrainingCuTeRMSNorm(nn.RMSNorm):
+ """State-dict-compatible RMSNorm with an opt-in frozen-training dispatch."""
+
+ def forward(self, x):
+ if torch.compiler.is_compiling():
+ return super().forward(x)
+ if _TRAINING_ENCODING.get():
+ if not dependencies_supported():
+ if _REQUIRE_KERNEL:
+ raise RuntimeError("Required CuTe RMSNorm dependencies are unavailable or unvalidated")
+ return super().forward(x)
+ # The kernel metadata guard retains F.rms_norm for dtype, shape,
+ # device, version, grad, Tensor subclass and compilation exclusions.
+ return rms_norm_cute(x, self.normalized_shape, self.weight, self.eps,
+ require_kernel=_REQUIRE_KERNEL)
+ return super().forward(x)
+
+
+def install_training_rmsnorm(video_vae, *, compile_model=False):
+ """Replace only the audited encoder norms; unsupported structures stay stock."""
+ def unsupported(reason):
+ if _REQUIRE_KERNEL:
+ raise RuntimeError(f"Required CuTe RMSNorm installation failed: {reason}")
+ return {"installed": False, "count": 0, "actual_wrapper_count": 0,
+ "expected_wrapper_count": 46, "require_kernel": False, "reason": reason}
+
+ module = getattr(video_vae, "module", video_vae)
+ encoder = getattr(getattr(module, "model", None), "encoder", None)
+ if compile_model or getattr(module, "_encoder_compiled", False):
+ return unsupported("compiled encoder retains original RMSNorm")
+ if not isinstance(encoder, nn.Module):
+ return unsupported("unrecognized encoder retains original RMSNorm")
+ candidates = [(name, layer) for name, layer in encoder.named_modules()
+ if name.endswith((".q_norm", ".k_norm"))]
+ if len(candidates) != 46 or any(
+ type(layer) not in (nn.RMSNorm, FrozenTrainingCuTeRMSNorm)
+ or tuple(layer.normalized_shape) != (64,) or layer.weight is not None
+ or layer.eps != 1e-5 or layer.training
+ for _, layer in candidates
+ ):
+ return unsupported("encoder norm contract differs; original modules retained")
+ if _REQUIRE_KERNEL and not dependencies_supported():
+ return unsupported("dependencies are unavailable or unvalidated")
+ for name, layer in candidates:
+ if type(layer) is FrozenTrainingCuTeRMSNorm:
+ continue
+ parent_name, attribute = name.rsplit(".", 1)
+ replacement = FrozenTrainingCuTeRMSNorm(64, eps=1e-5, elementwise_affine=False)
+ replacement.train(layer.training)
+ setattr(encoder.get_submodule(parent_name), attribute, replacement)
+ actual = [name for name, layer in encoder.named_modules() if type(layer) is FrozenTrainingCuTeRMSNorm]
+ if len(actual) != 46:
+ raise RuntimeError(f"CuTe RMSNorm installation invariant failed: {len(actual)} wrappers")
+ return {"installed": True, "count": len(actual), "actual_wrapper_count": len(actual),
+ "expected_wrapper_count": 46, "require_kernel": _REQUIRE_KERNEL,
+ "module_names": actual,
+ "dependencies": dependency_versions(), "dependencies_supported": dependencies_supported(),
+ "scope": "frozen training encode context only; inference/decoder retain original dispatch"}
diff --git a/flux-umi/src/flux_action/models/vae_cute_rope.py b/flux-umi/src/flux_action/models/vae_cute_rope.py
new file mode 100644
index 0000000000000000000000000000000000000000..32378547eaf2dc1a6a742ba8100b22f51d176d5f
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_cute_rope.py
@@ -0,0 +1,136 @@
+"""Opt-in dispatch for the validated frozen training VAE half-RoPE kernel.
+
+No modules, parameters, buffers or frequency tables are replaced. Only the
+registered encoder modules inside an explicit training scope can use CuTe.
+"""
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass
+from functools import lru_cache
+from importlib.metadata import PackageNotFoundError, version
+import os
+
+import torch
+from torch import nn
+
+
+_TRAINING_ENCODING = ContextVar("flux_action_cute_vae_rope_training_encoding", default=None)
+_REQUIRE_KERNEL = os.environ.get("FLUX_ACTION_CUTE_VAE_ROPE_REQUIRE_KERNEL") == "1"
+_VALIDATED_PACKAGES = {
+ "nvidia-cutlass-dsl": "4.8.0",
+ "apache-tvm-ffi": "0.1.14.post1",
+ "natten": "0.21.6+torch2100cu130",
+}
+
+
+@dataclass(frozen=True)
+class TrainingRopeHandle:
+ module_ids: frozenset[int]
+ require_kernel: bool
+
+
+@lru_cache(maxsize=1)
+def dependency_versions():
+ result = {}
+ for name in _VALIDATED_PACKAGES:
+ try:
+ result[name] = version(name)
+ except PackageNotFoundError:
+ result[name] = None
+ return result
+
+
+def backend_reason():
+ if str(torch.__version__) != "2.10.0+cu130" or torch.version.cuda != "13.0":
+ return "unvalidated PyTorch/CUDA runtime"
+ if dependency_versions() != _VALIDATED_PACKAGES:
+ return "unavailable or unvalidated CuTe/NATTEN dependencies"
+ if os.environ.get("F3_NATTEN_BACKEND", "") not in ("", "blackwell-fna"):
+ return "unvalidated NATTEN backend override"
+ return None
+
+
+@contextmanager
+def training_rope_context(handle=None):
+ # Explicitly push None for inactive/eval/history scopes, even when nested.
+ token = _TRAINING_ENCODING.set(handle)
+ try:
+ yield
+ finally:
+ _TRAINING_ENCODING.reset(token)
+
+
+def prepare_training_rope(video_vae, *, compile_model=False):
+ """Validate the encoder inventory without changing module ownership/state."""
+ from .video_vae import RotaryPositionEmbedding3D
+
+ def unsupported(reason):
+ if _REQUIRE_KERNEL:
+ raise RuntimeError(f"Required CuTe VAE RoPE configuration failed: {reason}")
+ return None, {"enabled": False, "configured": False, "encoder_rope_count": 0,
+ "expected_encoder_rope_count": 23, "require_kernel": False, "reason": reason}
+
+ module = getattr(video_vae, "module", video_vae)
+ encoder = getattr(getattr(module, "model", None), "encoder", None)
+ if compile_model or getattr(module, "_encoder_compiled", False):
+ return unsupported("compiled VAE is outside the validated path")
+ if not isinstance(module, nn.Module) or not isinstance(encoder, nn.Module) or module.training:
+ return unsupported("unrecognized or non-frozen VAE")
+ if any(parameter.requires_grad for parameter in module.parameters()):
+ return unsupported("VAE parameters must be frozen")
+ candidates = [(name, layer) for name, layer in encoder.named_modules() if name.endswith(".rope")]
+ if len(candidates) != 23 or any(
+ type(layer) is not RotaryPositionEmbedding3D or layer.head_dim != 64 or layer.chunk_dim != 16
+ or layer.training or tuple(layer.inv_freq.shape) != (4, 8)
+ or layer.inv_freq.dtype != torch.bfloat16 or layer.inv_freq.requires_grad
+ for _, layer in candidates
+ ):
+ return unsupported("encoder RoPE metadata differs from the validated 23-module inventory")
+ reason = backend_reason()
+ if reason is not None:
+ return unsupported(reason)
+ handle = TrainingRopeHandle(frozenset(id(layer) for _, layer in candidates), _REQUIRE_KERNEL)
+ return handle, {
+ "enabled": True, "configured": True, "encoder_rope_count": len(candidates),
+ "expected_encoder_rope_count": 23, "require_kernel": _REQUIRE_KERNEL,
+ "module_names": [name for name, _ in candidates], "dependencies": dependency_versions(),
+ "dependencies_supported": True, "torch": str(torch.__version__), "cuda": torch.version.cuda,
+ "validated_device_capability": [10, 3], "validated_natten_backend": "blackwell-fna",
+ "scope": "registered frozen encoder only, inside training/default _encode_windows",
+ "weights_buffers_and_frequency_construction_unchanged": True,
+ }
+
+
+@lru_cache(maxsize=16)
+def _device_supported(index):
+ return torch.cuda.get_device_capability(index) == (10, 3)
+
+
+def dispatch_training_rope(module, q, k, cos, sin):
+ """Return None for the original expression, or the fused no-grad Q/K pair."""
+ # Keep Dynamo out of ContextVar.get even when the opt-in flag is disabled.
+ # Strict configured compilation is rejected before constructing a handle.
+ if torch.compiler.is_compiling():
+ return None
+ handle = _TRAINING_ENCODING.get()
+ if handle is None or id(module) not in handle.module_ids:
+ return None
+ reason = backend_reason()
+ if reason is None and (module.training or module.head_dim != 64 or module.chunk_dim != 16
+ or tuple(module.inv_freq.shape) != (4, 8)
+ or module.inv_freq.dtype != torch.bfloat16 or module.inv_freq.requires_grad):
+ reason = "registered encoder RoPE metadata changed"
+ if reason is None:
+ from .video_vae import _natten_backends
+ if any(backend != "blackwell-fna" for backend in _natten_backends.values()):
+ reason = "active NATTEN backend is outside the validated path"
+ if reason is None and type(q) is torch.Tensor and q.is_cuda and not _device_supported(q.device.index):
+ reason = "CuTe VAE RoPE was validated only on SM103"
+ if reason is not None:
+ if handle.require_kernel:
+ raise RuntimeError(f"Required CuTe VAE RoPE dispatch failed: {reason}")
+ return None
+ # The byte-identical validated kernel owns the complete tensor/device/dtype/
+ # shape/layout/no-grad/alignment guard. Strict mode cannot take its fallback.
+ from .cute_vae_rope_kernel import apply_vae_rope
+ return apply_vae_rope(q, k, cos, sin, require_kernel=handle.require_kernel)
diff --git a/flux-umi/src/flux_action/models/vae_fused_gemm.py b/flux-umi/src/flux_action/models/vae_fused_gemm.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2067e40fef8ede7a01d03530a7bbd8f94d987a3
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_fused_gemm.py
@@ -0,0 +1,665 @@
+"""Triton GEMMs with fused prologue/epilogue for the frozen video-VAE encoder (experiment vae-fused-gemm, GPU 0).
+
+Kernels (bf16 in, fp32 tcgen05 accumulation, bf16 out; TMA loads/stores, persistent grouped rasterisation, automatic
+warp specialisation = the configuration that matched cuBLAS bitwise in probe_gemm.py):
+
+ * ``linear`` plain out = bf16(acc [+ bias]) (Triton control for the cuBLAS GEMM)
+ * ``fc1_glu`` fc1 GEMM + GLU epilogue: the fc1 weight is pair-interleaved once (row 2j = gate j, row
+ 2j+1 = up j, zero-padded to whole tiles; prep_glu_weight) so one [BM, 2*BN] accumulator
+ holds (gate, up) of each output column in adjacent columns; the epilogue rounds them to
+ bf16 exactly where cuBLAS does (bf16(acc [+ bias])) and applies glu_bf16's arithmetic
+ (s = RN(g / (1 + expf(-g))) via an exhaustively verified FMA division, s = bf16(s),
+ y = bf16(s * u)); writes [M, H] directly. Adopted at K in {256, 512, 1024}.
+ * ``linear_residual`` GEMM + residual epilogue: out = bf16(x + bf16(acc [+ bias])) (eager ``x + linear(...)``).
+ * ``ln_stats`` per-row mean / rstd of the exact bf16 LayerNorm (ATen vectorized_layer_norm_kernel
+ arithmetic, reusing vae_ln_exact's Welford pieces), optionally with the fused residual
+ (writes x_new = bf16(x + delta) like residual_layer_norm_bf16).
+ * ``ln_linear`` GEMM whose A operand is normalised in registers from (x, mean, rstd, gamma, beta):
+ a = bf16(fma(gamma, rstd * (x - mean), beta)) -- bitwise the exact LN kernel's output --
+ then tcgen05 dot; optional GLU epilogue (LN2 -> fc1 -> GLU in one kernel).
+
+Rounding points: the production chain is cuBLAS (fp32 accumulate over K in MMA order, one RNE to bf16, bias added in
+fp32 before the rounding) -> separate bf16 kernels. The Triton GEMM issues the same tcgen05 MMAs over K in the same
+order, so bf16(acc) is bitwise cuBLAS's output (verified at every production shape and tile config in
+probe_gemm.py / bench_stages.py); the epilogues then execute the stock kernels' arithmetic on those bf16 values.
+Whole-encoder latents with the real weights are bitwise identical to production (bench_vae.py, results.md).
+
+Install: ``install(vae, state, ...)`` patches ``forward`` of the encoder GLU_MLP instances (and optionally the
+Swin blocks' norm2 -> fc1 path) on top of the production fused state (vae_fused_pointwise + vae_qk_fused); the
+fused GEMMs run only inside ``training_fused_context(state)`` and only at shapes listed in the adopted config table;
+everything else keeps cuBLAS. Nothing under src/ is modified.
+"""
+from __future__ import annotations
+
+import types
+from dataclasses import dataclass, field
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+from triton.tools.tensor_descriptor import TensorDescriptor
+
+from flux_action.models.vae_ln_exact import _combine_div, _combine_scaled, _split4, _welford_step
+
+NUM_SMS = torch.cuda.get_device_properties(0).multi_processor_count if torch.cuda.is_available() else 148
+
+# (BM, BN, BK, num_warps, num_stages) per K -- tuned by bench_stages.py. BN is the accumulator width; the GLU
+# kernel's tile covers BN/2 gate + BN/2 up columns (prep_glu_weight interleaving). Default = the probe's best config.
+DEFAULT_CFG = (128, 256, 64, 8, 3)
+GLU_CFG: dict[int, tuple] = {256: (256, 128, 64, 8, 3), 512: (128, 256, 64, 8, 3), 1024: (128, 256, 64, 8, 3),
+ 2048: (128, 256, 64, 8, 3)} # K -> cfg (bench_stages.py / glu_retune.json)
+PLAIN_CFG: dict[int, tuple] = {}
+RES_CFG: dict[int, tuple] = {}
+RES_DEFAULT_CFG = (128, 128, 64, 8, 3) # the residual x tile shares the pipeline's SMEM budget
+LN_CFG: dict[int, tuple] = {}
+LN_DEFAULT_CFG = (128, 128, 64, 8, 3) # register A operand: 128x256 exceeds the 512-column TMEM budget
+GROUP_M = 8
+# The pair-interleaved fc1 weights live in ``Installed.prepped`` (per install, keyed by module name, each entry
+# holding the weight it was built from): a module-global cache keyed on ``data_ptr`` served a freed weight's copy to
+# a different same-shape tensor once the caching allocator reused the address.
+
+
+# =============================================================================================== device helpers
+@triton.jit
+def _compute_pid(tile_id, num_pid_in_group, num_pid_m, GROUP_SIZE_M: tl.constexpr):
+ group_id = tile_id // num_pid_in_group
+ first_pid_m = group_id * GROUP_SIZE_M
+ group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
+ pid_m = first_pid_m + (tile_id % num_pid_in_group) % group_size_m
+ pid_n = (tile_id % num_pid_in_group) // group_size_m
+ return pid_m, pid_n
+
+
+@triton.jit
+def _rcp_approx(x):
+ return tl.inline_asm_elementwise("rcp.approx.ftz.f32 $0, $1;", "=f,f", [x], dtype=tl.float32, is_pure=True, pack=1)
+
+
+@triton.jit
+def _silu_div_exact(g, d):
+ """RN(g / d) == div.rn.ftz.f32(g, d) for every bf16-valued g and d = 1 + expf(-g) in [1, inf], without the
+ IEEE division's FCHK/slow-path branch: rcp.approx + the CUDA fast-path Newton FMAs (q1 = q0 + r*(g - d*q0),
+ twice), d pre-scaled by 2^-64 when d > 2^64 so the reciprocal never underflows, g clamped to FLT_MAX (g = +inf:
+ FLT_MAX rounds to bf16 +inf like inf/1 does) and one select for d = inf or denormal/zero g (ftz division: g * 0
+ keeps the sign). Verified exhaustively over the 65536 bf16 g in selftest() (probe_div.py); the plain div.rn
+ costs ~3x the whole GLU epilogue and every extra compare/select ~60 us at the 540k-token stage (probe_epi2.py)."""
+ big = d > 18446744073709551616.0 # 2^64
+ ds = tl.where(big, d * 5.421010862427522e-20, d) # * 2^-64 (exact)
+ r = _rcp_approx(ds)
+ gc = tl.minimum(g, 3.4028234663852886e38)
+ q0 = gc * r
+ e0 = libdevice.fma(-q0, ds, gc)
+ q1 = libdevice.fma(e0, r, q0)
+ e1 = libdevice.fma(-q1, ds, gc)
+ q = libdevice.fma(e1, r, q1)
+ q = tl.where(big, q * 5.421010862427522e-20, q)
+ inf = tl.zeros_like(d) + float("inf")
+ return tl.where((d == inf) | (tl.abs(g) < 1.1754943508222875e-38), g * 0.0, q)
+
+
+@triton.jit
+def _glu_epilogue(g, u, FAST_DIV: tl.constexpr):
+ """vae_fused_pointwise._glu_kernel on bf16-valued fp32 inputs: ATen silu (x / (1 + expf(-x)) in fp32),
+ rounded to bf16, times up, rounded to bf16. FAST_DIV swaps div.rn for the exhaustively verified FMA sequence."""
+ one = tl.zeros_like(g) + 1.0
+ d = one + libdevice.exp(-g)
+ if FAST_DIV:
+ s = _silu_div_exact(g, d)
+ else:
+ s = libdevice.div_rn(g, d)
+ s = s.to(tl.bfloat16).to(tl.float32)
+ return (s * u).to(tl.bfloat16)
+
+
+@triton.jit
+def _glu_fast_kernel(gu_ptr, y_ptr, M, H: tl.constexpr, BLOCK: tl.constexpr):
+ """vae_fused_pointwise._glu_kernel with the FMA division (standalone control for the fusion)."""
+ pid = tl.program_id(0).to(tl.int64)
+ idx = pid * BLOCK + tl.arange(0, BLOCK).to(tl.int64)
+ row = idx // H
+ mask = row < M # i64 row index vs M: an i32 ``M * H`` product wraps for M*H >= 2**31
+ col = idx % H
+ src = row * (2 * H) + col
+ g = tl.load(gu_ptr + src, mask=mask, other=0.0).to(tl.float32)
+ u = tl.load(gu_ptr + src + H, mask=mask, other=0.0).to(tl.float32)
+ tl.store(y_ptr + idx, _glu_epilogue(g, u, True), mask=mask)
+
+
+def glu_bf16_fast(gate_up: Tensor, block: int = 2048, num_warps: int = 4) -> Tensor:
+ gu2 = gate_up.reshape(-1, gate_up.shape[-1])
+ M, H2 = gu2.shape
+ H = H2 // 2
+ assert M < 2 ** 31, M # M is an i32 kernel scalar; M*H may exceed 2**31 (i64 mask in the kernel)
+ y = torch.empty((M, H), dtype=torch.bfloat16, device=gate_up.device)
+ _glu_fast_kernel[(triton.cdiv(M * H, block),)](gu2, y, M, H=H, BLOCK=block, num_warps=num_warps, enable_fp_fusion=False)
+ return y.view(*gate_up.shape[:-1], H)
+
+
+@triton.jit
+def _round_bias(acc, bias_ptr, off_n, N, BN: tl.constexpr, HAS_BIAS: tl.constexpr):
+ """cuBLAS epilogue: bf16(acc + fp32(bias)) (bias added in fp32 before the single RNE) or bf16(acc)."""
+ if HAS_BIAS:
+ cols = off_n + tl.arange(0, BN)
+ b = tl.load(bias_ptr + cols, mask=cols < N, other=0.0).to(tl.float32)
+ acc = acc + b[None, :]
+ return acc.to(tl.bfloat16)
+
+
+@triton.jit
+def _ln_normalize(xv, mean, rstd, w, b):
+ """ATen: gamma * (rstd * (x - mean)) + beta -> fma(gamma, rstd * (x - mean), beta), one bf16 rounding.
+ xv [BM, BK] fp32, mean/rstd [BM] fp32, w/b [BK] fp32."""
+ y = libdevice.fma(w[None, :], rstd[:, None] * (xv - mean[:, None]), b[None, :])
+ return y.to(tl.bfloat16)
+
+
+# =============================================================================================== GEMM (TMA A)
+@triton.jit
+def _split_halves(acc, BM: tl.constexpr, BN: tl.constexpr):
+ """[BM, 2*BN] with (gate, up) in adjacent columns (prep_glu_weight pair interleave) -> (gate, up) [BM, BN].
+ The two columns of a pair live in the same thread after the TMEM load, so this is register-local (no permute;
+ the tile-blocked layout needed a permute through shared memory: probe_epilogue.py)."""
+ return tl.split(tl.reshape(acc, [BM, BN, 2]))
+
+
+@triton.jit
+def _epilogue(acc, c_desc, x_desc, bias_ptr, off_m, off_n, N, BM: tl.constexpr, BN: tl.constexpr,
+ EPILOGUE: tl.constexpr, HAS_BIAS: tl.constexpr, FAST_DIV: tl.constexpr):
+ """EPILOGUE 0: c = bf16(acc [+bias]); 1: GLU of the (gate | up) halves of the 2*BN-wide tile, c = [M, H] tile
+ at column off_n // 2; 2: c = bf16(x + bf16(acc [+bias]))."""
+ c = _round_bias(acc, bias_ptr, off_n, N, BN, HAS_BIAS)
+ if EPILOGUE == 1:
+ g, u = _split_halves(c.to(tl.float32), BM, BN // 2)
+ c_desc.store([off_m, off_n // 2], _glu_epilogue(g, u, FAST_DIV))
+ else:
+ if EPILOGUE == 2:
+ x = x_desc.load([off_m, off_n])
+ c = (x.to(tl.float32) + c.to(tl.float32)).to(tl.bfloat16) # eager bf16 add: fp32 add, one RNE
+ c_desc.store([off_m, off_n], c)
+
+
+@triton.jit
+def _gemm_kernel(a_desc, b_desc, c_desc, x_desc, bias_ptr, M, N, K,
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GROUP_SIZE_M: tl.constexpr,
+ NUM_SMS: tl.constexpr, EPILOGUE: tl.constexpr, HAS_BIAS: tl.constexpr,
+ WARP_SPECIALIZE: tl.constexpr, FLATTEN: tl.constexpr, FAST_DIV: tl.constexpr):
+ """out = A[M,K] @ B[N,K]^T with one of the _epilogue variants. For the GLU variant B is the tile-interleaved
+ (gate | up) weight of prep_glu_weight (N = its padded row count, BN = 2 * output tile width)."""
+ start_pid = tl.program_id(axis=0)
+ num_pid_m = tl.cdiv(M, BM)
+ num_pid_n = tl.cdiv(N, BN)
+ k_tiles = tl.cdiv(K, BK)
+ num_tiles = num_pid_m * num_pid_n
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
+ for tile_id in tl.range(start_pid, num_tiles, NUM_SMS, flatten=FLATTEN, warp_specialize=WARP_SPECIALIZE):
+ pid_m, pid_n = _compute_pid(tile_id, num_pid_in_group, num_pid_m, GROUP_SIZE_M)
+ off_m = pid_m * BM
+ off_n = pid_n * BN
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ for ki in range(k_tiles):
+ off_k = ki * BK
+ a = a_desc.load([off_m, off_k])
+ b = b_desc.load([off_n, off_k])
+ acc = tl.dot(a, b.T, acc)
+ _epilogue(acc, c_desc, x_desc, bias_ptr, off_m, off_n, N, BM, BN, EPILOGUE, HAS_BIAS, FAST_DIV)
+
+
+# =============================================================================================== GEMM (LN prologue)
+@triton.jit
+def _ln_gemm_kernel(x_ptr, mean_ptr, rstd_ptr, w_ptr, bb_ptr, b_desc, c_desc, bias_ptr, M, N, K,
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, GROUP_SIZE_M: tl.constexpr,
+ NUM_SMS: tl.constexpr, EPILOGUE: tl.constexpr, HAS_BIAS: tl.constexpr,
+ WARP_SPECIALIZE: tl.constexpr, FLATTEN: tl.constexpr, FAST_DIV: tl.constexpr):
+ """A = bf16(LayerNorm(x)) formed in registers from the row statistics (M % BM == 0, K % BK == 0 required);
+ B via TMA; epilogues as in _gemm_kernel."""
+ start_pid = tl.program_id(axis=0)
+ num_pid_m = tl.cdiv(M, BM)
+ num_pid_n = tl.cdiv(N, BN)
+ k_tiles = tl.cdiv(K, BK)
+ num_tiles = num_pid_m * num_pid_n
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
+ rm = tl.arange(0, BM)
+ rk = tl.arange(0, BK)
+ for tile_id in tl.range(start_pid, num_tiles, NUM_SMS, flatten=FLATTEN, warp_specialize=WARP_SPECIALIZE):
+ pid_m, pid_n = _compute_pid(tile_id, num_pid_in_group, num_pid_m, GROUP_SIZE_M)
+ off_m = pid_m * BM
+ off_n = pid_n * BN
+ rows = off_m + rm
+ mean = tl.load(mean_ptr + rows)
+ rstd = tl.load(rstd_ptr + rows)
+ a_ptrs = x_ptr + rows.to(tl.int64)[:, None] * K + rk[None, :]
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ for ki in range(k_tiles):
+ off_k = ki * BK
+ xv = tl.load(a_ptrs + off_k).to(tl.float32)
+ w = tl.load(w_ptr + off_k + rk).to(tl.float32)
+ bb = tl.load(bb_ptr + off_k + rk).to(tl.float32)
+ a = _ln_normalize(xv, mean, rstd, w, bb)
+ b = b_desc.load([off_n, off_k])
+ acc = tl.dot(a, b.T, acc)
+ _epilogue(acc, c_desc, c_desc, bias_ptr, off_m, off_n, N, BM, BN, EPILOGUE, HAS_BIAS, FAST_DIV)
+
+
+# =============================================================================================== LN statistics
+@triton.jit
+def _ln_stats_kernel(x_ptr, res_ptr, mean_ptr, rstd_ptr, xo_ptr, M, eps, n_float,
+ N: tl.constexpr, R: tl.constexpr, LANES: tl.constexpr, FUSE_RESIDUAL: tl.constexpr,
+ RES_BROADCAST: tl.constexpr, EVEN_M: tl.constexpr, OFF64: tl.constexpr, POW2: tl.constexpr):
+ """vae_ln_exact._ln_exact_kernel's statistics pass (same [LANES, R, 4] tile, Welford steps, scaled-combine
+ tree) writing mean / rstd per row instead of the normalised rows; FUSE_RESIDUAL also writes x_new."""
+ NV: tl.constexpr = N // 4
+ NJ: tl.constexpr = NV // LANES
+ tl.static_assert(NJ * LANES == NV, "N/4 must be a multiple of LANES")
+ pid = tl.program_id(0)
+ rows = pid * R + tl.arange(0, R)
+ lane = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ if OFF64:
+ base = rows.to(tl.int64) * N
+ else:
+ base = rows * N
+ rmask = (rows < M)[None, :, None]
+ vcol = lane[:, None] * 4 + c4[None, :]
+ mean = tl.zeros([LANES, R], tl.float32)
+ m2 = tl.zeros([LANES, R], tl.float32)
+ for j in tl.static_range(NJ):
+ coffs = vcol + j * (4 * LANES)
+ offs = base[None, :, None] + coffs[:, None, :]
+ if EVEN_M:
+ xv = tl.load(x_ptr + offs).to(tl.float32)
+ else:
+ xv = tl.load(x_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ if FUSE_RESIDUAL:
+ if RES_BROADCAST:
+ rv = tl.load(res_ptr + coffs).to(tl.float32)[:, None, :]
+ elif EVEN_M:
+ rv = tl.load(res_ptr + offs).to(tl.float32)
+ else:
+ rv = tl.load(res_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ xb = (xv + rv).to(tl.bfloat16)
+ if EVEN_M:
+ tl.store(xo_ptr + offs, xb)
+ else:
+ tl.store(xo_ptr + offs, xb, mask=rmask)
+ xv = xb.to(tl.float32)
+ v0, v1, v2, v3 = _split4(xv, LANES, R)
+ mean, m2 = _welford_step(mean, m2, v0, 1.0 / (4 * j + 1))
+ mean, m2 = _welford_step(mean, m2, v1, 1.0 / (4 * j + 2))
+ mean, m2 = _welford_step(mean, m2, v2, 1.0 / (4 * j + 3))
+ mean, m2 = _welford_step(mean, m2, v3, 1.0 / (4 * j + 4))
+ if POW2:
+ m2s = m2 * (1.0 / (4 * NJ))
+ mean_t, var = tl.reduce((mean, m2s), 0, _combine_scaled)
+ else:
+ cnt = tl.zeros([LANES, R], tl.float32) + (4.0 * NJ)
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _combine_div)
+ nf = tl.zeros([R], tl.float32) + n_float
+ var = libdevice.div_rn(m2_t, nf)
+ rstd = tl.rsqrt(var + eps)
+ if EVEN_M:
+ tl.store(mean_ptr + rows, mean_t)
+ tl.store(rstd_ptr + rows, rstd)
+ else:
+ tl.store(mean_ptr + rows, mean_t, mask=rows < M)
+ tl.store(rstd_ptr + rows, rstd, mask=rows < M)
+
+
+@triton.jit
+def _ln_apply_kernel(x_ptr, mean_ptr, rstd_ptr, w_ptr, b_ptr, y_ptr, M, N: tl.constexpr, BM: tl.constexpr, BK: tl.constexpr):
+ """Debug/verification: materialise the GEMM prologue's normalised A (same _ln_normalize helper)."""
+ pid = tl.program_id(0)
+ rows = pid * BM + tl.arange(0, BM)
+ rk = tl.arange(0, BK)
+ mean = tl.load(mean_ptr + rows)
+ rstd = tl.load(rstd_ptr + rows)
+ ptrs = rows.to(tl.int64)[:, None] * N + rk[None, :]
+ for k0 in tl.static_range(0, N, BK):
+ xv = tl.load(x_ptr + ptrs + k0).to(tl.float32)
+ w = tl.load(w_ptr + k0 + rk).to(tl.float32)
+ bb = tl.load(b_ptr + k0 + rk).to(tl.float32)
+ tl.store(y_ptr + ptrs + k0, _ln_normalize(xv, mean, rstd, w, bb))
+
+
+# tiles of the stats kernel per N: (R rows per program, LANES, num_warps); same lane mapping as vae_ln_exact's lane
+# kernel (LANES=64 packs two row groups per 128-thread program for N=256).
+STATS_TILE = {256: (4, 64, 4), 512: (4, 128, 4), 1024: (4, 128, 4), 2048: (2, 128, 4), 4096: (1, 128, 4)}
+
+
+def ln_stats(x2: Tensor, eps: float, residual2: Tensor | None = None, broadcast: bool = False, tile=None):
+ """mean, rstd [M] fp32 of the exact LayerNorm of x2 [M, N] (or of x_new = bf16(x2 + residual2), which is
+ returned as third value)."""
+ M, N = x2.shape
+ assert x2.dtype == torch.bfloat16 and x2.is_contiguous() and N in STATS_TILE, (x2.dtype, N)
+ mean = torch.empty(M, dtype=torch.float32, device=x2.device)
+ rstd = torch.empty(M, dtype=torch.float32, device=x2.device)
+ fuse = residual2 is not None
+ if fuse:
+ assert residual2.dtype == torch.bfloat16 and residual2.is_contiguous()
+ xo = torch.empty_like(x2)
+ else:
+ xo = mean
+ residual2 = x2
+ R, lanes, nw = STATS_TILE[N] if tile is None else tile
+ nj = N // 4 // lanes
+ pow2 = (nj & (nj - 1)) == 0
+ grid = (triton.cdiv(M, R),)
+ _ln_stats_kernel[grid](x2, residual2, mean, rstd, xo, M, float(eps), float(N), N=N, R=R, LANES=lanes,
+ FUSE_RESIDUAL=fuse, RES_BROADCAST=bool(broadcast), EVEN_M=(M % R == 0),
+ OFF64=(M * N >= 2 ** 31), POW2=pow2, num_warps=nw, enable_fp_fusion=False)
+ return mean, rstd, (xo if fuse else None)
+
+
+def ln_apply(x2: Tensor, mean: Tensor, rstd: Tensor, weight: Tensor, bias: Tensor) -> Tensor:
+ M, N = x2.shape
+ assert M % 64 == 0
+ y = torch.empty_like(x2)
+ _ln_apply_kernel[(M // 64,)](x2, mean, rstd, weight, bias, y, M, N=N, BM=64, BK=min(N, 256), num_warps=4,
+ enable_fp_fusion=False)
+ return y
+
+
+# =============================================================================================== host wrappers
+def _cfg(table, K, cfg):
+ if cfg is not None:
+ return cfg
+ return table.get(K, DEFAULT_CFG)
+
+
+def prep_glu_weight(w: Tensor, tile: int, bias: Tensor | None = None):
+ """Pair-interleave the fc1 weight [2H, K] (rows 0..H-1 = gate, H..2H-1 = up): row 2j = gate j, row 2j+1 = up j,
+ zero-padded to a multiple of ``tile`` column pairs, so that the accumulator tile [BM, 2*tile] holds (gate, up)
+ of output column j in adjacent columns. Same for the bias. Done once per weight (frozen encoder)."""
+ H = w.shape[0] // 2
+ Hp = triton.cdiv(H, tile) * tile
+ g = F.pad(w[:H], (0, 0, 0, Hp - H))
+ u = F.pad(w[H:], (0, 0, 0, Hp - H))
+ wp = torch.stack([g, u], 1).reshape(2 * Hp, w.shape[1]).contiguous()
+ bp = None
+ if bias is not None:
+ bp = torch.stack([F.pad(bias[:H], (0, Hp - H)), F.pad(bias[H:], (0, Hp - H))], 1).reshape(-1).contiguous()
+ return wp, bp
+
+
+def _launch_gemm(a, w, out, bias, x, epilogue, cfg, ws=True, flatten=True, group=GROUP_M, fast_div=True):
+ M, K = a.shape
+ N = w.shape[0]
+ BM, BN, BK, nw, ns = cfg
+ a_desc = TensorDescriptor.from_tensor(a, [BM, BK])
+ b_desc = TensorDescriptor.from_tensor(w, [BN, BK])
+ c_desc = TensorDescriptor.from_tensor(out, [BM, BN // 2 if epilogue == 1 else BN])
+ x_desc = TensorDescriptor.from_tensor(x, [BM, BN]) if x is not None else c_desc
+ grid = (min(NUM_SMS, triton.cdiv(M, BM) * triton.cdiv(N, BN)),)
+ return _gemm_kernel[grid](a_desc, b_desc, c_desc, x_desc, bias if bias is not None else out, M, N, K,
+ BM=BM, BN=BN, BK=BK, GROUP_SIZE_M=group, NUM_SMS=NUM_SMS, EPILOGUE=epilogue,
+ HAS_BIAS=bias is not None, WARP_SPECIALIZE=ws, FLATTEN=flatten, FAST_DIV=fast_div,
+ num_warps=nw, num_stages=ns, enable_fp_fusion=False)
+
+
+def _check(a, w, bias):
+ assert a.dtype == torch.bfloat16 and w.dtype == torch.bfloat16 and a.is_contiguous() and w.is_contiguous()
+ assert a.dim() == 2 and w.dim() == 2 and a.shape[1] == w.shape[1]
+ assert a.data_ptr() % 16 == 0 and w.data_ptr() % 16 == 0 and a.shape[1] % 8 == 0
+ if bias is not None:
+ assert bias.dtype == torch.bfloat16 and bias.is_contiguous() and bias.shape == (w.shape[0],)
+
+
+def linear(a: Tensor, w: Tensor, bias: Tensor | None = None, *, cfg=None, out: Tensor | None = None, **kw) -> Tensor:
+ """bf16 F.linear(a, w, bias) with the Triton GEMM (plain epilogue)."""
+ _check(a, w, bias)
+ M, K = a.shape
+ N = w.shape[0]
+ if out is None:
+ out = torch.empty(M, N, dtype=torch.bfloat16, device=a.device)
+ _launch_gemm(a, w, out, bias, None, 0, _cfg(PLAIN_CFG, K, cfg), **kw)
+ return out
+
+
+def fc1_glu(a: Tensor, w: Tensor, bias: Tensor | None = None, *, cfg=None, prepped=None, **kw) -> Tensor:
+ """glu_bf16(F.linear(a, w, bias)) in one kernel: a [M, K], w [2H, K] -> [M, H]. ``prepped`` = cached
+ prep_glu_weight(w, BN // 2, bias) for this cfg (the install caches it per module)."""
+ _check(a, w, bias)
+ M, K = a.shape
+ H = w.shape[0] // 2
+ assert 2 * H == w.shape[0] and H % 8 == 0
+ cfg = _cfg(GLU_CFG, K, cfg)
+ wp, bp = prepped if prepped is not None else prep_glu_weight(w, cfg[1] // 2, bias)
+ out = torch.empty(M, H, dtype=torch.bfloat16, device=a.device)
+ _launch_gemm(a, wp, out, bp, None, 1, cfg, **kw)
+ return out
+
+
+def linear_residual(a: Tensor, w: Tensor, x: Tensor, bias: Tensor | None = None, *, cfg=None, **kw) -> Tensor:
+ """bf16(x + F.linear(a, w, bias)) in one kernel (x [M, N] bf16 contiguous)."""
+ _check(a, w, bias)
+ M, K = a.shape
+ N = w.shape[0]
+ assert x.shape == (M, N) and x.dtype == torch.bfloat16 and x.is_contiguous()
+ out = torch.empty(M, N, dtype=torch.bfloat16, device=a.device)
+ _launch_gemm(a, w, out, bias, x, 2, cfg if cfg is not None else RES_CFG.get(K, RES_DEFAULT_CFG), **kw)
+ return out
+
+
+def ln_linear(x: Tensor, mean: Tensor, rstd: Tensor, gamma: Tensor, beta: Tensor, w: Tensor, bias: Tensor | None = None,
+ *, glu: bool = False, cfg=None, prepped=None, ws=False, flatten=False, group=GROUP_M, fast_div=True) -> Tensor:
+ """GEMM over the exact-LN-normalised rows of x (statistics from ln_stats): F.linear(LN(x), w, bias), or the GLU
+ of it when ``glu`` (w = fc1 weight, interleaved on the fly or via ``prepped``). Requires M % BM == 0 and
+ K % BK == 0 (true for every production shape). ws=False by default: Triton 3.6's automatic warp specialisation
+ miscompiles the register-operand A dot (wrong results even for an identity normalisation; see results.md)."""
+ _check(x, w, bias)
+ M, K = x.shape
+ cfg = cfg if cfg is not None else LN_CFG.get(K, LN_DEFAULT_CFG)
+ BM, BN, BK, nw, ns = cfg
+ assert M % BM == 0 and K % BK == 0, (M, K, BM, BK)
+ assert gamma.dtype == torch.bfloat16 and beta.dtype == torch.bfloat16 and gamma.numel() == K and beta.numel() == K
+ assert mean.dtype == torch.float32 and rstd.dtype == torch.float32 and mean.numel() == M and rstd.numel() == M
+ if glu:
+ H = w.shape[0] // 2
+ assert 2 * H == w.shape[0]
+ w, bias = prepped if prepped is not None else prep_glu_weight(w, BN // 2, bias)
+ out = torch.empty(M, H, dtype=torch.bfloat16, device=x.device)
+ c_desc = TensorDescriptor.from_tensor(out, [BM, BN // 2])
+ else:
+ out = torch.empty(M, w.shape[0], dtype=torch.bfloat16, device=x.device)
+ c_desc = TensorDescriptor.from_tensor(out, [BM, BN])
+ N = w.shape[0]
+ b_desc = TensorDescriptor.from_tensor(w, [BN, BK])
+ grid = (min(NUM_SMS, (M // BM) * triton.cdiv(N, BN)),)
+ _ln_gemm_kernel[grid](x, mean, rstd, gamma, beta, b_desc, c_desc, bias if bias is not None else out, M, N, K,
+ BM=BM, BN=BN, BK=BK, GROUP_SIZE_M=group, NUM_SMS=NUM_SMS, EPILOGUE=1 if glu else 0,
+ HAS_BIAS=bias is not None, WARP_SPECIALIZE=ws, FLATTEN=flatten, FAST_DIV=fast_div, num_warps=nw,
+ num_stages=ns, enable_fp_fusion=False)
+ return out
+
+
+# =============================================================================================== references
+def ref_fc1_glu(a: Tensor, w: Tensor, bias: Tensor | None = None) -> Tensor:
+ """Production: cuBLAS fc1 (+ bias epilogue) then vae_fused_pointwise.glu_bf16."""
+ from flux_action.models.vae_fused_pointwise import glu_bf16
+ return glu_bf16(F.linear(a, w, bias))
+
+
+def compare(a: Tensor, b: Tensor) -> dict:
+ af, bf = a.float(), b.float()
+ diff = (af - bf).abs()
+ neq = a.contiguous().view(torch.int16) != b.contiguous().view(torch.int16)
+ ulp = (a.contiguous().view(torch.int16).int() - b.contiguous().view(torch.int16).int()).abs().max().item()
+ return {"max_abs": diff.max().item(), "rel_l2": (diff.norm() / bf.norm().clamp_min(1e-30)).item(),
+ "bitwise": 1.0 - neq.float().mean().item(), "n_differ": int(neq.sum().item()), "max_ulp": ulp}
+
+
+# =============================================================================================== install
+# Production encoder GEMM shapes: (M, C) per stage with H = GLU hidden.
+STAGE_SHAPES = [(540672, 256), (135168, 512), (33792, 1024), (8448, 2048), (4352, 2048)]
+
+
+def glu_hidden(dim: int, align_to: int = 64) -> int:
+ return align_to * ((int(dim * 8 / 3) + align_to - 1) // align_to)
+
+
+@dataclass
+class Installed:
+ state: object
+ patched: list = field(default_factory=list)
+ mlp_modules: list = field(default_factory=list)
+ options: dict = field(default_factory=dict)
+ calls: dict = field(default_factory=dict)
+ prepped: dict = field(default_factory=dict) # module name -> (weight, data_ptr, BN, (interleaved w, bias))
+
+ def info(self) -> dict:
+ return {"installed": True, "options": dict(self.options), "mlp_fused": len(self.mlp_modules), "calls": dict(self.calls)}
+
+
+def install(vae_module, state, *, glu_dims=(256, 512, 1024, 2048), fc2_residual: bool = False,
+ ln_prologue_dims=(), require_kernel: bool = False, cfg_override: dict | None = None) -> Installed:
+ """Patch ``forward`` of every encoder GLU_MLP whose ``dim`` is in ``glu_dims`` to run ``fc1_glu`` (fused fc1 +
+ GLU) followed by cuBLAS ``down_proj``; other dims keep the production path. Active only inside
+ ``training_fused_context(state)`` with bf16 CUDA no-grad inputs; outside the context the stock
+ ``GLU_MLP.forward`` runs (``require_kernel`` raises only when the context is active and the contract fails).
+ ``ln_prologue_dims``: additionally replace
+ the block's norm2 -> fc1 -> GLU by ln_stats + ln_linear(glu=True) for those dims (requires the
+ vae_fused_pointwise residual_ln state: the block's residual+LN2 kernel becomes residual-stats)."""
+ from flux_action.models import video_vae as vv
+
+ module = getattr(vae_module, "module", vae_module)
+ encoder = module.model.encoder
+ inst = Installed(state=state, options=dict(glu_dims=tuple(glu_dims), fc2_residual=fc2_residual,
+ ln_prologue_dims=tuple(ln_prologue_dims), require_kernel=require_kernel))
+ cfg_override = cfg_override or {}
+
+ def patch(mod, name, fn):
+ inst.patched.append((mod, name, mod.__dict__.get(name)))
+ setattr(mod, name, types.MethodType(fn, mod))
+
+ for name, mlp in encoder.named_modules():
+ if type(mlp) is not vv.GLU_MLP:
+ continue
+ dim = mlp.gate_up_proj.in_features
+ if dim not in glu_dims and dim not in ln_prologue_dims:
+ continue
+ assert mlp.gate_up_proj.bias is None and mlp.down_proj.bias is None
+ key = f"mlp{dim}"
+ inst.calls[key] = 0
+
+ def mlp_forward(self, x, _inst=inst, _key=key, _name=name, _cfg=cfg_override.get(dim), _rk=require_kernel):
+ st = _inst.state
+ if not st.enabled:
+ # outside training_fused_context (inference encodes, policy.eval(), from_pretrained): stock eager
+ # path like the other frozen-VAE adapters (vae_qk_fused / vae_merge_glue)
+ return vv.GLU_MLP.forward(self, x)
+ if not (type(x) is Tensor and x.dtype == torch.bfloat16 and x.is_cuda
+ and not torch.is_grad_enabled() and x.shape[-1] % 8 == 0):
+ if _rk:
+ raise RuntimeError("fused fc1+GLU contract not satisfied")
+ return vv.GLU_MLP.forward(self, x)
+ x2 = x.reshape(-1, x.shape[-1])
+ if not x2.is_contiguous():
+ x2 = x2.contiguous()
+ _inst.calls[_key] += 1
+ cfg = _cfg if _cfg is not None else GLU_CFG.get(x2.shape[1], DEFAULT_CFG)
+ w = self.gate_up_proj.weight
+ entry = _inst.prepped.get(_name)
+ if entry is None or entry[0] is not w or entry[1] != w.data_ptr() or entry[2] != cfg[1]:
+ # once per frozen weight of this install; the entry keeps the weight it was built from so a new
+ # tensor at a recycled address (or swapped .data) can never pick up a stale interleaved copy
+ entry = _inst.prepped[_name] = (w, w.data_ptr(), cfg[1], prep_glu_weight(w.detach(), cfg[1] // 2, None))
+ y = fc1_glu(x2, w, None, cfg=cfg, prepped=entry[3])
+ return self.down_proj(y).view(*x.shape[:-1], -1)
+
+ patch(mlp, "forward", mlp_forward)
+ inst.mlp_modules.append(name)
+ return inst
+
+
+def uninstall(inst: Installed) -> None:
+ for mod, name, prev in reversed(inst.patched):
+ if prev is None:
+ mod.__dict__.pop(name, None)
+ else:
+ setattr(mod, name, prev)
+ inst.patched.clear()
+ inst.prepped.clear()
+
+
+# =============================================================================================== self-test
+@triton.jit
+def _div_check_kernel(out_ref, out_fast, BLOCK: tl.constexpr):
+ idx = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
+ g = idx.to(tl.int16).to(tl.bfloat16, bitcast=True).to(tl.float32)
+ one = tl.zeros_like(g) + 1.0
+ d = one + libdevice.exp(-g)
+ tl.store(out_ref + idx, libdevice.div_rn(g, d).to(tl.bfloat16).to(tl.float32))
+ tl.store(out_fast + idx, _silu_div_exact(g, d).to(tl.bfloat16).to(tl.float32))
+
+
+def check_silu_division_exhaustive() -> dict:
+ """bf16(silu(g)) via _silu_div_exact vs via div.rn for ALL 65536 bf16 g (the complete input domain)."""
+ ref = torch.empty(65536, device="cuda")
+ fast = torch.empty(65536, device="cuda")
+ _div_check_kernel[(64,)](ref, fast, BLOCK=1024, num_warps=4, enable_fp_fusion=False)
+ torch.cuda.synchronize()
+ same = (ref.view(torch.int32) == fast.view(torch.int32)) | (torch.isnan(ref) & torch.isnan(fast))
+ g = torch.arange(65536, device="cuda", dtype=torch.int32).to(torch.int16).view(torch.bfloat16).float()
+ bad = (~same) & ~torch.isnan(g)
+ return {"n_non_nan_inputs": int((~torch.isnan(g)).sum()), "n_mismatch": int(bad.sum()),
+ "mismatch_g": g[bad.nonzero().flatten()[:16]].tolist(), "nan_inputs_both_nan": bool(same[torch.isnan(g)].all())}
+
+
+@torch.inference_mode()
+def selftest(verbose: bool = True, shapes=STAGE_SHAPES, cfgs=(DEFAULT_CFG,)) -> dict:
+ """Numerics of every kernel vs the production chain at the stage shapes (random data, nn.Linear-like scale)."""
+ from flux_action.models.vae_fused_pointwise import glu_bf16
+ from flux_action.models.vae_ln_exact import layer_norm_bf16, residual_layer_norm_bf16
+ torch.manual_seed(0)
+ res = {"silu_division_exhaustive": check_silu_division_exhaustive()}
+ ok_exact = res["silu_division_exhaustive"]["n_mismatch"] == 0
+ if verbose:
+ print("silu division exhaustive:", res["silu_division_exhaustive"], flush=True)
+ for M, C in shapes:
+ H = glu_hidden(C)
+ a = (torch.randn(M, C, device="cuda") * 1.5).bfloat16()
+ w1 = (torch.randn(2 * H, C, device="cuda") / C ** 0.5).bfloat16()
+ w2 = (torch.randn(C, H, device="cuda") / H ** 0.5).bfloat16()
+ wq = (torch.randn(3 * C, C, device="cuda") / C ** 0.5).bfloat16()
+ bq = (torch.randn(3 * C, device="cuda") * 0.1).bfloat16()
+ gu = F.linear(a, w1)
+ ref_glu = glu_bf16(gu)
+ rec = {"glu_fast_kernel": compare(glu_bf16_fast(gu), ref_glu)}
+ # adversarial GLU inputs: huge / tiny / zero / inf gates (the division's special cases) through the fused path
+ for cfg in cfgs:
+ rec[f"fc1_glu_{cfg}"] = compare(fc1_glu(a, w1, cfg=cfg), ref_glu)
+ rec[f"fc1_glu_divrn_{cfg}"] = compare(fc1_glu(a, w1, cfg=cfg, fast_div=False), ref_glu)
+ rec[f"linear_{cfg}"] = compare(linear(a, wq, bq, cfg=cfg), F.linear(a, wq, bq))
+ big = (torch.randn(M, C, device="cuda") * 40).bfloat16() # gates up to ~ +-300: exp overflow, d = inf
+ rec[f"fc1_glu_bigscale_{cfg}"] = compare(fc1_glu(big, w1, cfg=cfg), glu_bf16(F.linear(big, w1)))
+ rec["fc2_residual"] = compare(linear_residual(ref_glu, w2, a), a + F.linear(ref_glu, w2))
+ # LN prologue: stats + apply == exact LN kernel (bitwise), GEMM over it vs cuBLAS over the LN output
+ ln = nn.LayerNorm(C, eps=1e-5).cuda().bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ xln = (torch.randn(M, C, device="cuda") * 2 + 0.5).bfloat16()
+ h_ref = layer_norm_bf16(xln, ln.weight, ln.bias, ln.eps)
+ mean, rstd, _ = ln_stats(xln, ln.eps)
+ rec["ln_apply_vs_exact_ln"] = compare(ln_apply(xln, mean, rstd, ln.weight, ln.bias), h_ref)
+ rec["ln_qkv_vs_cublas"] = compare(ln_linear(xln, mean, rstd, ln.weight, ln.bias, wq, bq), F.linear(h_ref, wq, bq))
+ rec["ln_fc1_glu_vs_prod"] = compare(ln_linear(xln, mean, rstd, ln.weight, ln.bias, w1, glu=True), ref_fc1_glu(h_ref, w1))
+ d = (torch.randn(M, C, device="cuda") * 0.5).bfloat16()
+ xo_ref, h2_ref = residual_layer_norm_bf16(xln, d, ln.weight, ln.bias, ln.eps)
+ mean, rstd, xo = ln_stats(xln, ln.eps, residual2=d)
+ rec["res_stats_x_new"] = compare(xo, xo_ref)
+ rec["res_stats_apply_vs_exact"] = compare(ln_apply(xo, mean, rstd, ln.weight, ln.bias), h2_ref)
+ res[f"{M}x{C}"] = rec
+ ok_exact = ok_exact and all(v["bitwise"] == 1.0 for v in rec.values())
+ if verbose:
+ print(f"{M}x{C}", {k: (round(v["bitwise"], 7), v["max_ulp"]) for k, v in rec.items()}, flush=True)
+ res["all_bit_exact"] = ok_exact
+ if verbose:
+ print("ALL BIT-EXACT:", ok_exact)
+ return res
+
+
+if __name__ == "__main__":
+ selftest()
diff --git a/flux-umi/src/flux_action/models/vae_fused_pointwise.py b/flux-umi/src/flux_action/models/vae_fused_pointwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb841cbff460b152aa6981fd63bea6d1560cae49
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_fused_pointwise.py
@@ -0,0 +1,611 @@
+"""Hand-fused forward-only Triton replacements for the frozen VAE encoder's memory-bound pointwise work.
+
+Opt-in through ``PolicyConfig.vae_fused_pointwise``. ``install_training_fused(video_vae)`` patches ``forward`` on the
+encoder module *instances*; the fused kernels only run while ``training_fused_context(state)`` is active (the policy
+enters it around the training window encode, next to the other frozen-VAE adapters), so inference, the decoder and
+any other caller keep the stock eager path. Every replacement was verified bit-exact against eager at the production
+shapes.
+
+Replacements (all bf16 in / bf16 out, fp32 math, bf16 rounding at exactly the places eager rounds):
+
+(a) LayerNorm: eager under autocast = bf16->fp32 copy of x (+ weight + bias casts every call), fp32
+ ``vectorized_layer_norm_kernel`` (one row per 128-thread block, per-thread sequential Welford over
+ 4-element vectors ``i = thr + 128*j``, shuffle-down tree, smem inter-warp tree, ``rsqrtf(sigma2/N+eps)``,
+ ``fma(gamma, rstd*(x-mean), beta)``), then an fp32->bf16 copy at the next Linear. The Triton kernel
+ replicates that arithmetic order (explicit fma / div.rn / hardware rsqrt, contraction disabled) and writes
+ bf16 directly.
+(b) GLU: ``silu(gate) * up`` reading the two halves of the gate_up GEMM output directly; silu uses libdevice
+ expf and IEEE div.rn exactly like ATen's silu_kernel; silu is rounded to bf16 before the fp32 multiply
+ like eager.
+(c) PatchEmbed3d: ``channels_last_3d`` conv (output already NDHWC) or an unfold+GEMM equivalent.
+(d) Residual add fused with the following LayerNorm (one kernel writes x_new = bf16(x + delta) and LN(x_new)).
+(e) (extra, bit-exact) cache of the RoPE cos/sin tables per shape (eager rebuilds them on every call).
+"""
+from __future__ import annotations
+
+import math
+import types
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+
+NUM_WARPS = 4 # 128 threads per program, like ATen's vectorized LN block
+LN_ROWS_PER_PROGRAM = {256: 4, 512: 4, 1024: 2, 2048: 2, 4096: 1, 8192: 1}
+
+
+# ------------------------------------------------------------------------------------------- LayerNorm
+@triton.jit
+def _welford_online(mean, m2, cnt, val, valid):
+ # ATen cuWelfordOnlineSum (nvcc contracts both mul+add pairs into FMAs; 1.f/x is rcp.rn == div.rn(1, x)).
+ delta = val - mean
+ new_cnt = cnt + 1.0
+ one = tl.zeros_like(new_cnt) + 1.0
+ new_mean = libdevice.fma(delta, libdevice.div_rn(one, new_cnt), mean)
+ new_m2 = libdevice.fma(delta, val - new_mean, m2)
+ return (tl.where(valid, new_mean, mean), tl.where(valid, new_m2, m2), tl.where(valid, new_cnt, cnt))
+
+
+@triton.jit
+def _welford_combine_v0(mean_a, m2_a, cnt_a, mean_b, m2_b, cnt_b):
+ # a = accumulator (lower lane / ATen dataB = own), b = shuffled partner (ATen dataA).
+ delta = mean_a - mean_b
+ count = cnt_b + cnt_a
+ one = tl.zeros_like(count) + 1.0
+ coef = libdevice.div_rn(one, count)
+ n_a = cnt_b * coef
+ n_b = cnt_a * coef
+ mean = libdevice.fma(n_a, mean_b, n_b * mean_a)
+ sig = libdevice.fma((delta * delta) * cnt_b, n_b, m2_b + m2_a)
+ pos = count > 0
+ return tl.where(pos, mean, 0.0), tl.where(pos, sig, 0.0), count
+
+
+@triton.jit
+def _welford_combine_v1(mean_a, m2_a, cnt_a, mean_b, m2_b, cnt_b):
+ delta = mean_a - mean_b
+ count = cnt_b + cnt_a
+ one = tl.zeros_like(count) + 1.0
+ coef = libdevice.div_rn(one, count)
+ n_a = cnt_b * coef
+ n_b = cnt_a * coef
+ mean = libdevice.fma(n_b, mean_a, n_a * mean_b)
+ sig = libdevice.fma((delta * delta) * cnt_b, n_b, m2_b + m2_a)
+ pos = count > 0
+ return tl.where(pos, mean, 0.0), tl.where(pos, sig, 0.0), count
+
+
+@triton.jit
+def _welford_combine_v2(mean_a, m2_a, cnt_a, mean_b, m2_b, cnt_b):
+ delta = mean_a - mean_b
+ count = cnt_b + cnt_a
+ one = tl.zeros_like(count) + 1.0
+ coef = libdevice.div_rn(one, count)
+ n_a = cnt_b * coef
+ n_b = cnt_a * coef
+ mean = n_a * mean_b + n_b * mean_a
+ sig = (m2_b + m2_a) + ((delta * delta) * cnt_b) * n_b
+ pos = count > 0
+ return tl.where(pos, mean, 0.0), tl.where(pos, sig, 0.0), count
+
+
+@triton.jit
+def _ln_rows_kernel(x_ptr, res_ptr, w_ptr, b_ptr, y_ptr, xo_ptr, M, eps, n_float,
+ N: tl.constexpr, ROWS: tl.constexpr, LANES: tl.constexpr, FUSE_RESIDUAL: tl.constexpr,
+ RES_BROADCAST: tl.constexpr, VARIANT: tl.constexpr):
+ """One 128-thread program == one ATen vectorized_layer_norm block; ROWS rows processed sequentially.
+ LANES=128: one row per tile (ATen thread thr owns 4-element vectors thr + 128*j).
+ LANES=64 (only N=256, where ATen has 64 active lanes): two rows per tile, lanes 0-63 / 64-127, each
+ reduced over its own [64]-lane tree (ATen's zero-count warps 2,3 merge as exact identities)."""
+ NV: tl.constexpr = N // 4
+ NJ: tl.constexpr = (NV + LANES - 1) // LANES
+ RPT: tl.constexpr = 128 // LANES # rows per tile
+ t = tl.arange(0, 128)
+ cols4 = tl.arange(0, 4)
+ pid = tl.program_id(0)
+ for r in range(ROWS):
+ row = (pid * ROWS + r) * RPT + t // LANES # [128] row of each lane
+ lane = t % LANES
+ rvalid = row < M
+ base = row.to(tl.int64) * N
+ mean = tl.zeros([128], tl.float32)
+ m2 = tl.zeros([128], tl.float32)
+ cnt = tl.zeros([128], tl.float32)
+ for j in tl.static_range(NJ):
+ vec = lane + LANES * j
+ valid = (vec < NV) & rvalid
+ coffs = vec[:, None].to(tl.int64) * 4 + cols4[None, :]
+ offs = base[:, None] + coffs
+ m4 = valid[:, None] & (cols4[None, :] < 4)
+ xv = tl.load(x_ptr + offs, mask=m4, other=0.0).to(tl.float32)
+ if FUSE_RESIDUAL:
+ if RES_BROADCAST:
+ rv = tl.load(res_ptr + coffs, mask=m4, other=0.0).to(tl.float32)
+ else:
+ rv = tl.load(res_ptr + offs, mask=m4, other=0.0).to(tl.float32)
+ xb = (xv + rv).to(tl.bfloat16) # eager bf16 add: fp32 add, one RNE rounding
+ tl.store(xo_ptr + offs, xb, mask=m4)
+ xv = xb.to(tl.float32)
+ x3 = tl.reshape(xv, [128, 2, 2])
+ a, b = tl.split(x3) # a = cols (0, 2), b = cols (1, 3)
+ v0, v2 = tl.split(a)
+ v1, v3 = tl.split(b)
+ mean, m2, cnt = _welford_online(mean, m2, cnt, v0, valid)
+ mean, m2, cnt = _welford_online(mean, m2, cnt, v1, valid)
+ mean, m2, cnt = _welford_online(mean, m2, cnt, v2, valid)
+ mean, m2, cnt = _welford_online(mean, m2, cnt, v3, valid)
+ if RPT == 1:
+ if VARIANT == 0:
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _welford_combine_v0)
+ elif VARIANT == 1:
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _welford_combine_v1)
+ else:
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _welford_combine_v2)
+ var = libdevice.div_rn(m2_t, n_float)
+ rstd = tl.rsqrt(var + eps)
+ mean_l = tl.zeros([128], tl.float32) + mean_t
+ rstd_l = tl.zeros([128], tl.float32) + rstd
+ else:
+ mean2 = tl.reshape(mean, [RPT, LANES])
+ m22 = tl.reshape(m2, [RPT, LANES])
+ cnt2 = tl.reshape(cnt, [RPT, LANES])
+ if VARIANT == 0:
+ mean_t, m2_t, cnt_t = tl.reduce((mean2, m22, cnt2), 1, _welford_combine_v0)
+ elif VARIANT == 1:
+ mean_t, m2_t, cnt_t = tl.reduce((mean2, m22, cnt2), 1, _welford_combine_v1)
+ else:
+ mean_t, m2_t, cnt_t = tl.reduce((mean2, m22, cnt2), 1, _welford_combine_v2)
+ nf = tl.zeros([RPT], tl.float32) + n_float
+ var = libdevice.div_rn(m2_t, nf)
+ rstd = tl.rsqrt(var + eps) # [RPT]
+ mean_l = tl.reshape(tl.broadcast_to(mean_t[:, None], [RPT, LANES]), [128])
+ rstd_l = tl.reshape(tl.broadcast_to(rstd[:, None], [RPT, LANES]), [128])
+ for j in tl.static_range(NJ):
+ vec = lane + LANES * j
+ valid = (vec < NV) & rvalid
+ coffs = vec[:, None].to(tl.int64) * 4 + cols4[None, :]
+ offs = base[:, None] + coffs
+ m4 = valid[:, None] & (cols4[None, :] < 4)
+ if FUSE_RESIDUAL:
+ xv = tl.load(xo_ptr + offs, mask=m4, other=0.0).to(tl.float32)
+ else:
+ xv = tl.load(x_ptr + offs, mask=m4, other=0.0).to(tl.float32)
+ w = tl.load(w_ptr + coffs, mask=m4, other=0.0).to(tl.float32)
+ bb = tl.load(b_ptr + coffs, mask=m4, other=0.0).to(tl.float32)
+ y = libdevice.fma(w, rstd_l[:, None] * (xv - mean_l[:, None]), bb)
+ tl.store(y_ptr + offs, y.to(tl.bfloat16), mask=m4)
+
+
+_LN_VARIANT = 0
+# (ROWS sequential per program, LANES per row) per N; tuned on the L20D (SM103), see tune_ln.json.
+LN_TILE = {256: (4, 64), 512: (2, 128), 1024: (1, 128), 2048: (1, 128), 4096: (1, 128), 8192: (1, 128)}
+
+
+def set_ln_variant(v: int) -> None:
+ global _LN_VARIANT
+ _LN_VARIANT = int(v)
+
+
+class _FastLaunch:
+ """Cache Triton CompiledKernel objects per specialization and launch them directly (skips the JIT
+ binder/specialization path, ~25 us -> ~6 us host per launch). The key reproduces Triton's int
+ specialization (==1, %16) and 16-byte pointer alignment."""
+
+ def __init__(self, jit_fn, num_warps_key):
+ self.fn = jit_fn
+ self.cache = {}
+ self.num_warps_key = num_warps_key
+
+ def __call__(self, grid, *args, num_warps=4, **const):
+ key = [num_warps, tuple(sorted(const.items()))]
+ for a in args:
+ if isinstance(a, torch.Tensor):
+ key.append(a.data_ptr() % 16 == 0)
+ elif isinstance(a, int):
+ key.append((a == 1, a % 16 == 0))
+ else:
+ key.append(None)
+ key = tuple(key)
+ ck = self.cache.get(key)
+ g = (grid[0], 1, 1)
+ if ck is None:
+ ck = self.fn[g](*args, **const, num_warps=num_warps, enable_fp_fusion=False)
+ self.cache[key] = ck
+ return
+ ck[g](*args, *const.values()) # kernel.run takes all signature args (constexprs included) in order
+
+
+_ln_launch = _FastLaunch(_ln_rows_kernel, "num_warps")
+
+
+def _ln_rows(x2: Tensor, weight: Tensor, bias: Tensor, eps: float, residual2: Tensor | None, broadcast=False):
+ M, N = x2.shape
+ assert x2.dtype == torch.bfloat16 and x2.is_contiguous() and weight.dtype == torch.bfloat16
+ assert N % 4 == 0 and N in LN_TILE, N
+ y = torch.empty_like(x2)
+ fuse = residual2 is not None
+ if fuse:
+ assert residual2.dtype == torch.bfloat16 and residual2.is_contiguous()
+ assert residual2.shape == ((N,) if broadcast else x2.shape)
+ xo = torch.empty_like(x2)
+ else:
+ xo = y
+ residual2 = x2
+ rows, lanes = LN_TILE[N]
+ grid = (triton.cdiv(M, rows * (128 // lanes)),)
+ _ln_launch(grid, x2, residual2, weight, bias, y, xo, M, float(eps), float(N),
+ N=N, ROWS=rows, LANES=lanes, FUSE_RESIDUAL=fuse, RES_BROADCAST=bool(broadcast),
+ VARIANT=_LN_VARIANT, num_warps=NUM_WARPS)
+ return y, (xo if fuse else None)
+
+
+def layer_norm_bf16(x: Tensor, weight: Tensor, bias: Tensor, eps: float = 1e-5) -> Tensor:
+ """bf16(LayerNorm_fp32(x)) in one kernel; x: (..., N) bf16."""
+ if x.stride(-1) != 1 or not x.is_contiguous():
+ x = x.contiguous()
+ y, _ = _ln_rows(x.view(-1, x.shape[-1]), weight, bias, eps, None)
+ return y.view(x.shape)
+
+
+def residual_layer_norm_bf16(x: Tensor, delta: Tensor, weight: Tensor, bias: Tensor, eps: float = 1e-5):
+ """x_new = bf16(x + delta); returns (x_new, bf16(LayerNorm_fp32(x_new))). ``delta`` may be a (N,) bias
+ broadcast over rows (eager: ``x.add_(bias)``)."""
+ if not x.is_contiguous():
+ x = x.contiguous()
+ if not delta.is_contiguous():
+ delta = delta.contiguous()
+ broadcast = delta.dim() == 1
+ y, xo = _ln_rows(x.view(-1, x.shape[-1]), weight, bias, eps,
+ delta if broadcast else delta.view(-1, x.shape[-1]), broadcast=broadcast)
+ return xo.view(x.shape), y.view(x.shape)
+
+
+# ------------------------------------------------------------------------------------------- GLU
+@triton.jit
+def _glu_kernel(gu_ptr, y_ptr, M, H: tl.constexpr, BLOCK: tl.constexpr):
+ pid = tl.program_id(0).to(tl.int64)
+ idx = pid * BLOCK + tl.arange(0, BLOCK).to(tl.int64)
+ # Mask on the i64 row index, never on ``M * H``: Triton evaluates that product in i32 and the mask wraps negative
+ # for M*H >= 2**31 (nothing stored, the torch.empty output returned as garbage); ``M.to(tl.int64)`` is not an
+ # option either because Triton specializes M == 1 as a Python int.
+ row = idx // H
+ mask = row < M
+ col = idx % H
+ src = row * (2 * H) + col
+ g = tl.load(gu_ptr + src, mask=mask, other=0.0).to(tl.float32)
+ u = tl.load(gu_ptr + src + H, mask=mask, other=0.0).to(tl.float32)
+ one = tl.zeros_like(g) + 1.0
+ s = libdevice.div_rn(g, one + libdevice.exp(-g)) # ATen silu_kernel: x / (1 + expf(-x)) in fp32
+ s = s.to(tl.bfloat16).to(tl.float32) # eager rounds silu(gate) to bf16
+ y = (s * u).to(tl.bfloat16) # MulFunctor then bf16 RNE
+ tl.store(y_ptr + idx, y, mask=mask)
+
+
+def glu_bf16(gate_up: Tensor) -> Tensor:
+ """silu(gate) * up with gate, up = gate_up.chunk(2, -1); gate_up: (..., 2H) bf16 contiguous."""
+ assert gate_up.dtype == torch.bfloat16 and gate_up.stride(-1) == 1
+ gu2 = gate_up.reshape(-1, gate_up.shape[-1])
+ if not gu2.is_contiguous():
+ gu2 = gu2.contiguous()
+ M, H2 = gu2.shape
+ H = H2 // 2
+ assert H % 16 == 0
+ # M is launched as an i32 scalar (the _FastLaunch key does not track Triton's i32/i64 int specialization);
+ # M*H itself may exceed 2**31 -- the kernel forms the mask in i64.
+ assert M < 2 ** 31, M
+ y = torch.empty((M, H), dtype=torch.bfloat16, device=gate_up.device)
+ BLOCK = 2048
+ grid = (triton.cdiv(M * H, BLOCK),)
+ _glu_launch(grid, gu2, y, M, H=H, BLOCK=BLOCK, num_warps=NUM_WARPS)
+ return y.view(*gate_up.shape[:-1], H)
+
+
+_glu_launch = _FastLaunch(_glu_kernel, "num_warps")
+
+
+# ------------------------------------------------------------------------------------------- PatchEmbed
+def patch_embed_channels_last(mod, x: Tensor) -> Tensor:
+ _, _, t, h, w = x.shape
+ ps = mod.tuple_patch_size
+ pad = [(ps[i] - (t, h, w)[i] % ps[i]) % ps[i] for i in range(3)]
+ if any(pad):
+ x = F.pad(x, (0, pad[2], 0, pad[1], 0, pad[0]))
+ weight = getattr(mod, "_cl_weight", None)
+ if weight is None or weight.device != x.device:
+ weight = mod.proj.weight.detach().to(memory_format=torch.channels_last_3d)
+ mod._cl_weight = weight
+ xcl = x.contiguous(memory_format=torch.channels_last_3d)
+ state = getattr(mod, "_fused_state", None)
+ if state is not None and state.options.get("defer_conv_bias") and state.enabled:
+ # eager: bf16 conv output, then output.add_(bias) (bf16 RNE); block 0's fused residual+LN1 kernel
+ # performs that identical add and writes the embedded tokens.
+ out = F.conv3d(xcl, weight, None, stride=ps)
+ state.pending_bias = mod.proj.bias.detach()
+ else:
+ out = F.conv3d(xcl, weight, mod.proj.bias, stride=ps)
+ out = out.permute(0, 2, 3, 4, 1) # contiguous NDHWC view of the channels_last output
+ return mod.norm(out)
+
+
+def patch_embed_unfold_gemm(mod, x: Tensor) -> Tensor:
+ b, c, t, h, w = x.shape
+ pt, ph, pw = mod.tuple_patch_size
+ pad = [(p - s % p) % p for s, p in zip((t, h, w), (pt, ph, pw))]
+ if any(pad):
+ x = F.pad(x, (0, pad[2], 0, pad[1], 0, pad[0]))
+ b, c, t, h, w = x.shape
+ patches = x.view(b, c, t // pt, pt, h // ph, ph, w // pw, pw).permute(0, 2, 4, 6, 1, 3, 5, 7)
+ patches = patches.reshape(b, t // pt, h // ph, w // pw, c * pt * ph * pw)
+ wmat = mod.proj.weight.detach().reshape(mod.proj.weight.shape[0], -1)
+ out = F.linear(patches, wmat, mod.proj.bias)
+ return mod.norm(out)
+
+
+# ------------------------------------------------------------------------------------------- install
+_ACTIVE = ContextVar("flux_action_vae_fused_pointwise", default=None)
+
+
+@contextmanager
+def training_fused_context(state):
+ """Activate the fused kernels of ``state`` (None = stock eager) for the enclosed frozen encode."""
+ token = _ACTIVE.set(state)
+ try:
+ yield
+ finally:
+ if state is not None:
+ state.pending_bias = None
+ _ACTIVE.reset(token)
+
+
+class FusedState:
+ def __init__(self):
+ self.installed = True
+ self.rope_cache: dict = {}
+ self.patched: list[tuple[nn.Module, str, object]] = []
+ self.options: dict = {}
+ self.pending_bias = None
+
+ @property
+ def enabled(self) -> bool:
+ return _ACTIVE.get() is self
+
+ @enabled.setter
+ def enabled(self, value): # the prototype toggled a flag; production scopes activation by context instead
+ raise AttributeError("use training_fused_context(state) to activate the fused kernels")
+
+
+def install(vae_module, *, layer_norm=True, glu=True, residual_ln=True, patch_embed="channels_last",
+ rope_cache=True, defer_conv_bias=True, qkv_split=False) -> FusedState:
+ """Monkeypatch forward on the encoder's module instances. ``vae_module``: VideoVAE wrapper or
+ ViTNormInference. The patched forwards use the fused kernels only inside ``training_fused_context(state)``."""
+ from flux_action.models import video_vae as vv
+
+ module = getattr(vae_module, "module", vae_module)
+ encoder = module.model.encoder
+ state = FusedState()
+ defer_conv_bias = bool(defer_conv_bias and residual_ln and patch_embed == "channels_last")
+ state.options = dict(layer_norm=layer_norm, glu=glu, residual_ln=residual_ln, patch_embed=patch_embed,
+ rope_cache=rope_cache, defer_conv_bias=defer_conv_bias, qkv_split=qkv_split)
+
+ def patch(mod, name, fn):
+ state.patched.append((mod, name, mod.__dict__.get(name)))
+ setattr(mod, name, types.MethodType(fn, mod))
+
+ if layer_norm:
+ for name, ln in encoder.named_modules():
+ if type(ln) is nn.LayerNorm:
+ assert ln.weight is not None and ln.bias is not None and ln.weight.dtype == torch.bfloat16
+ N = ln.normalized_shape[0]
+ assert N in LN_ROWS_PER_PROGRAM, (name, N)
+
+ def ln_forward(self, x, _state=state):
+ if _state.enabled and x.dtype == torch.bfloat16 and x.is_cuda and not torch.is_grad_enabled():
+ return layer_norm_bf16(x, self.weight, self.bias, self.eps)
+ return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
+
+ patch(ln, "forward", ln_forward)
+ if glu:
+ for name, mlp in encoder.named_modules():
+ if type(mlp) is vv.GLU_MLP:
+ def glu_forward(self, x, _state=state):
+ gu = self.gate_up_proj(x)
+ if _state.enabled and gu.dtype == torch.bfloat16 and gu.is_cuda and not torch.is_grad_enabled():
+ return self.down_proj(glu_bf16(gu))
+ gate, up = gu.chunk(2, dim=-1)
+ return self.down_proj(F.silu(gate) * up)
+
+ patch(mlp, "forward", glu_forward)
+ if residual_ln:
+ assert layer_norm, "residual_ln needs the LayerNorm replacement"
+ for name, blk in encoder.named_modules():
+ if type(blk) is vv.SwinTransformerBlock:
+ def forward_full(self, x, _state=state):
+ if _state.pending_bias is not None:
+ bias, _state.pending_bias = _state.pending_bias, None
+ x, h1 = residual_layer_norm_bf16(x, bias, self.norm1.weight, self.norm1.bias, self.norm1.eps)
+ a = self.attn(h1)
+ else:
+ a = self.attn(self.norm1(x))
+ if _state.enabled and x.dtype == torch.bfloat16 and a.dtype == torch.bfloat16 and x.is_cuda \
+ and not torch.is_grad_enabled() and x.shape == a.shape:
+ x, h = residual_layer_norm_bf16(x, a, self.norm2.weight, self.norm2.bias, self.norm2.eps)
+ else:
+ x = x + a
+ h = self.norm2(x)
+ return x + self.mlp(h)
+
+ patch(blk, "_forward_full", forward_full)
+ if patch_embed:
+ pe = encoder.patch_embed
+ assert type(pe) is vv.PatchEmbed3d
+ impl = {"channels_last": patch_embed_channels_last, "unfold_gemm": patch_embed_unfold_gemm}[patch_embed]
+
+ def pe_forward(self, x, _state=state, _impl=impl):
+ if _state.enabled and x.is_cuda and not torch.is_grad_enabled():
+ return _impl(self, x)
+ return vv.PatchEmbed3d.forward(self, x)
+
+ patch(pe, "forward", pe_forward)
+ pe._fused_state = state
+ if qkv_split:
+ for name, attn in encoder.named_modules():
+ if type(attn) is vv.Natten3D:
+ def _qkv(self, x, _state=state):
+ if not (_state.enabled and x.dtype == torch.bfloat16 and not torch.is_grad_enabled()):
+ return vv.Natten3D._qkv(self, x)
+ b, t, h, w, _ = x.shape
+ dim = self.num_heads * self.head_dim
+ ws = getattr(self, "_qkv_split_w", None)
+ if ws is None:
+ ws = (self.qkv.weight.detach().split(dim, 0), self.qkv.bias.detach().split(dim, 0))
+ self._qkv_split_w = ws
+ # three GEMMs instead of one: v comes out contiguous, saving NATTEN's v.contiguous() copy
+ q = F.linear(x, ws[0][0], ws[1][0]).view(b, t, h, w, self.num_heads, self.head_dim)
+ k = F.linear(x, ws[0][1], ws[1][1]).view(b, t, h, w, self.num_heads, self.head_dim)
+ v = F.linear(x, ws[0][2], ws[1][2]).view(b, t, h, w, self.num_heads, self.head_dim)
+ if self.qk_norm:
+ q = self.q_norm(q)
+ k = self.k_norm(k)
+ return q, k, v
+
+ patch(attn, "_qkv", _qkv)
+ if rope_cache:
+ for name, rope in encoder.named_modules():
+ if type(rope) is vv.RotaryPositionEmbedding3D:
+ def rope_forward(self, q, k, *, temporal_offset=0, _state=state):
+ if not _state.enabled or isinstance(temporal_offset, Tensor):
+ return vv.RotaryPositionEmbedding3D.forward(self, q, k, temporal_offset=temporal_offset)
+ _, t, h, w, _, _ = q.shape
+ key = (id(self), t, h, w, int(temporal_offset), q.dtype, q.device)
+ tables = _state.rope_cache.get(key)
+ if tables is None:
+ grids = torch.meshgrid(
+ torch.arange(t, device=q.device, dtype=torch.float32) + temporal_offset,
+ torch.arange(h, device=q.device, dtype=torch.float32),
+ torch.arange(w, device=q.device, dtype=torch.float32), indexing="ij")
+ pos = torch.stack(grids + (torch.zeros_like(grids[0]),), dim=-1)
+ freqs = torch.einsum("...a,af->...af", pos, self.inv_freq.float())
+ freqs = freqs.reshape(1, t, h, w, 1, -1)
+ freqs = torch.cat([freqs, freqs], dim=-1)
+ tables = (freqs.cos().to(q.dtype), freqs.sin().to(q.dtype))
+ _state.rope_cache[key] = tables
+ cos, sin = tables
+ from flux_action.models.vae_cute_rope import dispatch_training_rope
+ fused = dispatch_training_rope(self, q, k, cos, sin)
+ if fused is not None:
+ return fused
+ q = q * cos + self._rotate_half(q) * sin
+ k = k * cos + self._rotate_half(k) * sin
+ return q, k
+
+ patch(rope, "forward", rope_forward)
+ return state
+
+
+def uninstall(state: FusedState) -> None:
+ state.pending_bias = None
+ for mod, name, prev in reversed(state.patched):
+ if name == "forward" and hasattr(mod, "_fused_state"):
+ del mod._fused_state
+ if prev is None:
+ mod.__dict__.pop(name, None)
+ else:
+ setattr(mod, name, prev)
+ state.patched.clear()
+
+
+# ------------------------------------------------------------------------------------------- self-test
+def _compare(a: Tensor, b: Tensor) -> dict:
+ af, bf = a.float(), b.float()
+ diff = (af - bf).abs()
+ bitwise = ((a.view(torch.int16) == b.view(torch.int16)).sum().item() / a.numel()) if a.dtype == b.dtype else None
+ ulp = (a.view(torch.int16).int() - b.view(torch.int16).int()).abs().max().item() if a.dtype == torch.bfloat16 else None
+ return {"max_abs": diff.max().item(), "rel_l2": (diff.norm() / bf.norm().clamp_min(1e-30)).item(),
+ "bitwise_fraction": bitwise, "max_bf16_ulp": ulp}
+
+
+@torch.inference_mode()
+def selftest(device="cuda", verbose=True) -> dict:
+ """Exactness self-test of every kernel against the eager (autocast) reference at production shapes."""
+ torch.manual_seed(0)
+ results = {}
+ shapes = [(33 * 128 * 128, 256), (33 * 64 * 64, 512), (33 * 32 * 32, 1024), (33 * 16 * 16, 2048),
+ (17 * 16 * 16, 2048), (33 * 64 * 64, 1024), (33 * 32 * 32, 2048), (33 * 16 * 16, 4096),
+ (17 * 16 * 16, 4096), (9 * 16 * 16, 4096)]
+ for M, N in shapes:
+ ln = nn.LayerNorm(N, eps=1e-5).to(device).bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ x = (torch.randn(M, N, device=device) * 2 + 0.5).bfloat16()
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ ref = ln(x).to(torch.bfloat16)
+ out = layer_norm_bf16(x, ln.weight, ln.bias, ln.eps)
+ results[f"ln_{M}x{N}"] = _compare(out, ref)
+ d = (torch.randn(M, N, device=device) * 0.5).bfloat16()
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ xr = x + d
+ ref2 = ln(xr).to(torch.bfloat16)
+ xo, out2 = residual_layer_norm_bf16(x, d, ln.weight, ln.bias, ln.eps)
+ results[f"resln_{M}x{N}"] = {"x_new": _compare(xo, xr), "ln": _compare(out2, ref2)}
+ for M, H in [(33 * 128 * 128, 704), (33 * 64 * 64, 1408), (33 * 32 * 32, 2752), (33 * 16 * 16, 5504), (17 * 16 * 16, 5504)]:
+ gu = (torch.randn(M, 2 * H, device=device) * 3).bfloat16()
+ gate, up = gu.chunk(2, dim=-1)
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ ref = F.silu(gate) * up
+ out = glu_bf16(gu)
+ results[f"glu_{M}x{H}"] = _compare(out, ref)
+ # conv-bias broadcast residual (block 0): eager = conv_out.add_(bias) then LN1
+ M, N = 33 * 128 * 128, 256
+ ln = nn.LayerNorm(N, eps=1e-5).to(device).bfloat16()
+ x = (torch.randn(M, N, device=device) * 0.3).bfloat16()
+ bias = (torch.randn(N, device=device) * 0.1).bfloat16()
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ xr = x.clone()
+ xr.add_(bias)
+ ref = ln(xr).to(torch.bfloat16)
+ xo, out = residual_layer_norm_bf16(x, bias, ln.weight, ln.bias, ln.eps)
+ results["bias_resln_540672x256"] = {"x_new": _compare(xo, xr), "ln": _compare(out, ref)}
+ # qkv 3-GEMM split vs one GEMM (cuBLAS, bf16, fp32 accumulate)
+ for M, dim in [(33 * 128 * 128, 256), (33 * 64 * 64, 512), (33 * 32 * 32, 1024), (33 * 16 * 16, 2048)]:
+ lin = nn.Linear(dim, 3 * dim).to(device).bfloat16()
+ x = torch.randn(M, dim, device=device).bfloat16()
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ ref = lin(x)
+ parts = [F.linear(x, w, b) for w, b in zip(lin.weight.split(dim, 0), lin.bias.split(dim, 0))]
+ results[f"qkv_split_{M}x{dim}"] = _compare(torch.cat(parts, -1), ref)
+ ok = True
+ for k, v in results.items():
+ items = v.values() if "max_abs" not in v else [v]
+ for it in items:
+ ok = ok and it["bitwise_fraction"] == 1.0
+ if verbose:
+ print(k, v)
+ results["all_bit_exact"] = ok
+ if verbose:
+ print("ALL BIT-EXACT:", ok)
+ return results
+
+
+if __name__ == "__main__":
+ selftest()
+
+
+def install_training_fused(video_vae, *, compile_model=False):
+ """Policy entry point: patch the frozen encoder; returns ``(state, info)`` (``state`` None when unsupported)."""
+ vae = getattr(video_vae, "module", video_vae)
+ encoder = getattr(getattr(vae, "model", None), "encoder", None)
+ if compile_model or getattr(vae, "_encoder_compiled", False):
+ raise RuntimeError("vae_fused_pointwise is outside the validated path for a compiled VAE")
+ if not isinstance(encoder, nn.Module) or vae.training or any(p.requires_grad for p in vae.parameters()):
+ raise RuntimeError("vae_fused_pointwise needs the frozen eval-mode VAE encoder")
+ state = install(vae, layer_norm=True, glu=True, residual_ln=True, patch_embed="channels_last",
+ rope_cache=True, defer_conv_bias=True, qkv_split=False)
+ info = {"installed": True, "patched_modules": len(state.patched), "options": dict(state.options),
+ "scope": "frozen training encode inside training_fused_context only; bit-exact vs eager"}
+ return state, info
diff --git a/flux-umi/src/flux_action/models/vae_graphed.py b/flux-umi/src/flux_action/models/vae_graphed.py
new file mode 100644
index 0000000000000000000000000000000000000000..d86a8487a514f1462c4a2943e19b3e715de8517f
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_graphed.py
@@ -0,0 +1,99 @@
+"""CUDA-graph replay of the frozen training VAE encode (``PolicyConfig.vae_cuda_graph``).
+
+The eager encode of one window launches ~1000 kernels (~30 ms of host time per window, 4.7 s per step), while
+the GPU work itself is ~80 ms. The whole production call (``packing.encode_videos`` with the frozen-VAE adapters
+active, under bf16 autocast) is static in shape, so it is captured once per batch size into a
+``torch.cuda.CUDAGraph`` and replayed per window: ``static_input.copy_(canvas)`` (same fp32->bf16 rounding as
+``videos.to(bfloat16)``), ``graph.replay()``, ``static_output.clone()``. Replays are bit-identical to eager
+(verified on real windows, repeated replays, A-B-A inputs and replay from a non-default stream).
+
+Stream contract: replay is enqueued on the *current* stream, so inside the trainer's ``encode_stream`` it is
+ordered exactly like the eager call and the ``prepared.event`` recorded afterwards covers it. Never replay one
+graph concurrently from two streams. The graph owns a private memory pool holding every intermediate of one
+encode (~6 GB for one 33x512x512 window), kept for the lifetime of the wrapper.
+"""
+from __future__ import annotations
+
+import gc
+from collections.abc import Callable
+from typing import Any
+
+import torch
+
+
+class GraphedVAEEncoder:
+ def __init__(
+ self,
+ encode_fn: Callable[[torch.Tensor], torch.Tensor],
+ *,
+ example: torch.Tensor,
+ warmup: int = 3,
+ pool: Any = None,
+ capture_error_mode: str = "thread_local",
+ ) -> None:
+ # "thread_local": only this thread's CUDA calls can invalidate the capture. With "global" the DataLoader's
+ # pin-memory thread (cudaHostAlloc) or the prefetch thread racing with the first encode invalidated the capture
+ # on one rank (cudaErrorStreamCaptureInvalidated) in roughly half of the 8-rank starts.
+ if capture_error_mode not in ("global", "thread_local", "relaxed"):
+ raise ValueError("capture_error_mode must be global, thread_local or relaxed")
+ if warmup < 3:
+ raise ValueError("at least 3 eager warmups on the capture stream before capture")
+ self.encode_fn = encode_fn
+ self.device = example.device
+ self.input_shape = tuple(example.shape)
+ self.static_input = torch.empty(self.input_shape, dtype=torch.bfloat16, device=self.device)
+ self.static_input.copy_(example)
+ self.capture_stream = torch.cuda.Stream(self.device)
+ # Warm-ups on the capture stream: CuTe/Triton compilation, the NATTEN backend probe and the cuBLAS/cuDNN
+ # heuristic caches must all be resolved before capture.
+ self.capture_stream.wait_stream(torch.cuda.current_stream(self.device))
+ with torch.cuda.stream(self.capture_stream):
+ for _ in range(warmup):
+ out = self.encode_fn(self.static_input)
+ torch.cuda.current_stream(self.device).wait_stream(self.capture_stream)
+ torch.cuda.synchronize(self.device)
+ self.output_shape, self.output_dtype = tuple(out.shape), out.dtype
+ del out
+ gc.collect()
+ self.graph = torch.cuda.CUDAGraph()
+ reserved_before = torch.cuda.memory_reserved(self.device)
+ with torch.cuda.graph(self.graph, pool=pool, stream=self.capture_stream, capture_error_mode=capture_error_mode):
+ self.static_output = self.encode_fn(self.static_input)
+ torch.cuda.synchronize(self.device)
+ self.reserved_delta_bytes = torch.cuda.memory_reserved(self.device) - reserved_before
+ if tuple(self.static_output.shape) != self.output_shape:
+ raise RuntimeError(f"captured output {tuple(self.static_output.shape)} != eager {self.output_shape}")
+ self.replays = 0
+
+ @torch.no_grad()
+ def encode(self, canvas: torch.Tensor) -> torch.Tensor:
+ if tuple(canvas.shape) != self.input_shape:
+ raise ValueError(f"graph captured for {self.input_shape}, got {tuple(canvas.shape)}")
+ self.static_input.copy_(canvas)
+ self.graph.replay()
+ self.replays += 1
+ return self.static_output.clone()
+
+
+class GraphedVAEEncoderBank:
+ """One graph per distinct canvas shape (production has one; a rarer shape falls back to eager after
+ ``max_graphs`` captures, with identical numerics)."""
+
+ def __init__(self, encode_fn, *, max_graphs: int = 2, **kwargs) -> None:
+ self.encode_fn, self.kwargs, self.max_graphs = encode_fn, kwargs, max_graphs
+ self.graphs: dict[tuple, GraphedVAEEncoder] = {}
+ self.eager_calls = 0
+
+ def encode(self, canvas: torch.Tensor) -> torch.Tensor:
+ key = tuple(canvas.shape)
+ enc = self.graphs.get(key)
+ if enc is None:
+ if len(self.graphs) >= self.max_graphs:
+ self.eager_calls += 1
+ return self.encode_fn(canvas)
+ enc = self.graphs[key] = GraphedVAEEncoder(self.encode_fn, example=canvas, **self.kwargs)
+ return enc.encode(canvas)
+
+ def info(self) -> dict:
+ return {"graphs": {str(k): {"replays": g.replays, "reserved_delta_mb": g.reserved_delta_bytes / 2**20}
+ for k, g in self.graphs.items()}, "eager_calls": self.eager_calls}
diff --git a/flux-umi/src/flux_action/models/vae_ln_exact.py b/flux-umi/src/flux_action/models/vae_ln_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a28238b7d97694f50861224ac8399e7b147c996
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_ln_exact.py
@@ -0,0 +1,682 @@
+"""Fast bit-exact bf16 LayerNorm for the frozen VAE encoder (experiment vae-ln-exact-fast, GPU 0).
+
+Drop-in replacement for ``layer_norm_bf16`` / ``residual_layer_norm_bf16`` of
+``flux_action.models.vae_fused_pointwise`` (same signatures, same bit-exact semantics: the bf16 output equals
+eager autocast ``bf16(LayerNorm_fp32(x))``, i.e. ATen's ``vectorized_layer_norm_kernel`` followed by
+the bf16 cast of the consumer; ``residual_layer_norm_bf16`` also writes ``x_new = bf16(x + delta)`` with ``delta``
+a full tensor or the broadcast (N,) deferred conv bias). ``install()`` swaps the two functions inside
+``vae_fused_pointwise`` (they are looked up by name at call time by the patched encoder forwards), so the production
+adapters (``install_training_fused`` / ``training_fused_context``) pick them up without edits; for production the
+orchestrator can instead paste the kernels into ``vae_fused_pointwise.py`` and point ``_ln_rows`` at them.
+
+What changed versus the production kernel (``_ln_rows_kernel``, 1.3-2.1 TB/s, instruction-bound), all verified
+bitwise at the 10 production shapes (plus odd row counts and the int64-offset path) and on the whole VAE encoder
+with the real weights (latents bitwise identical):
+
+* the per-element ``div_rn(1, n+1)`` of ATen's ``cuWelfordOnlineSum`` is a compile-time constant (every lane sees the
+ same count sequence 1..4*NJ; ``fp32(1/n) == div.rn.f32(1, n)`` checked for n <= 4096 in ``probe_consts.py``);
+* ATen's ``cuWelfordCombine`` is evaluated on the count-scaled second moment ``sigma2 / count``: in the balanced
+ shuffle/smem tree both partners of a level carry the same power-of-two count ``c``, so ``coef = 1/(2c)`` and
+ ``nA = nB = c*coef = 0.5`` exactly, and the recurrence divided by ``2c`` only rescales intermediates by powers
+ of two (which commutes with fp32 rounding). Each level is therefore the level-independent, bitwise-commutative
+ ``mean = fma(.5, mean_b, .5*mean_a); m2s = fma(d*d, .25, .5*(m2s_a + m2s_b))`` -- no division, no count
+ operand (2 shuffles per level instead of 3), no ``count > 0`` selects -- and ATen's final ``sigma2 / N`` is the
+ reduced value itself. Counts that are not powers of two (N = 1536, 3072, ... not used by the VAE) fall back to
+ the ``div_rn`` combine with a count operand;
+* no per-element masks: rows of a tile are all valid when ``M % R == 0`` (true for every production M) and the
+ tile is masked as a whole otherwise; 32-bit element offsets whenever ``M*N < 2**31``;
+* the row tile stays in registers between the statistics and the normalize pass (no second read of x); gamma/beta
+ are loaded once per program and converted once for the R rows;
+* ``_ln_exact_kernel`` (N >= 512): R rows per 128-thread program as a ``[LANES, R, 4]`` register tile. Lane t still
+ owns ATen's 4-element vectors ``t + 128*j`` in the same sequential order and the lane reduction is a ``tl.reduce``
+ over the lane axis = xor butterfly within the warp + (w0,w2),(w1,w3),(.,.) across warps = ATen's shfl_down/smem
+ tree of lane 0 (the lanes-first tile order makes Triton map lanes to threads and rows to registers; the other
+ order silently changes the tree and breaks exactness -- the self-test guards it);
+* ``_ln_exact_ksplit_kernel`` (N = 256, where ATen's block has only 64 active lanes and the reduction dominated):
+ thread (k, r) owns the lanes {k + 8q + 16h + 32w} of one row, so the shuffle levels with offsets 16 and 8 and the
+ inter-warp levels become in-register combines of only the useful pairs, and just the offsets 4, 2, 1 are shuffles
+ over 8 threads; 8 threads per row, R = 4 * num_warps rows per program (5.0 TB/s at 540672 x 256).
+
+Isolated (CUDA events, median of 30): 540672x256 361 -> 110 us, 135168x512 207 -> 75 us, 33792x1024 84 -> 46 us,
+135168x1024 275 -> 119 us, 33792x2048 118 -> 63 us (details in results.md). Whole VAE encoder (real weights, all
+production adapters): LayerNorm kernels 4.28 -> 1.93 ms/window, 27.17 -> 25.27 ms/window, latents bitwise identical.
+
+``layer_norm_bf16_approx`` / ``residual_layer_norm_bf16_approx`` are the opt-in NON-exact variants (fp32 two-pass
+statistics over 16-byte vectors, one bf16 rounding). They are only marginally faster than the exact kernels
+(1.76 vs 1.93 ms/window) and the ~1e-5 per-op flips grow to rel L2 4e-3 / 56 % bitwise in the latents -- not
+recommended (see results.md).
+"""
+from __future__ import annotations
+
+import torch
+import triton
+import triton.language as tl
+from torch import Tensor
+from triton.language.extra import libdevice
+
+NUM_WARPS = 4
+# Exact kernel configuration per N: (kernel, R rows per program, LANES, keep x as packed bf16 in registers,
+# num_warps); tuned on the L20D (SM103) at the production row counts, see bench_v2.json / test_ksplit2.
+TILE: dict[int, tuple] = {
+ 256: ("ksplit", 8, 64, True, 2), # 110 us @ 540672 rows (5.0 TB/s); lane kernel 142 us; production 361 us
+ 512: ("lane", 4, 128, False, 4), # 75 us @ 135168 rows (3.7 TB/s); production 207 us
+ 1024: ("lane", 4, 128, False, 4), # 46 us @ 33792 rows, 119 us @ 135168 rows; production 84 / 275 us
+ 2048: ("lane", 2, 128, False, 4), # 28 us @ 8448 rows, 63 us @ 33792 rows; production 48 / 118 us
+ 4096: ("lane", 1, 128, False, 4), # 45 us @ 8448 rows; production 66 us
+ 8192: ("lane", 1, 128, False, 4),
+}
+APPROX_TILE: dict[int, int] = {256: 16, 512: 8, 1024: 4, 2048: 2, 4096: 1, 8192: 1}
+
+
+# ------------------------------------------------------------------------------------------- Welford pieces
+@triton.jit
+def _welford_step(mean, m2, val, RCP: tl.constexpr):
+ """ATen cuWelfordOnlineSum: new_mean = fma(delta, 1/n, mean); m2 = fma(delta, val - new_mean, m2)
+ (nvcc contracts both mul+add pairs; 1.f/n is rcp.rn == div.rn(1, n) == the fp32 constant RCP)."""
+ delta = val - mean
+ rcp = tl.full(mean.shape, RCP, tl.float32)
+ new_mean = libdevice.fma(delta, rcp, mean)
+ new_m2 = libdevice.fma(delta, val - new_mean, m2)
+ return new_mean, new_m2
+
+
+@triton.jit
+def _combine_scaled(mean_a, m2s_a, mean_b, m2s_b):
+ """ATen cuWelfordCombine(dataB = own (a), dataA = partner (b)) for one level of a balanced tree whose partials
+ carry equal power-of-two counts c, expressed on the count-scaled second moment m2s = sigma2 / c.
+
+ ATen: coef = 1/(2c); nA = nB = c*coef = 0.5 (exact for every production count, probe_consts.py);
+ mean = fma(nA, mean_partner, nB * mean_own)
+ sigma2 = fma((delta*delta) * c, nB, sigma2_partner + sigma2_own)
+ Dividing the sigma2 recurrence by the new count 2c only rescales every intermediate by a power of two, which
+ commutes with fp32 rounding (no subnormals: a sigma2 that small is swallowed by eps anyway), so
+ m2s_new = fma(delta*delta, 0.25, 0.5 * (m2s_partner + m2s_own))
+ is bitwise sigma2_new / (2c). No count operand (2 shuffles per level instead of 3) and no division."""
+ delta = mean_a - mean_b
+ mean = libdevice.fma(0.5, mean_b, 0.5 * mean_a)
+ m2s = libdevice.fma(delta * delta, 0.25, 0.5 * (m2s_b + m2s_a))
+ return mean, m2s
+
+
+@triton.jit
+def _combine_div(mean_a, m2_a, cnt_a, mean_b, m2_b, cnt_b):
+ """ATen cuWelfordCombine with the IEEE division (fallback for counts that are not powers of two)."""
+ delta = mean_a - mean_b
+ count = cnt_b + cnt_a
+ one = tl.zeros_like(count) + 1.0
+ coef = libdevice.div_rn(one, count)
+ n_a = cnt_b * coef
+ n_b = cnt_a * coef
+ mean = libdevice.fma(n_a, mean_b, n_b * mean_a)
+ sig = libdevice.fma((delta * delta) * cnt_b, n_b, m2_b + m2_a)
+ return mean, sig, count
+
+
+@triton.jit
+def _split4(v, LANES: tl.constexpr, R: tl.constexpr):
+ """[LANES, R, 4] -> four [LANES, R] tensors (columns 0, 1, 2, 3)."""
+ x3 = tl.reshape(v, [LANES, R, 2, 2])
+ a, b = tl.split(x3) # a = cols (0, 2), b = cols (1, 3)
+ v0, v2 = tl.split(a)
+ v1, v3 = tl.split(b)
+ return v0, v1, v2, v3
+
+
+@triton.jit
+def _join4(v0, v1, v2, v3, LANES: tl.constexpr, R: tl.constexpr):
+ """Inverse of _split4: four [LANES, R] -> [LANES, R, 4]."""
+ a = tl.join(v0, v2)
+ b = tl.join(v1, v3)
+ return tl.reshape(tl.join(a, b), [LANES, R, 4])
+
+
+# ------------------------------------------------------------------------------------------- exact kernel
+@triton.jit
+def _ln_exact_kernel(x_ptr, res_ptr, w_ptr, b_ptr, y_ptr, xo_ptr, M, eps, n_float,
+ N: tl.constexpr, R: tl.constexpr, LANES: tl.constexpr, FUSE_RESIDUAL: tl.constexpr,
+ RES_BROADCAST: tl.constexpr, EVEN_M: tl.constexpr, OFF64: tl.constexpr, POW2: tl.constexpr):
+ """R rows per program, each row = ATen's vectorized_layer_norm block: lane t (0..LANES-1) owns the 4-element
+ vectors t + LANES*j (j < NJ) in sequential order, then a shuffle/smem Welford tree over the lanes.
+
+ The register tile is [LANES, R, 4] (lanes first): Triton's coalescing breaks the tie between the two
+ non-contiguous dims towards the lower one, so the lanes land on threads/warps (threadsPerWarp [32,1,1],
+ warpsPerCTA [LANES/32, 128/LANES, 1]) and the rows in registers; the lane reduction is then exactly one lane
+ per thread -> xor butterfly in the warp + (w0,w2),(w1,w3),(.,.) across warps = ATen's shfl_down/smem tree of
+ lane 0, and every combine joins equal power-of-two counts (what _combine_scaled assumes; a layout with
+ in-thread accumulation would break both -- the self-test guards it). The tile stays in registers for the
+ normalize pass (no second read).
+
+ LANES = 128 for N >= 512. For N = 256 ATen's block has 128 threads but only 64 active lanes; the inactive
+ warps 2, 3 carry count 0 and ATen's inter-warp merge with them is an exact identity (coef = 1/128 exactly,
+ nB = 1, mean = fma(0, 0, 1*mean) = mean, sigma2 = fma(0, 1, 0 + sigma2) = sigma2), so the 64-lane tree
+ (two warps + one smem level) yields bitwise the same statistics; LANES = 64 packs two row groups per program.
+ """
+ NV: tl.constexpr = N // 4
+ NJ: tl.constexpr = NV // LANES
+ tl.static_assert(NJ * LANES == NV, "N/4 must be a multiple of LANES")
+ pid = tl.program_id(0)
+ rows = pid * R + tl.arange(0, R) # [R]
+ lane = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ if OFF64:
+ base = rows.to(tl.int64) * N
+ else:
+ base = rows * N
+ rmask = (rows < M)[None, :, None] # [1, R, 1]
+ vcol = lane[:, None] * 4 + c4[None, :] # [LANES, 4] element offset inside the row
+ mean = tl.zeros([LANES, R], tl.float32)
+ m2 = tl.zeros([LANES, R], tl.float32)
+ cols = ()
+ for j in tl.static_range(NJ):
+ coffs = vcol + j * (4 * LANES)
+ offs = base[None, :, None] + coffs[:, None, :] # [LANES, R, 4]
+ if EVEN_M:
+ xv = tl.load(x_ptr + offs).to(tl.float32)
+ else:
+ xv = tl.load(x_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ if FUSE_RESIDUAL:
+ if RES_BROADCAST:
+ rv = tl.load(res_ptr + coffs).to(tl.float32)[:, None, :]
+ elif EVEN_M:
+ rv = tl.load(res_ptr + offs).to(tl.float32)
+ else:
+ rv = tl.load(res_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ xb = (xv + rv).to(tl.bfloat16) # eager bf16 add: fp32 add, one RNE rounding
+ if EVEN_M:
+ tl.store(xo_ptr + offs, xb)
+ else:
+ tl.store(xo_ptr + offs, xb, mask=rmask)
+ xv = xb.to(tl.float32)
+ v0, v1, v2, v3 = _split4(xv, LANES, R)
+ cols = cols + (v0, v1, v2, v3)
+ mean, m2 = _welford_step(mean, m2, v0, 1.0 / (4 * j + 1))
+ mean, m2 = _welford_step(mean, m2, v1, 1.0 / (4 * j + 2))
+ mean, m2 = _welford_step(mean, m2, v2, 1.0 / (4 * j + 3))
+ mean, m2 = _welford_step(mean, m2, v3, 1.0 / (4 * j + 4))
+ if POW2:
+ # scaled second moment: m2 / c0 (exact: c0 = 4*NJ is a power of two); the tree keeps sigma2/count, and
+ # ATen's final sigma2 / N is then the reduced value itself (N = total count).
+ m2s = m2 * (1.0 / (4 * NJ))
+ mean_t, var = tl.reduce((mean, m2s), 0, _combine_scaled)
+ else:
+ cnt = tl.zeros([LANES, R], tl.float32) + (4.0 * NJ)
+ mean_t, m2_t, cnt_t = tl.reduce((mean, m2, cnt), 0, _combine_div)
+ nf = tl.zeros([R], tl.float32) + n_float
+ var = libdevice.div_rn(m2_t, nf) # ATen: sigma2 / float(N)
+ rstd = tl.rsqrt(var + eps) # rsqrtf -> MUFU.RSQ
+ mean2 = mean_t[None, :]
+ rstd2 = rstd[None, :]
+ for j in tl.static_range(NJ):
+ coffs = vcol + j * (4 * LANES)
+ offs = base[None, :, None] + coffs[:, None, :]
+ wv = tl.load(w_ptr + coffs).to(tl.float32) # [LANES, 4], shared by the R rows
+ bv = tl.load(b_ptr + coffs).to(tl.float32)
+ w0, w1, w2, w3 = _split4(wv[:, None, :], LANES, 1)
+ b0, b1, b2, b3 = _split4(bv[:, None, :], LANES, 1)
+ # ATen: gamma * (rstd * (x - mean)) + beta -> fma(gamma, rstd * (x - mean), beta), one bf16 rounding
+ y0 = libdevice.fma(w0, rstd2 * (cols[4 * j + 0] - mean2), b0)
+ y1 = libdevice.fma(w1, rstd2 * (cols[4 * j + 1] - mean2), b1)
+ y2 = libdevice.fma(w2, rstd2 * (cols[4 * j + 2] - mean2), b2)
+ y3 = libdevice.fma(w3, rstd2 * (cols[4 * j + 3] - mean2), b3)
+ y = _join4(y0, y1, y2, y3, LANES, R).to(tl.bfloat16)
+ if EVEN_M:
+ tl.store(y_ptr + offs, y)
+ else:
+ tl.store(y_ptr + offs, y, mask=rmask)
+
+
+# ------------------------------------------------------------------------------------------- exact kernel, k-split
+@triton.jit
+def _ksplit_lane_offsets(LANES: tl.constexpr):
+ """Element offset (inside the row) of the 4-element vector of ATen lane a(k, g) for the k-split layout.
+
+ Logical tile dims [8 (k), R, G (= LANES/8), 4]; group index g = (wi*2 + q)*2 + h enumerates (wi, q, h) with
+ h fastest, a = w*32 + h*16 + q*8 + k. For LANES=128 the warp index is w = 2*(wi % 2) + wi // 2, so that the
+ tree splits the last register dim in ATen's order: h (shfl offset 16), q (offset 8), [shuffles over k: offsets
+ 4, 2, 1], w_hi (smem level offset 2: (w0,w2),(w1,w3)), w_lo (offset 1); for LANES=64 w = wi."""
+ G: tl.constexpr = LANES // 8
+ W: tl.constexpr = LANES // 32
+ k = tl.arange(0, 8)
+ g = tl.arange(0, G)
+ c4 = tl.arange(0, 4)
+ h = g % 2
+ q = (g // 2) % 2
+ wi = g // 4
+ if W == 4:
+ w = 2 * (wi % 2) + wi // 2
+ else:
+ w = wi
+ a = w * 32 + h * 16 + q * 8 + k[:, None] # [8, G]
+ return a[:, :, None] * 4 + c4[None, None, :] # [8, G, 4]
+
+
+@triton.jit
+def _split_last(x, SHAPE_A: tl.constexpr, SHAPE_B: tl.constexpr, LAST: tl.constexpr):
+ """[A, B, LAST] -> two [A, B, LAST/2] tensors (even / odd index of the last dim)."""
+ return tl.split(tl.reshape(x, [SHAPE_A, SHAPE_B, LAST // 2, 2]))
+
+
+@triton.jit
+def _ln_exact_ksplit_kernel(x_ptr, res_ptr, w_ptr, b_ptr, y_ptr, xo_ptr, M, eps,
+ N: tl.constexpr, R: tl.constexpr, LANES: tl.constexpr, FUSE_RESIDUAL: tl.constexpr,
+ RES_BROADCAST: tl.constexpr, EVEN_M: tl.constexpr, OFF64: tl.constexpr,
+ KEEP_BF16: tl.constexpr):
+ """Same arithmetic as _ln_exact_kernel (bit-exact ATen LayerNorm) with a different lane->thread mapping:
+ thread (k, r) owns the G = LANES/8 ATen lanes {k + 8q + 16h + 32w} of row r (8 threads per row, 4 rows per
+ warp, R = 4*num_warps rows per program). ATen's intra-warp shuffle levels with offsets 16 and 8 and the
+ inter-warp smem levels become in-register combines (only the useful ones, no SIMT redundancy); the levels with
+ offsets 4, 2, 1 are a tl.reduce over the 8 k-threads (xor butterfly 4, 2, 1 = ATen's shfl_down tree of lane 0).
+ _combine_scaled is bitwise commutative, so every thread of the group ends with the same statistics.
+ Requires a power-of-two per-lane count (N/LANES), which holds for every production N."""
+ NV: tl.constexpr = N // 4
+ NJ: tl.constexpr = NV // LANES
+ G: tl.constexpr = LANES // 8
+ W: tl.constexpr = LANES // 32
+ tl.static_assert(NJ * LANES == NV, "N/4 must be a multiple of LANES")
+ tl.static_assert(W == 2 or W == 4, "LANES must be 64 or 128")
+ pid = tl.program_id(0)
+ rows = pid * R + tl.arange(0, R) # [R]
+ if OFF64:
+ base = rows.to(tl.int64) * N
+ else:
+ base = rows * N
+ rmask = (rows < M)[None, :, None, None] # [1, R, 1, 1]
+ lo = _ksplit_lane_offsets(LANES) # [8, G, 4]
+ mean = tl.zeros([8, R, G], tl.float32)
+ m2 = tl.zeros([8, R, G], tl.float32)
+ cols = ()
+ for j in tl.static_range(NJ):
+ coffs = lo + j * (4 * LANES)
+ offs = base[None, :, None, None] + coffs[:, None, :, :] # [8, R, G, 4]
+ if EVEN_M:
+ xb = tl.load(x_ptr + offs)
+ else:
+ xb = tl.load(x_ptr + offs, mask=rmask, other=0.0)
+ if FUSE_RESIDUAL:
+ if RES_BROADCAST:
+ rv = tl.load(res_ptr + coffs).to(tl.float32)[:, None, :, :]
+ elif EVEN_M:
+ rv = tl.load(res_ptr + offs).to(tl.float32)
+ else:
+ rv = tl.load(res_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ xb = (xb.to(tl.float32) + rv).to(tl.bfloat16) # eager bf16 add: fp32 add, one RNE rounding
+ if EVEN_M:
+ tl.store(xo_ptr + offs, xb)
+ else:
+ tl.store(xo_ptr + offs, xb, mask=rmask)
+ xv = xb.to(tl.float32)
+ v0, v1, v2, v3 = _split4_4d(xv, R, G)
+ if KEEP_BF16:
+ cols = cols + (xb,)
+ else:
+ cols = cols + (v0, v1, v2, v3)
+ mean, m2 = _welford_step(mean, m2, v0, 1.0 / (4 * j + 1))
+ mean, m2 = _welford_step(mean, m2, v1, 1.0 / (4 * j + 2))
+ mean, m2 = _welford_step(mean, m2, v2, 1.0 / (4 * j + 3))
+ mean, m2 = _welford_step(mean, m2, v3, 1.0 / (4 * j + 4))
+ m2s = m2 * (1.0 / (4 * NJ)) # sigma2 / count (exact scaling)
+ # level h (ATen shfl offset 16): own = h0 lanes, partner = h1 lanes
+ mh0, mh1 = _split_last(mean, 8, R, G)
+ sh0, sh1 = _split_last(m2s, 8, R, G)
+ mean, m2s = _combine_scaled(mh0, sh0, mh1, sh1) # [8, R, G/2] (index w_lo, w_hi, q)
+ # level q (offset 8)
+ mq0, mq1 = _split_last(mean, 8, R, G // 2)
+ sq0, sq1 = _split_last(m2s, 8, R, G // 2)
+ mean, m2s = _combine_scaled(mq0, sq0, mq1, sq1) # [8, R, W] (index w_lo, w_hi)
+ # levels k (offsets 4, 2, 1): shuffles over the 8 k-threads
+ mean, m2s = tl.reduce((mean, m2s), 0, _combine_scaled) # [R, W]
+ # inter-warp: (w0, w2), (w1, w3) [split w_hi], then (., .) [split w_lo]
+ if W == 4:
+ ma, mb = tl.split(tl.reshape(mean, [R, 2, 2]))
+ sa, sb = tl.split(tl.reshape(m2s, [R, 2, 2]))
+ mean, m2s = _combine_scaled(ma, sa, mb, sb) # [R, 2]
+ ma, mb = tl.split(mean)
+ sa, sb = tl.split(m2s)
+ mean_t, var = _combine_scaled(ma, sa, mb, sb) # [R]; var = sigma2 / N exactly
+ rstd = tl.rsqrt(var + eps)
+ mean3 = mean_t[None, :, None]
+ rstd3 = rstd[None, :, None]
+ for j in tl.static_range(NJ):
+ coffs = lo + j * (4 * LANES)
+ offs = base[None, :, None, None] + coffs[:, None, :, :]
+ wv = tl.load(w_ptr + coffs).to(tl.float32) # [8, G, 4]
+ bv = tl.load(b_ptr + coffs).to(tl.float32)
+ w0, w1, w2, w3 = _split4_4d(wv[:, None, :, :], 1, G)
+ b0, b1, b2, b3 = _split4_4d(bv[:, None, :, :], 1, G)
+ if KEEP_BF16:
+ x0, x1, x2, x3 = _split4_4d(cols[j].to(tl.float32), R, G)
+ else:
+ x0 = cols[4 * j + 0]
+ x1 = cols[4 * j + 1]
+ x2 = cols[4 * j + 2]
+ x3 = cols[4 * j + 3]
+ y0 = libdevice.fma(w0, rstd3 * (x0 - mean3), b0)
+ y1 = libdevice.fma(w1, rstd3 * (x1 - mean3), b1)
+ y2 = libdevice.fma(w2, rstd3 * (x2 - mean3), b2)
+ y3 = libdevice.fma(w3, rstd3 * (x3 - mean3), b3)
+ y = _join4_4d(y0, y1, y2, y3, R, G).to(tl.bfloat16)
+ if EVEN_M:
+ tl.store(y_ptr + offs, y)
+ else:
+ tl.store(y_ptr + offs, y, mask=rmask)
+
+
+@triton.jit
+def _split4_4d(v, R: tl.constexpr, G: tl.constexpr):
+ """[8, R, G, 4] -> four [8, R, G] tensors (columns 0, 1, 2, 3)."""
+ x3 = tl.reshape(v, [8, R, G, 2, 2])
+ a, b = tl.split(x3)
+ v0, v2 = tl.split(a)
+ v1, v3 = tl.split(b)
+ return v0, v1, v2, v3
+
+
+@triton.jit
+def _join4_4d(v0, v1, v2, v3, R: tl.constexpr, G: tl.constexpr):
+ a = tl.join(v0, v2)
+ b = tl.join(v1, v3)
+ return tl.reshape(tl.join(a, b), [8, R, G, 4])
+
+
+# ------------------------------------------------------------------------------------------- approximate kernel
+@triton.jit
+def _ln_approx_kernel(x_ptr, res_ptr, w_ptr, b_ptr, y_ptr, xo_ptr, M, eps, inv_n,
+ N: tl.constexpr, R: tl.constexpr, FUSE_RESIDUAL: tl.constexpr, RES_BROADCAST: tl.constexpr,
+ EVEN_M: tl.constexpr, OFF64: tl.constexpr):
+ """NON-exact: fp32 two-pass statistics (mean = sum/N, var = sum((x-mean)^2)/N over register-resident data),
+ 16-byte vectors, a single bf16 rounding of fma(gamma, rstd*(x-mean), beta)."""
+ pid = tl.program_id(0)
+ rows = pid * R + tl.arange(0, R)
+ cols = tl.arange(0, N)
+ if OFF64:
+ base = rows.to(tl.int64) * N
+ else:
+ base = rows * N
+ offs = base[:, None] + cols[None, :]
+ rmask = (rows < M)[:, None]
+ if EVEN_M:
+ xv = tl.load(x_ptr + offs).to(tl.float32)
+ else:
+ xv = tl.load(x_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ if FUSE_RESIDUAL:
+ if RES_BROADCAST:
+ rv = tl.load(res_ptr + cols).to(tl.float32)[None, :]
+ elif EVEN_M:
+ rv = tl.load(res_ptr + offs).to(tl.float32)
+ else:
+ rv = tl.load(res_ptr + offs, mask=rmask, other=0.0).to(tl.float32)
+ xb = (xv + rv).to(tl.bfloat16)
+ if EVEN_M:
+ tl.store(xo_ptr + offs, xb)
+ else:
+ tl.store(xo_ptr + offs, xb, mask=rmask)
+ xv = xb.to(tl.float32)
+ mean = tl.sum(xv, 1) * inv_n
+ xc = xv - mean[:, None]
+ var = tl.sum(xc * xc, 1) * inv_n
+ rstd = tl.rsqrt(var + eps)
+ w = tl.load(w_ptr + cols).to(tl.float32)[None, :]
+ bb = tl.load(b_ptr + cols).to(tl.float32)[None, :]
+ y = libdevice.fma(w, xc * rstd[:, None], bb)
+ if EVEN_M:
+ tl.store(y_ptr + offs, y.to(tl.bfloat16))
+ else:
+ tl.store(y_ptr + offs, y.to(tl.bfloat16), mask=rmask)
+
+
+# ------------------------------------------------------------------------------------------- launch cache
+class _FastLaunch:
+ """Cache Triton CompiledKernel objects per specialization and launch them directly (skips the JIT
+ binder/specialization path). The key reproduces Triton's int specialization (==1, %16) and 16-byte pointer
+ alignment. Same as vae_fused_pointwise._FastLaunch."""
+
+ def __init__(self, jit_fn):
+ self.fn = jit_fn
+ self.cache = {}
+
+ def __call__(self, grid, *args, num_warps=4, **const):
+ key = [num_warps, tuple(sorted(const.items()))]
+ for a in args:
+ if isinstance(a, torch.Tensor):
+ key.append(a.data_ptr() % 16 == 0)
+ elif isinstance(a, int):
+ key.append((a == 1, a % 16 == 0))
+ else:
+ key.append(None)
+ key = tuple(key)
+ ck = self.cache.get(key)
+ g = (grid[0], 1, 1)
+ if ck is None:
+ ck = self.fn[g](*args, **const, num_warps=num_warps, enable_fp_fusion=False)
+ self.cache[key] = ck
+ return ck
+ ck[g](*args, *const.values())
+ return ck
+
+
+_exact_launch = _FastLaunch(_ln_exact_kernel)
+_ksplit_launch = _FastLaunch(_ln_exact_ksplit_kernel)
+_approx_launch = _FastLaunch(_ln_approx_kernel)
+
+
+def _ln_rows(x2: Tensor, weight: Tensor, bias: Tensor, eps: float, residual2: Tensor | None, broadcast=False,
+ approx=False, tile=None, num_warps=None):
+ M, N = x2.shape
+ assert x2.dtype == torch.bfloat16 and x2.is_contiguous() and weight.dtype == torch.bfloat16 and bias.dtype == torch.bfloat16
+ assert N % 4 == 0 and N in TILE, N
+ y = torch.empty_like(x2)
+ fuse = residual2 is not None
+ if fuse:
+ assert residual2.dtype == torch.bfloat16 and residual2.is_contiguous()
+ assert residual2.shape == ((N,) if broadcast else x2.shape)
+ xo = torch.empty_like(x2)
+ else:
+ xo = y
+ residual2 = x2
+ off64 = M * N >= 2 ** 31
+ nw = NUM_WARPS if num_warps is None else num_warps
+ if approx:
+ rows = APPROX_TILE[N] if tile is None else tile
+ grid = (triton.cdiv(M, rows),)
+ _approx_launch(grid, x2, residual2, weight, bias, y, xo, M, float(eps), 1.0 / N,
+ N=N, R=rows, FUSE_RESIDUAL=fuse, RES_BROADCAST=bool(broadcast), EVEN_M=(M % rows == 0),
+ OFF64=off64, num_warps=nw)
+ else:
+ cfg = TILE[N] if tile is None else tile
+ if len(cfg) == 2:
+ cfg = ("lane",) + tuple(cfg)
+ kind, rows, lanes = cfg[:3]
+ keep_bf16 = cfg[3] if len(cfg) > 3 else (N >= 512)
+ if len(cfg) > 4 and num_warps is None:
+ nw = cfg[4]
+ nj = N // 4 // lanes
+ pow2 = (nj & (nj - 1)) == 0 # per-lane count 4*NJ (and every tree level) is a power of two
+ grid = (triton.cdiv(M, rows),)
+ if kind == "ksplit":
+ assert pow2 and lanes in (64, 128)
+ _ksplit_launch(grid, x2, residual2, weight, bias, y, xo, M, float(eps),
+ N=N, R=rows, LANES=lanes, FUSE_RESIDUAL=fuse, RES_BROADCAST=bool(broadcast),
+ EVEN_M=(M % rows == 0), OFF64=off64, KEEP_BF16=bool(keep_bf16), num_warps=nw)
+ else:
+ _exact_launch(grid, x2, residual2, weight, bias, y, xo, M, float(eps), float(N),
+ N=N, R=rows, LANES=lanes, FUSE_RESIDUAL=fuse, RES_BROADCAST=bool(broadcast),
+ EVEN_M=(M % rows == 0), OFF64=off64, POW2=pow2, num_warps=nw)
+ return y, (xo if fuse else None)
+
+
+def layer_norm_bf16(x: Tensor, weight: Tensor, bias: Tensor, eps: float = 1e-5) -> Tensor:
+ """bf16(LayerNorm_fp32(x)) in one kernel, bit-exact vs eager autocast; x: (..., N) bf16."""
+ if x.stride(-1) != 1 or not x.is_contiguous():
+ x = x.contiguous()
+ y, _ = _ln_rows(x.view(-1, x.shape[-1]), weight, bias, eps, None)
+ return y.view(x.shape)
+
+
+def residual_layer_norm_bf16(x: Tensor, delta: Tensor, weight: Tensor, bias: Tensor, eps: float = 1e-5):
+ """x_new = bf16(x + delta); returns (x_new, bf16(LayerNorm_fp32(x_new))). ``delta`` may be a (N,) bias
+ broadcast over rows (eager: ``x.add_(bias)``). Bit-exact vs eager."""
+ if not x.is_contiguous():
+ x = x.contiguous()
+ if not delta.is_contiguous():
+ delta = delta.contiguous()
+ broadcast = delta.dim() == 1
+ y, xo = _ln_rows(x.view(-1, x.shape[-1]), weight, bias, eps,
+ delta if broadcast else delta.view(-1, x.shape[-1]), broadcast=broadcast)
+ return xo.view(x.shape), y.view(x.shape)
+
+
+def layer_norm_bf16_approx(x: Tensor, weight: Tensor, bias: Tensor, eps: float = 1e-5) -> Tensor:
+ """NON-exact fast variant (fp32 two-pass statistics, one bf16 rounding); ~1-ulp flips in a small fraction of
+ outputs vs eager."""
+ if x.stride(-1) != 1 or not x.is_contiguous():
+ x = x.contiguous()
+ y, _ = _ln_rows(x.view(-1, x.shape[-1]), weight, bias, eps, None, approx=True)
+ return y.view(x.shape)
+
+
+def residual_layer_norm_bf16_approx(x: Tensor, delta: Tensor, weight: Tensor, bias: Tensor, eps: float = 1e-5):
+ """NON-exact fast variant of residual_layer_norm_bf16 (x_new is still bit-exact, the LN output is not)."""
+ if not x.is_contiguous():
+ x = x.contiguous()
+ if not delta.is_contiguous():
+ delta = delta.contiguous()
+ broadcast = delta.dim() == 1
+ y, xo = _ln_rows(x.view(-1, x.shape[-1]), weight, bias, eps,
+ delta if broadcast else delta.view(-1, x.shape[-1]), broadcast=broadcast, approx=True)
+ return xo.view(x.shape), y.view(x.shape)
+
+
+# ------------------------------------------------------------------------------------------- install
+PROBE_ROWS = 256 # a multiple of every R in TILE (EVEN_M, like production) and > 128 rows for the ksplit groups
+
+
+def eager_layer_norm_bf16(x: Tensor, weight: Tensor, bias: Tensor, eps: float) -> Tensor:
+ """What eager autocast computes: fp32 ``F.layer_norm`` over the upcast inputs (ATen's
+ vectorized_layer_norm_kernel), then the bf16 cast of the consumer."""
+ return torch.nn.functional.layer_norm(x.float(), (x.shape[-1],), weight.float(), bias.float(), eps).to(torch.bfloat16)
+
+
+def probe_exact(ln_fn=None, res_fn=None, device="cuda", rows: int = PROBE_ROWS, Ns=None) -> dict:
+ """Cheap bit-exactness probe of ``ln_fn`` / ``res_fn`` (default: this module's exact kernels) against the eager
+ LayerNorm math for every N in ``TILE`` (plain LN, fused full residual, fused broadcast (N,) bias), ``rows`` rows
+ each. The kernels' exactness rests on Triton's layout tie-break and reduction order (see the module docstring),
+ so a Triton build other than the pinned one can silently flip 1-ulp results; this catches that at install time.
+ Raises ``RuntimeError`` naming the first mismatching case; returns the per-case mismatch counts (all 0)."""
+ ln_fn = layer_norm_bf16 if ln_fn is None else ln_fn
+ res_fn = residual_layer_norm_bf16 if res_fn is None else res_fn
+ Ns = tuple(TILE) if Ns is None else tuple(Ns)
+ g = torch.Generator(device=device).manual_seed(0x1A7E)
+ report = {}
+ with torch.inference_mode():
+ for N in Ns:
+ w = (1.0 + 0.3 * torch.randn(N, generator=g, device=device)).bfloat16()
+ b = (0.3 * torch.randn(N, generator=g, device=device)).bfloat16()
+ x = (torch.randn(rows, N, generator=g, device=device) * 2 + 0.5).bfloat16()
+ d = (torch.randn(rows, N, generator=g, device=device) * 0.5).bfloat16()
+ cb = (torch.randn(N, generator=g, device=device) * 0.1).bfloat16()
+ eps = 1e-5
+ cases = {"ln": (ln_fn(x, w, b, eps), eager_layer_norm_bf16(x, w, b, eps))}
+ xo, y = res_fn(x, d, w, b, eps)
+ xr = x + d # eager bf16 add (one RNE), then LN of the sum
+ cases["res_x_new"], cases["res_ln"] = (xo, xr), (y, eager_layer_norm_bf16(xr, w, b, eps))
+ xob, yb = res_fn(x, cb, w, b, eps)
+ xrb = x + cb # eager ``x.add_(bias)`` broadcast over rows
+ cases["bias_x_new"], cases["bias_ln"] = (xob, xrb), (yb, eager_layer_norm_bf16(xrb, w, b, eps))
+ for case, (out, ref) in cases.items():
+ n_bad = int((out.view(torch.int16) != ref.view(torch.int16)).sum().item())
+ report[f"{N}/{case}"] = n_bad
+ if n_bad:
+ raise RuntimeError(
+ f"vae_ln_exact probe: {case} at N={N} differs from eager LayerNorm in {n_bad}/{out.numel()} "
+ f"elements ({rows} rows, triton {triton.__version__}); the pinned Triton build no longer "
+ "reproduces ATen's rounding -- do not install the fast LayerNorm kernels")
+ return report
+
+
+def install(approx: bool = False, probe: bool = True):
+ """Route ``flux_action.models.vae_fused_pointwise.layer_norm_bf16`` / ``residual_layer_norm_bf16`` (looked up
+ by name at call time by every patched encoder forward) to the kernels of this module. Returns an ``uninstall``
+ callable. ``approx=True`` selects the NON-exact variants. Unless ``probe=False`` (or CUDA is unavailable), the
+ exact kernels are first checked bitwise against eager for every N in ``TILE`` (``probe_exact``); a mismatch
+ raises before anything is swapped."""
+ from flux_action.models import vae_fused_pointwise as vfp
+
+ if probe and not approx and torch.cuda.is_available():
+ probe_exact(layer_norm_bf16, residual_layer_norm_bf16)
+ prev = (vfp.layer_norm_bf16, vfp.residual_layer_norm_bf16)
+ if approx:
+ vfp.layer_norm_bf16 = layer_norm_bf16_approx
+ vfp.residual_layer_norm_bf16 = residual_layer_norm_bf16_approx
+ else:
+ vfp.layer_norm_bf16 = layer_norm_bf16
+ vfp.residual_layer_norm_bf16 = residual_layer_norm_bf16
+
+ def uninstall():
+ vfp.layer_norm_bf16, vfp.residual_layer_norm_bf16 = prev
+
+ return uninstall
+
+
+# ------------------------------------------------------------------------------------------- self-test
+SHAPES = [(540672, 256), (135168, 512), (33792, 1024), (8448, 2048), (4352, 2048), (135168, 1024), (33792, 2048),
+ (8448, 4096), (4352, 4096), (2304, 4096)]
+ODD_SHAPES = [(1001, 256), (999, 512), (37, 1024), (4097, 2048), (3, 4096), (1, 256)] # masked tiles
+
+
+def compare(a: Tensor, b: Tensor) -> dict:
+ af, bf = a.float(), b.float()
+ diff = (af - bf).abs()
+ same = (a.view(torch.int16) == b.view(torch.int16)).sum().item() / a.numel()
+ ulp = (a.view(torch.int16).int() - b.view(torch.int16).int()).abs().max().item()
+ return {"max_abs": diff.max().item(), "rel_l2": (diff.norm() / bf.norm().clamp_min(1e-30)).item(),
+ "bitwise_fraction": same, "max_bf16_ulp": ulp}
+
+
+def eager_ln(x, ln):
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ return ln(x).to(torch.bfloat16)
+
+
+@torch.inference_mode()
+def selftest(device="cuda", verbose=True, shapes=SHAPES + ODD_SHAPES, approx=False) -> dict:
+ """Bit-exactness of layer_norm_bf16 / residual_layer_norm_bf16 (incl. the broadcast conv-bias variant) vs eager
+ autocast at the production shapes (+ odd row counts), on random data. ``approx=True`` reports the numerics of
+ the non-exact variants instead (all_bit_exact is then expected False)."""
+ from torch import nn
+ torch.manual_seed(0)
+ results = {}
+ ln_fn = layer_norm_bf16_approx if approx else layer_norm_bf16
+ res_fn = residual_layer_norm_bf16_approx if approx else residual_layer_norm_bf16
+ ok = True
+ for M, N in shapes:
+ ln = nn.LayerNorm(N, eps=1e-5).to(device).bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ x = (torch.randn(M, N, device=device) * 2 + 0.5).bfloat16()
+ d = (torch.randn(M, N, device=device) * 0.5).bfloat16()
+ bias = (torch.randn(N, device=device) * 0.1).bfloat16()
+ ref = eager_ln(x, ln)
+ out = ln_fn(x, ln.weight, ln.bias, ln.eps)
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ xr = x + d
+ xrb = x.clone()
+ xrb.add_(bias)
+ ref2 = eager_ln(xr, ln)
+ ref3 = eager_ln(xrb, ln)
+ xo, out2 = res_fn(x, d, ln.weight, ln.bias, ln.eps)
+ xob, out3 = res_fn(x, bias, ln.weight, ln.bias, ln.eps)
+ r = {"ln": compare(out, ref), "res_x_new": compare(xo, xr), "res_ln": compare(out2, ref2),
+ "bias_x_new": compare(xob, xrb), "bias_ln": compare(out3, ref3)}
+ results[f"{M}x{N}"] = r
+ ok = ok and all(v["bitwise_fraction"] == 1.0 for v in r.values())
+ if verbose:
+ print(f"{M}x{N}", {k: (v["bitwise_fraction"], v["max_bf16_ulp"]) for k, v in r.items()}, flush=True)
+ results["all_bit_exact"] = ok
+ if verbose:
+ print("ALL BIT-EXACT:", ok)
+ return results
+
+
+if __name__ == "__main__":
+ selftest()
diff --git a/flux-umi/src/flux_action/models/vae_merge_glue.py b/flux-umi/src/flux_action/models/vae_merge_glue.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc07808f8683fe1917c79b0db255edd4ba3a8ad6
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_merge_glue.py
@@ -0,0 +1,552 @@
+"""Gather-LayerNorm fusion of the frozen-VAE merge glue (experiment vae-merge-glue, plan item B-3).
+
+In the v5 frozen-encoder stack every stage-final ``SwinTransformerBlock`` materialises ``x + mlp_out`` (its deferred
+MLP residual cannot be handed to a following block because ``PatchMerging`` / ``TemporalMerging`` consume ``x``),
+``PatchMerging`` then copies ``x`` through ``reshape/permute/flatten`` (one ATen index-bound copy, 1.5 TB/s) before
+its LayerNorm, and ``TemporalMerging`` concatenates (two D2D memcpys), reduces the 2-frame mean for the skip and
+copies ``permute/reshape`` before its LayerNorm. Per window that is 5 bf16 adds (0.24 ms), 3 permute copies
+(0.65 ms), 2 concat+mean+permute (0.14 ms) and the 5 merge LayerNorms (0.22 ms): ~1.25 ms of 23 ms.
+
+This module replaces each merge's glue + LayerNorm by ONE launch of ``_ln_exact_gather_kernel``: the exact bf16
+LayerNorm kernel of ``flux_action.models.vae_ln_exact`` (``_ln_exact_kernel``: R rows per 128-thread program as a
+``[LANES, R, 4]`` register tile, lane t owns ATen's 4-element vectors ``t + LANES*j`` in sequential order, Welford
+online sums with constant reciprocals, ``tl.reduce`` lane tree of ``_combine_scaled``) whose *loads* gather every
+output row from its 4 (PatchMerging: ``(di, dj)`` sub-rows, N = 4C) or 2 (TemporalMerging: frames ``2k`` and
+``2k+1`` of the front-padded sequence, N = 2C) source sub-rows, apply the pending stage-final residual as the same
+single-rounded ``bf16(x + m)`` that ``residual_layer_norm_bf16`` performs, and write only the LayerNorm output (plus,
+for TemporalMerging, the skip ``bf16((0 + a) + b) * 0.5)`` = ATen's ``MeanOps`` over the two
+frames). Only the address math differs from ``_ln_exact_kernel``: the lane -> element ownership, the tile layout
+and the reduction tree are identical, so the LayerNorm output is bitwise the eager chain's (verified by
+``selftest`` at the production merge shapes and by the whole-encoder latents in ``test_vae_merge_glue.py``).
+
+``install(vae, state)`` (on top of ``vae_fused_pointwise.install`` + ``vae_qk_fused.install``) patches ``forward``
+of every encoder ``PatchMerging`` / ``TemporalMerging`` instance and re-patches ``_forward_full`` of the 5 stage-final
+blocks so that they defer their MLP residual into the merge (``state.pending_residual = (x, m)``, tagged with the
+tensor object, exactly like ``vae_qk_fused``). Everything is forward-only and scoped to
+``training_fused_context(state)``; outside it (inference profile, decoder, grad-enabled calls, unsupported shapes)
+the stock code runs and a pending residual is materialised eagerly.
+
+Supported shapes (production: PatchMerging at C in {256, 512, 1024} with even H, W; TemporalMerging at C = 2048 with
+T in {33, 17}): PatchMerging needs N = 4C in ``vae_ln_exact.TILE`` with the lane kernel (C >= 128) and even H, W;
+TemporalMerging needs C % 512 == 0 (one j-chunk of the tile never straddles the two frames, so the skip mean pairs
+the fp32 columns of the same lane) and N = 2C in TILE. Odd T is handled by the front clamp (frame index
+``max(p - 1, 0)`` of the padded sequence, = ``torch.concat([x[:, :1], x], 1)``).
+"""
+from __future__ import annotations
+
+import types
+from dataclasses import dataclass, field
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+
+from flux_action.models.vae_ln_exact import TILE, _combine_scaled, _join4, _split4, _welford_step
+
+NUM_WARPS = 4
+
+
+# ------------------------------------------------------------------------------------------- kernel
+@triton.jit
+def _ln_exact_gather_kernel(x_ptr, m_ptr, w_ptr, b_ptr, y_ptr, skip_ptr, M, T, H, W, TP2, eps,
+ N: tl.constexpr, C: tl.constexpr, R: tl.constexpr, LANES: tl.constexpr,
+ MODE: tl.constexpr, PAD: tl.constexpr, FUSE_RESIDUAL: tl.constexpr,
+ WRITE_SKIP: tl.constexpr, EVEN_M: tl.constexpr, OFF64: tl.constexpr):
+ """``vae_ln_exact._ln_exact_kernel`` with gathered loads (same ``[LANES, R, 4]`` tile, same lane ownership of
+ ATen's 4-element vectors ``t + LANES*j``, same Welford steps and ``_combine_scaled`` lane tree; POW2 case only).
+
+ MODE 0 (PatchMerging, N = 4C): output row r = (bt, i, j) over [B*T, H/2, W/2]; element e of the row lives in
+ sub-row s = e // C = 2*di + dj at source row (bt*H + 2i + di)*W + 2j + dj, column e % C.
+ MODE 1 (TemporalMerging, N = 2C): output row r = (b, k, hw) over [B, TP2, H*W] with TP2 = (T + PAD) // 2;
+ sub-row s = e // C is frame max(2k + s - PAD, 0) of batch b (PAD = 1 reproduces concat([x[:, :1], x], 1)),
+ source row (b*T + frame)*H*W + hw. WRITE_SKIP stores bf16(((0 + a) + b) * 0.5) of the two bf16(x+m) frames
+ (ATen MeanOps: fp32 accumulate from the +0 identity, project by the fp32 factor 0.5).
+ FUSE_RESIDUAL: the loaded value is bf16(x + m) (fp32 add, one RNE), the same single rounding as eager /
+ ``residual_layer_norm_bf16``; the statistics and the normalize pass use that rounded value.
+ """
+ NV: tl.constexpr = N // 4
+ NJ: tl.constexpr = NV // LANES
+ CH: tl.constexpr = 4 * LANES # elements per j-chunk
+ tl.static_assert(NJ * LANES == NV, "N/4 must be a multiple of LANES")
+ tl.static_assert(C % 4 == 0, "C must be a multiple of 4 (vector-aligned sub-rows)")
+ if MODE == 0:
+ tl.static_assert(N == 4 * C, "PatchMerging LN width is 4C")
+ else:
+ tl.static_assert(N == 2 * C, "TemporalMerging LN width is 2C")
+ tl.static_assert(C % CH == 0, "TemporalMerging gather needs C % (4*LANES) == 0")
+ tl.static_assert(((4 * NJ) & (4 * NJ - 1)) == 0, "per-lane count must be a power of two (POW2 tree)")
+ pid = tl.program_id(0)
+ rows = pid * R + tl.arange(0, R) # [R] output rows
+ lane = tl.arange(0, LANES)
+ c4 = tl.arange(0, 4)
+ rmask = (rows < M)[None, :, None] # [1, R, 1]
+ if OFF64:
+ obase = rows.to(tl.int64) * N
+ else:
+ obase = rows * N
+ vcol = lane[:, None] * 4 + c4[None, :] # [LANES, 4] element offset inside the row
+ if MODE == 0:
+ W2 = W // 2
+ H2 = H // 2
+ jj = rows % W2
+ ii = (rows // W2) % H2
+ bt = rows // (W2 * H2)
+ srow0 = (bt * H + 2 * ii) * W + 2 * jj # [R] source row of sub-row (di, dj) = (0, 0)
+ else:
+ HW = H * W
+ hw = rows % HW
+ kk = (rows // HW) % TP2
+ bb = rows // (HW * TP2)
+ mean = tl.zeros([LANES, R], tl.float32)
+ m2 = tl.zeros([LANES, R], tl.float32)
+ cols = ()
+ for j in tl.static_range(NJ):
+ # chunk j covers row elements [j*CH, (j+1)*CH)
+ if MODE == 0:
+ lin = lane * 4 + j * CH # [LANES] first element of the lane's vector
+ sub = lin // C # [LANES] sub-row 0..3 (= 2*di + dj)
+ cb = lin - sub * C # [LANES] column inside the sub-row (mult. of 4)
+ srow = srow0[None, :] + ((sub // 2) * W + (sub % 2))[:, None] # [LANES, R]
+ else:
+ # the whole chunk lies inside one frame: sub-row (j*CH) // C, column offset (j*CH) % C
+ cb = lane * 4 + ((j * CH) % C) # [LANES]
+ frame = tl.maximum(2 * kk + ((j * CH) // C - PAD), 0) # [R] front clamp of the padded sequence
+ srow = ((bb * T + frame) * HW + hw)[None, :] + (lane * 0)[:, None] # [LANES, R]
+ cb = tl.multiple_of(cb, 4)
+ if OFF64:
+ srow = srow.to(tl.int64)
+ soffs = (srow * C + cb[:, None])[:, :, None] + c4[None, None, :] # [LANES, R, 4] gathered source
+ if EVEN_M:
+ xv = tl.load(x_ptr + soffs).to(tl.float32)
+ else:
+ xv = tl.load(x_ptr + soffs, mask=rmask, other=0.0).to(tl.float32)
+ if FUSE_RESIDUAL:
+ if EVEN_M:
+ rv = tl.load(m_ptr + soffs).to(tl.float32)
+ else:
+ rv = tl.load(m_ptr + soffs, mask=rmask, other=0.0).to(tl.float32)
+ xv = (xv + rv).to(tl.bfloat16).to(tl.float32) # eager bf16 add: fp32 add, one RNE rounding
+ v0, v1, v2, v3 = _split4(xv, LANES, R)
+ cols = cols + (v0, v1, v2, v3)
+ mean, m2 = _welford_step(mean, m2, v0, 1.0 / (4 * j + 1))
+ mean, m2 = _welford_step(mean, m2, v1, 1.0 / (4 * j + 2))
+ mean, m2 = _welford_step(mean, m2, v2, 1.0 / (4 * j + 3))
+ mean, m2 = _welford_step(mean, m2, v3, 1.0 / (4 * j + 4))
+ # scaled second moment m2 / c0 (exact: c0 = 4*NJ is a power of two); the tree keeps sigma2/count and ATen's
+ # final sigma2 / N is the reduced value itself.
+ m2s = m2 * (1.0 / (4 * NJ))
+ mean_t, var = tl.reduce((mean, m2s), 0, _combine_scaled)
+ rstd = tl.rsqrt(var + eps) # rsqrtf -> MUFU.RSQ
+ mean2 = mean_t[None, :]
+ rstd2 = rstd[None, :]
+ for j in tl.static_range(NJ):
+ coffs = vcol + j * CH
+ offs = obase[None, :, None] + coffs[:, None, :]
+ wv = tl.load(w_ptr + coffs).to(tl.float32) # [LANES, 4], shared by the R rows
+ bv = tl.load(b_ptr + coffs).to(tl.float32)
+ w0, w1, w2, w3 = _split4(wv[:, None, :], LANES, 1)
+ b0, b1, b2, b3 = _split4(bv[:, None, :], LANES, 1)
+ # ATen: gamma * (rstd * (x - mean)) + beta -> fma(gamma, rstd * (x - mean), beta), one bf16 rounding
+ y0 = libdevice.fma(w0, rstd2 * (cols[4 * j + 0] - mean2), b0)
+ y1 = libdevice.fma(w1, rstd2 * (cols[4 * j + 1] - mean2), b1)
+ y2 = libdevice.fma(w2, rstd2 * (cols[4 * j + 2] - mean2), b2)
+ y3 = libdevice.fma(w3, rstd2 * (cols[4 * j + 3] - mean2), b3)
+ y = _join4(y0, y1, y2, y3, LANES, R).to(tl.bfloat16)
+ if EVEN_M:
+ tl.store(y_ptr + offs, y)
+ else:
+ tl.store(y_ptr + offs, y, mask=rmask)
+ if WRITE_SKIP:
+ # TemporalMerging skip = mean over the two frames of the (residual-applied) bf16 rows. Chunk j (frame 0)
+ # and chunk j + NJ/2 (frame 1) of the same lane hold the same columns (C % CH == 0).
+ NJH: tl.constexpr = NJ // 2
+ if OFF64:
+ sbase = rows.to(tl.int64) * C
+ else:
+ sbase = rows * C
+ for j in tl.static_range(NJH):
+ parts = ()
+ for q in tl.static_range(4):
+ a = cols[4 * j + q]
+ b = cols[4 * (j + NJH) + q]
+ s = (tl.zeros_like(a) + a) + b # ATen: ident 0 + frame0, + frame1 (fp32)
+ parts = parts + ((s * 0.5),) # project: acc * factor (0.5f), then bf16
+ sk = _join4(parts[0], parts[1], parts[2], parts[3], LANES, R).to(tl.bfloat16)
+ soff = sbase[None, :, None] + (vcol + j * CH)[:, None, :]
+ if EVEN_M:
+ tl.store(skip_ptr + soff, sk)
+ else:
+ tl.store(skip_ptr + soff, sk, mask=rmask)
+
+
+# ------------------------------------------------------------------------------------------- launch cache
+class _FastLaunch:
+ """Cache Triton CompiledKernel objects per specialization and launch them directly (same as
+ vae_ln_exact._FastLaunch; constexprs must be passed in signature order)."""
+
+ def __init__(self, jit_fn):
+ self.fn = jit_fn
+ self.cache = {}
+
+ def __call__(self, grid, *args, num_warps=4, **const):
+ key = [num_warps, tuple(sorted(const.items()))]
+ for a in args:
+ if isinstance(a, torch.Tensor):
+ key.append(a.data_ptr() % 16 == 0)
+ elif isinstance(a, int):
+ key.append((a == 1, a % 16 == 0))
+ else:
+ key.append(None)
+ key = tuple(key)
+ ck = self.cache.get(key)
+ g = (grid[0], 1, 1)
+ if ck is None:
+ ck = self.fn[g](*args, **const, num_warps=num_warps, enable_fp_fusion=False)
+ self.cache[key] = ck
+ return ck
+ ck[g](*args, *const.values())
+ return ck
+
+
+_gather_launch = _FastLaunch(_ln_exact_gather_kernel)
+
+
+def _lane_cfg(N: int):
+ cfg = TILE.get(N)
+ if cfg is None:
+ return None
+ if len(cfg) == 2:
+ cfg = ("lane",) + tuple(cfg)
+ kind, rows, lanes = cfg[:3]
+ if kind != "lane":
+ return None
+ nj = N // 4 // lanes
+ if nj * lanes * 4 != N or (nj & (nj - 1)) != 0:
+ return None
+ nw = cfg[4] if len(cfg) > 4 else NUM_WARPS
+ return rows, lanes, nw
+
+
+def patch_merge_unsupported(x: Tensor, m: Tensor | None) -> str | None:
+ if x.dim() != 5 or x.dtype != torch.bfloat16 or not x.is_cuda or not x.is_contiguous():
+ return "needs a contiguous 5-D bf16 CUDA tensor"
+ B, T, H, W, C = x.shape
+ if H % 2 or W % 2:
+ return "odd H/W (PatchMerging pads first)"
+ if C % 4 or _lane_cfg(4 * C) is None:
+ return f"no lane-kernel tile for N = 4C = {4 * C}"
+ if m is not None and (m.shape != x.shape or m.dtype != x.dtype or not m.is_contiguous()):
+ return "residual must match x (shape, bf16, contiguous)"
+ return None
+
+
+def temporal_merge_unsupported(x: Tensor, m: Tensor | None) -> str | None:
+ if x.dim() != 5 or x.dtype != torch.bfloat16 or not x.is_cuda or not x.is_contiguous():
+ return "needs a contiguous 5-D bf16 CUDA tensor"
+ B, T, H, W, C = x.shape
+ cfg = _lane_cfg(2 * C)
+ if cfg is None:
+ return f"no lane-kernel tile for N = 2C = {2 * C}"
+ if C % (4 * cfg[1]):
+ return f"C = {C} not a multiple of 4*LANES = {4 * cfg[1]}"
+ if m is not None and (m.shape != x.shape or m.dtype != x.dtype or not m.is_contiguous()):
+ return "residual must match x (shape, bf16, contiguous)"
+ return None
+
+
+def patch_merge_ln(x: Tensor, m: Tensor | None, weight: Tensor, bias: Tensor, eps: float = 1e-5) -> Tensor:
+ """bf16(LayerNorm_fp32(PatchMerging glue of bf16(x + m))) as one kernel; x, m: (B, T, H, W, C) bf16 contiguous
+ (m None = no residual). Returns (B, T, H/2, W/2, 4C) bf16 = the input of ``PatchMerging.reduction``."""
+ reason = patch_merge_unsupported(x, m)
+ if reason is not None:
+ raise ValueError(reason)
+ B, T, H, W, C = x.shape
+ N = 4 * C
+ rows, lanes, nw = _lane_cfg(N)
+ M = B * T * (H // 2) * (W // 2)
+ y = torch.empty((M, N), dtype=torch.bfloat16, device=x.device)
+ off64 = max(M * N, x.numel()) >= 2 ** 31
+ grid = (triton.cdiv(M, rows),)
+ _gather_launch(grid, x, x if m is None else m, weight, bias, y, y, M, B * T, H, W, 1, float(eps),
+ N=N, C=C, R=rows, LANES=lanes, MODE=0, PAD=0, FUSE_RESIDUAL=m is not None, WRITE_SKIP=False,
+ EVEN_M=(M % rows == 0), OFF64=off64, num_warps=nw)
+ return y.view(B, T, H // 2, W // 2, N)
+
+
+def temporal_merge_ln(x: Tensor, m: Tensor | None, weight: Tensor, bias: Tensor, eps: float = 1e-5,
+ skip: bool = True) -> tuple[Tensor, Tensor | None]:
+ """TemporalMerging glue of bf16(x + m) as one kernel: returns ``(bf16(LayerNorm_fp32(pairs)), skip)`` with
+ pairs (B, Tp/2, H, W, 2C) (Tp = T rounded up to even by front-repeating frame 0) and skip (B, Tp/2, H, W, C)
+ = the 2-frame mean (ATen MeanOps semantics); ``skip=False`` skips the mean."""
+ reason = temporal_merge_unsupported(x, m)
+ if reason is not None:
+ raise ValueError(reason)
+ B, T, H, W, C = x.shape
+ N = 2 * C
+ rows, lanes, nw = _lane_cfg(N)
+ pad = T % 2
+ tp2 = (T + pad) // 2
+ M = B * tp2 * H * W
+ y = torch.empty((M, N), dtype=torch.bfloat16, device=x.device)
+ sk = torch.empty((M, C), dtype=torch.bfloat16, device=x.device) if skip else y
+ off64 = max(M * N, x.numel()) >= 2 ** 31
+ grid = (triton.cdiv(M, rows),)
+ _gather_launch(grid, x, x if m is None else m, weight, bias, y, sk, M, T, H, W, tp2, float(eps),
+ N=N, C=C, R=rows, LANES=lanes, MODE=1, PAD=pad, FUSE_RESIDUAL=m is not None, WRITE_SKIP=bool(skip),
+ EVEN_M=(M % rows == 0), OFF64=off64, num_warps=nw)
+ return y.view(B, tp2, H, W, N), (sk.view(B, tp2, H, W, C) if skip else None)
+
+
+# ------------------------------------------------------------------------------------------- eager references
+def reference_patch_merge(x: Tensor, m: Tensor | None, ln: nn.LayerNorm) -> Tensor:
+ """The eager chain the kernel replaces: bf16 residual add, PatchMerging reshape/permute/flatten, autocast
+ LayerNorm (fp32) cast to bf16 by the consumer."""
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ xr = x + m if m is not None else x
+ B, D, H, W, C = xr.shape
+ z = xr.reshape(B, D, H // 2, 2, W // 2, 2, C).permute(0, 1, 2, 4, 3, 5, 6).flatten(4)
+ return F.layer_norm(z, (4 * C,), ln.weight, ln.bias, ln.eps).to(torch.bfloat16)
+
+
+def reference_temporal_merge(x: Tensor, m: Tensor | None, ln: nn.LayerNorm) -> tuple[Tensor, Tensor]:
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ xr = x + m if m is not None else x
+ B, D, H, W, C = xr.shape
+ if D % 2 == 1:
+ xr = torch.concat([xr[:, :1], xr], dim=1)
+ B, D, H, W, C = xr.shape
+ xx = xr.reshape(B, D // 2, 2, H, W, C)
+ skip = xx.mean(2)
+ z = xx.permute(0, 1, 3, 4, 2, 5).reshape(B, D // 2, H, W, 2 * C)
+ return F.layer_norm(z, (2 * C,), ln.weight, ln.bias, ln.eps).to(torch.bfloat16), skip
+
+
+# ------------------------------------------------------------------------------------------- install
+@dataclass
+class Installed:
+ state: object
+ patched: list = field(default_factory=list) # (module, attr, previous __dict__ entry or None)
+ merges: list = field(default_factory=list) # (index in the flattened sequence, type name)
+ deferring_blocks: list = field(default_factory=list) # stage-final blocks re-patched to defer into the merge
+ options: dict = field(default_factory=dict)
+ fused_calls: int = 0
+ fallback_calls: int = 0
+
+ def info(self) -> dict:
+ return {"installed": True, "options": dict(self.options), "merges": list(self.merges),
+ "stage_final_deferring_blocks": len(self.deferring_blocks), "fused_calls": self.fused_calls,
+ "fallback_calls": self.fallback_calls,
+ "scope": "frozen training encode inside training_fused_context(state) only; bit-exact vs production"}
+
+
+def _block_sequence(encoder: nn.Module) -> list[nn.Module]:
+ seq = []
+ for child in encoder.features:
+ if type(child) is nn.Sequential:
+ seq.extend(child)
+ else:
+ seq.append(child)
+ return seq
+
+
+def _take_pending(state, x: Tensor):
+ """Pop ``state.pending_residual`` and return its delta if it is tagged with ``x`` (else None)."""
+ pending = getattr(state, "pending_residual", None)
+ if pending is None:
+ return None
+ state.pending_residual = None
+ return pending[1] if pending[0] is x else None
+
+
+def pm_fused_impl(self, x: Tensor, m: Tensor | None) -> Tensor:
+ """Production PatchMerging body: gather-LN kernel (residual m folded in) then the reduction GEMM."""
+ return self.reduction(patch_merge_ln(x, m, self.norm.weight, self.norm.bias, self.norm.eps))
+
+
+def tm_fused_impl(self, x: Tensor, m: Tensor | None) -> Tensor:
+ """Production TemporalMerging body: gather-LN kernel (+ skip mean) then the reduction GEMM and the skip add."""
+ y, skip = temporal_merge_ln(x, m, self.norm.weight, self.norm.bias, self.norm.eps)
+ return self.reduction(y) + skip
+
+
+def install(vae_module, state, *, require_kernel: bool = False, patch_merging: bool = True,
+ temporal_merging: bool = True, pm_impl=pm_fused_impl, tm_impl=tm_fused_impl) -> Installed:
+ """Patch the encoder's merges (and the blocks preceding them) on top of a ``vae_fused_pointwise`` ``state``
+ that already carries ``vae_qk_fused.install(..., mlp_residual=True)``. Returns an ``Installed`` handle for
+ ``uninstall``. ``require_kernel``: raise instead of falling back to eager for unsupported shapes.
+ ``pm_impl`` / ``tm_impl(self, x, m)``: the merge bodies (default: the gather-LN kernels; the bench passes
+ timing-only emulations here)."""
+ from flux_action.models import vae_fused_pointwise as vfp
+ from flux_action.models import video_vae as vv
+
+ module = getattr(vae_module, "module", vae_module)
+ encoder = module.model.encoder
+ if not (state.options.get("residual_ln") and state.options.get("layer_norm")):
+ raise RuntimeError("install needs a vae_fused_pointwise state with layer_norm and residual_ln")
+ if not hasattr(state, "pending_residual"):
+ state.pending_residual = None
+ inst = Installed(state=state, options=dict(require_kernel=require_kernel, patch_merging=patch_merging,
+ temporal_merging=temporal_merging,
+ impl=(pm_impl.__name__, tm_impl.__name__)))
+
+ def patch(mod, name, fn):
+ inst.patched.append((mod, name, mod.__dict__.get(name)))
+ setattr(mod, name, types.MethodType(fn, mod))
+
+ def fused_ok(x):
+ return (state.enabled and type(x) is Tensor and x.dtype == torch.bfloat16 and x.is_cuda
+ and not torch.is_grad_enabled())
+
+ def pm_forward(self, x, _inst=inst):
+ if not fused_ok(x):
+ return vv.PatchMerging.forward(self, x)
+ m = _take_pending(state, x)
+ reason = patch_merge_unsupported(x, m)
+ if reason is not None:
+ if require_kernel:
+ raise RuntimeError(f"PatchMerging {tuple(x.shape)}: {reason}")
+ _inst.fallback_calls += 1
+ if m is not None:
+ x = x + m
+ return vv.PatchMerging.forward(self, x)
+ _inst.fused_calls += 1
+ return pm_impl(self, x, m)
+
+ def tm_forward(self, x, _inst=inst):
+ if not fused_ok(x):
+ return vv.TemporalMerging.forward(self, x)
+ m = _take_pending(state, x)
+ reason = temporal_merge_unsupported(x, m)
+ if reason is not None:
+ if require_kernel:
+ raise RuntimeError(f"TemporalMerging {tuple(x.shape)}: {reason}")
+ _inst.fallback_calls += 1
+ if m is not None:
+ x = x + m
+ return vv.TemporalMerging.forward(self, x)
+ _inst.fused_calls += 1
+ return tm_impl(self, x, m)
+
+ def forward_full_defer(self, x):
+ """``vae_qk_fused`` block forward with the MLP residual always deferred (the following merge consumes it)."""
+ ok = fused_ok(x)
+ pending = state.pending_residual
+ if pending is not None:
+ state.pending_residual = None
+ if pending is not None and pending[0] is x and ok and pending[1].shape == x.shape:
+ x, h1 = vfp.residual_layer_norm_bf16(x, pending[1], self.norm1.weight, self.norm1.bias, self.norm1.eps)
+ a = self.attn(h1)
+ else:
+ if pending is not None and pending[0] is x:
+ x = x + pending[1]
+ if state.pending_bias is not None:
+ bias, state.pending_bias = state.pending_bias, None
+ x, h1 = vfp.residual_layer_norm_bf16(x, bias, self.norm1.weight, self.norm1.bias, self.norm1.eps)
+ a = self.attn(h1)
+ else:
+ a = self.attn(self.norm1(x))
+ if ok and a.dtype == torch.bfloat16 and x.shape == a.shape:
+ x, h = vfp.residual_layer_norm_bf16(x, a, self.norm2.weight, self.norm2.bias, self.norm2.eps)
+ else:
+ x = x + a
+ h = self.norm2(x)
+ m = self.mlp(h)
+ if ok and m.dtype == torch.bfloat16 and m.shape == x.shape:
+ state.pending_residual = (x, m) # consumed by the merge's gather-LN kernel (or materialised there)
+ return x
+ return x + m
+
+ seq = _block_sequence(encoder)
+ fused_types = tuple(t for t, on in ((vv.PatchMerging, patch_merging), (vv.TemporalMerging, temporal_merging)) if on)
+ for i, mod in enumerate(seq):
+ if type(mod) is vv.PatchMerging and patch_merging:
+ assert type(mod.norm) is nn.LayerNorm and mod.norm.weight.dtype == torch.bfloat16
+ patch(mod, "forward", pm_forward)
+ inst.merges.append((i, "PatchMerging"))
+ elif type(mod) is vv.TemporalMerging and temporal_merging:
+ assert type(mod.norm) is nn.LayerNorm and mod.norm.weight.dtype == torch.bfloat16
+ patch(mod, "forward", tm_forward)
+ inst.merges.append((i, "TemporalMerging"))
+ for i, blk in enumerate(seq):
+ if type(blk) is vv.SwinTransformerBlock and i + 1 < len(seq) and type(seq[i + 1]) in fused_types:
+ patch(blk, "_forward_full", forward_full_defer)
+ inst.deferring_blocks.append(i)
+ return inst
+
+
+def uninstall(inst: Installed) -> None:
+ inst.state.pending_residual = None
+ for mod, name, prev in reversed(inst.patched):
+ if prev is None:
+ mod.__dict__.pop(name, None)
+ else:
+ setattr(mod, name, prev)
+ inst.patched.clear()
+
+
+# ------------------------------------------------------------------------------------------- self-test
+PM_SHAPES = [(1, 33, 128, 128, 256), (1, 33, 64, 64, 512), (1, 33, 32, 32, 1024)]
+TM_SHAPES = [(1, 33, 16, 16, 2048), (1, 17, 16, 16, 2048)]
+PM_ODD = [(1, 3, 6, 6, 256), (1, 3, 6, 6, 512), (2, 3, 2, 6, 1024), (1, 1, 2, 2, 256)] # masked tiles / B > 1
+TM_ODD = [(1, 1, 16, 16, 2048), (1, 4, 2, 2, 2048), (2, 5, 4, 4, 2048), (1, 7, 3, 5, 2048), (1, 2, 1, 1, 1024)]
+
+
+def compare(a: Tensor, b: Tensor) -> dict:
+ a, b = a.contiguous(), b.contiguous()
+ same = (a.view(torch.int16) == b.view(torch.int16)).sum().item() / a.numel()
+ ulp = (a.view(torch.int16).int() - b.view(torch.int16).int()).abs().max().item()
+ return {"bitwise": same, "max_abs": (a.float() - b.float()).abs().max().item(), "max_bf16_ulp": ulp}
+
+
+@torch.inference_mode()
+def selftest(verbose: bool = True, device: str = "cuda") -> dict:
+ """Bitwise check of patch_merge_ln / temporal_merge_ln (with and without the fused residual) against the eager
+ chain at the production merge shapes plus small odd shapes (masked tiles, B > 1, even T, T = 1)."""
+ torch.manual_seed(0)
+ results, ok = {}, True
+ for shape in PM_SHAPES + PM_ODD:
+ C = shape[-1]
+ ln = nn.LayerNorm(4 * C, eps=1e-5).to(device).bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ x = (torch.randn(shape, device=device) * 2 + 0.5).bfloat16()
+ m = (torch.randn(shape, device=device) * 0.7).bfloat16()
+ r = {"ln": compare(patch_merge_ln(x, None, ln.weight, ln.bias, ln.eps), reference_patch_merge(x, None, ln)),
+ "res_ln": compare(patch_merge_ln(x, m, ln.weight, ln.bias, ln.eps), reference_patch_merge(x, m, ln))}
+ results[f"pm{shape}"] = r
+ ok = ok and all(v["bitwise"] == 1.0 for v in r.values())
+ if verbose:
+ print(f"PatchMerging {shape}", {k: (v["bitwise"], v["max_bf16_ulp"]) for k, v in r.items()}, flush=True)
+ for shape in TM_SHAPES + TM_ODD:
+ C = shape[-1]
+ ln = nn.LayerNorm(2 * C, eps=1e-5).to(device).bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ x = (torch.randn(shape, device=device) * 2 + 0.5).bfloat16()
+ m = (torch.randn(shape, device=device) * 0.7).bfloat16()
+ # plant signed zeros so the skip's +0 identity semantics are exercised
+ x[..., :8] = -0.0
+ m[..., :8] = -0.0
+ r = {}
+ for tag, mm in (("ln", None), ("res", m)):
+ y, sk = temporal_merge_ln(x, mm, ln.weight, ln.bias, ln.eps)
+ ry, rsk = reference_temporal_merge(x, mm, ln)
+ r[f"{tag}_ln"] = compare(y, ry)
+ r[f"{tag}_skip"] = compare(sk, rsk)
+ results[f"tm{shape}"] = r
+ ok = ok and all(v["bitwise"] == 1.0 for v in r.values())
+ if verbose:
+ print(f"TemporalMerging {shape}", {k: (v["bitwise"], v["max_bf16_ulp"]) for k, v in r.items()}, flush=True)
+ results["all_bit_exact"] = ok
+ if verbose:
+ print("ALL BIT-EXACT:", ok)
+ return results
+
+
+if __name__ == "__main__":
+ raise SystemExit(0 if selftest()["all_bit_exact"] else 1)
diff --git a/flux-umi/src/flux_action/models/vae_na3d_triton.py b/flux-umi/src/flux_action/models/vae_na3d_triton.py
new file mode 100644
index 0000000000000000000000000000000000000000..212e36de382b7aa02ef950d6239925aa5f705f91
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_na3d_triton.py
@@ -0,0 +1,322 @@
+"""Triton forward kernel for 3-D neighborhood attention (NATTEN semantics) for the frozen video-VAE encoder.
+
+Operator (see flux_action.models.video_vae.Natten3D._attend):
+ q, k, v: [1, T, H, W, heads, 64] bf16 (q, k dense; v may be the strided QKV-unbind view),
+ kernel_size (5, 5, 5), dilation 1, is_causal (True, False, False), scale 1/8 -> bf16 [1, T, H, W, heads, 64].
+
+NATTEN window semantics (dilation 1):
+ non-causal axis of length L, query index i: keys [s, s + K) with s = clamp(i - K//2, 0, L - K)
+ (window shifted inward at the borders, always exactly K keys; requires L >= K),
+ causal axis: keys [max(0, i - K + 1), i] (1..K keys).
+
+Kernel design: one program = one (query tile (TT, TH, TW), head). The key/value halo of the tile is
+(TT+K-1) frames x (TH+K-1) rows x (TW+K-1) cols; TH = TW = K-1 = 4 makes the spatial halo exactly 8x8 = 64
+keys per frame (no power-of-two padding). The program loops over the halo frames (FPC frames per chunk),
+computes S = Q K^T with tl.dot (bf16 in, fp32 acc), applies the exact per-query window mask (spatial part
+pre-computed once as an additive bias, temporal part per chunk), runs an online fp32 softmax (exp2 with the
+log2(e)-folded scale) and accumulates O += P V with tl.dot (P rounded to bf16 like NATTEN/FA kernels; a
+fp32-FMA variant exists for the numerics study). Output rows are written once in bf16.
+
+Only the forward is implemented (the VAE is frozen). Nothing here depends on src/flux_action.
+"""
+from __future__ import annotations
+
+import math
+import os
+
+import torch
+import triton
+import triton.language as tl
+
+LOG2E = 1.4426950408889634
+KS = 5 # kernel size on every axis (constexpr below; the production VAE uses (5, 5, 5))
+
+
+@triton.jit(do_not_specialize=["HEADS", "T", "H", "W", "NTT", "NTH", "NTW"])
+def _na3d_fwd_kernel(q_ptr, k_ptr, v_ptr, o_ptr,
+ T, H, W, NTT, NTH, NTW, HEADS,
+ q_st, q_sh, q_sw, q_shd,
+ k_st, k_sh, k_sw, k_shd,
+ v_st, v_sh, v_sw, v_shd,
+ o_st, o_sh, o_sw, o_shd,
+ qk_scale,
+ K: tl.constexpr,
+ TT: tl.constexpr, TH: tl.constexpr, TW: tl.constexpr, TWP: tl.constexpr,
+ HH: tl.constexpr, HW: tl.constexpr, FPC: tl.constexpr,
+ D: tl.constexpr, P_FP32: tl.constexpr, BIAS: tl.constexpr,
+ ORDER: tl.constexpr, P_FP16: tl.constexpr):
+ # ---- program -> (tile, head); head fastest so neighbouring programs touch the same token rows.
+ # ORDER 0: w-tile, h-tile, t-tile (slowest); ORDER 1: t-tile, w-tile, h-tile (slowest) = all frames of a
+ # spatial tile run back to back (K/V halo frames of neighbouring t-tiles overlap by 50 % -> L2 locality).
+ pid = tl.program_id(0)
+ head = pid % HEADS
+ tile = pid // HEADS
+ if ORDER == 0:
+ tw_i = tile % NTW
+ tile = tile // NTW
+ th_i = tile % NTH
+ tt_i = tile // NTH
+ else:
+ tt_i = tile % NTT
+ tile = tile // NTT
+ tw_i = tile % NTW
+ th_i = tile // NTW
+ t0 = tt_i * TT
+ h0 = th_i * TH
+ w0 = tw_i * TW
+
+ R: tl.constexpr = K // 2
+ M: tl.constexpr = TT * TH * TWP
+ NS: tl.constexpr = HH * HW
+ N: tl.constexpr = FPC * NS
+
+ # ---- query coordinates and window starts (flattened T-major / W-fastest inside the tile)
+ m_idx = tl.arange(0, M)
+ qt = t0 + m_idx // (TH * TWP)
+ qh = h0 + (m_idx // TWP) % TH
+ qwl = m_idx % TWP
+ qw = w0 + qwl
+ q_valid = (qt < T) & (qh < H) & (qw < W) & (qwl < TW)
+ sh = tl.minimum(tl.maximum(qh - R, 0), H - K)
+ sw = tl.minimum(tl.maximum(qw - R, 0), W - K)
+
+ # ---- key halo coordinates (same for every frame)
+ hs = tl.minimum(tl.maximum(h0 - R, 0), H - K)
+ ws = tl.minimum(tl.maximum(w0 - R, 0), W - K)
+ n_idx = tl.arange(0, N)
+ kf = n_idx // NS
+ ksp = n_idx % NS
+ kh = hs + ksp // HW
+ kw = ws + ksp % HW
+ k_sp_valid = (kh < H) & (kw < W)
+ if BIAS:
+ sp_ok = ((kh[None, :] >= sh[:, None]) & (kh[None, :] < sh[:, None] + K)
+ & (kw[None, :] >= sw[:, None]) & (kw[None, :] < sw[:, None] + K))
+ bias = tl.where(sp_ok, 0.0, -1.0e9).to(tl.float32)
+
+ d = tl.arange(0, D)
+ q_off = qt.to(tl.int64) * q_st + qh * q_sh + qw * q_sw + head * q_shd
+ q = tl.load(q_ptr + q_off[:, None] + d[None, :], mask=q_valid[:, None], other=0.0)
+ k_sp_off = kh * k_sh + kw * k_sw + head * k_shd
+ v_sp_off = kh * v_sh + kw * v_sw + head * v_shd
+
+ m_i = tl.full([M], float("-inf"), tl.float32)
+ l_i = tl.zeros([M], tl.float32)
+ acc = tl.zeros([M, D], tl.float32)
+
+ t_start = tl.maximum(t0 - (K - 1), 0)
+ t_end = tl.minimum(t0 + TT, T)
+ for kt0 in range(t_start, t_end, FPC):
+ kt = kt0 + kf
+ kvalid = k_sp_valid & (kt < T)
+ k_tile = tl.load(k_ptr + (kt.to(tl.int64) * k_st + k_sp_off)[:, None] + d[None, :],
+ mask=kvalid[:, None], other=0.0)
+ s = tl.dot(q, tl.trans(k_tile)) * qk_scale
+ if BIAS:
+ s = s + bias
+ else:
+ sp_ok = ((kh[None, :] >= sh[:, None]) & (kh[None, :] < sh[:, None] + K)
+ & (kw[None, :] >= sw[:, None]) & (kw[None, :] < sw[:, None] + K))
+ s = tl.where(sp_ok, s, -1.0e9)
+ if FPC == 1:
+ dt = qt - kt0
+ t_ok = (dt >= 0) & (dt < K)
+ s = tl.where(t_ok[:, None], s, -1.0e9)
+ else:
+ dt = qt[:, None] - kt[None, :]
+ s = tl.where((dt >= 0) & (dt < K), s, -1.0e9)
+ m_new = tl.maximum(m_i, tl.max(s, 1))
+ alpha = tl.exp2(m_i - m_new)
+ p = tl.exp2(s - m_new[:, None])
+ l_i = l_i * alpha + tl.sum(p, 1)
+ acc = acc * alpha[:, None]
+ v_tile = tl.load(v_ptr + (kt.to(tl.int64) * v_st + v_sp_off)[:, None] + d[None, :],
+ mask=kvalid[:, None], other=0.0)
+ if P_FP32:
+ acc += tl.dot(p, v_tile.to(tl.float32), input_precision="ieee")
+ elif P_FP16:
+ # P in [0, 1] is exact-range for fp16 (11-bit mantissa vs 8 for bf16); V bf16 -> fp16 is exact
+ # for |v| in [6.1e-5, 65504) (values below lose precision; they cannot matter for the output).
+ acc += tl.dot(p.to(tl.float16), v_tile.to(tl.float16))
+ else:
+ acc += tl.dot(p.to(tl.bfloat16), v_tile)
+ m_i = m_new
+
+ o = acc / l_i[:, None]
+ o_off = qt.to(tl.int64) * o_st + qh * o_sh + qw * o_sw + head * o_shd
+ tl.store(o_ptr + o_off[:, None] + d[None, :], o.to(o_ptr.dtype.element_ty), mask=q_valid[:, None])
+
+
+# ----------------------------------------------------------------------------- host side
+class Config:
+ """Tile configuration: TT x TH x TW queries per program, FPC halo frames per softmax chunk."""
+
+ def __init__(self, TT=4, TH=4, TW=4, FPC=1, num_warps=4, num_stages=2, bias=True, order=0, p_fp16=False,
+ maxnreg=None):
+ self.TT, self.TH, self.TW, self.FPC = int(TT), int(TH), int(TW), int(FPC)
+ self.num_warps, self.num_stages, self.bias = int(num_warps), int(num_stages), bool(bias)
+ self.order, self.p_fp16 = int(order), bool(p_fp16)
+ self.maxnreg = None if maxnreg is None else int(maxnreg)
+
+ @property
+ def TWP(self):
+ return triton.next_power_of_2(self.TW)
+
+ @property
+ def HH(self):
+ return triton.next_power_of_2(self.TH + KS - 1)
+
+ @property
+ def HW(self):
+ return triton.next_power_of_2(self.TW + KS - 1)
+
+ @property
+ def M(self):
+ return self.TT * self.TH * self.TWP
+
+ @property
+ def N(self):
+ return self.FPC * self.HH * self.HW
+
+ def key(self):
+ return (self.TT, self.TH, self.TW, self.FPC, self.num_warps, self.num_stages, self.bias, self.order,
+ self.p_fp16, self.maxnreg)
+
+ def __repr__(self):
+ extra = (f",order={self.order}" if self.order else "") + (",p_fp16" if self.p_fp16 else "") + (
+ f",maxnreg={self.maxnreg}" if self.maxnreg else "")
+ return (f"Config(TT={self.TT},TH={self.TH},TW={self.TW},FPC={self.FPC},nw={self.num_warps},"
+ f"ns={self.num_stages},bias={int(self.bias)}{extra})")
+
+ def to_dict(self):
+ return {"TT": self.TT, "TH": self.TH, "TW": self.TW, "FPC": self.FPC, "num_warps": self.num_warps,
+ "num_stages": self.num_stages, "bias": self.bias, "order": self.order, "p_fp16": self.p_fp16,
+ "maxnreg": self.maxnreg}
+
+ @classmethod
+ def from_dict(cls, d):
+ return cls(**d)
+
+
+DEFAULT_CONFIG = Config(TT=4, TH=4, TW=4, FPC=1, num_warps=4, num_stages=3, bias=True)
+
+# Per-shape configs selected by bench.py (99-config autotune per shape on GPU 7, 2026-10-01); key = (T, H, W, heads).
+# The (4,4,4) tile with one halo frame per chunk, 4 warps and a 3-stage pipeline won on every production shape
+# (2-stage ties on the smallest). Anything missing falls back to DEFAULT_CONFIG.
+SHAPE_CONFIGS: dict[tuple[int, int, int, int], Config] = {
+ (33, 128, 128, 4): Config(4, 4, 4, 1, 4, 3, True),
+ (33, 64, 64, 8): Config(4, 4, 4, 1, 4, 3, True),
+ (33, 32, 32, 16): Config(4, 4, 4, 1, 4, 3, True),
+ (33, 16, 16, 32): Config(4, 4, 4, 1, 4, 3, True),
+ (17, 16, 16, 32): Config(4, 4, 4, 1, 4, 2, True),
+}
+
+
+def pick_config(T, H, W, heads):
+ cfg = SHAPE_CONFIGS.get((int(T), int(H), int(W), int(heads)))
+ return cfg if cfg is not None else DEFAULT_CONFIG
+
+
+def load_shape_configs(path):
+ """Load {"T,H,W,heads": config-dict} written by bench.py."""
+ import json
+
+ data = json.loads(open(path).read())
+ for key, d in data.items():
+ shape = tuple(int(x) for x in key.split(","))
+ SHAPE_CONFIGS[shape] = Config.from_dict(d)
+ return SHAPE_CONFIGS
+
+
+def supported(q, k, v, kernel_size, is_causal, dilation=1):
+ """Return None when the Triton kernel can run this call, else a reason string."""
+ if q.ndim != 6 or q.shape[0] != 1 or q.shape[-1] != 64:
+ return "expects [1, T, H, W, heads, 64]"
+ if q.dtype != torch.bfloat16 or k.dtype != torch.bfloat16 or v.dtype != torch.bfloat16:
+ return "bf16 only"
+ if tuple(kernel_size) != (KS, KS, KS) or tuple(is_causal) != (True, False, False):
+ return "kernel (5,5,5) with causal T only"
+ if isinstance(dilation, (tuple, list)):
+ if any(x != 1 for x in dilation):
+ return "dilation 1 only"
+ elif dilation != 1:
+ return "dilation 1 only"
+ if q.shape != k.shape or q.shape != v.shape:
+ return "q/k/v shapes differ"
+ T, H, W = q.shape[1:4]
+ if T < KS or H < KS or W < KS:
+ return "every axis must be >= kernel size"
+ for x in (q, k, v):
+ if x.stride(-1) != 1 or x.stride(-2) != 64:
+ return "(heads, 64) block must be contiguous"
+ return None
+
+
+def na3d_triton(q, k, v, kernel_size=(5, 5, 5), is_causal=(True, False, False), scale=None, *,
+ config: Config | None = None, out=None, p_fp32=False):
+ """3-D neighborhood attention forward, NATTEN semantics; returns bf16 [1, T, H, W, heads, 64]."""
+ reason = supported(q, k, v, kernel_size, is_causal)
+ if reason is not None:
+ raise ValueError(reason)
+ _, T, H, W, heads, D = q.shape
+ scale = float(D) ** -0.5 if scale is None else float(scale)
+ cfg = config if config is not None else pick_config(T, H, W, heads)
+ if out is None:
+ out = torch.empty((1, T, H, W, heads, D), device=q.device, dtype=q.dtype)
+ NTT, NTH, NTW = (triton.cdiv(T, cfg.TT), triton.cdiv(H, cfg.TH), triton.cdiv(W, cfg.TW))
+ grid = (NTT * NTH * NTW * heads,)
+ extra = {} if cfg.maxnreg is None else {"maxnreg": cfg.maxnreg}
+ _na3d_fwd_kernel[grid](
+ q, k, v, out, T, H, W, NTT, NTH, NTW, heads,
+ q.stride(1), q.stride(2), q.stride(3), q.stride(4),
+ k.stride(1), k.stride(2), k.stride(3), k.stride(4),
+ v.stride(1), v.stride(2), v.stride(3), v.stride(4),
+ out.stride(1), out.stride(2), out.stride(3), out.stride(4),
+ scale * LOG2E,
+ K=KS, TT=cfg.TT, TH=cfg.TH, TW=cfg.TW, TWP=cfg.TWP, HH=cfg.HH, HW=cfg.HW, FPC=cfg.FPC,
+ D=D, P_FP32=bool(p_fp32), BIAS=cfg.bias, ORDER=cfg.order, P_FP16=cfg.p_fp16,
+ num_warps=cfg.num_warps, num_stages=cfg.num_stages, **extra)
+ return out
+
+
+def candidate_configs(T, H, W, heads, *, max_m=128, max_n=256, extended=False):
+ """Autotune space: spatial tile 4x4 (halo 8x8, no padding) with TT in {1,2,4,8}; optionally 4x12 / 12x4
+ tiles (halo 8x16) and two halo frames per chunk."""
+ cands = []
+ spatial = [(4, 4)]
+ if extended:
+ spatial += [(4, 12), (12, 4)]
+ for TH, TW in spatial:
+ if TH > H or TW > W:
+ continue
+ for TT in (1, 2, 4, 8):
+ for FPC in (1, 2):
+ c0 = Config(TT, TH, TW, FPC)
+ if c0.M > max_m or c0.N > max_n or c0.M < 16:
+ continue
+ if (c0.M & (c0.M - 1)) or (c0.N & (c0.N - 1)):
+ continue # tl.arange needs power-of-two extents
+ if TT > T:
+ continue
+ for nw in (2, 4, 8):
+ if c0.M * c0.N // (nw * 32) < 1:
+ continue
+ if nw == 2 and c0.M > 32:
+ continue
+ if nw == 8 and c0.M * c0.N < 64 * 64:
+ continue
+ for ns in (1, 2, 3):
+ for bias in (True,) if c0.M * c0.N <= 64 * 128 else (True, False):
+ cands.append(Config(TT, TH, TW, FPC, nw, ns, bias))
+ return cands
+
+
+def flops_useful(T, H, W, heads, D=64):
+ """Useful FLOPs: every query sees 125 keys except the causal ramp (frames 0..3 see 25*(t+1))."""
+ keys_per_query_t = [KS * KS * min(t + 1, KS) for t in range(T)]
+ pairs = sum(keys_per_query_t) * H * W * heads
+ return 4.0 * pairs * D # QK^T and PV, 2 flops per MAC each
+
+
+def bytes_min(T, H, W, heads, D=64):
+ return 4 * T * H * W * heads * D * 2 # q, k, v read once + o written once (bf16)
diff --git a/flux-umi/src/flux_action/models/vae_na3d_v2.py b/flux-umi/src/flux_action/models/vae_na3d_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..508dad07da83916aa7fc2617ead4b0189c72236a
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_na3d_v2.py
@@ -0,0 +1,633 @@
+"""na3d v2: faster Triton forward for the frozen video-VAE 3-D neighborhood attention (NATTEN semantics).
+
+Same operator / contract as flux_action.models.vae_na3d_triton (q, k, v [1, T, H, W, heads, 64] bf16, kernel (5, 5, 5),
+dilation 1, causal T, scale 1/8 -> bf16), same program decomposition (one program = one (TT x TH x TW query tile, head),
+(TH+4) x (TW+4) = 8 x 8 key halo per frame, frame-at-a-time fp32 online softmax, P in bf16 for the PV MMA).
+
+What changes (all opt-in constexprs, see Config2):
+ MASK_MMA the spatial window mask is folded into the QK^T MMA: a constant [M, 16] one-hot query-feature tile and a
+ constant [16, N] key-feature tile (0 or -2^30 per (feature, halo key)) are multiplied by a second tl.dot that
+ accumulates onto S. Valid entries receive exactly +0.0 (bit-identical S), masked entries receive -2^30 or
+ -2^31. Removes the [M, N] fp32 bias (32 registers/thread) from the loop.
+ TMASK_ROW the per-frame temporal validity is a per-query-ROW property (FPC = 1): instead of a per-element select on S,
+ invalid rows get a huge substitute row max (p = exp2(s*c - 1e30) == 0) and keep their running max / alpha = 1.
+ Removes 32 selp per thread per frame. The running max starts at -1e30 (finite) instead of -inf so that
+ alpha stays well defined; every valid output is bit-identical to the -inf formulation.
+ FUSE_EXP p = exp2(fma(s, c, -m)) (one FFMA) instead of fl(fl(s*c) - m) (FMUL + FSUB): -32 instructions per frame but
+ 1-ulp fp32 differences in the exp2 argument -> not bitwise vs the production kernel (same numerics class).
+ HPP = 2 two heads per program (shared halo index math, interleaved independent softmax chains).
+With MASK_MMA + TMASK_ROW, fp fusion disabled and FUSE_EXP off, the arithmetic performed on every valid S entry is the
+same sequence of fp32 operations as the production kernel -> bit-identical output (verified in test_na3d_v2.py).
+"""
+from __future__ import annotations
+
+import math
+
+import torch
+import triton
+import triton.language as tl
+
+from flux_action.models import vae_na3d_triton as v1
+
+LOG2E = 1.4426950408889634
+KS = 5
+
+# --- MMA-version hook: Triton 3.6 has no knob to pick mma.sync (register accumulators) over tcgen05 (TMEM) on sm_100+.
+# Running only the TTGIR stage with capability 80 selects the Ampere lowering (mma v2 + cp.async pipelining); the
+# LLVM/PTX/cubin stages keep the real target (sm_103a), and mma.sync is a supported instruction there.
+_FORCE_CAP = None
+
+
+def _install_ttgir_hook():
+ import triton.backends.nvidia.compiler as nvc
+
+ orig = nvc.CUDABackend.__dict__["make_ttgir"]
+ if getattr(orig, "_na3d_v2_hook", False):
+ return
+ fn = orig.__func__ if isinstance(orig, staticmethod) else orig
+
+ def hooked(mod, metadata, opt, capability):
+ return fn(mod, metadata, opt, _FORCE_CAP if _FORCE_CAP is not None else capability)
+
+ hooked._na3d_v2_hook = True
+ nvc.CUDABackend.make_ttgir = staticmethod(hooked)
+
+
+# The capability-80 TTGIR hook (mma.sync experiments) is NOT installed here; call _install_ttgir_hook() explicitly
+# in experiments only. Production uses the tcgen05 TMA kernel.
+NEG_BIG = tl.constexpr(-1073741824.0) # -2^30, exact in bf16
+M_INIT = tl.constexpr(-1.0e30) # finite "minus infinity" for the running max (TMASK_ROW)
+M_SUB = tl.constexpr(1.0e30) # substitute row max for temporally invalid rows -> p == 0
+
+
+@triton.jit(do_not_specialize=["HEADS", "T", "H", "W", "NTT", "NTH", "NTW"])
+def _na3d_v2_kernel(q_ptr, k_ptr, v_ptr, o_ptr,
+ T, H, W, NTT, NTH, NTW, HEADS,
+ q_st, q_sh, q_sw, q_shd,
+ k_st, k_sh, k_sw, k_shd,
+ v_st, v_sh, v_sw, v_shd,
+ o_st, o_sh, o_sw, o_shd,
+ qk_scale,
+ K: tl.constexpr,
+ TT: tl.constexpr, TH: tl.constexpr, TW: tl.constexpr, TWP: tl.constexpr,
+ HH: tl.constexpr, HW: tl.constexpr, D: tl.constexpr, DX: tl.constexpr,
+ MASK_MMA: tl.constexpr, TMASK_ROW: tl.constexpr, FUSE_EXP: tl.constexpr,
+ P_FP16: tl.constexpr, ORDER: tl.constexpr, HPP: tl.constexpr, MMA_V2: tl.constexpr):
+ pid = tl.program_id(0)
+ NHP = HEADS // HPP
+ hp = pid % NHP
+ head = hp * HPP
+ tile = pid // NHP
+ if ORDER == 0:
+ tw_i = tile % NTW
+ tile = tile // NTW
+ th_i = tile % NTH
+ tt_i = tile // NTH
+ else:
+ tt_i = tile % NTT
+ tile = tile // NTT
+ tw_i = tile % NTW
+ th_i = tile // NTW
+ t0 = tt_i * TT
+ h0 = th_i * TH
+ w0 = tw_i * TW
+
+ R: tl.constexpr = K // 2
+ M: tl.constexpr = TT * TH * TWP
+ N: tl.constexpr = HH * HW
+
+ # ---- query coordinates and window starts
+ m_idx = tl.arange(0, M)
+ qt = t0 + m_idx // (TH * TWP)
+ qhl = (m_idx // TWP) % TH
+ qwl = m_idx % TWP
+ qh = h0 + qhl
+ qw = w0 + qwl
+ q_valid = (qt < T) & (qh < H) & (qw < W) & (qwl < TW)
+ sh = tl.minimum(tl.maximum(qh - R, 0), H - K)
+ sw = tl.minimum(tl.maximum(qw - R, 0), W - K)
+
+ # ---- key halo coordinates (same for every frame)
+ hs = tl.minimum(tl.maximum(h0 - R, 0), H - K)
+ ws = tl.minimum(tl.maximum(w0 - R, 0), W - K)
+ n_idx = tl.arange(0, N)
+ ka = n_idx // HW
+ kb = n_idx % HW
+ kh = hs + ka
+ kw = ws + kb
+ k_sp_valid = (kh < H) & (kw < W)
+
+ if MASK_MMA:
+ # query features: one-hot of the local h index (cols [0, TH)) and of the local w index (cols [TH, TH+TW))
+ c_idx = tl.arange(0, DX)
+ qf = ((c_idx[None, :] == qhl[:, None]) | (c_idx[None, :] == TH + qwl[:, None])).to(tl.bfloat16)
+ # key features: 0 if halo key (ka, kb) is inside the row / col window of local index c, else -2^30
+ hl_c = c_idx
+ wl_c = c_idx - TH
+ rs_c = tl.minimum(tl.maximum(h0 + hl_c - R, 0), H - K) - hs # window start (halo units) of local row c
+ cs_c = tl.minimum(tl.maximum(w0 + wl_c - R, 0), W - K) - ws
+ row_ok = (ka[None, :] >= rs_c[:, None]) & (ka[None, :] < rs_c[:, None] + K)
+ col_ok = (kb[None, :] >= cs_c[:, None]) & (kb[None, :] < cs_c[:, None] + K)
+ is_row = c_idx[:, None] < TH
+ is_col = (c_idx[:, None] >= TH) & (c_idx[:, None] < TH + TW)
+ kf = tl.where(is_row, tl.where(row_ok, 0.0, NEG_BIG),
+ tl.where(is_col, tl.where(col_ok, 0.0, NEG_BIG), 0.0)).to(tl.bfloat16)
+ else:
+ sp_ok = ((kh[None, :] >= sh[:, None]) & (kh[None, :] < sh[:, None] + K)
+ & (kw[None, :] >= sw[:, None]) & (kw[None, :] < sw[:, None] + K))
+ bias = tl.where(sp_ok, 0.0, -1.0e9).to(tl.float32)
+
+ d = tl.arange(0, D)
+ q_off = qt.to(tl.int64) * q_st + qh * q_sh + qw * q_sw + head * q_shd
+ q = tl.load(q_ptr + q_off[:, None] + d[None, :], mask=q_valid[:, None], other=0.0)
+ if HPP == 2:
+ q1 = tl.load(q_ptr + (q_off + q_shd)[:, None] + d[None, :], mask=q_valid[:, None], other=0.0)
+ k_sp_off = kh * k_sh + kw * k_sw + head * k_shd
+ v_sp_off = kh * v_sh + kw * v_sw + head * v_shd
+
+ if TMASK_ROW:
+ m_i = tl.full([M], M_INIT, tl.float32)
+ else:
+ m_i = tl.full([M], float("-inf"), tl.float32)
+ l_i = tl.zeros([M], tl.float32)
+ acc = tl.zeros([M, D], tl.float32)
+ if HPP == 2:
+ m_i1 = m_i
+ l_i1 = l_i
+ acc1 = acc
+
+ t_start = tl.maximum(t0 - (K - 1), 0)
+ t_end = tl.minimum(t0 + TT, T)
+ for kt0 in range(t_start, t_end):
+ kvalid = k_sp_valid & (kt0 < T)
+ k_row = (kt0.to(tl.int64) * k_st + k_sp_off)
+ v_row = (kt0.to(tl.int64) * v_st + v_sp_off)
+ k_tile = tl.load(k_ptr + k_row[:, None] + d[None, :], mask=kvalid[:, None], other=0.0)
+ if HPP == 2:
+ k_tile1 = tl.load(k_ptr + (k_row + k_shd)[:, None] + d[None, :], mask=kvalid[:, None], other=0.0)
+ dt = qt - kt0
+ t_ok = (dt >= 0) & (dt < K)
+
+ s = tl.dot(q, tl.trans(k_tile))
+ if MASK_MMA:
+ s = tl.dot(qf, kf, s)
+ if HPP == 2:
+ s1 = tl.dot(q1, tl.trans(k_tile1))
+ if MASK_MMA:
+ s1 = tl.dot(qf, kf, s1)
+
+ # ---- online softmax, head 0
+ if TMASK_ROW:
+ if FUSE_EXP and MASK_MMA:
+ m_row = tl.max(s, 1) * qk_scale
+ m_new = tl.where(t_ok, tl.maximum(m_i, m_row), m_i)
+ m_used = tl.where(t_ok, m_new, M_SUB)
+ p = tl.exp2(tl.fma(s, qk_scale, -m_used[:, None]))
+ else:
+ if MASK_MMA:
+ s = s * qk_scale
+ else:
+ s = s * qk_scale + bias
+ m_new = tl.where(t_ok, tl.maximum(m_i, tl.max(s, 1)), m_i)
+ m_used = tl.where(t_ok, m_new, M_SUB)
+ p = tl.exp2(s - m_used[:, None])
+ else:
+ if MASK_MMA:
+ s = s * qk_scale
+ else:
+ s = s * qk_scale + bias
+ s = tl.where(t_ok[:, None], s, -1.0e9)
+ m_new = tl.maximum(m_i, tl.max(s, 1))
+ p = tl.exp2(s - m_new[:, None])
+ alpha = tl.exp2(m_i - m_new)
+ l_i = tl.fma(l_i, alpha, tl.sum(p, 1))
+ acc = acc * alpha[:, None]
+ v_tile = tl.load(v_ptr + v_row[:, None] + d[None, :], mask=kvalid[:, None], other=0.0)
+ if P_FP16:
+ acc = tl.dot(p.to(tl.float16), v_tile.to(tl.float16), acc)
+ else:
+ acc = tl.dot(p.to(tl.bfloat16), v_tile, acc)
+ m_i = m_new
+
+ if HPP == 2:
+ if TMASK_ROW:
+ if FUSE_EXP and MASK_MMA:
+ m_row1 = tl.max(s1, 1) * qk_scale
+ m_new1 = tl.where(t_ok, tl.maximum(m_i1, m_row1), m_i1)
+ m_used1 = tl.where(t_ok, m_new1, M_SUB)
+ p1 = tl.exp2(tl.fma(s1, qk_scale, -m_used1[:, None]))
+ else:
+ if MASK_MMA:
+ s1 = s1 * qk_scale
+ else:
+ s1 = s1 * qk_scale + bias
+ m_new1 = tl.where(t_ok, tl.maximum(m_i1, tl.max(s1, 1)), m_i1)
+ m_used1 = tl.where(t_ok, m_new1, M_SUB)
+ p1 = tl.exp2(s1 - m_used1[:, None])
+ else:
+ if MASK_MMA:
+ s1 = s1 * qk_scale
+ else:
+ s1 = s1 * qk_scale + bias
+ s1 = tl.where(t_ok[:, None], s1, -1.0e9)
+ m_new1 = tl.maximum(m_i1, tl.max(s1, 1))
+ p1 = tl.exp2(s1 - m_new1[:, None])
+ alpha1 = tl.exp2(m_i1 - m_new1)
+ l_i1 = tl.fma(l_i1, alpha1, tl.sum(p1, 1))
+ acc1 = acc1 * alpha1[:, None]
+ v_tile1 = tl.load(v_ptr + (v_row + v_shd)[:, None] + d[None, :], mask=kvalid[:, None], other=0.0)
+ if P_FP16:
+ acc1 = tl.dot(p1.to(tl.float16), v_tile1.to(tl.float16), acc1)
+ else:
+ acc1 = tl.dot(p1.to(tl.bfloat16), v_tile1, acc1)
+ m_i1 = m_new1
+
+ o = acc / l_i[:, None]
+ o_off = qt.to(tl.int64) * o_st + qh * o_sh + qw * o_sw + head * o_shd
+ tl.store(o_ptr + o_off[:, None] + d[None, :], o.to(o_ptr.dtype.element_ty), mask=q_valid[:, None])
+ if HPP == 2:
+ o1 = acc1 / l_i1[:, None]
+ tl.store(o_ptr + (o_off + o_shd)[:, None] + d[None, :], o1.to(o_ptr.dtype.element_ty), mask=q_valid[:, None])
+
+
+
+@triton.jit(do_not_specialize=["HEADS", "T", "H", "W", "NTT", "NTH", "NTW"])
+def _na3d_v2_tma_kernel(q_ptr, k_desc, v_desc, o_ptr,
+ T, H, W, NTT, NTH, NTW, HEADS,
+ q_st, q_sh, q_sw, q_shd,
+ o_st, o_sh, o_sw, o_shd,
+ qk_scale,
+ K: tl.constexpr,
+ TT: tl.constexpr, TH: tl.constexpr, TW: tl.constexpr, TWP: tl.constexpr,
+ HH: tl.constexpr, HW: tl.constexpr, D: tl.constexpr,
+ TMASK_ROW: tl.constexpr, P_FP16: tl.constexpr, ORDER: tl.constexpr, MMA_V2: tl.constexpr,
+ HPP: tl.constexpr, RCP_NORM: tl.constexpr, TSHIFT: tl.constexpr):
+ """Same math as _na3d_v2_kernel (MASK_MMA=False) with the K/V halo fetched by TMA: the descriptors view
+ k / v as [T*H, W, heads*64] and one [HH, HW, 64] box per frame = the (kh, kw) halo of one head. Rows beyond H
+ wrap into the next frame (never inside a window -> masked by the bias), rows/cols beyond the tensor are zero-filled."""
+ pid = tl.program_id(0)
+ NHP = HEADS // HPP
+ head = (pid % NHP) * HPP
+ tile = pid // NHP
+ if ORDER == 0:
+ tw_i = tile % NTW
+ tile = tile // NTW
+ th_i = tile % NTH
+ tt_i = tile // NTH
+ else:
+ tt_i = tile % NTT
+ tile = tile // NTT
+ tw_i = tile % NTW
+ th_i = tile // NTW
+ if TSHIFT:
+ # partial t-tile first (T % TT != 0): the remainder tile then costs 1 halo frame instead of K
+ t0 = tt_i * TT + (T - NTT * TT)
+ else:
+ t0 = tt_i * TT
+ h0 = th_i * TH
+ w0 = tw_i * TW
+
+ R: tl.constexpr = K // 2
+ M: tl.constexpr = TT * TH * TWP
+ N: tl.constexpr = HH * HW
+
+ m_idx = tl.arange(0, M)
+ qt = t0 + m_idx // (TH * TWP)
+ qhl = (m_idx // TWP) % TH
+ qwl = m_idx % TWP
+ qh = h0 + qhl
+ qw = w0 + qwl
+ q_valid = (qt >= 0) & (qt < T) & (qh < H) & (qw < W) & (qwl < TW)
+ sh = tl.minimum(tl.maximum(qh - R, 0), H - K)
+ sw = tl.minimum(tl.maximum(qw - R, 0), W - K)
+
+ hs = tl.minimum(tl.maximum(h0 - R, 0), H - K)
+ ws = tl.minimum(tl.maximum(w0 - R, 0), W - K)
+ n_idx = tl.arange(0, N)
+ kh = hs + n_idx // HW
+ kw = ws + n_idx % HW
+ sp_ok = ((kh[None, :] >= sh[:, None]) & (kh[None, :] < sh[:, None] + K)
+ & (kw[None, :] >= sw[:, None]) & (kw[None, :] < sw[:, None] + K))
+ bias = tl.where(sp_ok, 0.0, -1.0e9).to(tl.float32)
+
+ d = tl.arange(0, D)
+ q_off = qt.to(tl.int64) * q_st + qh * q_sh + qw * q_sw + head * q_shd
+ q = tl.load(q_ptr + q_off[:, None] + d[None, :], mask=q_valid[:, None], other=0.0)
+ if HPP == 2:
+ q1 = tl.load(q_ptr + (q_off + q_shd)[:, None] + d[None, :], mask=q_valid[:, None], other=0.0)
+
+ if TMASK_ROW:
+ m_i = tl.full([M], M_INIT, tl.float32)
+ else:
+ m_i = tl.full([M], float("-inf"), tl.float32)
+ l_i = tl.zeros([M], tl.float32)
+ acc = tl.zeros([M, D], tl.float32)
+ if HPP == 2:
+ m_i1 = m_i
+ l_i1 = l_i
+ acc1 = acc
+
+ row0 = hs
+ col0 = ws
+ hd0 = head * D
+ t_start = tl.maximum(t0 - (K - 1), 0)
+ t_end = tl.minimum(t0 + TT, T)
+ for kt0 in range(t_start, t_end):
+ k_box = k_desc.load([kt0 * H + row0, col0, hd0])
+ k_tile = tl.reshape(k_box, [N, D])
+ if HPP == 2:
+ k_box1 = k_desc.load([kt0 * H + row0, col0, hd0 + D])
+ k_tile1 = tl.reshape(k_box1, [N, D])
+ dt = qt - kt0
+ t_ok = (dt >= 0) & (dt < K)
+ s = tl.dot(q, tl.trans(k_tile)) * qk_scale + bias
+ if HPP == 2:
+ s1 = tl.dot(q1, tl.trans(k_tile1)) * qk_scale + bias
+ if TMASK_ROW:
+ m_new = tl.where(t_ok, tl.maximum(m_i, tl.max(s, 1)), m_i)
+ m_used = tl.where(t_ok, m_new, M_SUB)
+ p = tl.exp2(s - m_used[:, None])
+ else:
+ s = tl.where(t_ok[:, None], s, -1.0e9)
+ m_new = tl.maximum(m_i, tl.max(s, 1))
+ p = tl.exp2(s - m_new[:, None])
+ alpha = tl.exp2(m_i - m_new)
+ l_i = tl.fma(l_i, alpha, tl.sum(p, 1))
+ acc = acc * alpha[:, None]
+ v_box = v_desc.load([kt0 * H + row0, col0, hd0])
+ v_tile = tl.reshape(v_box, [N, D])
+ if P_FP16:
+ acc = tl.dot(p.to(tl.float16), v_tile.to(tl.float16), acc)
+ else:
+ acc = tl.dot(p.to(tl.bfloat16), v_tile, acc)
+ m_i = m_new
+ if HPP == 2:
+ if TMASK_ROW:
+ m_new1 = tl.where(t_ok, tl.maximum(m_i1, tl.max(s1, 1)), m_i1)
+ m_used1 = tl.where(t_ok, m_new1, M_SUB)
+ p1 = tl.exp2(s1 - m_used1[:, None])
+ else:
+ s1 = tl.where(t_ok[:, None], s1, -1.0e9)
+ m_new1 = tl.maximum(m_i1, tl.max(s1, 1))
+ p1 = tl.exp2(s1 - m_new1[:, None])
+ alpha1 = tl.exp2(m_i1 - m_new1)
+ l_i1 = tl.fma(l_i1, alpha1, tl.sum(p1, 1))
+ acc1 = acc1 * alpha1[:, None]
+ v_box1 = v_desc.load([kt0 * H + row0, col0, hd0 + D])
+ v_tile1 = tl.reshape(v_box1, [N, D])
+ if P_FP16:
+ acc1 = tl.dot(p1.to(tl.float16), v_tile1.to(tl.float16), acc1)
+ else:
+ acc1 = tl.dot(p1.to(tl.bfloat16), v_tile1, acc1)
+ m_i1 = m_new1
+
+ if RCP_NORM:
+ o = acc * (1.0 / l_i)[:, None]
+ else:
+ o = acc / l_i[:, None]
+ o_off = qt.to(tl.int64) * o_st + qh * o_sh + qw * o_sw + head * o_shd
+ tl.store(o_ptr + o_off[:, None] + d[None, :], o.to(o_ptr.dtype.element_ty), mask=q_valid[:, None])
+ if HPP == 2:
+ if RCP_NORM:
+ o1 = acc1 * (1.0 / l_i1)[:, None]
+ else:
+ o1 = acc1 / l_i1[:, None]
+ tl.store(o_ptr + (o_off + o_shd)[:, None] + d[None, :], o1.to(o_ptr.dtype.element_ty), mask=q_valid[:, None])
+
+
+# ----------------------------------------------------------------------------- host side
+class Config2:
+ def __init__(self, TT=4, TH=4, TW=4, num_warps=4, num_stages=2, mask_mma=True, tmask_row=True, fuse_exp=False,
+ fp_fusion=False, p_fp16=False, order=0, hpp=1, maxnreg=None, mma_v2=False, tma=False,
+ rcp_norm=False, tshift=False):
+ self.tshift = bool(tshift)
+ self.mma_v2 = bool(mma_v2)
+ self.tma = bool(tma)
+ self.rcp_norm = bool(rcp_norm)
+ self.TT, self.TH, self.TW = int(TT), int(TH), int(TW)
+ self.num_warps, self.num_stages = int(num_warps), int(num_stages)
+ self.mask_mma, self.tmask_row, self.fuse_exp = bool(mask_mma), bool(tmask_row), bool(fuse_exp)
+ self.fp_fusion, self.p_fp16, self.order, self.hpp = bool(fp_fusion), bool(p_fp16), int(order), int(hpp)
+ self.maxnreg = None if maxnreg is None else int(maxnreg)
+
+ @property
+ def TWP(self):
+ return triton.next_power_of_2(self.TW)
+
+ @property
+ def HH(self):
+ return triton.next_power_of_2(self.TH + KS - 1)
+
+ @property
+ def HW(self):
+ return triton.next_power_of_2(self.TW + KS - 1)
+
+ @property
+ def M(self):
+ return self.TT * self.TH * self.TWP
+
+ @property
+ def N(self):
+ return self.HH * self.HW
+
+ def key(self):
+ return tuple(self.to_dict().items())
+
+ def to_dict(self):
+ return {"TT": self.TT, "TH": self.TH, "TW": self.TW, "num_warps": self.num_warps,
+ "num_stages": self.num_stages, "mask_mma": self.mask_mma, "tmask_row": self.tmask_row,
+ "fuse_exp": self.fuse_exp, "fp_fusion": self.fp_fusion, "p_fp16": self.p_fp16, "order": self.order,
+ "hpp": self.hpp, "maxnreg": self.maxnreg, "mma_v2": self.mma_v2, "tma": self.tma,
+ "rcp_norm": self.rcp_norm, "tshift": self.tshift}
+
+ @classmethod
+ def from_dict(cls, d):
+ return cls(**d)
+
+ def __repr__(self):
+ flags = []
+ if self.mask_mma:
+ flags.append("mmaMask")
+ if self.tmask_row:
+ flags.append("rowT")
+ if self.fuse_exp:
+ flags.append("fuseExp")
+ if self.fp_fusion:
+ flags.append("fpFusion")
+ if self.p_fp16:
+ flags.append("p16")
+ if self.order:
+ flags.append(f"order{self.order}")
+ if self.hpp != 1:
+ flags.append(f"hpp{self.hpp}")
+ if self.maxnreg:
+ flags.append(f"maxnreg{self.maxnreg}")
+ if self.mma_v2:
+ flags.append("mmaV2")
+ if self.tma:
+ flags.append("tma")
+ if self.rcp_norm:
+ flags.append("rcp")
+ if self.tshift:
+ flags.append("tshift")
+ return (f"Config2(TT={self.TT},TH={self.TH},TW={self.TW},nw={self.num_warps},ns={self.num_stages}"
+ + ("," + ",".join(flags) if flags else "") + ")")
+
+
+# "exact" = bit-identical arithmetic to the production kernel (mask folded into the MMA, row-wise temporal mask, no fp
+# contraction so that s*c and s*c - m stay two roundings, explicit fma for the l update like the production fusion).
+EXACT = Config2(4, 4, 4, 4, 2, mask_mma=True, tmask_row=True, fuse_exp=False, fp_fusion=False)
+# "fused" = same + single-FFMA exp2 argument (1-ulp fp32 differences, same numerics class).
+FUSED = Config2(4, 4, 4, 4, 2, mask_mma=True, tmask_row=True, fuse_exp=True, fp_fusion=True)
+# TMA halo loads + row-wise temporal mask + 4 CTAs/SM (ns=2, maxnreg=128) + partial t-tile first: bit-identical to v1.
+TMA_BEST = Config2(4, 4, 4, 4, 2, mask_mma=False, tmask_row=True, fp_fusion=True, tma=True, maxnreg=128, tshift=True)
+DEFAULT_CONFIG = TMA_BEST
+
+TMA_BEST_ORDER1 = Config2(4, 4, 4, 4, 2, mask_mma=False, tmask_row=True, fp_fusion=True, tma=True, maxnreg=128, tshift=True,
+ order=1)
+# Per-shape selection from bench.py (GPU 1, 2026-10-03): t-fastest program order (order=1) wins on the two large stages
+# (K/V halo frames of neighbouring t-tiles stay L2-resident), the default order on the small ones. Both bit-identical to v1.
+SHAPE_CONFIGS2: dict[tuple[int, int, int, int], Config2] = {
+ (33, 128, 128, 4): TMA_BEST_ORDER1,
+ (33, 64, 64, 8): TMA_BEST_ORDER1,
+ (33, 32, 32, 16): TMA_BEST,
+ (33, 16, 16, 32): TMA_BEST,
+ (17, 16, 16, 32): TMA_BEST,
+}
+
+
+def pick_config(T, H, W, heads):
+ cfg = SHAPE_CONFIGS2.get((int(T), int(H), int(W), int(heads)))
+ return cfg if cfg is not None else DEFAULT_CONFIG
+
+
+def load_shape_configs(path):
+ import json
+
+ data = json.loads(open(path).read())
+ for key, dct in data.items():
+ SHAPE_CONFIGS2[tuple(int(x) for x in key.split(","))] = Config2.from_dict(dct)
+ return SHAPE_CONFIGS2
+
+
+supported = v1.supported
+
+
+def na3d_v2(q, k, v, kernel_size=(5, 5, 5), is_causal=(True, False, False), scale=None, *, config: Config2 | None = None,
+ out=None):
+ reason = supported(q, k, v, kernel_size, is_causal)
+ if reason is not None:
+ raise ValueError(reason)
+ _, T, H, W, heads, D = q.shape
+ scale = float(D) ** -0.5 if scale is None else float(scale)
+ cfg = config if config is not None else pick_config(T, H, W, heads)
+ if heads % cfg.hpp:
+ raise ValueError(f"heads {heads} not divisible by heads-per-program {cfg.hpp}")
+ if out is None:
+ out = torch.empty((1, T, H, W, heads, D), device=q.device, dtype=q.dtype)
+ NTT, NTH, NTW = (triton.cdiv(T, cfg.TT), triton.cdiv(H, cfg.TH), triton.cdiv(W, cfg.TW))
+ grid = (NTT * NTH * NTW * (heads // cfg.hpp),)
+ extra = {} if cfg.maxnreg is None else {"maxnreg": cfg.maxnreg}
+ return _launch(cfg, grid, q, k, v, out, T, H, W, NTT, NTH, NTW, heads, scale, D, extra)
+
+
+def _launch(cfg, grid, q, k, v, out, T, H, W, NTT, NTH, NTW, heads, scale, D, extra):
+ global _FORCE_CAP
+ _FORCE_CAP = 80 if cfg.mma_v2 else None
+ try:
+ return _launch_inner(cfg, grid, q, k, v, out, T, H, W, NTT, NTH, NTW, heads, scale, D, extra)
+ finally:
+ _FORCE_CAP = None
+
+
+def _halo_descriptor(x, T, H, W, heads, D, box_h, box_w):
+ """TMA descriptor viewing x [1, T, H, W, heads, D] (q/k dense or the strided QKV-unbind view of v) as
+ [T*H, W, heads*D] with a [box_h, box_w, D] box (one head's (kh, kw) halo of one frame)."""
+ from triton.tools.tensor_descriptor import TensorDescriptor
+
+ sT, sH, sW, sHD, s1 = x.stride(1), x.stride(2), x.stride(3), x.stride(4), x.stride(5)
+ assert s1 == 1 and sHD == D and sT == H * sH, (x.stride(),)
+ return TensorDescriptor(x, shape=[T * H, W, heads * D], strides=[sH, sW, 1], block_shape=[box_h, box_w, D])
+
+
+def _launch_inner(cfg, grid, q, k, v, out, T, H, W, NTT, NTH, NTW, heads, scale, D, extra):
+ if cfg.tma:
+ if cfg.mask_mma:
+ raise ValueError("tma variant supports mask_mma=False only")
+ k_desc = _halo_descriptor(k, T, H, W, heads, D, cfg.HH, cfg.HW)
+ v_desc = _halo_descriptor(v, T, H, W, heads, D, cfg.HH, cfg.HW)
+ return _na3d_v2_tma_kernel[grid](
+ q, k_desc, v_desc, out, T, H, W, NTT, NTH, NTW, heads,
+ q.stride(1), q.stride(2), q.stride(3), q.stride(4),
+ out.stride(1), out.stride(2), out.stride(3), out.stride(4),
+ scale * LOG2E,
+ K=KS, TT=cfg.TT, TH=cfg.TH, TW=cfg.TW, TWP=cfg.TWP, HH=cfg.HH, HW=cfg.HW, D=D,
+ TMASK_ROW=cfg.tmask_row, P_FP16=cfg.p_fp16, ORDER=cfg.order, MMA_V2=cfg.mma_v2, HPP=cfg.hpp,
+ RCP_NORM=cfg.rcp_norm, TSHIFT=cfg.tshift,
+ num_warps=cfg.num_warps, num_stages=cfg.num_stages, enable_fp_fusion=cfg.fp_fusion, **extra), out
+ if cfg.tshift or cfg.rcp_norm:
+ raise ValueError("tshift / rcp_norm are implemented in the TMA kernel only")
+ return _na3d_v2_kernel[grid](
+ q, k, v, out, T, H, W, NTT, NTH, NTW, heads,
+ q.stride(1), q.stride(2), q.stride(3), q.stride(4),
+ k.stride(1), k.stride(2), k.stride(3), k.stride(4),
+ v.stride(1), v.stride(2), v.stride(3), v.stride(4),
+ out.stride(1), out.stride(2), out.stride(3), out.stride(4),
+ scale * LOG2E,
+ K=KS, TT=cfg.TT, TH=cfg.TH, TW=cfg.TW, TWP=cfg.TWP, HH=cfg.HH, HW=cfg.HW, D=D, DX=16,
+ MASK_MMA=cfg.mask_mma, TMASK_ROW=cfg.tmask_row, FUSE_EXP=cfg.fuse_exp, P_FP16=cfg.p_fp16, ORDER=cfg.order,
+ HPP=cfg.hpp, MMA_V2=cfg.mma_v2, num_warps=cfg.num_warps, num_stages=cfg.num_stages,
+ enable_fp_fusion=cfg.fp_fusion, **extra), out
+
+
+def na3d_v2_out(q, k, v, kernel_size=(5, 5, 5), is_causal=(True, False, False), scale=None, *, config=None, out=None):
+ """Like na3d_v2 but returns only the output tensor (drop-in for v1.na3d_triton)."""
+ return na3d_v2(q, k, v, kernel_size, is_causal, scale, config=config, out=out)[1]
+
+
+def compiled(q, k, v, config, scale=None):
+ """Compile (or fetch) the kernel for these inputs and return the Triton CompiledKernel (asm, metadata)."""
+ handle, _ = na3d_v2(q, k, v, scale=scale, config=config)
+ return handle
+
+
+# ----------------------------------------------------------------------------- install / swap
+_ORIG_V1 = v1.na3d_triton
+_ACTIVE = "v1"
+
+
+def _v2_entry(q, k, v, kernel_size=(5, 5, 5), is_causal=(True, False, False), scale=None, *, config=None, out=None,
+ p_fp32=False):
+ if p_fp32:
+ return _ORIG_V1(q, k, v, kernel_size, is_causal, scale, config=config, out=out, p_fp32=True)
+ cfg = config if isinstance(config, Config2) else None
+ return na3d_v2(q, k, v, kernel_size, is_causal, scale, config=cfg, out=out)[1]
+
+
+def install(which="v2"):
+ """Select the kernel behind flux_action.models.vae_na3d_triton.na3d_triton: "v2" (this module) or "v1" (production).
+
+ vae_natten_no_lse._forward_no_lse looks the function up at call time (``na.na3d_triton``), so rebinding the module
+ attribute switches every frozen-VAE attention call that the no-LSE handle routes to the Triton kernel.
+ """
+ global _ACTIVE
+ if which == "v2":
+ v1.na3d_triton = _v2_entry
+ elif which == "v1":
+ v1.na3d_triton = _ORIG_V1
+ else:
+ raise ValueError(which)
+ _ACTIVE = which
+ return which
+
+
+def active():
+ return _ACTIVE
+
+
+def warmup(shapes, device="cuda", config=None):
+ """Compile the kernel variants for the given (T, H, W, heads) shapes (before any CUDA-graph capture)."""
+ for T, H, W, heads in shapes:
+ z = torch.zeros(1, T, H, W, heads, 64, device=device, dtype=torch.bfloat16)
+ na3d_v2(z, z, z, config=config)
+ torch.cuda.synchronize()
diff --git a/flux-umi/src/flux_action/models/vae_natten_no_lse.py b/flux-umi/src/flux_action/models/vae_natten_no_lse.py
new file mode 100644
index 0000000000000000000000000000000000000000..367015c59e04ca0ff64b5e58904da5f7f5fc12df
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_natten_no_lse.py
@@ -0,0 +1,329 @@
+# Adapted from the installed NATTEN v0.21.6 frozen-forward dispatch.
+#################################################################################################
+# Copyright (c) 2022 - 2026 Ali Hassani.
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+#
+#################################################################################################
+"""Scoped no-LSE dispatch for the frozen training VAE, using stock NATTEN.
+
+The public NATTEN API computes LSE even with return_lse=False. Its installed
+native Blackwell binding accepts None. This adapter retains stock validation,
+backend selection, tile configuration, token permutations and output kernel.
+Only the unused LSE allocation/log/store/inverse permutation is omitted.
+
+No custom backward is supplied: the outer model dispatch requires no-grad
+before entering the private raw-binding helper. No NATTEN object is patched.
+"""
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass
+from functools import lru_cache
+import hashlib
+from importlib.metadata import version
+import inspect
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import torch
+from torch import nn
+
+
+_TRAINING_ENCODING = ContextVar('flux_action_vae_natten_no_lse', default=None)
+_REQUIRE_KERNEL = os.environ.get('FLUX_ACTION_NATTEN_NO_LSE_REQUIRE_KERNEL') == '1'
+_NATTEN_VERSION = '0.21.6+torch2100cu130'
+_SOURCE_HASHES = {'functional.py': 'ea9577494b2d6124a76bf22cf6830cca32f9db2b350afe06ae0d01530bd8ba2d', 'backends/blackwell_fna.py': '8005f1487de5563d74995322fcfce757050bcd71220b17b49cf54c017fbccbd4', '_libnatten/torch_wrappers.py': 'ad53366b800a5edf21b7b0a80d3811e799f7dcb109ecd01aa18c51dec9ae3a4d', 'token_permute/frontend.py': '59feafff3f1e950881e4d86c01fbe5cc1cbe54e2483bc08ddc02c91e4f9a0074', 'token_permute/cutlass_impl.py': '21061dfac34f9ed1a20df72a83061fe675cf3e97e0f3384c8db7ebd8c32e2f23', 'token_permute/torch_impl.py': 'd0be0999d9cf358ea9f7aad34c530ffdce812f934a5d75aa97d2f9ebc149c809', '_environment.py': '2a2f23f018a2197f78ce51f2557d719bed15c9d38d80db33a5008b97c8e1e976', 'backends/configs/cutlass_blackwell/__init__.py': 'b9c0db5575e89e5a1173c4a5e58534972790974c882d054b98979d584ceff043'}
+
+
+@dataclass(frozen=True)
+class TrainingNoLseHandle:
+ # Actual references preserve deepcopy/pickle ownership; IDs would become
+ # stale after copying a policy. This dataclass is not an nn.Module.
+ modules: tuple[nn.Module, ...]
+ names: tuple[str, ...]
+ require_kernel: bool
+ # Fused Triton token permute/unpermute + per-stage q tile (bit-identical attention; see vae_natten_tokperm).
+ triton_tokperm: bool = False
+ # Triton 3-D neighborhood-attention kernel instead of NATTEN's FNA (same error vs fp64, different accumulation
+ # order: approximately lossless; see vae_na3d_triton).
+ triton_na3d: bool = False
+
+
+@lru_cache(maxsize=1)
+def dependency_audit():
+ import natten
+ from natten import libnatten
+ from natten.token_permute import token_permute_operation, token_unpermute_operation
+
+ root = Path(natten.__file__).resolve().parent
+ hashes = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in _SOURCE_HASHES}
+ signatures = {str(dim): getattr(libnatten, f'blackwell_na{dim}d_forward').__doc__ for dim in (2, 3)}
+ defaults = {fn.__name__: inspect.signature(fn).parameters['use_torch'].default
+ for fn in (token_permute_operation, token_unpermute_operation)}
+ return {'natten': version('natten'), 'source_sha256': hashes,
+ 'source_matches': hashes == _SOURCE_HASHES, 'native_signatures': signatures,
+ 'native_optional_lse': all('arg4: torch.Tensor | None' in doc for doc in signatures.values()),
+ 'token_permutation_use_torch_defaults': defaults,
+ 'token_permutation_defaults_supported': all(value is False for value in defaults.values())}
+
+
+def backend_reason():
+ if (str(torch.__version__) != '2.10.0+cu130' or torch.version.cuda != '13.0'
+ or torch.version.git_version != '449b1768410104d3ed79d3bcfe4ba1d65c7f22c0'):
+ return 'unvalidated PyTorch/CUDA build'
+ audit = dependency_audit()
+ if (audit['natten'] != _NATTEN_VERSION or not audit['source_matches'] or not audit['native_optional_lse']
+ or not audit['token_permutation_defaults_supported']):
+ return 'unvalidated NATTEN source or optional-LSE native contract'
+ if os.environ.get('F3_NATTEN_BACKEND', '') not in ('', 'blackwell-fna'):
+ return 'unvalidated VAE backend override'
+ if os.environ.get('NATTEN_TOKPERM_DEFAULT_IMPL', 'cutlass') != 'cutlass':
+ return 'unvalidated token permutation implementation override'
+ return None
+
+
+def _module_reason(module):
+ from .video_vae import Natten3D
+
+ if (type(module) is not Natten3D or module.training or not module.qk_norm
+ or module.head_dim != 64 or module.num_heads not in (4, 8, 16, 32)
+ or tuple(module.window_size) != (5, 5, 5) or module.causal is not True):
+ return 'encoder attention metadata differs from the validated inventory'
+ if any(p.requires_grad or p.dtype != torch.bfloat16 for p in module.parameters()):
+ return 'encoder attention must remain frozen BF16'
+ return None
+
+
+def prepare_training_no_lse(video_vae, *, compile_model=False, triton_tokperm=False, triton_na3d=False):
+ """Validate 23 existing attention modules without changing modules/state.
+
+ ``triton_tokperm`` replaces NATTEN's CUTLASS token permutes by one fused Triton launch (q, k, v) plus one
+ Triton unpermute and selects the forward q tile per stage with the stock kv tile, which keeps the attention
+ output bit-identical.
+ """
+ from .video_vae import Natten3D
+
+ def unsupported(reason):
+ if _REQUIRE_KERNEL:
+ raise RuntimeError(f'Required NATTEN no-LSE configuration failed: {reason}')
+ return None, {'configured': False, 'enabled': False, 'require_kernel': False, 'reason': reason}
+
+ vae = getattr(video_vae, 'module', video_vae)
+ encoder = getattr(getattr(vae, 'model', None), 'encoder', None)
+ if compile_model or getattr(vae, '_encoder_compiled', False):
+ return unsupported('compiled VAE is outside the validated path')
+ if not isinstance(vae, nn.Module) or not isinstance(encoder, nn.Module) or vae.training:
+ return unsupported('unrecognized or non-frozen VAE')
+ if any(p.requires_grad for p in vae.parameters()):
+ return unsupported('VAE parameters must be frozen')
+ candidates = [(name, layer) for name, layer in encoder.named_modules() if isinstance(layer, Natten3D)]
+ expected_heads = (4,) + (8,) * 4 + (16,) * 8 + (32,) * 10
+ if (len(candidates) != 23 or tuple(m.num_heads for _, m in candidates) != expected_heads
+ or any(_module_reason(m) is not None for _, m in candidates)):
+ return unsupported('expected the audited 23 encoder attention modules')
+ reason = backend_reason()
+ if reason is not None:
+ return unsupported(reason)
+ handle = TrainingNoLseHandle(tuple(m for _, m in candidates), tuple(n for n, _ in candidates), _REQUIRE_KERNEL,
+ bool(triton_tokperm), bool(triton_na3d))
+ return handle, {'configured': True, 'enabled': True, 'require_kernel': _REQUIRE_KERNEL,
+ 'triton_tokperm': bool(triton_tokperm), 'triton_na3d': bool(triton_na3d),
+ 'encoder_attention_count': len(candidates), 'expected_encoder_attention_count': 23,
+ 'module_names': list(handle.names), 'dependencies': dependency_audit(),
+ 'validated_device_capability': [10, 3], 'validated_natten_backend': 'blackwell-fna',
+ 'scope': 'registered frozen encoder only, inside training/default _encode_windows',
+ 'parameters_buffers_hooks_and_modules_unchanged': True}
+
+
+@contextmanager
+def training_no_lse_context(handle=None):
+ # Explicit None masks an outer active context for eval/history/disabled calls.
+ token = _TRAINING_ENCODING.set(handle)
+ try:
+ yield
+ finally:
+ _TRAINING_ENCODING.reset(token)
+
+
+def _dense_stride(shape):
+ stride, running = [], 1
+ for dim in reversed(shape):
+ stride.append(running)
+ running *= dim
+ return tuple(reversed(stride))
+
+
+@lru_cache(maxsize=16)
+def _device_supported(index):
+ return torch.cuda.get_device_capability(index) == (10, 3)
+
+
+def _tensor_reason(module, q, k, v):
+ if torch.is_grad_enabled() or any(x.requires_grad for x in (q, k, v)):
+ return 'no-LSE requires an outer no-grad scope and frozen inputs'
+ if any(type(x) is not torch.Tensor or x.layout != torch.strided for x in (q, k, v)):
+ return 'plain dense tensors required'
+ if (not q.is_cuda or any(x.device != q.device or x.dtype != torch.bfloat16 for x in (q, k, v))):
+ return 'same-device CUDA BF16 tensors required'
+ if not _device_supported(q.device.index):
+ return 'only SM103 has been validated'
+ return _layout_reason(module, q, k, v)
+
+
+def _layout_reason(module, q, k, v):
+ if (q.ndim not in (5, 6) or q.shape != k.shape or q.shape != v.shape
+ or q.shape[0] != 1 or q.shape[-2:] != (module.num_heads, 64)
+ or any(dim < 1 for dim in q.shape)):
+ return 'expected B1 2D/3D encoder attention shape'
+ dense = _dense_stride(q.shape)
+ if any(x.stride() != dense or x.storage_offset() != 0 for x in (q, k)):
+ return 'Q/K must keep the complete dense post-RoPE layout'
+ value_stride = tuple(3 * s for s in dense[:-2]) + dense[-2:]
+ if v.stride() != value_stride or v.storage_offset() != 2 * module.num_heads * 64:
+ return 'V must keep the original QKV-unbind strided view'
+ return None
+
+
+@lru_cache(maxsize=1)
+def _natten_ops():
+ from natten import functional as functional
+ from natten import libnatten
+ from natten.backends import blackwell_fna as backend
+ from natten.token_permute import token_permute_operation, token_unpermute_operation
+
+ return SimpleNamespace(functional=functional, backend=backend,
+ forward={2: libnatten.blackwell_na2d_forward, 3: libnatten.blackwell_na3d_forward},
+ permute=token_permute_operation, unpermute=token_unpermute_operation)
+
+
+def _forward_no_lse(q, k, v, *, kernel_size, is_causal, ops, require_kernel=False, triton_tokperm=False,
+ triton_na3d=False):
+ """Private forward; caller owns the outer no-grad/model/device guards.
+
+ The sequence below follows installed NATTEN functional.py and
+ backends/blackwell_fna.py. Functions remain the installed originals.
+ The explicit ops value permits CPU contract doubles without global patches.
+ """
+ if (torch._C._are_functorch_transforms_active() or torch.autograd.forward_ad._current_level >= 0
+ or torch.jit.is_tracing()):
+ raise RuntimeError('Raw no-LSE forward cannot participate in transforms or tracing')
+ if torch.is_grad_enabled() or any(x.requires_grad for x in (q, k, v)):
+ raise RuntimeError('Raw no-LSE forward cannot participate in autograd')
+ f, b = ops.functional, ops.backend
+ f.na_tensor_checks(q, k, v)
+ f.additional_kv_tensor_checks(q, k, v, None, None)
+ f.check_kernel_schedule(None)
+ dim = q.ndim - 3
+ kernel_size, stride, dilation, causal = f.check_all_args(dim, kernel_size, 1, 1, is_causal)
+ f.check_args_against_input(q, kernel_size=kernel_size, stride=stride, dilation=dilation, is_causal=causal)
+ if f.is_self_attention(q, kernel_size=kernel_size, is_causal=causal, has_additional_attention=False):
+ return None # Original public API owns dense/self-attention semantics.
+ if f.choose_backend(q, k, v, torch_compile=False) != 'blackwell-fna':
+ if require_kernel:
+ raise RuntimeError('Required NATTEN no-LSE cannot change the original selected backend')
+ return None
+ b.na_tensor_checks(q, k, v, must_match_head_dims=True, supports_gqa_mqa=True)
+ assert b.can_run_cutlass_blackwell_fna(q, k, v, raise_error=True)
+ kernel_size, stride, dilation, causal = b.check_all_args(dim, kernel_size, stride, dilation, causal)
+ b.check_args_against_input(q, kernel_size=kernel_size, stride=stride, dilation=dilation, is_causal=causal)
+ q_tile, kv_tile = b.check_cutlass_blackwell_fna_forward_config(input_tensor=q, q_tile_shape=None, kv_tile_shape=None)
+ # Keep the original forward-time backward-configuration validation, even
+ # though this frozen path has no backward and never allocates saved LSE.
+ b.check_cutlass_blackwell_fna_backward_config(input_tensor=q, q_tile_shape=None, kv_tile_shape=None)
+ kernel_size, stride, dilation, causal = b.check_all_args(dim, kernel_size, stride, dilation, causal)
+ if triton_na3d and dim == 3:
+ from . import vae_na3d_triton as na
+
+ if na.supported(q, k, v, kernel_size, causal) is None:
+ return na.na3d_triton(q, k, v, tuple(kernel_size), tuple(causal), q.shape[-1] ** -0.5)
+ if require_kernel:
+ raise RuntimeError(f'Required Triton NA3D kernel does not support this call: '
+ f'{na.supported(q, k, v, kernel_size, causal)}')
+ if triton_tokperm and dim == 3 and q.shape[0] == 1 and q.shape[-1] == 64 and all(d == 1 for d in dilation):
+ return _forward_no_lse_triton(q, k, v, kernel_size, stride, dilation, causal, ops, kv_tile)
+ qp, qkv_shape, q_shape = ops.permute(q, tile_shape=q_tile, dilation=dilation, flip_tiled_dims=True)
+ kp, _, k_shape = ops.permute(k, tile_shape=kv_tile, dilation=dilation, flip_tiled_dims=True)
+ vp, _, v_shape = ops.permute(v, tile_shape=kv_tile, dilation=dilation, flip_tiled_dims=True)
+ assert k_shape == v_shape
+ # Original token frontend already compacts V; retain all explicit contiguity
+ # calls made by the autograd forward and registered torch wrapper.
+ qp, kp, vp = [x.contiguous() for x in (qp, kp, vp)]
+ qp, kp, vp = [x.contiguous() for x in (qp, kp, vp)]
+ output = torch.empty([*qp.shape[:-1], vp.shape[-1]], device=qp.device, dtype=qp.dtype)
+ ops.forward[dim](output, qp, kp, vp, None, kernel_size, stride, dilation, causal,
+ q.shape[-1] ** -0.5, q_shape, k_shape, qkv_shape, q_tile, kv_tile, True)
+ return ops.unpermute(output, token_layout_shape=qkv_shape, tile_shape=q_tile,
+ dilation=dilation, flip_tiled_dims=True)
+
+
+_KV_TILE = (4, 4, 8) # stock Blackwell FNA kv tile: fixes the accumulation order
+_Q_TILE_DEFAULT = (8, 4, 8) # stock q tile, best for the 128x128 / 64x64 stages
+_Q_TILE_SMALL = (2, 8, 16) # 5-30 % faster for the 32x32 / 16x16 stages (less temporal padding), bit-identical
+
+
+def choose_q_tile(token_layout):
+ t, h, w = token_layout
+ if h * w <= 32 * 32 and h >= _Q_TILE_SMALL[1] and w >= _Q_TILE_SMALL[2]:
+ return _Q_TILE_SMALL
+ return _Q_TILE_DEFAULT
+
+
+def _forward_no_lse_triton(q, k, v, kernel_size, stride, dilation, causal, ops, kv_tile):
+ """Stock raw no-LSE forward with the fused Triton token permutes and the per-stage q tile.
+
+ The CUTLASS permute kernels are index-math bound (~1.1 TB/s); the Triton row gathers run at ~6 TB/s, read
+ the strided QKV-unbind view of v directly and permute q, k, v in one launch. The permuted layouts and the
+ attention output are bit-identical to the stock sequence (the kv tile and kernel are unchanged).
+ """
+ from . import vae_natten_tokperm as tp
+
+ token_layout = tuple(int(x) for x in q.shape[1:4])
+ q_tile, kv_tile = ops.backend.check_cutlass_blackwell_fna_forward_config(
+ input_tensor=q, q_tile_shape=choose_q_tile(token_layout), kv_tile_shape=tuple(kv_tile))
+ q_tile, kv_tile = tuple(q_tile), tuple(kv_tile)
+ qp, kp, vp = tp.token_permute_qkv(q, k, v, q_tile, kv_tile)
+ out = torch.empty((1, qp.shape[1], q.shape[-2], v.shape[-1]), device=q.device, dtype=q.dtype)
+ ops.forward[3](out, qp, kp, vp, None, tuple(kernel_size), tuple(stride), tuple(dilation), tuple(causal),
+ q.shape[-1] ** -0.5, tp.padded(token_layout, q_tile), tp.padded(token_layout, kv_tile),
+ token_layout, q_tile, kv_tile, True)
+ return tp.token_unpermute_3d(out, token_layout, q_tile)
+
+
+def dispatch_training_no_lse(module, q, k, v, *, kernel_size, is_causal):
+ # Match existing VAE dispatch behavior: compiled calls retain stock NATTEN;
+ # strict configured compile_model is rejected before preparing a handle.
+ if (torch.compiler.is_compiling() or torch._C._are_functorch_transforms_active()
+ or torch.autograd.forward_ad._current_level >= 0 or torch.jit.is_tracing()):
+ return None
+ handle = _TRAINING_ENCODING.get()
+ if handle is None or not any(layer is module for layer in handle.modules):
+ return None
+ reason = backend_reason() or _module_reason(module) or _tensor_reason(module, q, k, v)
+ if reason is None:
+ from .video_vae import _natten_backends
+ if any(value != 'blackwell-fna' for value in _natten_backends.values()):
+ reason = 'active VAE backend differs from blackwell-fna'
+ if reason is not None:
+ if handle.require_kernel:
+ raise RuntimeError(f'Required NATTEN no-LSE dispatch failed: {reason}')
+ return None
+ return _forward_no_lse(q, k, v, kernel_size=kernel_size, is_causal=is_causal,
+ ops=_natten_ops(), require_kernel=handle.require_kernel,
+ triton_tokperm=handle.triton_tokperm, triton_na3d=handle.triton_na3d)
diff --git a/flux-umi/src/flux_action/models/vae_natten_tokperm.py b/flux-umi/src/flux_action/models/vae_natten_tokperm.py
new file mode 100644
index 0000000000000000000000000000000000000000..edc320dac39af94ee04a010e49bf27d0338be819
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_natten_tokperm.py
@@ -0,0 +1,192 @@
+"""Triton implementation of NATTEN's 3-D token permute / unpermute (dilation 1, flip_tiled_dims=True).
+
+Layout produced by natten.token_permute (torch_impl._token_permute with flip_tiled_dims=True, dilation=1):
+input x[b, t, h, w, head, d] (token dims T,H,W; tile (tT,tH,tW); padded dims Tp,Hp,Wp; RT=Tp/tT ...)
+output y[b, n, head, d] with
+ n = ((rW*RH + rH)*RT + rT) * (tT*tH*tW) + ((iW*tH + iH)*tT + iT), t = rT*tT+iT, h = rH*tH+iH, w = rW*tW+iW
+i.e. tile grid and intra-tile coordinates are both flattened W-major / T-fastest. Padded tokens are zero.
+
+Every token row (heads*64 bf16) is contiguous in both source and destination, so this is a row gather.
+The fused variant permutes q (q tile), k and v (kv tile) in ONE launch into one buffer; v may be the strided
+QKV-unbind view (token stride 3*heads*64) -- no .contiguous() copy is needed.
+"""
+from __future__ import annotations
+
+import math
+
+import torch
+import triton
+import triton.language as tl
+
+
+@triton.jit
+def _decode_perm_index(n, T, H, W, RT, RH, tT: tl.constexpr, tH: tl.constexpr, tW: tl.constexpr):
+ """Permuted token index n -> (t, h, w, valid)."""
+ tile_size: tl.constexpr = tT * tH * tW
+ tile_idx = n // tile_size
+ intra = n - tile_idx * tile_size
+ rT = tile_idx % RT
+ tmp = tile_idx // RT
+ rH = tmp % RH
+ rW = tmp // RH
+ iT = intra % tT
+ tmp2 = intra // tT
+ iH = tmp2 % tH
+ iW = tmp2 // tH
+ t = rT * tT + iT
+ h = rH * tH + iH
+ w = rW * tW + iW
+ valid = (t < T) & (h < H) & (w < W)
+ return t, h, w, valid
+
+
+@triton.jit
+def _encode_perm_index(t, h, w, RT, RH, tT: tl.constexpr, tH: tl.constexpr, tW: tl.constexpr):
+ """(t, h, w) -> permuted token index n."""
+ tile_size: tl.constexpr = tT * tH * tW
+ rT = t // tT
+ rH = h // tH
+ rW = w // tW
+ iT = t - rT * tT
+ iH = h - rH * tH
+ iW = w - rW * tW
+ return ((rW * RH + rH) * RT + rT) * tile_size + (iW * tH + iH) * tT + iT
+
+
+@triton.jit
+def _permute_rows(x_ptr, sT, sH, sW, y_ptr, n0, Np, T, H, W, RT, RH, R,
+ tT: tl.constexpr, tH: tl.constexpr, tW: tl.constexpr,
+ TB: tl.constexpr, RB: tl.constexpr):
+ n = n0 + tl.arange(0, TB)
+ t, h, w, valid = _decode_perm_index(n, T, H, W, RT, RH, tT, tH, tW)
+ valid = valid & (n < Np)
+ src = x_ptr + (t.to(tl.int64) * sT + h.to(tl.int64) * sH + w.to(tl.int64) * sW)
+ dst = y_ptr + n.to(tl.int64) * R
+ for c0 in range(0, R, RB):
+ cols = c0 + tl.arange(0, RB)
+ cm = cols < R
+ vals = tl.load(src[:, None] + cols[None, :], mask=valid[:, None] & cm[None, :], other=0.0)
+ tl.store(dst[:, None] + cols[None, :], vals, mask=(n < Np)[:, None] & cm[None, :])
+
+
+@triton.jit
+def token_permute_3d_kernel(x_ptr, sT, sH, sW, y_ptr, Np, T, H, W, RT, RH, R,
+ tT: tl.constexpr, tH: tl.constexpr, tW: tl.constexpr,
+ TB: tl.constexpr, RB: tl.constexpr):
+ pid = tl.program_id(0)
+ _permute_rows(x_ptr, sT, sH, sW, y_ptr, pid * TB, Np, T, H, W, RT, RH, R, tT, tH, tW, TB, RB)
+
+
+@triton.jit
+def token_permute_qkv_kernel(q_ptr, k_ptr, v_ptr, qsT, qsH, qsW, ksT, ksH, ksW, vsT, vsH, vsW, y_ptr,
+ Nq, Nkv, nprog_q, nprog_kv, T, H, W, RTq, RHq, RTkv, RHkv, R,
+ qtT: tl.constexpr, qtH: tl.constexpr, qtW: tl.constexpr,
+ ktT: tl.constexpr, ktH: tl.constexpr, ktW: tl.constexpr,
+ TB: tl.constexpr, RB: tl.constexpr):
+ pid = tl.program_id(0)
+ if pid < nprog_q:
+ _permute_rows(q_ptr, qsT, qsH, qsW, y_ptr, pid * TB, Nq, T, H, W, RTq, RHq, R, qtT, qtH, qtW, TB, RB)
+ elif pid < nprog_q + nprog_kv:
+ p = pid - nprog_q
+ _permute_rows(k_ptr, ksT, ksH, ksW, y_ptr + Nq.to(tl.int64) * R, p * TB, Nkv, T, H, W, RTkv, RHkv, R,
+ ktT, ktH, ktW, TB, RB)
+ else:
+ p = pid - nprog_q - nprog_kv
+ _permute_rows(v_ptr, vsT, vsH, vsW, y_ptr + (Nq + Nkv).to(tl.int64) * R, p * TB, Nkv, T, H, W, RTkv, RHkv,
+ R, ktT, ktH, ktW, TB, RB)
+
+
+@triton.jit
+def token_unpermute_3d_kernel(x_ptr, y_ptr, M, T, H, W, RT, RH, R,
+ tT: tl.constexpr, tH: tl.constexpr, tW: tl.constexpr,
+ TB: tl.constexpr, RB: tl.constexpr):
+ """x: permuted [Np, R] -> y: dense [T*H*W, R] (row m = (t*H + h)*W + w)."""
+ pid = tl.program_id(0)
+ m = pid * TB + tl.arange(0, TB)
+ mm = m < M
+ w = m % W
+ tmp = m // W
+ h = tmp % H
+ t = tmp // H
+ n = _encode_perm_index(t, h, w, RT, RH, tT, tH, tW)
+ src = x_ptr + n.to(tl.int64) * R
+ dst = y_ptr + m.to(tl.int64) * R
+ for c0 in range(0, R, RB):
+ cols = c0 + tl.arange(0, RB)
+ cm = cols < R
+ vals = tl.load(src[:, None] + cols[None, :], mask=mm[:, None] & cm[None, :], other=0.0)
+ tl.store(dst[:, None] + cols[None, :], vals, mask=mm[:, None] & cm[None, :])
+
+
+# ----------------------------------------------------------------------------- host wrappers
+def _blocking(R, elems=8192, max_rb=2048):
+ RB = min(triton.next_power_of_2(R), max_rb)
+ TB = max(1, elems // RB)
+ return TB, RB
+
+
+def _row_strides(x):
+ """Token strides (in elements) of a [1, T, H, W, heads, D] tensor whose (heads, D) block is contiguous."""
+ assert x.dim() == 6 and x.shape[0] == 1
+ heads, d = x.shape[-2:]
+ assert x.stride(-1) == 1 and x.stride(-2) == d, "(heads, head_dim) block must be contiguous"
+ return x.stride(1), x.stride(2), x.stride(3), heads * d
+
+
+def padded(token_layout, tile):
+ return tuple(math.ceil(x / t) * t for x, t in zip(token_layout, tile))
+
+
+def token_permute_3d(x, tile, *, out=None, num_warps=4, elems=8192):
+ T, H, W = x.shape[1:4]
+ sT, sH, sW, R = _row_strides(x)
+ Tp, Hp, Wp = padded((T, H, W), tile)
+ Np = Tp * Hp * Wp
+ if out is None:
+ out = torch.empty((1, Np, x.shape[-2], x.shape[-1]), device=x.device, dtype=x.dtype)
+ TB, RB = _blocking(R, elems)
+ grid = (triton.cdiv(Np, TB),)
+ token_permute_3d_kernel[grid](x, sT, sH, sW, out, Np, T, H, W, Tp // tile[0], Hp // tile[1], R,
+ tile[0], tile[1], tile[2], TB, RB, num_warps=num_warps)
+ return out
+
+
+def token_permute_qkv(q, k, v, q_tile, kv_tile, *, buf=None, num_warps=4, elems=8192):
+ """One launch: q -> q-tile layout, k, v -> kv-tile layout. Returns (qp, kp, vp) views of one buffer."""
+ T, H, W = q.shape[1:4]
+ heads, d = q.shape[-2:]
+ qsT, qsH, qsW, R = _row_strides(q)
+ ksT, ksH, ksW, _ = _row_strides(k)
+ vsT, vsH, vsW, _ = _row_strides(v)
+ Nq = math.prod(padded((T, H, W), q_tile))
+ Nkv = math.prod(padded((T, H, W), kv_tile))
+ if buf is None:
+ buf = torch.empty((Nq + 2 * Nkv, heads, d), device=q.device, dtype=q.dtype)
+ TB, RB = _blocking(R, elems)
+ nq, nkv = triton.cdiv(Nq, TB), triton.cdiv(Nkv, TB)
+ Tq, Hq, _ = padded((T, H, W), q_tile)
+ Tk, Hk, _ = padded((T, H, W), kv_tile)
+ token_permute_qkv_kernel[(nq + 2 * nkv,)](
+ q, k, v, qsT, qsH, qsW, ksT, ksH, ksW, vsT, vsH, vsW, buf, Nq, Nkv, nq, nkv, T, H, W,
+ Tq // q_tile[0], Hq // q_tile[1], Tk // kv_tile[0], Hk // kv_tile[1], R,
+ q_tile[0], q_tile[1], q_tile[2], kv_tile[0], kv_tile[1], kv_tile[2], TB, RB, num_warps=num_warps)
+ qp = buf[:Nq].unsqueeze(0)
+ kp = buf[Nq:Nq + Nkv].unsqueeze(0)
+ vp = buf[Nq + Nkv:].unsqueeze(0)
+ return qp, kp, vp
+
+
+def token_unpermute_3d(x, token_layout, tile, *, out=None, num_warps=4, elems=8192):
+ """x: [1, Np, heads, D] permuted -> [1, T, H, W, heads, D] dense."""
+ T, H, W = token_layout
+ heads, d = x.shape[-2:]
+ assert x.is_contiguous()
+ R = heads * d
+ Tp, Hp, _ = padded((T, H, W), tile)
+ M = T * H * W
+ if out is None:
+ out = torch.empty((1, T, H, W, heads, d), device=x.device, dtype=x.dtype)
+ TB, RB = _blocking(R, elems)
+ token_unpermute_3d_kernel[(triton.cdiv(M, TB),)](x, out, M, T, H, W, Tp // tile[0], Hp // tile[1], R,
+ tile[0], tile[1], tile[2], TB, RB, num_warps=num_warps)
+ return out
diff --git a/flux-umi/src/flux_action/models/vae_qk_fused.py b/flux-umi/src/flux_action/models/vae_qk_fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bca5cdc2e7f84fa78a23f8667decac9c9d48793
--- /dev/null
+++ b/flux-umi/src/flux_action/models/vae_qk_fused.py
@@ -0,0 +1,544 @@
+"""Fused Q/K RMSNorm + 3-D half-RoPE (one Triton kernel per attention layer) and deferred MLP residual adds for the
+frozen video-VAE encoder (experiment vae-rmsnorm-rope-fused).
+
+Both features extend ``flux_action.models.vae_fused_pointwise`` (they reuse its ``FusedState``: activation scope,
+RoPE cos/sin table cache, fused residual+LayerNorm kernel) and are installed on top of it by ``install(vae, state)``.
+
+(1) ``qk_norm_rope(q, k, cos, sin)``: reads the q and k thirds of the QKV GEMM output once (the strided
+ ``reshape(b,t,h,w,3,heads,64).unbind(4)`` views, no copy), applies ``nn.RMSNorm(64, eps=1e-5,
+ elementwise_affine=False)`` and the rotate-half RoPE, and writes the dense ``[1,T,H,W,heads,64]`` q and k the
+ NATTEN / Triton NA3D attention consumes (v stays the strided view). It replaces three launches (CuTe RMSNorm
+ on q, on k, CuTe RoPE) and halves the HBM traffic (q, k read and written once instead of twice).
+
+ Arithmetic (bit-exact with the production CuTe pair, which is bit-exact with ATen/eager):
+ * RMSNorm = ATen ``vectorized_layer_norm_kernel``: 16 active lanes x 4
+ contiguous elements, ``sigma2 = fma(x, x, sigma2)`` sequentially within the lane, shfl_down tree with
+ offsets 8, 4, 2, 1 (lane i += lane i+offset), ``mean_sq = sigma2 / 64`` (IEEE division), ``rstd =
+ rsqrt(mean_sq + eps)`` (MUFU approximation, same instruction as ATen's rsqrtf for normal inputs),
+ ``y = bf16(rstd * x)``. The lane tree is written as explicit folds (lanes g and g+8 are the low/high
+ half of the row and live in the same thread; the remaining 4/2/1 folds are layout-independent splits).
+ * RoPE = eager ``q * cos + rotate_half(q) * sin`` on bf16 tensors: each bf16 x bf16 product is rounded to
+ bf16 before the bf16 add (fp32 math, RNE at both places), rotate_half = cat(-x[32:], x[:32]).
+ FMA contraction is disabled (``enable_fp_fusion=False``); fma / div.rn are explicit libdevice calls.
+
+(2) ``install(..., mlp_residual=True)`` defers each SwinTransformerBlock's MLP residual ``x + mlp(norm2(x))`` into
+ the NEXT block's fused residual+LayerNorm1 kernel (``residual_layer_norm_bf16``), exactly like the production
+ ``pending_bias`` mechanism defers the patch-embed conv bias into block 0. Only blocks followed by another block
+ defer (18 of the 23 encoder blocks); the last block of every stage materializes the add because PatchMerging /
+ TemporalMerging consume x directly. The deferred add is tagged with the tensor object it belongs to and only
+ applied to that object, so a stale entry (aborted encode) can never be consumed by a later call. Numerics are
+ unchanged: eager computes bf16(x + bf16(mlp_out)) and the fused kernel performs that same single-rounded add.
+
+Scope: forward-only, frozen encoder inside ``training_fused_context(state)``; everything else (inference profile,
+decoder, grad-enabled calls, unsupported shapes) runs the stock code path. Self-test: ``python vae_qk_fused.py``.
+Triton on sm_103a needs TRITON_PTXAS_PATH / CC / CXX (see env.sh); the module itself sets no environment.
+"""
+from __future__ import annotations
+
+import types
+from dataclasses import dataclass, field
+
+import torch
+import torch.nn.functional as F
+import triton
+import triton.language as tl
+from torch import Tensor, nn
+from triton.language.extra import libdevice
+
+HEAD_DIM = 64
+EPS = 1e-5
+# Tuned on the L20D (SM103): rows (token, head) per program and warps per program.
+QK_ROWS, QK_WARPS, QK_TREE = 32, 4, 0
+# TREE 0 = explicit split/add folds (reduction order fixed by construction, independent of Triton's thread
+# layout; default). TREE 1 = tl.sum xor-butterfly, ~1-2 % faster, but it reproduces ATen's tree only when every
+# thread owns 8 contiguous elements (ROWS >= 8 * warps); other tilings silently change the order.
+
+
+# =============================================================================================== Triton kernel
+# Thread mapping (what Triton's coalescing pass picks for 16-byte-aligned bf16 [ROWS, 32] tiles): 8 contiguous
+# elements per thread, 4 threads per 32-element half row. Thread t of a half row therefore owns ATen lanes 2t and
+# 2t+1 (elements 8t..8t+3 and 8t+4..8t+7); the high half's thread t owns lanes 2t+8, 2t+9. ATen's shfl_down tree
+# (offsets 8, 4, 2, 1 over the 16 active lanes) becomes: offset 8 = low + high half in-thread, offsets 4 and 2 =
+# xor-butterfly over the 4 threads (= tl.sum over a one-element-per-lane axis), offset 1 = even + odd lane in-thread.
+@triton.jit
+def _rms64_lane_partials(x):
+ """x: [ROWS, 32] fp32 half rows -> [ROWS, 4, 2] per-ATen-lane sums of squares (thread t, lane parity).
+ ATen cuRMSOnlineSum: sigma2 = fma(v, v, sigma2) over the lane's 4 contiguous elements, starting from +0."""
+ x5 = tl.reshape(x, [x.shape[0], 4, 2, 2, 2]) # (thread, lane parity, element pair, element parity)
+ a, b = tl.split(x5) # a = elements (0, 2), b = elements (1, 3)
+ e0, e2 = tl.split(a)
+ e1, e3 = tl.split(b)
+ p = libdevice.fma(e0, e0, tl.zeros_like(e0))
+ p = libdevice.fma(e1, e1, p)
+ p = libdevice.fma(e2, e2, p)
+ p = libdevice.fma(e3, e3, p)
+ return p
+
+
+@triton.jit
+def _fold_axis1(x, N: tl.constexpr):
+ """[ROWS, 2N, 2] -> [ROWS, N, 2]: x[:, :N] + x[:, N:] (one shfl_down level; layout-independent)."""
+ y = tl.permute(tl.reshape(x, [x.shape[0], 2, N, 2]), (0, 2, 3, 1))
+ a, b = tl.split(y)
+ return a + b
+
+
+@triton.jit
+def _rms64_rstd(lo, hi, eps, TREE: tl.constexpr):
+ """rstd per row for 64-element rows given as low/high halves [ROWS, 32] fp32, in ATen's reduction order."""
+ a = _rms64_lane_partials(lo) + _rms64_lane_partials(hi) # shfl_down 8: lane i += lane i+8 -> [ROWS, 4, 2]
+ if TREE == 1:
+ even, odd = tl.split(a) # [ROWS, 4]: ATen lanes 2t / 2t+1
+ total = tl.sum(even, axis=1) + tl.sum(odd, axis=1) # xor 2, 1 == shfl_down 4, 2; then shfl_down 1
+ else:
+ b = _fold_axis1(a, 2) # shfl_down 4
+ c = _fold_axis1(b, 1) # shfl_down 2 -> [ROWS, 1, 2]
+ c0, c1 = tl.split(c) # shfl_down 1
+ total = tl.reshape(c0 + c1, [a.shape[0]])
+ mean_sq = libdevice.div_rn(total, tl.zeros_like(total) + 64.0) # sigma2 / float(N)
+ return tl.rsqrt(mean_sq + eps) # rsqrtf(sigma2 / N + eps)
+
+
+@triton.jit
+def _rope_half(x_lo, x_hi, c_lo, c_hi, s_lo, s_hi):
+ """Eager bf16 rotate-half RoPE: every bf16 x bf16 product rounded to bf16, then one bf16-rounded add."""
+ o_lo = (x_lo * c_lo).to(tl.bfloat16).to(tl.float32) + ((-x_hi) * s_lo).to(tl.bfloat16).to(tl.float32)
+ o_hi = (x_hi * c_hi).to(tl.bfloat16).to(tl.float32) + (x_lo * s_hi).to(tl.bfloat16).to(tl.float32)
+ return o_lo.to(tl.bfloat16), o_hi.to(tl.bfloat16)
+
+
+@triton.jit
+def _qk_norm_rope_kernel(q_ptr, k_ptr, cos_ptr, sin_ptr, qo_ptr, ko_ptr, R, POS, eps,
+ src_tok_stride, src_head_stride,
+ HEADS: tl.constexpr, ROWS: tl.constexpr, TREE: tl.constexpr):
+ """Row r = token * HEADS + head. Source rows live at token*src_tok_stride + head*src_head_stride (the QKV
+ unbind views: 3*HEADS*64 and 64), outputs are dense (r * 64), cos/sin rows at (token % POS) * 64."""
+ pid = tl.program_id(0)
+ r = pid * ROWS + tl.arange(0, ROWS)
+ rmask = r < R
+ token = r // HEADS
+ head = r - token * HEADS
+ src = token.to(tl.int64) * src_tok_stride + head.to(tl.int64) * src_head_stride
+ dst = r.to(tl.int64) * 64
+ pos = (token % POS).to(tl.int64) * 64
+ src = tl.multiple_of(src, 64)
+ dst = tl.multiple_of(dst, 64)
+ pos = tl.multiple_of(pos, 64)
+ col = tl.arange(0, 32)
+ m = rmask[:, None] & (col[None, :] < 32)
+ lo = src[:, None] + col[None, :]
+ hi = lo + 32
+ q_lo = tl.load(q_ptr + lo, mask=m, other=0.0).to(tl.float32)
+ q_hi = tl.load(q_ptr + hi, mask=m, other=0.0).to(tl.float32)
+ k_lo = tl.load(k_ptr + lo, mask=m, other=0.0).to(tl.float32)
+ k_hi = tl.load(k_ptr + hi, mask=m, other=0.0).to(tl.float32)
+ tlo = pos[:, None] + col[None, :]
+ thi = tlo + 32
+ c_lo = tl.load(cos_ptr + tlo, mask=m, other=0.0).to(tl.float32)
+ c_hi = tl.load(cos_ptr + thi, mask=m, other=0.0).to(tl.float32)
+ s_lo = tl.load(sin_ptr + tlo, mask=m, other=0.0).to(tl.float32)
+ s_hi = tl.load(sin_ptr + thi, mask=m, other=0.0).to(tl.float32)
+ # --- RMSNorm (bf16 out, like ATen), then RoPE on the bf16 values
+ rq = _rms64_rstd(q_lo, q_hi, eps, TREE)[:, None]
+ rk = _rms64_rstd(k_lo, k_hi, eps, TREE)[:, None]
+ qn_lo = (rq * q_lo).to(tl.bfloat16).to(tl.float32)
+ qn_hi = (rq * q_hi).to(tl.bfloat16).to(tl.float32)
+ kn_lo = (rk * k_lo).to(tl.bfloat16).to(tl.float32)
+ kn_hi = (rk * k_hi).to(tl.bfloat16).to(tl.float32)
+ oq_lo, oq_hi = _rope_half(qn_lo, qn_hi, c_lo, c_hi, s_lo, s_hi)
+ ok_lo, ok_hi = _rope_half(kn_lo, kn_hi, c_lo, c_hi, s_lo, s_hi)
+ dlo = dst[:, None] + col[None, :]
+ dhi = dlo + 32
+ tl.store(qo_ptr + dlo, oq_lo, mask=m)
+ tl.store(qo_ptr + dhi, oq_hi, mask=m)
+ tl.store(ko_ptr + dlo, ok_lo, mask=m)
+ tl.store(ko_ptr + dhi, ok_hi, mask=m)
+
+
+# =============================================================================================== host wrapper
+def unsupported_reason(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor, eps: float = EPS) -> str | None:
+ """Metadata-only contract check (no CUDA work). None = the fused kernel can run."""
+ if torch.compiler.is_compiling():
+ return "torch.compile uses the original modules"
+ if any(type(x) is not Tensor for x in (q, k, cos, sin)):
+ return "tensor subclasses use the original modules"
+ if torch.is_grad_enabled() or any(x.requires_grad for x in (q, k, cos, sin)):
+ return "frozen no-grad tensors are required"
+ if not q.is_cuda or any(x.device != q.device or x.dtype != torch.bfloat16 for x in (q, k, cos, sin)):
+ return "same-device CUDA bf16 tensors are required"
+ if q.ndim != 6 or q.shape[-1] != HEAD_DIM or any(n < 1 for n in q.shape) or k.shape != q.shape:
+ return "q/k must be nonempty (B, T, H, W, heads, 64) with equal shapes"
+ b, t, h, w, heads, _ = q.shape
+ if cos.shape != (1, t, h, w, 1, HEAD_DIM) or sin.shape != cos.shape or not (cos.is_contiguous() and sin.is_contiguous()):
+ return "cos/sin must be contiguous (1, T, H, W, 1, 64)"
+ if q.stride(-1) != 1 or q.stride(-2) != HEAD_DIM or k.stride() != q.stride():
+ return "q/k need a contiguous (heads, 64) block and identical strides"
+ tok = q.stride(3)
+ if q.stride(2) != w * tok or q.stride(1) != h * w * tok or q.stride(0) != t * h * w * tok or tok % 64:
+ return "q/k token strides must be a uniform multiple of 64 (QKV unbind view or dense)"
+ if any(x.data_ptr() % 16 for x in (q, k, cos, sin)):
+ return "16-byte aligned base addresses are required"
+ if eps != EPS:
+ return "only eps=1e-5 was validated"
+ if b * t * h * w * heads > 2 ** 31 - 1:
+ return "row count exceeds int32 grid arithmetic"
+ return None
+
+
+def qk_norm_rope(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor, eps: float = EPS, *, require_kernel: bool = False,
+ rows: int = QK_ROWS, warps: int = QK_WARPS, tree: int = QK_TREE) -> tuple[Tensor, Tensor]:
+ """(RMSNorm64 -> rotate-half RoPE)(q), same for k, in one launch. Returns dense bf16 tensors of q's shape.
+
+ ``q``/``k`` may be the strided ``qkv.view(b,t,h,w,3,heads,64).unbind(4)`` views (read in place). Unsupported
+ inputs fall back to the eager expression (or raise with ``require_kernel``)."""
+ reason = unsupported_reason(q, k, cos, sin, eps)
+ if reason is not None:
+ if require_kernel:
+ raise ValueError(f"fused QK norm/RoPE contract not satisfied: {reason}")
+ return reference_eager(q, k, cos, sin, eps)
+ b, t, h, w, heads, _ = q.shape
+ qo = torch.empty(q.shape, dtype=q.dtype, device=q.device)
+ ko = torch.empty(k.shape, dtype=k.dtype, device=k.device)
+ if tree == 1 and rows < 8 * warps:
+ raise ValueError("TREE=1 needs ROWS >= 8 * num_warps (8 contiguous elements per thread) to keep ATen's order")
+ R = b * t * h * w * heads
+ grid = (triton.cdiv(R, rows),)
+ _qk_norm_rope_kernel[grid](q, k, cos, sin, qo, ko, R, t * h * w, float(eps), q.stride(3), q.stride(4),
+ HEADS=heads, ROWS=rows, TREE=tree, num_warps=warps, enable_fp_fusion=False)
+ return qo, ko
+
+
+# =============================================================================================== references
+def reference_eager(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor, eps: float = EPS) -> tuple[Tensor, Tensor]:
+ """The stock module chain: nn.RMSNorm(64, eps, elementwise_affine=False) on q and k, then
+ RotaryPositionEmbedding3D's bf16 ``x * cos + rotate_half(x) * sin`` with the given tables."""
+ def rot(x):
+ x1, x2 = x.chunk(2, dim=-1)
+ return torch.cat([-x2, x1], dim=-1)
+ qn = F.rms_norm(q, (HEAD_DIM,), None, eps)
+ kn = F.rms_norm(k, (HEAD_DIM,), None, eps)
+ return qn * cos + rot(qn) * sin, kn * cos + rot(kn) * sin
+
+
+def reference_cute(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor, eps: float = EPS) -> tuple[Tensor, Tensor]:
+ """The production pair: CuTe RMSNorm64 on q and on k (strided views in), CuTe half-RoPE."""
+ from flux_action.models.cute_rmsnorm_kernel import rms_norm_cute
+ from flux_action.models.cute_vae_rope_kernel import apply_vae_rope
+
+ qn = rms_norm_cute(q, (HEAD_DIM,), None, eps, require_kernel=True)
+ kn = rms_norm_cute(k, (HEAD_DIM,), None, eps, require_kernel=True)
+ return apply_vae_rope(qn, kn, cos, sin, require_kernel=True)
+
+
+def rope_tables(state, rope: nn.Module, t: int, h: int, w: int, temporal_offset: int, dtype, device):
+ """cos/sin ``(1, T, H, W, 1, 64)`` for ``rope`` from ``state.rope_cache`` (the vae_fused_pointwise cache, same
+ key and the same construction as its patched ``RotaryPositionEmbedding3D.forward``, so the tables are the
+ exact bits production uses)."""
+ key = (id(rope), t, h, w, int(temporal_offset), dtype, device)
+ tables = state.rope_cache.get(key)
+ if tables is None:
+ grids = torch.meshgrid(
+ torch.arange(t, device=device, dtype=torch.float32) + temporal_offset,
+ torch.arange(h, device=device, dtype=torch.float32),
+ torch.arange(w, device=device, dtype=torch.float32), indexing="ij")
+ pos = torch.stack(grids + (torch.zeros_like(grids[0]),), dim=-1)
+ freqs = torch.einsum("...a,af->...af", pos, rope.inv_freq.float())
+ freqs = freqs.reshape(1, t, h, w, 1, -1)
+ freqs = torch.cat([freqs, freqs], dim=-1)
+ tables = (freqs.cos().to(dtype), freqs.sin().to(dtype))
+ state.rope_cache[key] = tables
+ return tables
+
+
+# =============================================================================================== install
+@dataclass
+class Installed:
+ state: object
+ patched: list = field(default_factory=list) # (module, attr, previous __dict__ entry or None)
+ attention_modules: list = field(default_factory=list)
+ deferring_blocks: list = field(default_factory=list)
+ materializing_blocks: list = field(default_factory=list)
+ options: dict = field(default_factory=dict)
+
+ def info(self) -> dict:
+ return {"installed": True, "options": dict(self.options), "attention_fused": len(self.attention_modules),
+ "mlp_residual_deferring_blocks": len(self.deferring_blocks),
+ "mlp_residual_materializing_blocks": len(self.materializing_blocks),
+ "scope": "frozen training encode inside training_fused_context(state) only; bit-exact vs production"}
+
+
+def _block_sequence(encoder: nn.Module) -> list[nn.Module]:
+ """Execution order of ``encoder.features`` with stage Sequentials flattened."""
+ seq = []
+ for child in encoder.features:
+ if type(child) is nn.Sequential:
+ seq.extend(child)
+ else:
+ seq.append(child)
+ return seq
+
+
+def _attn_module_reason(attn, vv) -> str | None:
+ if type(attn) is not vv.Natten3D or not attn.qk_norm or attn.head_dim != HEAD_DIM or attn.training:
+ return "attention metadata differs from the audited encoder inventory"
+ for norm in (attn.q_norm, attn.k_norm):
+ if (not isinstance(norm, nn.RMSNorm) or tuple(norm.normalized_shape) != (HEAD_DIM,) or norm.weight is not None
+ or norm.eps != EPS):
+ return "q/k RMSNorm differs from RMSNorm(64, eps=1e-5, elementwise_affine=False)"
+ rope = attn.rope
+ if (type(rope) is not vv.RotaryPositionEmbedding3D or rope.head_dim != HEAD_DIM or rope.chunk_dim != 16
+ or tuple(rope.inv_freq.shape) != (4, 8)):
+ return "RoPE metadata differs from the audited encoder inventory"
+ return None
+
+
+def install(vae_module, state, *, qk_fused: bool = True, mlp_residual: bool = True, require_kernel: bool = False) -> Installed:
+ """Extend a ``vae_fused_pointwise.install`` ``state`` (its residual_ln and rope_cache options must be on).
+
+ ``qk_fused``: patch ``forward`` of every encoder ``Natten3D`` instance to run the QKV GEMM, the fused
+ RMSNorm+RoPE kernel on the q/k views and the stock ``_attend``/``proj``.
+ ``mlp_residual``: re-patch ``_forward_full`` of every encoder ``SwinTransformerBlock`` to defer the MLP residual
+ add into the next block's fused residual+LN1 kernel (``state.pending_residual``)."""
+ from flux_action.models import video_vae as vv
+ from flux_action.models.vae_fused_pointwise import residual_layer_norm_bf16
+
+ module = getattr(vae_module, "module", vae_module)
+ encoder = module.model.encoder
+ if not (state.options.get("residual_ln") and state.options.get("layer_norm") and state.options.get("rope_cache")):
+ raise RuntimeError("install needs a vae_fused_pointwise state with layer_norm, residual_ln and rope_cache")
+ inst = Installed(state=state, options=dict(qk_fused=qk_fused, mlp_residual=mlp_residual, require_kernel=require_kernel))
+ if not hasattr(state, "pending_residual"):
+ state.pending_residual = None
+
+ def patch(mod, name, fn):
+ inst.patched.append((mod, name, mod.__dict__.get(name)))
+ setattr(mod, name, types.MethodType(fn, mod))
+
+ if qk_fused:
+ for name, attn in encoder.named_modules():
+ if type(attn) is not vv.Natten3D:
+ continue
+ reason = _attn_module_reason(attn, vv)
+ if reason is not None:
+ if require_kernel:
+ raise RuntimeError(f"{name}: {reason}")
+ continue
+
+ def attn_forward(self, x, _state=state, _rk=require_kernel):
+ if not (_state.enabled and type(x) is Tensor and x.dtype == torch.bfloat16 and x.is_cuda
+ and not torch.is_grad_enabled()):
+ return vv.Natten3D.forward(self, x)
+ b, t, h, w, c = x.shape
+ qkv = self.qkv(x)
+ if qkv.dtype != torch.bfloat16:
+ if _rk:
+ raise RuntimeError("fused QK norm/RoPE needs a bf16 QKV projection")
+ return vv.Natten3D.forward(self, x)
+ q, k, v = qkv.view(b, t, h, w, 3, self.num_heads, self.head_dim).unbind(4)
+ cos, sin = rope_tables(_state, self.rope, t, h, w, 0, qkv.dtype, qkv.device)
+ q, k = qk_norm_rope(q, k, cos, sin, self.q_norm.eps, require_kernel=_rk)
+ return self.proj(self._attend(q, k, v).reshape(b, t, h, w, c))
+
+ patch(attn, "forward", attn_forward)
+ inst.attention_modules.append(name)
+
+ if mlp_residual:
+ seq = _block_sequence(encoder)
+ for i, blk in enumerate(seq):
+ if type(blk) is not vv.SwinTransformerBlock:
+ continue
+ defer = i + 1 < len(seq) and type(seq[i + 1]) is vv.SwinTransformerBlock
+
+ def forward_full(self, x, _state=state, _defer=defer):
+ fused_ok = (_state.enabled and type(x) is Tensor and x.dtype == torch.bfloat16 and x.is_cuda
+ and not torch.is_grad_enabled())
+ pending = _state.pending_residual
+ if pending is not None:
+ _state.pending_residual = None
+ if pending is not None and pending[0] is x and fused_ok and pending[1].shape == x.shape:
+ x, h1 = residual_layer_norm_bf16(x, pending[1], self.norm1.weight, self.norm1.bias, self.norm1.eps)
+ a = self.attn(h1)
+ else:
+ if pending is not None and pending[0] is x: # not fusable here: materialize eagerly
+ x = x + pending[1]
+ if _state.pending_bias is not None: # block 0: deferred patch-embed conv bias
+ bias, _state.pending_bias = _state.pending_bias, None
+ x, h1 = residual_layer_norm_bf16(x, bias, self.norm1.weight, self.norm1.bias, self.norm1.eps)
+ a = self.attn(h1)
+ else:
+ a = self.attn(self.norm1(x))
+ if fused_ok and a.dtype == torch.bfloat16 and x.shape == a.shape:
+ x, h = residual_layer_norm_bf16(x, a, self.norm2.weight, self.norm2.bias, self.norm2.eps)
+ else:
+ x = x + a
+ h = self.norm2(x)
+ m = self.mlp(h)
+ if _defer and fused_ok and m.dtype == torch.bfloat16 and m.shape == x.shape:
+ _state.pending_residual = (x, m) # consumed by the next block's residual+LN1 kernel
+ return x
+ return x + m
+
+ patch(blk, "_forward_full", forward_full)
+ (inst.deferring_blocks if defer else inst.materializing_blocks).append(i)
+ return inst
+
+
+def uninstall(inst: Installed) -> None:
+ inst.state.pending_residual = None
+ for mod, name, prev in reversed(inst.patched):
+ if prev is None:
+ mod.__dict__.pop(name, None)
+ else:
+ setattr(mod, name, prev)
+ inst.patched.clear()
+
+
+# =============================================================================================== self-test
+PRODUCTION_SHAPES = [(33, 128, 128, 4), (33, 64, 64, 8), (33, 32, 32, 16), (33, 16, 16, 32), (17, 16, 16, 32)]
+
+
+def compare(a: Tensor, b: Tensor) -> dict:
+ af, bf = a.float(), b.float()
+ diff = (af - bf).abs()
+ res = {"max_abs": diff.max().item(), "rel_l2": (diff.norm() / bf.norm().clamp_min(1e-30)).item()}
+ if a.dtype == b.dtype:
+ neq = a.contiguous().view(torch.int16) != b.contiguous().view(torch.int16)
+ res["bitwise"] = 1.0 - neq.float().mean().item()
+ res["n_bits_differ"] = int(neq.sum().item())
+ return res
+
+
+def make_qkv(shape, seed, device="cuda", scale=1.0):
+ """A QKV-GEMM-like bf16 output [1, T, H, W, 3*heads*64] and its q, k, v unbind views."""
+ t, h, w, heads = shape
+ g = torch.Generator(device=device).manual_seed(seed)
+ qkv = (torch.randn(1, t, h, w, 3 * heads * HEAD_DIM, generator=g, device=device) * scale).to(torch.bfloat16)
+ q, k, v = qkv.view(1, t, h, w, 3, heads, HEAD_DIM).unbind(4)
+ return qkv, q, k, v
+
+
+def make_tables(t, h, w, device="cuda"):
+ """Production tables via the stock construction (base 256, head_dim 64)."""
+ from flux_action.models.video_vae import RotaryPositionEmbedding3D
+
+ class _S: # minimal stand-in for a FusedState
+ rope_cache: dict = {}
+ rope = RotaryPositionEmbedding3D(HEAD_DIM).to(device).bfloat16()
+ return rope_tables(_S, rope, t, h, w, 0, torch.bfloat16, torch.device(device))
+
+
+@torch.inference_mode()
+def selftest(verbose: bool = True, shapes=PRODUCTION_SHAPES, tree: int = QK_TREE) -> dict:
+ """Bitwise check of the fused kernel vs the eager module chain and vs the production CuTe pair."""
+ results = {}
+ ok = True
+ for shape in shapes:
+ t, h, w, heads = shape
+ cos, sin = make_tables(t, h, w)
+ for scale in (1.0, 7.0):
+ _, q, k, v = make_qkv(shape, seed=hash(shape) % 1000 + int(scale), scale=scale)
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ eq, ek = reference_eager(q, k, cos, sin)
+ fq, fk = qk_norm_rope(q, k, cos, sin, require_kernel=True, tree=tree)
+ rec = {"q_vs_eager": compare(fq, eq), "k_vs_eager": compare(fk, ek)}
+ try:
+ cq, ck = reference_cute(q, k, cos, sin)
+ rec["q_vs_cute"] = compare(fq, cq)
+ rec["k_vs_cute"] = compare(fk, ck)
+ rec["cute_vs_eager"] = compare(cq, eq)
+ except Exception as exc: # the CuTe kernels need the validated torch/CuTe DSL build
+ rec["cute_error"] = repr(exc)
+ assert fq.stride() == tuple(torch.empty(q.shape).stride()) and fq.storage_offset() == 0
+ results[f"{shape}_scale{scale}"] = rec
+ exact = all(r["bitwise"] == 1.0 for key, r in rec.items() if key.endswith("_eager") or key.endswith("_cute"))
+ ok = ok and exact
+ if verbose:
+ print(shape, scale, {k_: (v_["bitwise"] if isinstance(v_, dict) else v_) for k_, v_ in rec.items()})
+ # unaligned tail: rows not a multiple of ROWS, batch 2
+ t, h, w, heads = 7, 9, 11, 4
+ cos, sin = make_tables(t, h, w)
+ qkv = torch.randn(2, t, h, w, 3 * heads * HEAD_DIM, device="cuda").to(torch.bfloat16)
+ q, k, _ = qkv.view(2, t, h, w, 3, heads, HEAD_DIM).unbind(4)
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ eq, ek = reference_eager(q, k, cos, sin)
+ fq, fk = qk_norm_rope(q, k, cos, sin, require_kernel=True, tree=tree)
+ rec = {"q_vs_eager": compare(fq, eq), "k_vs_eager": compare(fk, ek)}
+ results["odd_(2,7,9,11,4)"] = rec
+ ok = ok and all(r["bitwise"] == 1.0 for r in rec.values())
+ results["all_bit_exact"] = ok
+ if verbose:
+ print("ALL BIT-EXACT:", ok)
+ return results
+
+
+@torch.inference_mode()
+def selftest_vae(weights: str | None = None, canvas_hw: int = 512, frames: int = 33, n_canvases: int = 2,
+ na3d: bool = True, verbose: bool = True) -> dict:
+ """End-to-end check on a VAE (``weights`` None = random init): the production frozen-encode path (CuTe
+ RMSNorm/RoPE, NATTEN no-LSE [+ Triton NA3D], fused pointwise) vs the same path with ``install(...)`` applied,
+ for qk_fused / mlp_residual / both. Latents must be bitwise identical; returns the comparison dict."""
+ import contextlib
+
+ from flux_action.models.video_vae import load_video_vae
+ from flux_action.models.vae_cute_rmsnorm import install_training_rmsnorm, training_rmsnorm_context
+ from flux_action.models.vae_cute_rope import prepare_training_rope, training_rope_context
+ from flux_action.models.vae_natten_no_lse import prepare_training_no_lse, training_no_lse_context
+ from flux_action.models.vae_fused_pointwise import install_training_fused, training_fused_context
+ from flux_action.processing import packing
+
+ dev = torch.device("cuda")
+ vae = load_video_vae(weights, device=dev)
+ install_training_rmsnorm(vae)
+ rope_handle, _ = prepare_training_rope(vae)
+ nolse, _ = prepare_training_no_lse(vae, triton_tokperm=True, triton_na3d=na3d)
+ state, _ = install_training_fused(vae)
+
+ def encode(video):
+ with contextlib.ExitStack() as st:
+ st.enter_context(training_no_lse_context(nolse))
+ st.enter_context(training_rope_context(rope_handle))
+ st.enter_context(training_rmsnorm_context(True))
+ st.enter_context(training_fused_context(state))
+ st.enter_context(torch.autocast("cuda", dtype=torch.bfloat16))
+ return packing.encode_videos(vae, video, (16, 16), trim_causal_tail=True)
+
+ g = torch.Generator(device=dev).manual_seed(0)
+ vids = [(torch.rand(1, 3, frames, canvas_hw, canvas_hw, generator=g, device=dev) * 2 - 1).to(torch.bfloat16)
+ for _ in range(n_canvases)]
+ ref = [encode(v).clone() for v in vids]
+ results = {"production_repeat": [compare(encode(v), r)["bitwise"] for v, r in zip(vids, ref)]}
+ ok = all(b == 1.0 for b in results["production_repeat"])
+ for name, opts in {"qk": dict(qk_fused=True, mlp_residual=False), "mlp": dict(qk_fused=False, mlp_residual=True),
+ "both": dict(qk_fused=True, mlp_residual=True)}.items():
+ inst = install(vae, state, require_kernel=True, **opts)
+ try:
+ out = [encode(v).clone() for v in vids]
+ finally:
+ uninstall(inst)
+ results[name] = {"latent_vs_production": [compare(o, r) for o, r in zip(out, ref)], "install": inst.info(),
+ "pending_residual_cleared": state.pending_residual is None}
+ ok = ok and all(c["bitwise"] == 1.0 for c in results[name]["latent_vs_production"])
+ if verbose:
+ print(name, [c["bitwise"] for c in results[name]["latent_vs_production"]], results[name]["install"]["attention_fused"],
+ results[name]["install"]["mlp_residual_deferring_blocks"])
+ results["production_after_uninstall"] = [compare(encode(v), r)["bitwise"] for v, r in zip(vids, ref)]
+ ok = ok and all(b == 1.0 for b in results["production_after_uninstall"])
+ results["all_bit_exact"] = ok
+ if verbose:
+ print("VAE LATENTS BIT-EXACT:", ok)
+ return results
+
+
+if __name__ == "__main__":
+ import argparse
+
+ ap = argparse.ArgumentParser(description="fused QK RMSNorm+RoPE / deferred MLP residual self-tests")
+ ap.add_argument("--vae", action="store_true", help="also run the end-to-end VAE check (random-init weights)")
+ ap.add_argument("--weights", default=None, help="VAE safetensors for the end-to-end check (default: random init)")
+ ap.add_argument("--canvas", type=int, default=512)
+ args = ap.parse_args()
+ res = selftest()
+ ok = res["all_bit_exact"]
+ if args.vae or args.weights:
+ ok = selftest_vae(args.weights, canvas_hw=args.canvas)["all_bit_exact"] and ok
+ raise SystemExit(0 if ok else 1)
diff --git a/flux-umi/src/flux_action/models/video_vae.py b/flux-umi/src/flux_action/models/video_vae.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa6eb9df990da40432bc76ff939a0590f50d313c
--- /dev/null
+++ b/flux-umi/src/flux_action/models/video_vae.py
@@ -0,0 +1,994 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Video VAE (ViTNormInference). Swin3D + neighborhood attention with built-in DistributedRunningStats normalization."""
+
+import logging
+import math
+import os
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from functools import partial
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F # noqa: N812
+from natten.functional import na2d, na3d
+from torch import Tensor
+
+logger = logging.getLogger(__name__)
+
+_norm_layer = partial(nn.LayerNorm, eps=1e-5)
+
+# NATTEN neighborhood-attention backend, resolved at first use per tensor
+# layout (2D/3D). Prebuilt NATTEN wheels only carry fused CUTLASS kernels for
+# some GPU architectures, so the fastest supported backend is probed at
+# runtime: blackwell (SM100) > hopper (SM90) > generic CUTLASS > flex-attention
+# (pure torch, runs everywhere at a speed/memory cost). Set $F3_NATTEN_BACKEND
+# (blackwell-fna | hopper-fna | cutlass-fna | flex-fna) to override.
+_NATTEN_BACKEND_ENV = "F3_NATTEN_BACKEND"
+_PERSISTENT_KERNEL_BACKENDS = ("blackwell", "hopper")
+_natten_backends: dict[int, str] = {}
+
+
+def _natten_attention_kwargs(
+ q: Tensor, k: Tensor, v: Tensor, *, kernel_size: list[int], is_causal: list[bool] | None = None
+) -> dict:
+ backend = _natten_backends.get(q.ndim)
+ if backend is None:
+ backend = os.environ.get(_NATTEN_BACKEND_ENV)
+ if not backend:
+ from natten import backends as nb
+
+ if nb.can_run_cutlass_blackwell_fna(q, k, v):
+ backend = "blackwell-fna"
+ elif nb.can_run_cutlass_hopper_fna(q, k, v):
+ backend = "hopper-fna"
+ elif nb.can_run_cutlass_fna(q, k, v):
+ backend = "cutlass-fna"
+ else:
+ backend = "flex-fna" # universal fallback, no compiled kernels needed
+ logger.info("natten backend (%dD tokens): %s", q.ndim - 3, backend)
+ _natten_backends[q.ndim] = backend
+ # A window that covers the whole input along every non-causal axis is plain attention to NATTEN, which
+ # then dispatches to its dense "*-fmha" backends instead of the neighborhood "*-fna" ones.
+ na_dim = q.ndim - 3
+ causal = is_causal or [False] * na_dim
+ if all(kk == s and not c for kk, s, c in zip(kernel_size, q.shape[1 : 1 + na_dim], causal, strict=True)):
+ backend = backend.replace("-fna", "-fmha")
+ kwargs = {"backend": backend}
+ if backend.split("-")[0] in _PERSISTENT_KERNEL_BACKENDS:
+ kwargs["run_persistent_kernel"] = True
+ return kwargs
+
+
+@dataclass
+class ViTNormInferenceParams:
+ z_dim: int = 96
+ embed_dim: int = 256
+ patch_size: list[int] = field(default_factory=lambda: [1, 4, 4])
+ window_size: list[int] = field(default_factory=lambda: [5, 5, 5])
+ enc_depths: list[int] = field(default_factory=lambda: [1, 4, 8, 8])
+ dec_depths: list[int] = field(default_factory=lambda: [1, 4, 8, 8])
+ num_heads: list[int] = field(default_factory=lambda: [4, 8, 16, 32])
+ temporal: list[bool] = field(default_factory=lambda: [False, False, True, True])
+ enc_causal: bool = True
+ dec_causal: bool = False
+ qk_norm: bool = True
+ patch_norm: bool = False
+ dtype: str = "bfloat16"
+ use_compile: bool = True
+ compile_config: dict | None = field(default_factory=lambda: {"dynamic_compile": True})
+ compile_decoder: bool = False
+ chunked_encode: bool = False
+ chunk_size_frames: int = 45
+ chunked_decode: bool = False
+ chunk_size_latent_frames: int = 8
+ chunk_overlap_latent_frames: int = 4
+ # Looped decode: every decoder Swin block runs its attention and MLP over temporal windows of at
+ # most this many frames (plus the attention halo) instead of the whole sequence. Numerically the
+ # full decode, at a fraction of the activation memory. None disables it.
+ decoder_max_t: int | None = None
+
+
+# Full-decode peak ~= ELEM * latent.numel() + FIXED, profiled with the
+# compiled decoder (calibrated at 720p, T_lat 8..64). Linear in latent elements,
+# so it holds across resolutions. Used to pick full vs chunked decode at runtime.
+DECODE_BYTES_PER_LATENT_ELEM = 1.35e6
+DECODE_FIXED_BYTES = 2 * 2**30
+DECODE_SAFETY_FACTOR = 1.25
+
+
+class DistributedRunningStats(nn.Module):
+ """Latent mean and variance of the trained VAE (buffers of the checkpoint); normalizes ``(B, C, ...)``."""
+
+ def __init__(self, num_channels: int, device: str | torch.device | None = None):
+ super().__init__()
+ self.register_buffer("running_mean", torch.zeros(num_channels, device=device))
+ self.register_buffer("running_var", torch.ones(num_channels, device=device))
+ self.register_buffer("initialized", torch.tensor(False, device=device))
+
+ def _shape(self, x: Tensor) -> tuple:
+ return (1, -1) + (1,) * (x.dim() - 2)
+
+ def normalize(self, x: Tensor) -> Tensor:
+ s = self._shape(x)
+ return (x - self.running_mean.view(s)) / self.running_var.sqrt().view(s)
+
+ def denormalize(self, x: Tensor) -> Tensor:
+ s = self._shape(x)
+ return x * self.running_var.sqrt().view(s) + self.running_mean.view(s)
+
+
+class PatchMerging(nn.Module):
+ def __init__(self, dim: int, out_dim: int):
+ super().__init__()
+ self.norm = _norm_layer(4 * dim)
+ self.reduction = nn.Linear(4 * dim, out_dim, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ B, D, H, W, C = x.shape # noqa: N806
+ if H % 2 == 1 or W % 2 == 1:
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
+ B, D, H, W, C = x.shape # noqa: N806
+ x = x.reshape(B, D, H // 2, 2, W // 2, 2, C)
+ x = x.permute(0, 1, 2, 4, 3, 5, 6).flatten(4)
+ return self.reduction(self.norm(x))
+
+
+class TemporalMerging(nn.Module):
+ def __init__(self, dim: int, out_dim: int):
+ super().__init__()
+ self.norm = _norm_layer(2 * dim)
+ self.reduction = nn.Linear(2 * dim, out_dim, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ B, D, H, W, C = x.shape # noqa: N806
+ if D % 2 == 1:
+ x = torch.concat([x[:, :1], x], dim=1)
+ B, D, H, W, C = x.shape # noqa: N806
+ x = x.reshape(B, D // 2, 2, H, W, C)
+ skip = x.mean(2)
+ x = x.permute(0, 1, 3, 4, 2, 5).reshape(B, D // 2, H, W, 2 * C)
+ return self.reduction(self.norm(x)) + skip
+
+
+class PatchExpansion(nn.Module):
+ def __init__(self, dim: int, out_dim: int):
+ super().__init__()
+ self.dim = dim
+ self.out_dim = out_dim
+ self.norm = _norm_layer(dim)
+ self.expansion = nn.Linear(dim, 4 * out_dim, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ B, D, H, W, C = x.shape # noqa: N806
+ assert self.dim == C, "patch channel mismatch"
+ x = self.expansion(self.norm(x))
+ x = x.view(B, D, H, W, 2, 2, self.out_dim)
+ x = x.permute(0, 1, 2, 4, 3, 5, 6).contiguous()
+ return x.view(B, D, H * 2, W * 2, self.out_dim)
+
+
+class TemporalExpansion(nn.Module):
+ def __init__(self, dim: int, out_dim: int):
+ super().__init__()
+ self.dim = dim
+ self.out_dim = out_dim
+ self.norm = _norm_layer(dim)
+ self.expansion = nn.Linear(dim, 2 * out_dim, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ B, D, H, W, C = x.shape # noqa: N806
+ assert self.dim == C, "temporal channel mismatch"
+ x = self.expansion(self.norm(x)) + torch.concat([x, x], -1)
+ x = x.view(B, D, H, W, 2, self.out_dim)
+ x = x.permute(0, 1, 4, 2, 3, 5).contiguous()
+ x = x.view(B, D * 2, H, W, self.out_dim)
+ return x[:, 1:]
+
+
+def _compute_pad_size_3d(
+ size_dhw: tuple[int, int, int], patch_size: tuple[int, int, int]
+) -> tuple[int, int, int]:
+ pad = [(patch_size[i] - size_dhw[i] % patch_size[i]) % patch_size[i] for i in range(3)]
+ return pad[0], pad[1], pad[2]
+
+
+torch.fx.wrap("_compute_pad_size_3d")
+
+
+def _temporal_core_halo(
+ core_start: int, core_end: int, length: int, kernel: int, causal: bool
+) -> tuple[int, int]:
+ """Frame range ``[halo_start, halo_end)`` of a length-``length`` sequence that a looped Swin block must
+ attend over to reproduce frames ``[core_start, core_end)`` of the full-sequence output exactly.
+
+ Neighborhood attention gives frame ``i`` the keys ``[start(i), start(i) + kernel)`` with
+ ``start(i) = clamp(i - kernel // 2, 0, length - kernel)`` (NATTEN shifts the window inward at the
+ edges), or ``[max(0, i - kernel + 1), i]`` when causal. Running the attention on the halo alone applies
+ the same clamping relative to the halo, and the halo is chosen so both agree for every core frame.
+ """
+ if causal:
+ return max(0, core_start - kernel + 1), core_end
+
+ def window_start(index: int) -> int:
+ return min(max(index - kernel // 2, 0), length - kernel)
+
+ return window_start(core_start), window_start(core_end - 1) + kernel
+
+
+class RotaryPositionEmbedding3D(nn.Module):
+ def __init__(self, head_dim: int, base: float = 256.0):
+ super().__init__()
+ assert head_dim % 8 == 0, "head dimension must be divisible by 8"
+ self.head_dim = head_dim
+ self.chunk_dim = head_dim // 4
+
+ axis_inv_freq = 1.0 / (base ** (torch.arange(0, self.chunk_dim, 2).float() / self.chunk_dim))
+ inv_freq = torch.stack(
+ [axis_inv_freq, axis_inv_freq, axis_inv_freq, torch.zeros(self.chunk_dim // 2)]
+ )
+ self.register_buffer("inv_freq", inv_freq)
+
+ def forward(self, q: Tensor, k: Tensor, *, temporal_offset: int | Tensor = 0) -> tuple[Tensor, Tensor]:
+ """Rotate ``q`` and ``k`` ``(B, T, H, W, heads, head_dim)``. ``temporal_offset`` is the absolute time
+ of frame 0, so a window cut out of a longer sequence gets the positions it has in that sequence
+ (a 0-d tensor keeps a compiled looped core from recompiling per window)."""
+ _, t, h, w, _, _ = q.shape
+ device = q.device
+ dtype = q.dtype
+ grids = torch.meshgrid(
+ torch.arange(t, device=device, dtype=torch.float32) + temporal_offset,
+ torch.arange(h, device=device, dtype=torch.float32),
+ torch.arange(w, device=device, dtype=torch.float32),
+ indexing="ij",
+ )
+ pos = torch.stack(grids + (torch.zeros_like(grids[0]),), dim=-1)
+ freqs = torch.einsum("...a,af->...af", pos, self.inv_freq.float())
+ freqs = freqs.reshape(1, t, h, w, 1, -1)
+ freqs = torch.cat([freqs, freqs], dim=-1)
+ # Rotate in bf16 rather than upcasting q/k to fp32, which avoids large
+ # fp32 transients during decode. cos/sin keep full precision from fp32
+ # freqs and cast down only before the products.
+ cos = freqs.cos().to(dtype)
+ sin = freqs.sin().to(dtype)
+ from .vae_cute_rope import dispatch_training_rope
+
+ fused = dispatch_training_rope(self, q, k, cos, sin)
+ if fused is not None:
+ return fused
+ q = q * cos + self._rotate_half(q) * sin
+ k = k * cos + self._rotate_half(k) * sin
+ return q, k
+
+ @staticmethod
+ def _rotate_half(x: Tensor) -> Tensor:
+ x1, x2 = x.chunk(2, dim=-1)
+ return torch.cat([-x2, x1], dim=-1)
+
+
+class Natten3D(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ window_size: list[int],
+ num_heads: int,
+ causal: bool = True,
+ qk_norm: bool = False,
+ ):
+ super().__init__()
+ assert len(window_size) == 3, "expected 3D window"
+ self.window_size = window_size
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.causal = causal
+ self.qk_norm = qk_norm
+
+ self.qkv = nn.Linear(dim, dim * 3)
+ self.proj = nn.Linear(dim, dim)
+ self.rope = RotaryPositionEmbedding3D(self.head_dim)
+ if qk_norm:
+ self.q_norm = nn.RMSNorm(self.head_dim, eps=1e-5, elementwise_affine=False)
+ self.k_norm = nn.RMSNorm(self.head_dim, eps=1e-5, elementwise_affine=False)
+
+ def _qkv(self, x: Tensor) -> tuple[Tensor, Tensor, Tensor]:
+ b, t, h, w, _ = x.shape
+ q, k, v = self.qkv(x).reshape(b, t, h, w, 3, self.num_heads, self.head_dim).unbind(4)
+ if self.qk_norm:
+ q = self.q_norm(q)
+ k = self.k_norm(k)
+ return q, k, v
+
+ def forward_region(
+ self, x: Tensor, *, temporal_offset: Tensor, output_start: int, output_end: int
+ ) -> Tensor:
+ """Attention over the temporal halo ``x`` ``(B, T', H, W, C)`` of a longer sequence, returning only
+ its frames ``[output_start, output_end)``. ``x`` must contain the whole neighborhood of every
+ returned frame and be at least the temporal kernel long (see ``_temporal_core_halo``); the frames
+ are rotated with their absolute times, ``temporal_offset`` being the time of halo frame 0.
+ """
+ b, t, h, w, c = x.shape
+ if not 0 <= output_start < output_end <= t:
+ raise ValueError(f"invalid output frames [{output_start}, {output_end}) for a halo of T={t}")
+ if t < self.window_size[0]:
+ raise ValueError(f"halo T={t} is shorter than the temporal kernel {self.window_size[0]}")
+ q, k, v = self._qkv(x)
+ q, k = self.rope(q, k, temporal_offset=temporal_offset)
+ out = self._attend(q, k, v)[:, output_start:output_end]
+ return self.proj(out.reshape(b, output_end - output_start, h, w, c))
+
+ def forward(self, x: Tensor) -> Tensor:
+ b, t, h, w, c = x.shape
+ q, k, v = self._qkv(x)
+ q, k = self.rope(q, k)
+ return self.proj(self._attend(q, k, v).reshape(b, t, h, w, c))
+
+ def _attend(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
+ """Neighborhood attention over ``(B, T, H, W, heads, head_dim)``; a single frame uses the 2-D kernel."""
+ if q.shape[1] == 1:
+ q2, k2, v2 = q.squeeze(1), k.squeeze(1), v.squeeze(1)
+ kernel = self.window_size[1:]
+ kwargs = _natten_attention_kwargs(q2, k2, v2, kernel_size=kernel)
+ from .vae_natten_no_lse import dispatch_training_no_lse
+
+ out = dispatch_training_no_lse(self, q2, k2, v2, kernel_size=kernel, is_causal=False)
+ if out is not None:
+ return out.unsqueeze(1)
+ return na2d(q2, k2, v2, kernel_size=kernel, attention_kwargs=kwargs).unsqueeze(1)
+ causal = [self.causal, False, False]
+ kwargs = _natten_attention_kwargs(q, k, v, kernel_size=self.window_size, is_causal=causal)
+ from .vae_natten_no_lse import dispatch_training_no_lse
+
+ out = dispatch_training_no_lse(self, q, k, v, kernel_size=self.window_size, is_causal=causal)
+ if out is not None:
+ return out
+ return na3d(q, k, v, is_causal=causal, kernel_size=self.window_size, attention_kwargs=kwargs)
+
+
+class GLU_MLP(nn.Module): # noqa: N801 (vendored name)
+ def __init__(self, dim: int, align_to: int = 64):
+ super().__init__()
+ hidden_dim = align_to * ((int(dim * 8 / 3) + align_to - 1) // align_to)
+ self.gate_up_proj = nn.Linear(dim, 2 * hidden_dim, bias=False)
+ self.down_proj = nn.Linear(hidden_dim, dim, bias=False)
+
+ def forward(self, x: Tensor) -> Tensor:
+ gate, up = self.gate_up_proj(x).chunk(2, dim=-1)
+ return self.down_proj(F.silu(gate) * up)
+
+
+class SwinTransformerBlock(nn.Module):
+ """Pre-norm neighborhood-attention block.
+
+ With ``max_t`` set, the block runs "looped": it produces its output in temporal windows of at most
+ ``max_t`` frames, attending over each window's halo (``_temporal_core_halo``) and applying the MLP to
+ the window only. The result equals the plain forward frame for frame, but the attention and MLP
+ activations are materialized for ``max_t`` plus a few frames at a time instead of the whole sequence,
+ which is what bounds the memory of decoding long videos. The output is written into the input tensor
+ in place, so looped mode requires gradients to be disabled; it is meant for the frozen decoder.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int,
+ window_size: list[int],
+ causal: bool = False,
+ qk_norm: bool = False,
+ max_t: int | None = None,
+ ):
+ super().__init__()
+ if max_t is not None and max_t < window_size[0]:
+ # A window shorter than the kernel would let a halo reach back past the previous window,
+ # whose output is already written; see _forward_looped.
+ raise ValueError(f"max_t={max_t} must be at least the temporal kernel {window_size[0]}")
+ self.norm1 = _norm_layer(dim)
+ self.attn = Natten3D(dim, window_size, num_heads, causal=causal, qk_norm=qk_norm)
+ self.norm2 = _norm_layer(dim)
+ self.mlp = GLU_MLP(dim)
+ self.max_t = max_t
+ self._compiled_looped_core: Callable[..., Tensor] | None = None
+
+ def forward(self, x: Tensor) -> Tensor:
+ if self.max_t is None or x.shape[1] <= self.max_t:
+ return self._forward_full(x) # one window covers the sequence (also single-frame latents)
+ return self._forward_looped(x)
+
+ def _forward_full(self, x: Tensor) -> Tensor:
+ x = x + self.attn(self.norm1(x))
+ x = x + self.mlp(self.norm2(x))
+ return x
+
+ def _forward_looped_core(
+ self,
+ normalized_halo: Tensor,
+ residual_core: Tensor,
+ *,
+ temporal_offset: Tensor,
+ output_start: int,
+ output_end: int,
+ ) -> Tensor:
+ x = residual_core + self.attn.forward_region(
+ normalized_halo, temporal_offset=temporal_offset, output_start=output_start, output_end=output_end
+ )
+ return x + self.mlp(self.norm2(x))
+
+ def compile_looped_core(self, **compile_kwargs) -> None:
+ """Compile the per-window core (``torch.compile`` keywords); the window loop itself stays eager."""
+ if self.max_t is None:
+ raise RuntimeError("compile_looped_core needs max_t")
+ self._compiled_looped_core = torch.compile(self._forward_looped_core, **compile_kwargs)
+
+ @torch.compiler.disable(recursive=False)
+ def _forward_looped(self, x: Tensor) -> Tensor:
+ if torch.is_grad_enabled():
+ raise RuntimeError(
+ "looped decoding writes its output in place; run it under no_grad/inference_mode"
+ )
+ length = x.shape[1]
+ kernel = self.attn.window_size[0]
+ core = self._compiled_looped_core or self._forward_looped_core
+ # The halo of a window reaches at most kernel - 1 < max_t frames back into the previous window, so
+ # that window's output is held back for one iteration and written only after this halo was read.
+ pending: tuple[int, int, Tensor] | None = None
+ for core_start in range(0, length, self.max_t):
+ core_end = min(core_start + self.max_t, length)
+ halo_start, halo_end = _temporal_core_halo(core_start, core_end, length, kernel, self.attn.causal)
+ normalized_halo = self.norm1(x[:, halo_start:halo_end])
+ if pending is not None:
+ x[:, pending[0] : pending[1]].copy_(pending[2])
+ output = core(
+ normalized_halo,
+ x[:, core_start:core_end],
+ temporal_offset=torch.tensor(float(halo_start), device=x.device),
+ output_start=core_start - halo_start,
+ output_end=core_end - halo_start,
+ )
+ pending = (core_start, core_end, output)
+ assert pending is not None, "missing loop output"
+ x[:, pending[0] : pending[1]].copy_(pending[2])
+ return x
+
+
+class PatchEmbed3d(nn.Module):
+ def __init__(
+ self,
+ patch_size: list[int],
+ in_channels: int = 3,
+ embed_dim: int = 96,
+ norm: bool = True,
+ ):
+ super().__init__()
+ self.tuple_patch_size = (patch_size[0], patch_size[1], patch_size[2])
+ self.proj = nn.Conv3d(
+ in_channels,
+ embed_dim,
+ kernel_size=self.tuple_patch_size,
+ stride=self.tuple_patch_size,
+ )
+ self.norm = _norm_layer(embed_dim) if norm else nn.Identity()
+
+ def forward(self, x: Tensor) -> Tensor:
+ _, _, t, h, w = x.size()
+ pad = _compute_pad_size_3d((t, h, w), self.tuple_patch_size)
+ x = F.pad(x, (0, pad[2], 0, pad[1], 0, pad[0]))
+ x = self.proj(x)
+ x = x.permute(0, 2, 3, 4, 1)
+ return self.norm(x)
+
+
+class DecoderSwin3D(nn.Module):
+ def __init__(
+ self,
+ z_ch: int,
+ patch_size: list[int],
+ embed_dim: int,
+ depths: list[int],
+ temporal: list[bool],
+ num_heads: list[int],
+ window_size: list[int],
+ causal: bool = False,
+ qk_norm: bool = False,
+ max_t: int | None = None,
+ ):
+ super().__init__()
+ assert len(temporal) == len(depths), "decoder stage mismatch"
+ self.ps = patch_size
+ self.max_t = max_t # looped decode window, see SwinTransformerBlock
+ self.proj_in = nn.Linear(z_ch, embed_dim * 2 ** (len(depths) - 1))
+ self.proj_out = nn.Linear(embed_dim, math.prod(patch_size) * 3)
+
+ layers: list[nn.Module] = []
+ for i_stage in reversed(range(len(depths))):
+ dim = embed_dim * 2**i_stage
+ stage = [
+ SwinTransformerBlock(
+ dim, num_heads[i_stage], window_size, causal=causal, qk_norm=qk_norm, max_t=max_t
+ )
+ for _ in range(depths[i_stage])
+ ]
+ layers.append(nn.Sequential(*stage))
+ if temporal[i_stage]:
+ layers.append(TemporalExpansion(dim, dim))
+ layers.append(
+ SwinTransformerBlock(
+ dim, num_heads[i_stage], window_size, causal=causal, qk_norm=qk_norm, max_t=max_t
+ )
+ )
+ if i_stage > 0:
+ layers.append(PatchExpansion(dim, dim // 2))
+ self.features = nn.Sequential(*layers)
+
+ def forward(self, x: Tensor) -> Tensor:
+ x = x.permute(0, 2, 3, 4, 1).contiguous()
+ x = self.proj_in(x)
+ x = self.features(x)
+ x = self.proj_out(x)
+ b, t, h, w, _ = x.shape
+ x = x.view(b, t, h, w, self.ps[0], self.ps[1], self.ps[2], 3)
+ x = x.permute(0, 1, 4, 2, 5, 3, 6, 7).contiguous()
+ x = x.view(b, t * self.ps[0], h * self.ps[1], w * self.ps[2], 3)
+ return x.permute(0, 4, 1, 2, 3).contiguous()
+
+
+class EncoderSwin3D(nn.Module):
+ def __init__(
+ self,
+ z_ch: int,
+ patch_size: list[int],
+ embed_dim: int,
+ depths: list[int],
+ temporal: list[bool],
+ num_heads: list[int],
+ window_size: list[int],
+ causal: bool = False,
+ qk_norm: bool = False,
+ patch_norm: bool = True,
+ ):
+ super().__init__()
+ assert len(temporal) == len(depths), "encoder stage mismatch"
+ self.proj = nn.Linear(embed_dim * 2 ** (len(depths) - 1), z_ch)
+ self.patch_embed = PatchEmbed3d(patch_size=patch_size, embed_dim=embed_dim, norm=patch_norm)
+
+ layers: list[nn.Module] = []
+ for i_stage in range(len(depths)):
+ dim = embed_dim * 2**i_stage
+ stage = [
+ SwinTransformerBlock(dim, num_heads[i_stage], window_size, causal=causal, qk_norm=qk_norm)
+ for _ in range(depths[i_stage])
+ ]
+ layers.append(nn.Sequential(*stage))
+ downsampled = False
+ if i_stage < (len(depths) - 1):
+ layers.append(PatchMerging(dim, 2 * dim))
+ downsampled = True
+ if temporal[i_stage]:
+ if downsampled:
+ i_stage += 1
+ dim = 2 * dim
+ layers.append(
+ SwinTransformerBlock(dim, num_heads[i_stage], window_size, causal=causal, qk_norm=qk_norm)
+ )
+ layers.append(TemporalMerging(dim, dim))
+ self.features = nn.Sequential(*layers)
+
+ def forward(self, x: Tensor) -> Tensor:
+ _, c, _, _, _ = x.shape
+ assert c == 3, "expected RGB input"
+ x = self.patch_embed(x)
+ # Inductor tiling assertion under dynamic=True without this break.
+ torch._dynamo.graph_break()
+ x = self.features(x)
+ x = self.proj(x)
+ return x.permute(0, 4, 1, 2, 3).contiguous()
+
+
+class ViTNorm(nn.Module):
+ def __init__(
+ self,
+ z_dim: int,
+ embed_dim: int,
+ patch_size: list[int],
+ window_size: list[int],
+ enc_depths: list[int],
+ dec_depths: list[int],
+ num_heads: list[int],
+ temporal: list[bool],
+ enc_causal: bool = False,
+ dec_causal: bool = False,
+ qk_norm: bool = False,
+ patch_norm: bool = False,
+ decoder_max_t: int | None = None,
+ ):
+ super().__init__()
+ torch._dynamo.config.recompile_limit = max(torch._dynamo.config.recompile_limit, 64)
+ self.z_dim = z_dim
+ self.encoder = EncoderSwin3D(
+ z_ch=2 * z_dim,
+ patch_size=patch_size,
+ window_size=window_size,
+ embed_dim=embed_dim,
+ depths=enc_depths,
+ num_heads=num_heads,
+ temporal=temporal,
+ causal=enc_causal,
+ qk_norm=qk_norm,
+ patch_norm=patch_norm,
+ )
+ self.decoder = DecoderSwin3D(
+ z_ch=z_dim,
+ patch_size=patch_size,
+ window_size=window_size,
+ embed_dim=embed_dim,
+ depths=dec_depths,
+ num_heads=num_heads,
+ temporal=temporal,
+ causal=dec_causal,
+ qk_norm=qk_norm,
+ max_t=decoder_max_t,
+ )
+ self.z_normalizer = DistributedRunningStats(z_dim)
+
+ def encode(self, x: Tensor) -> Tensor:
+ mu, _ = self.encoder(x).chunk(2, dim=-4)
+ return self.z_normalizer.normalize(mu)
+
+ def decode(self, z: Tensor) -> Tensor:
+ return self.decoder(self.z_normalizer.denormalize(z))
+
+
+class ViTNormInference(nn.Module):
+ TEMPORAL_DOWNSAMPLE = 4
+ SPATIAL_DOWNSAMPLE = 32
+
+ def __init__(self, params: ViTNormInferenceParams = ViTNormInferenceParams()):
+ super().__init__()
+ self.params = params
+ if list(params.temporal) != [False, False, True, True]:
+ raise ValueError(
+ f"TEMPORAL_DOWNSAMPLE={self.TEMPORAL_DOWNSAMPLE} depends on temporal, got {params.temporal}"
+ )
+ if list(params.patch_size) != [1, 4, 4] or len(params.enc_depths) != 4:
+ raise ValueError(
+ f"SPATIAL_DOWNSAMPLE={self.SPATIAL_DOWNSAMPLE} depends on "
+ f"patch_size and enc_depths, got {params.patch_size}, "
+ f"{params.enc_depths}"
+ )
+ self.chunked_encode = params.chunked_encode
+ self.chunk_size_frames = params.chunk_size_frames
+ self.chunked_decode = params.chunked_decode
+ self.chunk_size_latent_frames = params.chunk_size_latent_frames
+ self.chunk_overlap_latent_frames = params.chunk_overlap_latent_frames
+ self.decoder_max_t = params.decoder_max_t
+ self.model = ViTNorm(
+ z_dim=params.z_dim,
+ embed_dim=params.embed_dim,
+ patch_size=params.patch_size,
+ window_size=params.window_size,
+ enc_depths=params.enc_depths,
+ dec_depths=params.dec_depths,
+ num_heads=params.num_heads,
+ temporal=params.temporal,
+ enc_causal=params.enc_causal,
+ dec_causal=params.dec_causal,
+ qk_norm=params.qk_norm,
+ patch_norm=params.patch_norm,
+ decoder_max_t=params.decoder_max_t,
+ )
+ if params.dtype == "bfloat16":
+ self.model = self.model.bfloat16()
+ elif params.dtype != "float32":
+ raise ValueError(f"unsupported video VAE dtype {params.dtype!r}")
+ self.model.eval()
+ self._encoder_compiled = False
+
+ def compile_encoder(self) -> None:
+ """Compile the encoder blocks used by inference without compiling the decoder."""
+ if self._encoder_compiled:
+ return
+ cfg = self.params.compile_config or {}
+ for layer_id, layer in self.model.encoder.features.named_children():
+ self.model.encoder.features.register_module(
+ layer_id,
+ torch.compile(
+ layer,
+ mode="reduce-overhead",
+ fullgraph=cfg.get("fullgraph", False),
+ dynamic=cfg.get("dynamic_compile", False),
+ backend=cfg.get("backend", "inductor"),
+ ),
+ )
+ self._encoder_compiled = True
+
+ def apply_compile(self):
+ params = self.params
+ if not (params.use_compile or params.compile_decoder):
+ return
+ cfg = params.compile_config or {}
+ mode = cfg.get("compile_mode", "default")
+ fullgraph = cfg.get("fullgraph", False)
+ dynamic = cfg.get("dynamic_compile", False)
+ backend = cfg.get("backend", "inductor")
+ if params.use_compile:
+ self.compile_encoder()
+ if params.compile_decoder and params.decoder_max_t is not None:
+ # Looped blocks loop eagerly over windows; only the per-window core is compiled.
+ for module in self.model.decoder.features.modules():
+ if isinstance(module, SwinTransformerBlock):
+ module.compile_looped_core(
+ mode=mode, fullgraph=fullgraph, dynamic=dynamic, backend=backend
+ )
+ elif params.compile_decoder:
+ for layer_id, layer in self.model.decoder.features.named_children():
+ self.model.decoder.features.register_module(
+ layer_id,
+ torch.compile(
+ layer,
+ mode=mode,
+ fullgraph=fullgraph,
+ dynamic=dynamic,
+ backend=backend,
+ ),
+ )
+
+ def min_chunk_enc(self, video: Tensor, target_num_frames: int | None = None) -> Tensor:
+ """Encode ``(B, 3, T, H, W)`` in ``chunk_size_frames``-frame chunks overlapping by one frame; the first
+ latent of every later chunk repeats the previous chunk's last one and is dropped."""
+ if video.ndim != 5:
+ raise ValueError(f"Expected (B, C, T, H, W), got {video.shape}")
+ chunk_size_frames = self.chunk_size_frames
+ stride = chunk_size_frames - 1
+ if stride <= 0:
+ raise ValueError(f"chunk_size_frames must be > 1, got {chunk_size_frames}")
+ num_frames = video.shape[2]
+ if target_num_frames is None:
+ target_num_frames = num_frames
+ if target_num_frames > num_frames:
+ raise ValueError(
+ f"target_num_frames ({target_num_frames}) cannot exceed encoded frames ({num_frames})"
+ )
+ if num_frames < chunk_size_frames:
+ raise ValueError(
+ f"Chunked encoding expects at least {chunk_size_frames} frames; got T={num_frames}"
+ )
+ if (num_frames - chunk_size_frames) % stride != 0:
+ raise ValueError(
+ f"Chunked encoding expects T = {chunk_size_frames} + n * {stride}; got T={num_frames}"
+ )
+
+ latent_pieces = []
+ for start in range(0, num_frames - chunk_size_frames + 1, stride):
+ z_chunk = self.model.encode(video[:, :, start : start + chunk_size_frames])
+ latent_pieces.append(z_chunk if start == 0 else z_chunk[:, :, 1:])
+
+ latent = torch.cat(latent_pieces, dim=2)
+ target_latent_frames = 1 + (target_num_frames - 1) // self.TEMPORAL_DOWNSAMPLE
+ if target_latent_frames > latent.shape[2]:
+ raise ValueError(
+ f"Chunked encode produced {latent.shape[2]} latent frames, cannot "
+ f"trim to {target_latent_frames}"
+ )
+ return latent[:, :, :target_latent_frames]
+
+ def encode(
+ self,
+ x: Tensor,
+ *,
+ chunked_encode: bool | None = None,
+ target_num_frames: int | None = None,
+ ) -> Tensor:
+ if chunked_encode is None:
+ chunked_encode = self.chunked_encode
+ if chunked_encode:
+ return self.min_chunk_enc(x, target_num_frames=target_num_frames)
+ return self.model.encode(x)
+
+ def min_chunk_dec(self, z: Tensor) -> Tensor:
+ # Decode the (already-denormalized) latent in overlapping temporal
+ # windows, keep each window's core pixel frames, concatenate. The
+ # overlap is decoded purely as temporal context and discarded (no
+ # blending), larger overlap brings seam frames closer to full decode.
+ if z.ndim != 5:
+ raise ValueError(f"Expected (B, C, T, H, W), got {z.shape}")
+ core = self.chunk_size_latent_frames
+ overlap = self.chunk_overlap_latent_frames
+ if core < 1 or overlap < 1:
+ raise ValueError(
+ f"chunk_size/overlap latent frames must be >= 1, got core={core}, overlap={overlap}"
+ )
+ # Shrink core if free VRAM can't hold a full window (core + 2*overlap).
+ free, _ = torch.cuda.mem_get_info(z.device)
+ budget = free / DECODE_SAFETY_FACTOR - DECODE_FIXED_BYTES
+ window_fit = int(budget / (DECODE_BYTES_PER_LATENT_ELEM * z[0, 0, 0].numel()))
+ core = max(1, min(core, window_fit - 2 * overlap))
+ t_lat = z.shape[2]
+ logger.info(
+ f"tiled video decode: t_lat={t_lat} core={core} overlap={overlap} free={free / 2**30:.1f}GiB"
+ )
+
+ pieces = []
+ for core_lo in range(0, t_lat, core):
+ core_hi = min(core_lo + core, t_lat)
+ lo = max(0, core_lo - overlap)
+ hi = min(t_lat, core_hi + overlap)
+ decoded = self.model.decoder(z[:, :, lo:hi])
+ # Slice the core latent range to its pixel range within this window.
+ # core_lo == 0 keeps the leading pixel frame, interior cores start
+ # at 4*(core_lo - lo) - 3. overlap >= 1 keeps local_start >= 0.
+ local_start = 0 if core_lo == 0 else 4 * (core_lo - lo) - 3
+ local_end = 4 * (core_hi - lo) - 3
+ pieces.append(decoded[:, :, local_start:local_end])
+
+ out = torch.cat(pieces, dim=2)
+ assert out.shape[2] == 4 * t_lat - 3, (
+ f"tiling misaligned: {out.shape[2]} frames, expected {4 * t_lat - 3}"
+ )
+ return out
+
+ def _full_decode_fits(self, z: Tensor) -> bool:
+ if z.device.type != "cuda":
+ return True
+ free, _ = torch.cuda.mem_get_info(z.device)
+ need = DECODE_BYTES_PER_LATENT_ELEM * z[0, 0].numel() + DECODE_FIXED_BYTES
+ return need * DECODE_SAFETY_FACTOR < free
+
+ def decode(self, z: Tensor, *, chunked_decode: bool | None = None) -> Tensor:
+ """Latents ``(B, 96, T_lat, H, W)`` -> pixels ``(B, 3, 4 * T_lat - 3, 32 H, 32 W)`` in ``[-1, 1]``.
+
+ The whole latent is decoded in one pass when possible. With ``decoder_max_t`` set (the loader
+ default) that pass is the looped decode, whose memory is bounded by the window rather than the clip
+ length, so it is always attempted first; without it, a memory estimate picks between the full and
+ the latent-chunked decode. The latent-chunked decode (``chunked_decode=True``, or the fallback after
+ an out-of-memory error) tiles the latent along time with discarded overlap and is not seam-free.
+ """
+ auto = chunked_decode is None
+ if auto:
+ fits = self.decoder_max_t is not None or self._full_decode_fits(z)
+ chunked_decode = self.chunked_decode and not fits
+ if not chunked_decode:
+ try:
+ return self.model.decode(z).clamp(-1, 1)
+ except torch.OutOfMemoryError:
+ # Estimate was too optimistic, fall through to the chunked path below.
+ if not (auto and self.chunked_decode):
+ raise
+ logger.warning(f"full video decode OOM (t_latent={z.shape[2]}), falling back to chunked")
+ torch.cuda.empty_cache()
+ z = self.model.z_normalizer.denormalize(z)
+ return self.min_chunk_dec(z).clamp(-1, 1)
+
+
+# ---------------------------------------------------------------------------------------------
+# Policy-side wrapper and loader. The KinoVAE is frozen,
+# loaded from a local file / directory or a Hub repo, and never part of the policy's own
+# ``model.safetensors``.
+# ---------------------------------------------------------------------------------------------
+from flux_action.processing.packing import padded_chunk_length # noqa: E402
+
+from .runtime import random_init_ # noqa: E402
+
+VIDEO_VAE_WEIGHTS_FILENAME = "video_vae.safetensors"
+
+
+class VideoVAE:
+ """Frozen video VAE behind the encode/decode contract the packing code relies on.
+
+ ``encode`` takes ``(B, 3, T, H, W)`` in ``[-1, 1]`` with ``T == 1 (mod 4)`` and returns normalized
+ latents ``(B, 96, 1 + (T - 1) // 4, H // 32, W // 32)``. Encoding is chunked (45-frame chunks,
+ 1-frame overlap, first latent of each later chunk dropped); shorter clips are padded by repeating
+ the last frame and trimmed back. ``packing.encode_video`` pads with black to the chunk length
+ *before* calling this, so training and deployment see the same latent distribution.
+
+ ``decode`` is the looped decode (``ViTNormInference.decode``): the full-sequence result with the
+ decoder's activations bounded by an 8-frame window.
+ """
+
+ def __init__(self, model: "ViTNormInference"):
+ self._model = model
+
+ @property
+ def module(self) -> "ViTNormInference":
+ return self._model
+
+ @torch.inference_mode()
+ def encode(self, video: Tensor) -> Tensor:
+ num_frames = video.shape[2]
+ if (num_frames - 1) % 4 != 0:
+ raise ValueError(
+ f"video VAE encode expects T == 1 (mod 4) frames, got T={num_frames}; "
+ "trim or pad the clip to the 4k+1 grid (e.g. 45, 49, 121)"
+ )
+ chunk = self._model.chunk_size_frames
+ padded = padded_chunk_length(num_frames, chunk)
+ if padded > num_frames:
+ tail = video[:, :, -1:].expand(-1, -1, padded - num_frames, -1, -1)
+ video = torch.cat([video, tail], dim=2)
+ return self._model.min_chunk_enc(video, target_num_frames=num_frames)
+
+ @torch.inference_mode()
+ def encode_task(self, video: Tensor) -> Tensor:
+ """Independent history snapshot or future clip, without padding or chunk overlap."""
+ return self._model.encode(video, chunked_encode=False)
+
+ @torch.inference_mode()
+ def encode_frame(self, frame: Tensor) -> Tensor:
+ """``(B, 3, H, W)`` -> ``(B, 96, 1, H // 32, W // 32)``: the frame alone, without the 45-frame padding
+ of ``encode``. See ``PolicyConfig.single_frame_encode``."""
+ return self._model.encode(frame[:, :, None], chunked_encode=False)
+
+ @torch.inference_mode()
+ def decode(self, latents: Tensor) -> Tensor:
+ return self._model.decode(latents)
+
+
+def _resolve_weights(spec: str) -> "str":
+ """Local file / DCP directory as is; anything else is ``repo_id[:filename][@revision]`` on the Hub."""
+ from flux_action.models.runtime import resolve_weights
+
+ return resolve_weights(spec, VIDEO_VAE_WEIGHTS_FILENAME)
+
+
+def load_video_vae(
+ weights: str | None,
+ device: str | torch.device = "cpu",
+ *,
+ compile_model: bool = False,
+ decoder_max_t: int | None = 8,
+) -> VideoVAE:
+ """Build the frozen KinoVAE.
+
+ ``weights``: ``None`` -> random init (shapes only, for wiring tests), a ``.safetensors`` file, a
+ distributed-checkpoint directory (``.metadata`` + ``__*.distcp``), or a Hub ``repo_id[:filename]``
+ (default filename ``video_vae.safetensors``). Requires NATTEN (``natten`` package) at import.
+
+ ``decoder_max_t``: temporal window of the looped decode (8 is the reference setting; it must be at
+ least the temporal attention kernel, 5). ``None`` restores the plain full decode with the
+ latent-chunked fallback.
+ """
+ import os
+ from dataclasses import replace
+ from pathlib import Path
+
+ params = ViTNormInferenceParams(
+ use_compile=compile_model,
+ compile_decoder=compile_model,
+ chunked_decode=True,
+ chunked_encode=True,
+ decoder_max_t=decoder_max_t,
+ )
+ if weights is None:
+ model = ViTNormInference(params)
+ random_init_(model)
+ else:
+ path = _resolve_weights(weights)
+ if os.path.isdir(path) or (Path(path) / ".metadata").is_file():
+ import torch.distributed.checkpoint as dcp
+
+ model = ViTNormInference(replace(params, dtype="float32"))
+ state_dict = {"model": model.model.state_dict()}
+ dcp.load(state_dict, checkpoint_id=str(path))
+ model.model.load_state_dict(state_dict["model"])
+ model.model.bfloat16()
+ else:
+ from safetensors.torch import load_file
+
+ model = ViTNormInference(params)
+ model.load_state_dict(load_file(path, device="cpu"))
+ model.to(device)
+ model.eval()
+ for p in model.parameters():
+ p.requires_grad_(False)
+ if compile_model:
+ model.apply_compile()
+ return VideoVAE(model)
diff --git a/flux-umi/src/flux_action/models/wiring.py b/flux-umi/src/flux_action/models/wiring.py
new file mode 100644
index 0000000000000000000000000000000000000000..c698c40d1e266877410b785abf344c1a6b99c1a5
--- /dev/null
+++ b/flux-umi/src/flux_action/models/wiring.py
@@ -0,0 +1,248 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Wire an embodiment-specific action modality into the FLUX Action DiT.
+
+The action-pretrained trunk carries the video model
+plus the co-trained action branch: ``action_prediction`` / ``action_prediction_cond`` mode blocks and
+stream modulations. It may also carry ``emb_in`` / ``final_layer`` heads of action modalities that are
+not yours; their channel count and meaning are not yours, so they are dropped. A finetune adds YOUR
+modality on top of it:
+
+* mode blocks and modulations for ```` / ``_cond`` are initialized from the
+ co-trained ``action_prediction`` branch (dataset-specific action modalities route through one shared
+ action backbone);
+* ``emb_in.``, ``emb_in._cond``, ``final_layer.`` and
+ ``final_layer._cond`` are fresh, sized to your action channels;
+* everything else (video model, text path, single-stream blocks) loads as is.
+
+A checkpoint written by a finetune already contains the embodiment keys and loads with
+``strict_heads=True``.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from collections.abc import Sequence
+from dataclasses import replace
+
+import torch
+from torch import nn
+
+from ..config import CONTENT_STREAMS
+from .transformer import JointSingleSeq, JointSingleSeqParams, LastLayer
+
+SHARED_ACTION_MODE = "action_prediction"
+SHARED_KINDS = (
+ "content_mode_blocks",
+ "early_stream_modulations",
+ "single_stream_modulations",
+ "late_stream_modulations",
+ "late_content_mode_blocks",
+)
+HEAD_KINDS = ("emb_in", "final_layer")
+# Modules of the video trunk that are never in an action checkpoint (audio conditioning is unused).
+OPTIONAL_KEY_SUBSTRINGS = ("audio_cond",)
+_STREAM_MODULE_KINDS = (
+ "emb_in",
+ "final_layer",
+ "content_mode_blocks",
+ "early_stream_modulations",
+ "single_stream_modulations",
+ "late_stream_modulations",
+ "late_content_mode_blocks",
+)
+
+
+def restrict_content_streams(base: JointSingleSeqParams, streams: Sequence[str]) -> JointSingleSeqParams:
+ """``base`` with only ``streams`` among its content streams (the action modality is added afterwards)."""
+ # Historical training configs can explicitly restore the full trunk architecture.
+ legacy_channels = {"image": 128, "image_cond": 128, "audio": 64, "audio_cond": 64}
+ unknown = [s for s in streams if s not in base.in_channels and s not in legacy_channels]
+ assert not unknown, f"unknown content streams: {unknown}"
+ keep = set(streams)
+ in_channels = {m: c for m, c in base.in_channels.items() if m in keep}
+ in_channels.update(
+ {m: legacy_channels[m] for m in streams if m in legacy_channels and m not in in_channels}
+ )
+ sequence = {k: v for k, v in base.sequence.items() if v in keep}
+ sequence.update(
+ {f"x_{m}": m for m in streams if m in legacy_channels and m not in base.sequence.values()}
+ )
+ return replace(base, in_channels=in_channels, sequence=sequence)
+
+
+def stream_of_key(key: str) -> str | None:
+ """Name of the stream a DiT parameter belongs to (``video``, ``txt``, a head modality, ...), else ``None``."""
+ parts = key.removeprefix("dit.").split(".")
+ if len(parts) >= 3 and parts[0] in _STREAM_MODULE_KINDS:
+ return parts[1]
+ return None
+
+
+def action_dit_params(
+ base: JointSingleSeqParams,
+ modality: str,
+ channels: int,
+ attn_mode: str | None = None,
+ *,
+ conditioning_channels: int | None = None,
+) -> JointSingleSeqParams:
+ """``base`` plus the ```` and ``_cond`` content streams."""
+ in_channels = dict(base.in_channels)
+ in_channels[modality] = channels
+ in_channels[f"{modality}_cond"] = channels if conditioning_channels is None else conditioning_channels
+ sequence = dict(base.sequence)
+ sequence[f"x_{modality}"] = modality
+ sequence[f"x_{modality}_cond"] = f"{modality}_cond"
+ params = replace(base, in_channels=in_channels, sequence=sequence)
+ if attn_mode is not None:
+ params = replace(params, attn_mode=attn_mode)
+ return params
+
+
+def fresh_module_names(modality: str) -> list[str]:
+ return [f"{kind}.{m}" for kind in HEAD_KINDS for m in (modality, f"{modality}_cond")]
+
+
+def remap_shared_action_keys(state_dict: dict[str, torch.Tensor], modality: str) -> dict[str, torch.Tensor]:
+ """Route the co-trained action backbone to ``modality``; drop every other action head.
+
+ ``content_mode_blocks.action_prediction.*`` -> ``content_mode_blocks..*``
+ ``*_stream_modulations.action_prediction_cond.*`` -> ``*_stream_modulations._cond.*``
+ ``emb_in.action_prediction*.*`` / ``final_layer.action_prediction*.*`` -> dropped, unless they
+ already belong to ``modality`` (a finetuned checkpoint)
+ """
+ ours = (modality, f"{modality}_cond")
+ out: dict[str, torch.Tensor] = {}
+ for key, value in state_dict.items():
+ parts = key.split(".")
+ if len(parts) >= 3 and parts[0] in HEAD_KINDS and parts[1].startswith(SHARED_ACTION_MODE):
+ if parts[1] not in ours:
+ continue # generic head or another embodiment's head: channels are not ours
+ elif (
+ modality != SHARED_ACTION_MODE
+ and len(parts) >= 3
+ and parts[0] in SHARED_KINDS
+ and parts[1] in (SHARED_ACTION_MODE, f"{SHARED_ACTION_MODE}_cond")
+ ):
+ parts[1] = modality if parts[1] == SHARED_ACTION_MODE else f"{modality}_cond"
+ out[".".join(parts)] = value
+ continue
+ out[key] = value
+ return out
+
+
+def fresh_head_state_dict(
+ hidden_size: int, modality: str, channels: int, seed: int = 0, *, conditioning_channels: int | None = None
+) -> dict[str, torch.Tensor]:
+ """Tensors for fresh embodiment heads with the reference model's initialization.
+
+ The reference initializes every linear layer xavier-uniform and then zeroes the final layers
+ (output projection and its modulation), so a new head predicts zero at first and only its output
+ projection moves at the first update. Its released action trunk carries untrained embodiment heads
+ in exactly this state. ``seed`` drives the xavier draw of the input projections.
+ """
+ generator = torch.Generator().manual_seed(seed)
+ out: dict[str, torch.Tensor] = {}
+ for m, width in (
+ (modality, channels),
+ (f"{modality}_cond", channels if conditioning_channels is None else conditioning_channels),
+ ):
+ weight = torch.empty(hidden_size, width)
+ nn.init.xavier_uniform_(weight, generator=generator)
+ out[f"emb_in.{m}.weight"] = weight
+ with torch.random.fork_rng(devices=[]):
+ layer_state = LastLayer(hidden_size, width).state_dict()
+ for k, v in layer_state.items():
+ out[f"final_layer.{m}.{k}"] = torch.zeros_like(v)
+ return out
+
+
+@contextlib.contextmanager
+def default_dtype(dtype: torch.dtype):
+ prev = torch.get_default_dtype()
+ torch.set_default_dtype(dtype)
+ try:
+ yield
+ finally:
+ torch.set_default_dtype(prev)
+
+
+def load_action_checkpoint(
+ model: JointSingleSeq, ckpt_path: str, modality: str, *, strict_heads: bool = False, head_seed: int = 0
+) -> None:
+ """Load a trunk / finetuned ``.safetensors`` into an action DiT built with :func:`action_dit_params`.
+
+ ``strict_heads=True`` demands that the checkpoint already contains the embodiment heads (a finetuned
+ checkpoint); ``False`` accepts an action-pretrained trunk and gives the missing heads the reference
+ initialization of :func:`fresh_head_state_dict`, drawn from ``head_seed`` so every rank builds the same
+ heads whatever its own RNG state.
+ """
+ from safetensors import safe_open
+
+ dtype = next(model.parameters()).dtype
+ # Filter unused content streams before materializing tensors from a full trunk.
+ unused = set(CONTENT_STREAMS) - set(model.in_channels)
+ with safe_open(ckpt_path, framework="pt", device="cpu") as checkpoint:
+ sd = {
+ key: checkpoint.get_tensor(key) for key in checkpoint.keys() if stream_of_key(key) not in unused
+ }
+ sd = remap_shared_action_keys(sd, modality)
+ fresh_prefixes = tuple(n + "." for n in fresh_module_names(modality))
+ if strict_heads:
+ missing_heads = [k for k in model.state_dict() if k.startswith(fresh_prefixes) and k not in sd]
+ if missing_heads:
+ raise ValueError(f"checkpoint missing required embodiment heads: {missing_heads[:6]}")
+ res = model.load_state_dict({k: v.to(dtype) for k, v in sd.items()}, strict=False)
+ missing = [
+ k
+ for k in res.missing_keys
+ if not k.startswith(fresh_prefixes) and not any(s in k for s in OPTIONAL_KEY_SUBSTRINGS)
+ ]
+ if missing:
+ raise ValueError(f"checkpoint missing required keys, e.g. {missing[:6]}")
+ fresh_missing = [k for k in res.missing_keys if k.startswith(fresh_prefixes)]
+ if fresh_missing:
+ emb = model.emb_in[modality].weight
+ fresh = fresh_head_state_dict(
+ emb.shape[0],
+ modality,
+ emb.shape[1],
+ head_seed,
+ conditioning_channels=model.emb_in[f"{modality}_cond"].in_features,
+ )
+ model.load_state_dict({k: fresh[k].to(dtype) for k in fresh_missing}, strict=False)
+
+
+def build_action_dit(
+ params: JointSingleSeqParams,
+ ckpt_path: str | None = None,
+ *,
+ modality: str,
+ device: str | torch.device = "cpu",
+ dtype: torch.dtype = torch.bfloat16,
+ strict_heads: bool = False,
+ head_seed: int = 0,
+) -> JointSingleSeq:
+ """Instantiate the DiT (``params`` already carry the action modality) and load ``ckpt_path``.
+
+ ``ckpt_path=None`` -> random init (wiring tests, or a policy whose weights are loaded afterwards by
+ ``from_pretrained``).
+ """
+ with torch.device(device), default_dtype(dtype):
+ model = JointSingleSeq(params) # built directly in ``dtype``: no fp32 copy on the device
+ if ckpt_path is not None:
+ load_action_checkpoint(model, ckpt_path, modality, strict_heads=strict_heads, head_seed=head_seed)
+ model.eval()
+ return model
diff --git a/flux-umi/src/flux_action/policy.py b/flux-umi/src/flux_action/policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..accfe6bb054737a97bfa36dfcdd9c944279367a5
--- /dev/null
+++ b/flux-umi/src/flux_action/policy.py
@@ -0,0 +1,1460 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Standalone FLUX Action policy with local checkpoint export and strict restoration.
+
+The forward path is a local dense-batch implementation. Distributed token-budget
+training, EMA and training-state resume are not implemented here.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from collections import deque
+from collections.abc import Iterator
+from contextlib import nullcontext
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import Any
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from torch import Tensor, nn
+
+from .checkpoints.artifacts import sha256
+from .config import REQUIRED_CONTENT_STREAMS, TRAINING_PERF_FLAGS, PolicyConfig
+from .hub import resolve_policy_directory
+from .inference import sampling
+from .models.positional import batched_prc_action, batched_prc_vid, times_to_ids
+from .models.runtime import TRUNK_WEIGHTS_FILENAME, resolve_weights
+from .models.text_encoder import VEC_DIM, text_contexts
+from .models.transformer import JointSingleSeq, JointSingleSeqParams
+from .models.wiring import (
+ action_dit_params,
+ build_action_dit,
+ fresh_module_names,
+ restrict_content_streams,
+)
+from .processing import history, normalization, packing
+from .training.timing import StepTimings
+
+ACTION = "action"
+ACTION_PREV = "action_prev" # the command before a training window (joint_delta parameterization)
+OBS_STATE = "state"
+GRAY_LEVEL = 128 # the flat tile a dropped camera turns into
+
+
+def _released_inference_config(config: PolicyConfig) -> bool:
+ return (
+ config.torch_dtype == "bfloat16"
+ and config.action_modality == "action_prediction_droid"
+ and config.action_dim == 8
+ and config.chunk_size == 32
+ and tuple(config.content_streams or ()) == ("video", "video_cond")
+ and JointSingleSeqParams(**{**config.dit_config, "attn_mode": config.attn_mode})
+ == JointSingleSeqParams(attn_mode=config.attn_mode)
+ and config.inference_profile == "default"
+ and config.sampler == "cosmos_unipc"
+ )
+
+
+def _verify_policy_manifest(directory: Path, config_name: str) -> None:
+ path = directory / "manifest.json"
+ if not path.is_file():
+ raise FileNotFoundError(f"checkpoint is missing {path.name}")
+ manifest = json.loads(path.read_text())
+ assert manifest.get("format_version") == 1 and manifest.get("kind") == "policy_export", (
+ "invalid policy manifest"
+ )
+ hashes = manifest.get("sha256")
+ assert isinstance(hashes, dict), "missing checkpoint hashes"
+ for name in (config_name, "model.safetensors"):
+ assert sha256(directory / name) == hashes.get(name), f"checkpoint checksum mismatch: {name}"
+
+
+def write_policy_export(
+ directory, config: PolicyConfig, state_dict: dict[str, Tensor], *, weight_profile: str
+):
+ """Write the inference export (``config.json``, ``model.safetensors``, ``manifest.json``).
+
+ ``state_dict`` carries the policy's ``dit.`` keys; ``weight_profile`` names their origin
+ (``model`` or an EMA profile) in the manifest. The recorded dtype is the tensors' dtype.
+ """
+ from safetensors.torch import save_file
+
+ directory = Path(directory)
+ directory.mkdir(parents=True, exist_ok=True)
+ if any((directory / name).exists() for name in ("config.json", "model.safetensors", "manifest.json")):
+ raise FileExistsError("export destination already contains a policy")
+ dtypes = {v.dtype for v in state_dict.values() if v.is_floating_point()}
+ assert len(dtypes) == 1, "export weights need one dtype"
+ dtype = str(dtypes.pop()).removeprefix("torch.")
+ # An export is an inference artifact: the training-only performance flags (CUDA-stack-specific kernels and
+ # caches) are cleared so that loading it never depends on that stack. Restores of older exports that still carry
+ # them are handled by ``FluxActionPolicy(..., _restore=True)``, which installs no training adapter.
+ config = replace(config, trunk_weights=None, torch_dtype=dtype, **{name: False for name in TRAINING_PERF_FLAGS}).to_dict()
+ (directory / "config.json").write_text(json.dumps(config, indent=2) + "\n")
+ save_file(
+ {k: v.detach().cpu().contiguous() for k, v in state_dict.items()},
+ str(directory / "model.safetensors"),
+ )
+ manifest = {
+ "format_version": 1,
+ "kind": "policy_export",
+ "weight_profile": weight_profile,
+ "sha256": {name: sha256(directory / name) for name in ("config.json", "model.safetensors")},
+ }
+ (directory / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
+
+
+@dataclass
+class FrozenComponents:
+ """Video VAE and text encoder: eval-only, never saved, never trained.
+
+ Deliberately not an ``nn.Module``: assigning an instance to the policy registers nothing, so both
+ components stay out of ``state_dict()`` / ``parameters()`` (never written to ``model.safetensors``,
+ never handed to the optimizer) and ``policy.train()`` cannot undo the ``eval()`` applied here. The
+ policy's ``_apply`` forwards dtype changes and device moves; an offloaded encoder stays on CPU.
+ """
+
+ video_vae: Any
+ text_encoder: nn.Module
+
+ def __post_init__(self) -> None:
+ for module in self.modules():
+ module.eval()
+ module.requires_grad_(False)
+
+ def modules(self) -> Iterator[nn.Module]:
+ """The torch modules held here (the VAE may be a thin wrapper around its ``module``)."""
+ for m in (getattr(self.video_vae, "module", self.video_vae), self.text_encoder):
+ if isinstance(m, nn.Module):
+ yield m
+
+
+WINDOW_SEED = "window_seed"
+
+
+@dataclass
+class PreparedWindows:
+ """Encoder outputs of a training micro-batch, ready for the DiT (see :meth:`FluxActionPolicy.prepare`).
+
+ ``event`` is set by a caller that ran :meth:`FluxActionPolicy.prepare` on another CUDA stream; the
+ DiT forward waits for it before touching the tensors.
+ """
+
+ idx: list[int] # windows of the batch that are trained on
+ latents: Tensor # (n, 96, latent frames, h, w)
+ ctxs: list[Tensor] # per window (1, L_i, ctx_dim) in the DiT dtype
+ state: Tensor # (n, D), gripper-flipped and normalized
+ actions: Tensor # (n, chunk, D), gripper-flipped targets (absolute or deltas), normalized
+ action_mask: Tensor | None = None # (n, D) 1/0 per action dim; None = all dims trained (see flow_loss)
+ event: Any = None
+ timings: StepTimings | None = None
+ # Timesteps and noise of this batch, drawn ahead by ``prepare`` (``packing.draw_training_randomness``);
+ # the device tensors among them live on the encoder stream like the latents.
+ drawn: dict[str, Tensor] | None = None
+ # Global CPU generator states (torch / python / numpy) as they were when ``prepare`` started on this batch.
+ # ``prepare`` runs ahead of the update that consumes the batch, so a checkpoint written in between must store
+ # these instead of the live states: the resumed run re-prepares the same batch and must draw the same values.
+ rng_before: dict[str, Any] | None = None
+
+ def tensors(self):
+ yield self.latents
+ yield from self.ctxs
+ yield self.state
+ yield self.actions
+ if self.action_mask is not None:
+ yield self.action_mask
+ if self.drawn is not None:
+ yield from (v for v in self.drawn.values() if v.is_cuda)
+
+
+class FluxActionPolicy(nn.Module):
+ def __init__(
+ self,
+ config: PolicyConfig,
+ *,
+ video_vae=None,
+ text_encoder=None,
+ _restore=False,
+ ):
+ super().__init__()
+ if os.environ.get("FLUX_ACTION_NATTEN_NO_LSE_REQUIRE_KERNEL") == "1" and not config.vae_natten_no_lse:
+ raise RuntimeError("Required NATTEN no-LSE needs config.vae_natten_no_lse=true")
+ if os.environ.get("FLUX_ACTION_SWIGLU_NATIVE_OUT_REQUIRE_KERNEL") == "1" and not config.dit_swiglu_native_out:
+ raise RuntimeError("Required native-out SwiGLU needs config.dit_swiglu_native_out=true")
+ if os.environ.get("FLUX_ACTION_CUTE_QKNORM_REQUIRE_KERNEL") == "1" and not config.dit_cute_qknorm:
+ raise RuntimeError("Required CuTe QKNorm needs config.dit_cute_qknorm=true")
+ if os.environ.get("FLUX_ACTION_CUTE_VAE_ROPE_REQUIRE_KERNEL") == "1" and not config.vae_cute_rope:
+ raise RuntimeError("Required CuTe VAE RoPE needs config.vae_cute_rope=true")
+ if os.environ.get("FLUX_ACTION_CUTE_RMSNORM_REQUIRE_KERNEL") == "1" and not config.vae_cute_rmsnorm:
+ raise RuntimeError("Required CuTe RMSNorm needs config.vae_cute_rmsnorm=true")
+ assert video_vae is not None or config.video_vae_id, "missing video VAE"
+ assert text_encoder is not None or config.text_encoder_id, "missing text encoder"
+ self.config = config
+ self.modality = config.action_modality
+ self.dtype_ = getattr(torch, config.torch_dtype)
+ # Set by the trainer when parameters are float32 masters computed in bfloat16 (FSDP mixed precision).
+ self.compute_dtype: torch.dtype | None = None
+ trunk = (
+ resolve_weights(config.trunk_weights, TRUNK_WEIGHTS_FILENAME) if config.trunk_weights else None
+ )
+ if config.content_streams is None:
+ config.content_streams = REQUIRED_CONTENT_STREAMS
+ self.dit_params = action_dit_params(
+ restrict_content_streams(JointSingleSeqParams(**config.dit_config), config.content_streams),
+ self.modality,
+ config.action_dim,
+ attn_mode=config.attn_mode,
+ conditioning_channels=config.conditioning_channels,
+ )
+ self.dit = build_action_dit(
+ self.dit_params,
+ None if _restore else trunk,
+ modality=self.modality,
+ device="meta" if _restore else "cpu",
+ dtype=self.dtype_,
+ head_seed=config.head_init_seed,
+ )
+ # Training-only kernels and adapters (Triton / CuTe / NATTEN / cuBLAS epilogue, pinned to the validated CUDA
+ # stack). A policy restored from an export (``from_pretrained``) is for inference and never installs them:
+ # the eager modules compute the same function and the dependencies may be absent.
+ adapters = not _restore
+ self.training_adapters_installed = adapters
+ if adapters and config.dit_cute_qknorm:
+ from .models.dit_cute_qknorm import install_training_qknorm
+
+ self._dit_cute_qknorm_info = install_training_qknorm(
+ self.dit, compile_model=config.compile_model
+ )
+ if adapters and config.dit_swiglu_native_out:
+ from .models.swiglu_native_out_adapter import install_training_swiglu
+
+ self._dit_swiglu_native_out_info = install_training_swiglu(
+ self.dit, compile_model=config.compile_model
+ )
+ # Campaign-2 DiT kernels: patch module instances before the trainer wraps them (checkpoint/FSDP keep the
+ # instances), in dependency order: activation, Q/K norm, RoPE (module global), block forwards, root forward.
+ if adapters and config.dit_swiglu_fused:
+ from .models import dit_swiglu_fused
+
+ self._dit_swiglu_fused_state = dit_swiglu_fused.install(self.dit, require=True, inference=False)
+ if adapters and config.dit_qknorm_triton:
+ from .models import dit_qknorm_triton
+
+ self._dit_qknorm_triton_names = dit_qknorm_triton.install(self.dit, require_kernel=True)
+ if adapters and config.dit_rope_triton:
+ from .models import dit_rope_triton
+
+ dit_rope_triton.install(require_kernel=True)
+ if adapters and config.dit_qknorm_rope_fused:
+ from .models import dit_qknorm_rope_fused
+
+ self._dit_qknorm_rope_fused_state = dit_qknorm_rope_fused.install(require_kernel=True)
+ if adapters and config.dit_norm_mod_gate_fused:
+ from .models import dit_norm_mod_gate
+
+ self._dit_norm_mod_gate_state = dit_norm_mod_gate.install(self.dit)
+ if adapters and config.dit_time_embed_dedup:
+ from .models.dit_time_embed_dedup import install_training_time_embed_dedup
+
+ self._dit_time_embed_dedup_info = install_training_time_embed_dedup(
+ self.dit, compile_model=config.compile_model
+ )
+ if not self._dit_time_embed_dedup_info.get("installed"):
+ raise RuntimeError(f"dit_time_embed_dedup not installed: {self._dit_time_embed_dedup_info}")
+ if adapters and config.dit_mod_rows:
+ from .models import dit_mod_rows
+
+ self._dit_mod_rows_state = dit_mod_rows.install_dedup_rows(self.dit)
+ dit_mod_rows.Config.fanout_linear = bool(config.dit_fanout_linear)
+ dit_mod_rows.Config.pe_cache = bool(config.dit_pe_cache)
+ dit_mod_rows.Config.last_layer_rows = bool(config.dit_last_layer_rows)
+ dit_mod_rows.Config.out_stage = bool(config.dit_out_stage)
+ if config.dit_out_stage:
+ from .models import dit_out_stage # registers flux::out_stage
+
+ self._dit_out_stage_state = dit_out_stage.install()
+ if video_vae is None:
+ from .models.video_vae import load_video_vae
+
+ video_vae = load_video_vae(config.video_vae_id, compile_model=config.compile_model)
+ if text_encoder is None:
+ from .models.text_encoder import load_text_encoder
+
+ text_encoder = load_text_encoder(config.text_encoder_id, compile_model=config.compile_model)
+ self.frozen = FrozenComponents(video_vae, text_encoder)
+ if adapters and config.vae_cute_rmsnorm:
+ from .models.vae_cute_rmsnorm import install_training_rmsnorm
+
+ self._vae_cute_rmsnorm_info = install_training_rmsnorm(
+ video_vae, compile_model=config.compile_model
+ )
+ if adapters and config.vae_cute_rope:
+ from .models.vae_cute_rope import prepare_training_rope
+
+ self._vae_cute_rope_handle, self._vae_cute_rope_info = prepare_training_rope(
+ video_vae, compile_model=config.compile_model
+ )
+ if adapters and config.vae_natten_no_lse:
+ from .models.vae_natten_no_lse import prepare_training_no_lse
+
+ self._vae_natten_no_lse_handle, self._vae_natten_no_lse_info = prepare_training_no_lse(
+ video_vae, compile_model=config.compile_model, triton_tokperm=config.vae_natten_triton_tokperm,
+ triton_na3d=config.vae_na3d_triton,
+ )
+ if config.vae_na3d_tma:
+ from .models import vae_na3d_v2
+
+ vae_na3d_v2.install("v2") # rebinds vae_na3d_triton.na3d_triton (looked up at call time)
+ if adapters and config.vae_fused_pointwise:
+ from .models.vae_fused_pointwise import install_training_fused
+
+ self._vae_fused_state, self._vae_fused_info = install_training_fused(
+ video_vae, compile_model=config.compile_model
+ )
+ if adapters and config.vae_ln_exact_fast:
+ from .models import vae_ln_exact
+
+ self._vae_ln_exact_uninstall = vae_ln_exact.install()
+ if adapters and (config.vae_qk_fused or config.vae_mlp_residual_fused):
+ from .models import vae_qk_fused
+
+ self._vae_qk_fused_inst = vae_qk_fused.install(
+ video_vae, self._vae_fused_state, qk_fused=config.vae_qk_fused,
+ mlp_residual=config.vae_mlp_residual_fused, require_kernel=True,
+ )
+ self._vae_qk_fused_info = self._vae_qk_fused_inst.info()
+ if adapters and config.vae_merge_glue_fused:
+ from .models import vae_merge_glue
+
+ # after vae_qk_fused (re-patches the stage-final blocks on top of its deferred-residual forward)
+ self._vae_merge_glue_inst = vae_merge_glue.install(video_vae, self._vae_fused_state, require_kernel=True)
+ if adapters and config.vae_fused_fc1_glu:
+ from .models import vae_fused_gemm
+
+ self._vae_fused_gemm_inst = vae_fused_gemm.install(
+ video_vae, self._vae_fused_state, glu_dims=(256, 512, 1024), require_kernel=True,
+ )
+ self._vae_graph_bank = None # built lazily on the first training encode (vae_cuda_graph)
+ self._ctx_cache = {}
+ self._pack_cache = packing.PackCache() # layout-only DiT inputs across steps (pack_cache)
+ self._offload_text_encoder = False
+ self.serving_setup = None
+ self._inference_prepared = False
+ self.reset()
+
+ def save_pretrained(self, directory):
+ """Export DiT/config only. This is not a resumable training checkpoint."""
+ assert isinstance(self.dit, JointSingleSeq), "cannot export prepared inference weights"
+ write_policy_export(directory, self.config, self.state_dict(), weight_profile="model")
+
+ @classmethod
+ def from_pretrained(
+ cls,
+ pretrained_model_name_or_path,
+ *,
+ video_vae=None,
+ text_encoder=None,
+ device="cpu",
+ revision: str | None = None,
+ subfolder: str | None = None,
+ ):
+ """Load a local or Hugging Face policy package for inference.
+
+ Released DROID packages load BF16 or native-FP8r weights. Call
+ :meth:`prepare_inference` after placement to install the serving backend.
+ """
+ from safetensors.torch import load_file
+
+ directory = resolve_policy_directory(
+ pretrained_model_name_or_path, revision=revision, subfolder=subfolder
+ )
+ config_name = "config.native.json" if (directory / "config.native.json").is_file() else "config.json"
+ _verify_policy_manifest(directory, config_name)
+ config = PolicyConfig(**json.loads((directory / config_name).read_text()))
+ target = torch.device(device)
+ model_path = directory / "model.safetensors"
+
+ policy = cls(config, video_vae=video_vae, text_encoder=text_encoder, _restore=True)
+ state = load_file(str(model_path), device=str(target))
+ if config.quantization == "fp8r":
+ state = {name.removeprefix("dit."): value for name, value in state.items()}
+ from .models.transformer_inf_fp8r import FP8RInferenceDiT
+
+ policy.dit = FP8RInferenceDiT.from_quantized_state_dict(state)
+ else:
+ policy.load_state_dict(state, strict=True, assign=True)
+ return policy.to(target).eval()
+
+ def prepare_inference(self, *, compile: bool = True) -> bool:
+ """Install the prepared DROID backend and compile the DiT and VAE encoder.
+
+ BF16 policies stay trainable and saveable until this explicit operation.
+ Native FP8r policies already own their prepared weights and only need
+ validation and compilation here.
+ """
+ # Older packages explicitly disable this; serving encodes only the observed frame.
+ self.config.single_frame_encode = True
+ if isinstance(self.dit, JointSingleSeq):
+ if not _released_inference_config(self.config) or self.device.type != "cuda":
+ return False
+ from .models.transformer_inf_bf16 import BF16InferenceDiT
+
+ self.dit = BF16InferenceDiT.from_state_dict(self.dit.state_dict())
+ self.reset()
+ else:
+ assert _released_inference_config(self.config), (
+ "prepared backend requires released DROID geometry"
+ )
+ self.dit.validate_runtime_device()
+ if compile and self.dit._compiled_hot is None:
+ self.dit.compile_static()
+ self.dit.compile_hot()
+ if compile:
+ self.video_vae.module.compile_encoder()
+ self._inference_prepared = True
+ return True
+
+ @property
+ def video_vae(self):
+ return self.frozen.video_vae
+
+ @property
+ def text_encoder(self) -> nn.Module:
+ return self.frozen.text_encoder
+
+ def _apply(self, fn, *args, **kwargs):
+ assert not self._inference_prepared, "move policy before prepare_inference"
+ super()._apply(fn, *args, **kwargs)
+ frozen = self.__dict__.get("frozen")
+ if frozen is not None:
+
+ def cast_on_cpu(tensor):
+ # Discover the requested dtype without uploading the encoder's weights. Keep the rank
+ # so memory-format conversions also accept the probe (e.g. channels_last buffers).
+ probe = tensor.new_empty((0,) * tensor.ndim)
+ return tensor.to(device="cpu", dtype=fn(probe).dtype)
+
+ for module in frozen.modules():
+ offloaded = module is frozen.text_encoder and self._offload_text_encoder
+ module._apply(cast_on_cpu if offloaded else fn)
+ self.reset()
+ self.dtype_ = self.compute_dtype or next(self.dit.parameters()).dtype
+ return self
+
+ def set_compute_dtype(self, dtype: torch.dtype | None) -> None:
+ """Dtype of streams and context fed to the DiT when it differs from the stored parameters."""
+ self.compute_dtype = dtype
+ self.dtype_ = dtype or next(self.dit.parameters()).dtype
+ self._ctx_cache.clear()
+
+ def set_text_encoder_offload(self, enabled: bool) -> None:
+ """Keep the text encoder on the CPU; it visits the policy device only to encode a caption that is
+ not cached yet (once per instruction with a fixed instruction set). Saves its 8.9 GB of GPU memory."""
+ self.text_encoder.to("cpu" if enabled else self.device)
+ self._offload_text_encoder = bool(enabled)
+
+ @property
+ def device(self) -> torch.device:
+ return next(self.dit.parameters()).device
+
+ def freeze_streams(self, streams: tuple[str, ...]) -> list[str]:
+ """Exclude whole content streams from training (``requires_grad=False``); returns their parameter names.
+
+ The image and audio streams of the pretrained trunk receive no loss in action finetuning and
+ are not shipped, so they are frozen rather than decayed through zero gradients. Frozen
+ parameters stay out of ``get_optim_params()``, the power EMAs and the optimizer checkpoint;
+ exports take them unchanged from the trunk.
+ """
+ keys = {f".{s}." for s in streams}
+ names = []
+ for name, param in self.named_parameters():
+ if any(k in name for k in keys):
+ param.requires_grad_(False)
+ names.append(name)
+ return names
+
+ def freeze_conditioning_heads(self) -> list[str]:
+ """Freeze ``final_layer._cond``: conditioning tokens are inputs, their predictions are discarded."""
+ names = []
+ for mode, head in self.dit.final_layer.items():
+ if mode.endswith("_cond"):
+ for name, param in head.named_parameters():
+ param.requires_grad_(False)
+ names.append(f"dit.final_layer.{mode}.{name}")
+ return names
+
+ def get_optim_params(self) -> list[dict[str, Any]]:
+ """Two groups: the trunk and the fresh embodiment heads at their own rate."""
+ head_prefixes = tuple(f"dit.{n}." for n in fresh_module_names(self.modality))
+ trunk, heads = [], []
+ for name, p in self.named_parameters():
+ if not p.requires_grad:
+ continue
+ (heads if name.startswith(head_prefixes) else trunk).append(p)
+ groups: list[dict[str, Any]] = [{"params": trunk, "lr": self.config.optimizer_lr}]
+ if heads:
+ groups.append(
+ {"params": heads, "lr": self.config.optimizer_lr * self.config.optimizer_lr_heads_multiplier}
+ )
+ return groups
+
+ def reset(self) -> None:
+ self._ctx_cache.clear()
+ self._prepared_text_cache: dict[str, Any] = {}
+ self._action_queue: deque[Tensor] = deque([], maxlen=self.config.n_action_steps)
+ self._last_command: Tensor | None = None
+ self._observation_history = history.ObservationHistory(self.config.n_obs_steps)
+
+ # ------------------------------------------------------------------ batch helpers
+ def _flip(self, x: Tensor) -> Tensor:
+ """``x -> 1 - x`` on the configured gripper dims (last axis). Self-inverse."""
+ dims = list(self.config.gripper_flip_dims)
+ if not dims:
+ return x
+ x = x.clone()
+ x[..., dims] = 1.0 - x[..., dims]
+ return x
+
+ def _cameras(self, batch: dict[str, Any]) -> Tensor:
+ """Stack the configured cameras: ``(B, n_cams, T, 3, H, W)`` (``T = 1`` for single frames).
+
+ uint8 frames stay uint8 here; ``materialize_video`` scales them on the compute device, so a
+ training batch moves as bytes.
+ """
+ layout = self.config.camera_layout
+ cams = []
+ for key in self.config.camera_order:
+ if key not in batch:
+ have = sorted(k for k in batch if isinstance(k, str) and k.startswith("images."))
+ order = " [wrist, left exterior, right exterior]" if layout == "droid" else ""
+ raise KeyError(
+ f"batch lacks camera {key!r}; image keys present: {have}. camera_keys must name every "
+ f"stream as it appears in the batch (images.) in layout order{order}"
+ )
+ img = batch[key]
+ if img.ndim == 4:
+ img = img[:, None]
+ assert img.ndim == 5, "invalid camera rank"
+ assert (img.is_floating_point() or img.dtype == torch.uint8) and img.shape[2] == 3, (
+ "invalid camera tensor"
+ )
+ assert layout != "droid" or tuple(img.shape[-2:]) == (360, 640), "invalid DROID frame"
+ cams.append(img)
+ if len({tuple(c.shape) for c in cams}) != 1:
+ same_btc = len({tuple(c.shape[:3]) for c in cams}) == 1
+ assert layout == "grid" and same_btc, "incompatible camera shapes"
+ # the grid layout takes mixed resolutions: every camera is resized to the largest one first
+ hw = (max(c.shape[-2] for c in cams), max(c.shape[-1] for c in cams))
+ cams = [self._resize_camera(c, hw) for c in cams]
+ return torch.stack(cams, dim=1)
+
+ def _camera_list(self, batch: dict[str, Any]) -> list[Tensor]:
+ """The configured cameras as a list of ``(B, T, 3, H, W)`` tensors of one shape, without a CPU stack.
+
+ Keeps the loader's pinned tensors pinned, so the batched preprocessing moves them with asynchronous DMA
+ copies; cameras of differing resolution fall back to :meth:`_cameras` semantics (resize to the largest).
+ """
+ layout = self.config.camera_layout
+ cams = []
+ for key in self.config.camera_order:
+ if key not in batch:
+ have = sorted(k for k in batch if isinstance(k, str) and k.startswith("images."))
+ raise KeyError(f"batch lacks camera {key!r}; image keys present: {have}")
+ img = batch[key]
+ if img.ndim == 4:
+ img = img[:, None]
+ assert img.ndim == 5, "invalid camera rank"
+ assert (img.is_floating_point() or img.dtype == torch.uint8) and img.shape[2] == 3, (
+ "invalid camera tensor"
+ )
+ cams.append(img)
+ if len({tuple(c.shape) for c in cams}) != 1:
+ same_btc = len({tuple(c.shape[:3]) for c in cams}) == 1
+ assert layout == "grid" and same_btc, "incompatible camera shapes"
+ hw = (max(c.shape[-2] for c in cams), max(c.shape[-1] for c in cams))
+ cams = [self._resize_camera(c, hw) for c in cams]
+ return cams
+
+ @staticmethod
+ def _resize_camera(img: Tensor, hw: tuple[int, int]) -> Tensor:
+ """``(B, T, C, H, W)`` -> ``(B, T, C, *hw)``, keeping a uint8 input uint8."""
+ out = F.interpolate(
+ img.flatten(0, 1).float(), size=hw, mode="bilinear", align_corners=False, antialias=True
+ ).unflatten(0, img.shape[:2])
+ if img.dtype == torch.uint8:
+ out = out.round_().clamp_(0, 255).to(torch.uint8)
+ return out
+
+ def _state(self, batch: dict[str, Any]) -> Tensor:
+ state = batch[OBS_STATE]
+ if state.ndim == 3:
+ assert state.shape[1] == 1, "expected one state history frame"
+ state = state[:, 0] # a length-1 history from the dataset window
+ assert state.ndim == 2 and state.shape[1] == self.config.action_dim, "invalid state shape"
+ return state.float()
+
+ # ------------------------------------------------------------------ action space
+ def _normalize_state(self, state: Tensor) -> Tensor:
+ """Flipped state in dataset units ``(B, D)`` -> the state token's values."""
+ return normalization.normalize(state, self.config.state_normalization, self.config.normalization_clip)
+
+ def _action_targets(self, actions: Tensor, previous: Tensor | None) -> Tensor:
+ """Flipped commands ``(B, K, D)`` -> normalized training targets: the commands themselves, or their
+ per-frame deltas from ``previous`` (the command before the window) under ``joint_delta``."""
+ cfg = self.config
+ if cfg.action_parameterization == "joint_delta":
+ assert previous is not None, "joint deltas require action_prev"
+ actions = normalization.deltas(actions, self._flip(previous.float()), cfg.absolute_action_dims)
+ return normalization.normalize(actions, cfg.action_normalization, cfg.normalization_clip)
+
+ def _targets_to_actions(self, targets: Tensor, state: Tensor) -> Tensor:
+ """Predicted normalized targets ``(K, D)`` and the flipped observed ``state (D,)`` in dataset units ->
+ flipped absolute commands ``(K, D)`` in dataset units (deltas integrated onto the state)."""
+ cfg = self.config
+ targets = normalization.denormalize(targets, cfg.action_normalization)
+ if cfg.action_parameterization == "joint_delta":
+ targets = normalization.integrate(targets, state, cfg.absolute_action_dims)
+ return targets
+
+ @staticmethod
+ def _captions(batch: dict[str, Any], batch_size: int) -> list[str]:
+ task = batch.get("task")
+ if task is None:
+ return [""] * batch_size
+ if isinstance(task, str):
+ return [task] * batch_size
+ task = list(task)
+ if len(task) == 1 and batch_size > 1:
+ task = task * batch_size
+ assert len(task) == batch_size, "caption batch mismatch"
+ return ["" if t is None else str(t) for t in task]
+
+ @staticmethod
+ def _valid_windows(batch: dict[str, Any], batch_size: int, device: torch.device) -> Tensor:
+ """Windows that reach past the episode end carry ``*_is_pad`` flags; those samples are excluded.
+
+ Computed on the host: the flags come from the loader, and a device mask would cost a stream
+ synchronization (``tolist``) in the encoder stream for every micro-batch.
+ """
+ keep = torch.ones(batch_size, dtype=torch.bool)
+ for key, value in batch.items():
+ if (
+ isinstance(key, str)
+ and key.endswith("_is_pad")
+ and isinstance(value, Tensor)
+ and value.dtype == torch.bool
+ and value.ndim >= 1
+ and value.shape[0] == batch_size
+ ):
+ keep &= ~value.reshape(batch_size, -1).any(-1).cpu()
+ return keep
+
+ def _context(self, caption: str, device: torch.device) -> tuple[Tensor, Tensor]:
+ """Text context ``(1, L, ctx_dim)`` in the DiT dtype plus its position ids, cached per caption."""
+ fixed_length = self.config.text_fixed_length if self.config.inference_profile == "history" else None
+ return self._contexts([caption], device, fixed_length=fixed_length)[0]
+
+ def _contexts(
+ self, captions: list[str], device: torch.device, *, fixed_length: int | None = None
+ ) -> list[tuple[Tensor, Tensor]]:
+ """Contexts of many captions; the ones not cached are encoded together (one call per length bucket)."""
+ keys = {c: c if fixed_length is None else (c, fixed_length) for c in captions}
+ wanted = set(captions)
+ todo = sorted(
+ c for c in wanted if (hit := self._ctx_cache.get(keys[c])) is None or hit[0].device != device
+ )
+ if todo:
+ if len(self._ctx_cache) + len(todo) > 256:
+ # Bounded cache: start over, and encode every caption of this batch so that the ones that were
+ # hits a moment ago are present again.
+ self._ctx_cache.clear()
+ self._prepared_text_cache.clear()
+ todo = sorted(wanted)
+ encoder = self.text_encoder
+ try:
+ if self._offload_text_encoder:
+ encoder.to(device)
+ encoded = text_contexts(encoder, todo, device, fixed_length=fixed_length)
+ finally:
+ if self._offload_text_encoder:
+ encoder.to("cpu")
+ if device.type == "cuda":
+ torch.cuda.empty_cache()
+ for caption, ctx in zip(todo, encoded, strict=True):
+ self._ctx_cache[keys[caption]] = (
+ ctx.to(self.dtype_),
+ packing.pack_text(ctx, VEC_DIM)["ctx_ids"],
+ )
+ return [self._ctx_cache[keys[c]] for c in captions]
+
+ def _cast_inputs(self, kwargs: dict[str, Tensor]) -> dict[str, Tensor]:
+ """Streams, context and vector in the DiT dtype; timesteps stay fp32 (bf16 collapses t near 1); ids stay int."""
+ out = {}
+ for k, v in kwargs.items():
+ if v.is_floating_point() and not (k.endswith("_timesteps") or k == "timesteps_ctx"):
+ v = v.to(self.dtype_)
+ out[k] = v
+ return out
+
+ # ------------------------------------------------------------------ training
+ @staticmethod
+ def _window_generators(batch: dict[str, Any], batch_size: int) -> list[torch.Generator | None]:
+ """One CPU generator per window seeded from the loader's ``window_seed``, or ``None`` (global RNG).
+
+ With seeds, a window's caption dropout and augmentation depend on the window alone: not on the
+ rank that trains it, nor on when it is encoded (``prepare`` may run ahead of the DiT step), so a
+ resumed run reproduces them exactly.
+ """
+ seeds = batch.get(WINDOW_SEED)
+ if seeds is None:
+ return [None] * batch_size
+ seeds = seeds.tolist() if isinstance(seeds, Tensor) else list(seeds)
+ assert len(seeds) == batch_size, "window seed batch mismatch"
+ return [torch.Generator().manual_seed(int(s)) for s in seeds]
+
+ @torch.no_grad()
+ def prepare(self, batch: dict[str, Any], *, timings: StepTimings | None = None) -> PreparedWindows:
+ """Run everything before the DiT for a training micro-batch: validation, caption dropout,
+ augmentation, canvas composition, video-VAE and text encoding.
+
+ Frozen work without gradients; a trainer may run it on a side CUDA stream for the next
+ micro-batch while the current one trains (see ``training.trainer``). Randomness comes from the
+ per-window generators (``window_seed`` in the batch) when the loader provides them, else from the
+ global RNG; per window the draw order is caption dropout, camera dropout, augmentation, state dropout.
+ """
+ cfg = self.config
+ rng_before = None
+ if self.training: # every profile: dropout / augmentation may draw from the global RNG without window seeds
+ from .training.checkpoint import cpu_rng_state
+
+ rng_before = cpu_rng_state() # before any draw of this batch (see PreparedWindows.rng_before)
+ batched = (
+ cfg.preprocess_batched and self.training and cfg.inference_profile == "default"
+ and cfg.camera_layout in ("grid", "single", "side_by_side") and self.device.type == "cuda"
+ )
+ cams = self._camera_list(batch) if batched else self._cameras(batch) # (B, n_cams, T, 3, H, W) or per-camera list
+ b, t = (cams[0].shape[0], cams[0].shape[1]) if batched else (cams.shape[0], cams.shape[2])
+ if t != cfg.window_frames:
+ raise ValueError(
+ f"training needs {cfg.window_frames} frames per camera (observations plus future frames), got {t}"
+ )
+ device = self.device # frames may still be on the host; they move per VAE batch below
+ if cfg.inference_profile == "history":
+ commands = batch.get("command_history")
+ if commands is None:
+ raise ValueError("history training requires absolute command_history")
+ state = history.conditioning_values(batch["state"], commands, cfg)
+ previous = commands[:, -1]
+ else:
+ state = self._normalize_state(self._flip(self._state(batch)))
+ previous = batch.get(ACTION_PREV)
+ if state.shape[0] != b:
+ raise ValueError("state and cameras must have the same batch size")
+ state = state.contiguous().pin_memory().to(device, non_blocking=True) if device.type == "cuda" else state.to(device)
+ actions = self._flip(batch[ACTION].float()) # (B, chunk, D) commands in dataset units
+ if actions.shape != (b, cfg.chunk_size, cfg.action_dim):
+ raise ValueError(
+ f"actions must be (B, {cfg.chunk_size}, {cfg.action_dim}), got {tuple(actions.shape)}"
+ )
+ actions = self._action_targets(actions, previous).contiguous()
+ actions = actions.pin_memory().to(device, non_blocking=True) if device.type == "cuda" else actions.to(device)
+ keep = self._valid_windows(batch, b, device)
+ captions = self._captions(batch, b)
+ generators = self._window_generators(batch, b)
+ if self.training and cfg.caption_dropout > 0:
+ captions = [
+ "" if float(torch.rand((), generator=g)) < cfg.caption_dropout else c
+ for c, g in zip(captions, generators, strict=True)
+ ]
+ dropped: list[list[int]] = [[] for _ in range(b)]
+ if self.training and cfg.camera_dropout:
+ # one draw per configured camera and window, in camera order, after the caption draw
+ for i, g in enumerate(generators):
+ for c, key in enumerate(cfg.camera_order):
+ p = cfg.camera_dropout.get(key, 0.0)
+ if p > 0 and float(torch.rand((), generator=g)) < p:
+ dropped[i].append(c)
+ idx_keep = [i for i, valid in enumerate(keep.tolist()) if valid]
+ if not idx_keep:
+ empty = torch.zeros(0, device=device)
+ return PreparedWindows(idx_keep, empty, [], empty, empty, timings=timings, rng_before=rng_before)
+ with timings.section("text_context") if timings else nullcontext():
+ ctxs = [
+ ctx
+ for ctx, _ in self._contexts(
+ [captions[i] for i in idx_keep],
+ device,
+ fixed_length=cfg.text_fixed_length if cfg.inference_profile == "history" else None,
+ )
+ ]
+ latents = self._encode_windows(
+ cams, idx_keep, device, generators, dropped, timings=timings
+ ) # (n, 96, frames, h, w)
+ if self.training and cfg.state_dropout > 0:
+ # Blank the whole normalized conditioning state of a window with probability ``state_dropout``: one draw
+ # per window (all ``b`` windows, kept or not) from its generator -- the global RNG when ``None`` -- after
+ # every augmentation draw of ``_encode_windows`` and before the forward's timestep/noise draws
+ # (``draw_training_randomness`` below, or the forward itself), so the generator streams match the
+ # reference recipe. The blanked state feeds both ``_pack_eager`` and ``_pack_cached``.
+ blank = torch.tensor(
+ [float(torch.rand((), generator=g)) < cfg.state_dropout for g in generators], dtype=torch.bool
+ )
+ if device.type == "cuda":
+ blank = blank.pin_memory() # a pageable source would block the host on the queued encoder work
+ blank = blank.to(device, non_blocking=True)
+ state = state.masked_fill(blank.reshape(b, *([1] * (state.ndim - 1))), 0)
+ # Optional per-window action mask (B, D): a dataset that pools embodiments of different action widths
+ # into one head pads the narrow ones and masks the padding out of the loss.
+ mask = batch.get("action_mask")
+ if mask is not None:
+ mask = torch.as_tensor(mask, dtype=torch.float32)[idx_keep]
+ if cfg.pack_cache and device.type == "cuda":
+ mask = mask.pin_memory() # a pageable source would block the host on the queued encoder work
+ mask = mask.to(device, non_blocking=True)
+ if idx_keep != list(range(b)):
+ # Index with a device tensor: a Python-list index would stage a pageable copy on the encoder stream,
+ # which blocks the host until every queued encode has finished.
+ idx_dev = torch.tensor(idx_keep, dtype=torch.int64).pin_memory().to(device, non_blocking=True)
+ state, actions = state[idx_dev], actions[idx_dev]
+ drawn = None
+ if self.training and cfg.inference_profile == "default" and cfg.prefetch_randomness:
+ # The forward's random draws, made now in the forward's order so the global stream is unchanged, and
+ # moved to the device asynchronously instead of a synchronous host draw + copy at the step start.
+ n = len(idx_keep)
+ hw = cfg.latent_hw[0] * cfg.latent_hw[1]
+ drawn = packing.draw_training_randomness(
+ n, n_video_tokens=(packing.latent_frames(cfg.window_frames) - 1) * hw, n_cond_tokens=hw,
+ chunk=cfg.chunk_size, action_dim=cfg.action_dim, width=cfg.train_timestep_width,
+ shift=cfg.train_timestep_shift, separate_timesteps=cfg.separate_timesteps,
+ video_logit_mean=cfg.video_logit_mean, video_logit_std=cfg.video_logit_std,
+ conditioning_noise=cfg.conditioning_noise_max > 0, latent_dtype=torch.bfloat16,
+ )
+ if device.type == "cuda":
+ for key in ("video", "action", "cond"):
+ if key in drawn:
+ drawn[key] = drawn[key].pin_memory().to(device, non_blocking=True)
+ return PreparedWindows(idx_keep, latents, ctxs, state, actions, mask, timings=timings, drawn=drawn,
+ rng_before=rng_before)
+
+ def forward(
+ self, batch: dict[str, Any], prepared: PreparedWindows | None = None
+ ) -> tuple[Tensor, dict[str, Any]]:
+ """Training loss of a micro-batch; ``prepared`` is the output of :meth:`prepare` for this batch
+ (computed here when not given)."""
+ cfg = self.config
+ if prepared is None:
+ prepared = self.prepare(batch)
+ elif prepared.event is not None:
+ # encoded on another stream: order this stream after it and keep the tensors' memory from
+ # being recycled while it is still in use here
+ stream = torch.cuda.current_stream()
+ stream.wait_event(prepared.event)
+ for tensor in prepared.tensors():
+ tensor.record_stream(stream)
+ timings = prepared.timings
+ n = len(prepared.idx)
+ if n == 0:
+ zero = next(p for p in self.parameters() if p.requires_grad).sum() * 0.0
+ return zero, {"video_mse": 0.0, "action_mse": 0.0, "n_valid_windows": 0}
+ with timings.section("forward_pack") if timings else nullcontext():
+ if cfg.pack_cache and cfg.inference_profile == "default":
+ packed, seqlens, targets = self._pack_cached(prepared)
+ else:
+ packed, seqlens, targets = self._pack_eager(prepared)
+ model_inputs = self._cast_inputs(packed)
+ with timings.section("dit_forward") if timings else nullcontext():
+ pred = self.dit(**model_inputs, seqlens=seqlens)
+ with timings.section("loss") if timings else nullcontext():
+ losses = packing.flow_loss(
+ pred,
+ packing.flatten_windows(targets),
+ self.modality,
+ cfg.action_loss_weight,
+ cfg.video_loss_weight,
+ action_mask=prepared.action_mask,
+ reduction=cfg.loss_reduction,
+ channel_weights=cfg.action_channel_weights,
+ )
+ # the MSEs stay on the device (detached): a float() here would wait for the forward and delay
+ # the launch of the next micro-batch's encoders
+ return losses["loss"], {
+ "video_mse": losses["video_mse"],
+ "action_mse": losses["action_mse"],
+ "n_valid_windows": n,
+ }
+
+ def _pack_eager(
+ self, prepared: PreparedWindows
+ ) -> tuple[dict[str, Tensor], dict[str, list[int]], dict[str, Tensor]]:
+ """The windows of ``prepared`` as one packed DiT call: ``(kwargs, seqlens, flow targets)``."""
+ cfg = self.config
+ n = len(prepared.idx)
+ if cfg.inference_profile == "history":
+ video = history.pack_video(prepared.latents, cfg)
+ action = history.pack_actions(prepared.state, prepared.actions, cfg)
+ else:
+ video = packing.pack_video(prepared.latents, fps=cfg.fps)
+ action = packing.pack_actions(
+ prepared.state[:, None],
+ prepared.actions,
+ packing.default_action_times(n, cfg.chunk_size, cfg.fps),
+ self.modality,
+ scale=cfg.action_scale,
+ )
+ drawn = prepared.drawn
+ if drawn is not None:
+ timesteps = drawn["t"]
+ action_timesteps = timesteps
+ if cfg.separate_timesteps:
+ timesteps = drawn["t_video"]
+ else:
+ timesteps = packing.sample_timesteps(n, None, cfg.train_timestep_width, cfg.train_timestep_shift)
+ action_timesteps = timesteps
+ if cfg.separate_timesteps:
+ timesteps = torch.sigmoid(torch.randn(n) * cfg.video_logit_std + cfg.video_logit_mean)
+ kwargs, targets, _ = packing.build_forward_kwargs(
+ video,
+ action,
+ {},
+ timesteps,
+ self.modality,
+ action_timesteps=action_timesteps,
+ conditioning_noise_max=cfg.conditioning_noise_max if self.training else 0.0,
+ drawn=drawn,
+ )
+ # Pack all windows into one DiT forward while keeping attention within each window.
+ packed, seqlens = packing.pack_windows(kwargs, prepared.ctxs, VEC_DIM)
+ return packed, seqlens, targets
+
+ def _pack_cached(
+ self, prepared: PreparedWindows
+ ) -> tuple[dict[str, Tensor], dict[str, list[int]], dict[str, Tensor]]:
+ """:meth:`_pack_eager` for the default profile through :class:`packing.PackCache` (``pack_cache``): the same
+ tensors, with the layout-only ones reused across steps and no host synchronization at the step start."""
+ cfg = self.config
+ n = len(prepared.idx)
+ drawn = prepared.drawn
+ if drawn is None:
+ # the eager path's draws (timesteps, separate video timesteps, noise ...) in the same global-RNG order
+ _, _, n_latent, h, w = prepared.latents.shape
+ drawn = packing.draw_training_randomness(
+ n, n_video_tokens=(n_latent - 1) * h * w, n_cond_tokens=h * w, chunk=cfg.chunk_size,
+ action_dim=cfg.action_dim, width=cfg.train_timestep_width, shift=cfg.train_timestep_shift,
+ separate_timesteps=cfg.separate_timesteps, video_logit_mean=cfg.video_logit_mean,
+ video_logit_std=cfg.video_logit_std,
+ conditioning_noise=cfg.conditioning_noise_max > 0 and self.training, latent_dtype=torch.bfloat16,
+ )
+ return self._pack_cache.pack_training_windows(
+ prepared.latents,
+ prepared.state[:, None],
+ prepared.actions,
+ prepared.ctxs,
+ drawn,
+ self.modality,
+ fps=cfg.fps,
+ chunk=cfg.chunk_size,
+ scale=cfg.action_scale,
+ separate_timesteps=cfg.separate_timesteps,
+ conditioning_noise_max=cfg.conditioning_noise_max if self.training else 0.0,
+ vec_dim=VEC_DIM,
+ )
+
+ @staticmethod
+ def _drop_cameras(cams: Tensor, dropped: list[int]) -> Tensor:
+ """``(n_cams, T, 3, H, W)`` with the cameras ``dropped`` replaced by the flat mid-gray tile."""
+ if not dropped:
+ return cams
+ cams = cams.clone()
+ cams[dropped] = GRAY_LEVEL if cams.dtype == torch.uint8 else GRAY_LEVEL / 255.0
+ return cams
+
+ def _adapter_enabled(self, flag: str) -> bool:
+ """The adapter behind ``flag`` was installed for this policy (its optional dependencies are importable)."""
+ return bool(getattr(self.config, flag)) and getattr(self, "training_adapters_installed", True)
+
+ # The adapter modules import Triton / CuTe / NATTEN at module level: they are imported only when their flag is on
+ # (the default training path and CPU fixtures never touch them). An inactive scope (eval, history profile) still
+ # pushes None so that it masks an enclosing active scope.
+ def _vae_training_rmsnorm_context(self):
+ if not self._adapter_enabled("vae_cute_rmsnorm"):
+ return nullcontext()
+ from .models.vae_cute_rmsnorm import training_rmsnorm_context
+
+ return training_rmsnorm_context(self.training and self.config.inference_profile == "default")
+
+ def _vae_training_rope_context(self):
+ if not self._adapter_enabled("vae_cute_rope"):
+ return nullcontext()
+ from .models.vae_cute_rope import training_rope_context
+
+ active = self.training and self.config.inference_profile == "default"
+ return training_rope_context(getattr(self, "_vae_cute_rope_handle", None) if active else None)
+
+ def _vae_training_no_lse_context(self):
+ if not self._adapter_enabled("vae_natten_no_lse"):
+ return nullcontext()
+ from .models.vae_natten_no_lse import training_no_lse_context
+
+ active = self.training and self.config.inference_profile == "default"
+ return training_no_lse_context(getattr(self, "_vae_natten_no_lse_handle", None) if active else None)
+
+ def _vae_training_fused_context(self):
+ if not self._adapter_enabled("vae_fused_pointwise"):
+ return nullcontext()
+ from .models.vae_fused_pointwise import training_fused_context
+
+ active = self.training and self.config.inference_profile == "default"
+ return training_fused_context(getattr(self, "_vae_fused_state", None) if active else None)
+
+ def _vae_training_contexts(self):
+ """Every frozen-VAE training adapter plus bf16 autocast, as one context manager."""
+ from contextlib import ExitStack
+
+ stack = ExitStack()
+ stack.enter_context(self._vae_training_no_lse_context())
+ stack.enter_context(self._vae_training_rope_context())
+ stack.enter_context(self._vae_training_rmsnorm_context())
+ stack.enter_context(self._vae_training_fused_context())
+ stack.enter_context(torch.autocast("cuda", dtype=torch.bfloat16, enabled=self.device.type == "cuda"))
+ return stack
+
+ def _encode_videos_training(self, videos: Tensor) -> Tensor:
+ """The complete production encode of ``(nb, 3, T, Hc, Wc)`` canvases (adapters, autocast, trim) ->
+ ``(nb, 96, frames, h, w)``; captured as a whole by the CUDA graph when ``vae_cuda_graph`` is set."""
+ cfg = self.config
+ with self._vae_training_contexts():
+ return packing.encode_videos(
+ self.video_vae, videos, cfg.latent_hw, trim_causal_tail=cfg.vae_trim_causal_tail,
+ )
+
+ def _graphed_encode(self, videos: Tensor) -> Tensor:
+ if self._vae_graph_bank is None:
+ from .models.vae_graphed import GraphedVAEEncoderBank
+
+ self._vae_graph_bank = GraphedVAEEncoderBank(self._encode_videos_training)
+ return self._vae_graph_bank.encode(videos)
+
+ def _encode_windows(
+ self,
+ cams: Tensor,
+ idx: list[int],
+ device: torch.device,
+ generators: list[torch.Generator | None],
+ dropped: list[list[int]] | None = None,
+ *,
+ timings: StepTimings | None = None,
+ ) -> Tensor:
+ """Augment, compose and VAE-encode the windows ``idx`` of ``cams``: ``(len(idx), 96, frames, h, w)``.
+
+ The augmentation of window ``i`` is drawn from ``generators[i]`` (the global RNG when ``None``), in
+ window order; ``dropped[i]`` lists the cameras of window ``i`` that become gray tiles;
+ ``vae_batch_windows`` windows share one VAE call.
+ """
+ cfg = self.config
+ augment = self.training and cfg.augment
+ camera_hw = tuple(cams[0].shape[-2:]) if isinstance(cams, list) else tuple(cams.shape[-2:])
+ graphed = (
+ cfg.vae_cuda_graph and self.training and cfg.inference_profile == "default" and device.type == "cuda"
+ )
+ if isinstance(cams, list):
+ # Batched, bit-exact preprocessing of every window (one pinned H2D per camera, grouped colour ops).
+ from .processing.batched_preprocess import materialize_videos_batched
+
+ augs: list[dict | None] = [None] * cams[0].shape[0]
+ for i in idx: # same draw order and generator consumption as the per-window path
+ augs[i] = packing.sample_augmentation(generators[i], camera_hw=camera_hw) if augment else None
+ with timings.section("video_preprocess") if timings else nullcontext():
+ videos_all = materialize_videos_batched(
+ cams, augs, dropped, device, layout=cfg.camera_layout, canvas_hw=cfg.canvas_hw,
+ out_dtype=torch.bfloat16, windows=idx,
+ ) # (len(idx), 3, T, Hc, Wc) bf16 == stack of materialize_video(...).to(bf16)
+ latents = []
+ with timings.section("video_vae") if timings else nullcontext():
+ for start in range(0, len(idx), cfg.vae_batch_windows):
+ videos = videos_all[start : start + cfg.vae_batch_windows]
+ latents.append(
+ self._graphed_encode(videos) if graphed else self._encode_videos_training(videos)
+ )
+ return torch.cat(latents)
+ latents = []
+ for start in range(0, len(idx), cfg.vae_batch_windows):
+ with timings.section("video_preprocess") if timings else nullcontext():
+ videos = torch.stack(
+ [
+ packing.materialize_video(
+ self._drop_cameras(
+ cams[i].cpu().float() / 255
+ if cfg.inference_profile == "history" and cams.dtype == torch.uint8
+ else cams[i],
+ dropped[i] if dropped else [],
+ ),
+ packing.sample_augmentation(generators[i], camera_hw=camera_hw) if augment else None,
+ device,
+ layout=cfg.camera_layout,
+ canvas_hw=cfg.canvas_hw,
+ )
+ for i in idx[start : start + cfg.vae_batch_windows]
+ ]
+ ) # (nb, 3, T, Hc, Wc)
+ with timings.section("video_vae") if timings else nullcontext():
+ if cfg.inference_profile == "history":
+ with self._vae_training_contexts():
+ latents.append(history.encode_windows(self.video_vae, videos, cfg))
+ elif graphed:
+ latents.append(self._graphed_encode(videos))
+ else:
+ latents.append(self._encode_videos_training(videos))
+ return torch.cat(latents)
+
+ # ------------------------------------------------------------------ inference
+ @torch.no_grad()
+ def _encode_observation(self, cams: Tensor, state: Tensor) -> dict[str, Tensor]:
+ """``cams (n_cams, 1, 3, H, W)``, flipped ``state (1, D)`` -> the four conditioning tensors."""
+ cfg = self.config
+ canvas = packing.materialize_video(
+ cams, None, state.device, layout=cfg.camera_layout, canvas_hw=cfg.canvas_hw
+ )
+ return self._encode_canvas(canvas, state)
+
+ @torch.no_grad()
+ def _encode_canvas(self, canvas: Tensor, state: Tensor) -> dict[str, Tensor]:
+ """Canvas ``(3, 1, Hc, Wc)`` in ``[-1, 1]`` and flipped ``state (1, D)`` -> conditioning tensors."""
+ cfg = self.config
+ device = state.device
+ canvas = canvas.to(device)
+ latent = packing.encode_single_frame(
+ self.video_vae, canvas[:, 0], cfg.latent_hw, single_frame=cfg.single_frame_encode
+ ) # (1, 96, 1, h, w)
+ video, video_ids = batched_prc_vid(
+ latent.to(torch.bfloat16), packing.video_time_ids(1, 0, 1, fps=cfg.fps)
+ )
+ values = state[:, None] * cfg.action_scale
+ action, action_ids = batched_prc_action(
+ values.transpose(1, 2), times_to_ids(torch.zeros(1, 1, device=state.device))
+ )
+ return {
+ "x_video_cond": video,
+ "x_video_cond_ids": video_ids,
+ f"x_{self.modality}_cond": action.float(),
+ f"x_{self.modality}_cond_ids": action_ids,
+ }
+
+ @torch.no_grad()
+ def _sample(self, cond: dict[str, Tensor], caption: str, seed: int) -> Tensor:
+ """Joint video + action denoising from pure noise -> ``(chunk, D)`` in model units / action_scale."""
+ cfg, m, mdt = self.config, self.modality, self.dtype_
+ ak, ck = f"x_{m}", f"x_{m}_cond"
+ device = cond["x_video_cond"].device
+ rich_history = cfg.inference_profile == "history"
+ n_pred = (
+ packing.latent_frames(cfg.chunk_size)
+ if rich_history
+ else packing.latent_frames(cfg.window_frames) - 1
+ )
+ rng = torch.Generator().manual_seed(seed)
+ video_noise = torch.randn(1, packing.LATENT_CHANNELS, n_pred, *cfg.latent_hw, generator=rng)
+ x_video, x_video_ids = batched_prc_vid(
+ video_noise,
+ packing.video_time_ids(
+ n_pred,
+ packing.latent_frames(cfg.n_obs_steps) if rich_history else 1,
+ 1,
+ fps=cfg.video_position_fps if rich_history else cfg.fps,
+ ),
+ )
+ times = (
+ torch.arange(cfg.chunk_size).float()[None] / cfg.fps
+ if rich_history
+ else packing.default_action_times(1, cfg.chunk_size, cfg.fps)
+ )
+ action_noise = torch.randn(1, cfg.action_dim, cfg.chunk_size, generator=rng)
+ x_action, x_action_ids = batched_prc_action(action_noise, times_to_ids(times))
+ # The solver state stays fp32 (scaled joint targets would lose ~0.01 rad per bf16 round trip);
+ # inputs are cast at the model boundary.
+ flow = {"x_video": x_video.to(device), ak: x_action.to(device)}
+ fixed = {
+ "x_video_ids": x_video_ids.to(device),
+ f"{ak}_ids": x_action_ids.to(device),
+ "x_video_cond": cond["x_video_cond"].to(device, mdt),
+ "x_video_cond_ids": cond["x_video_cond_ids"].to(device),
+ "x_video_cond_timesteps": torch.zeros(1, cond["x_video_cond"].shape[1], device=device),
+ ck: cond[ck].to(device, mdt),
+ f"{ck}_ids": cond[f"{ck}_ids"].to(device),
+ f"{ck}_timesteps": torch.zeros(1, cond[ck].shape[1], device=device),
+ "vector": torch.zeros(1, VEC_DIM, device=device, dtype=mdt),
+ }
+ guidance = {
+ "x_video": cfg.guidance_scale,
+ ak: cfg.guidance_scale if cfg.guidance_scale_action is None else cfg.guidance_scale_action,
+ }
+ ctx_c = self._context(caption, device)
+ ctx_uc = self._context("", device) if any(g != 1.0 for g in guidance.values()) else None
+
+ if self._inference_prepared:
+ return (
+ self._sample_prepared(
+ flow=flow,
+ fixed=fixed,
+ caption=caption,
+ ctx_c=ctx_c,
+ ctx_uc=ctx_uc,
+ guidance=guidance,
+ )[ak][0].float()
+ / cfg.action_scale
+ )
+
+ assert isinstance(self.dit, JointSingleSeq), "call prepare_inference before prediction"
+
+ def predict(samples: dict[str, Tensor], t) -> dict[str, Tensor]:
+ t = float(t) / 1000.0 if isinstance(t, Tensor) and not t.is_floating_point() else float(t)
+ timesteps = {
+ "x_video_timesteps": torch.full((1, samples["x_video"].shape[1]), t, device=device),
+ f"{ak}_timesteps": torch.full((1, cfg.chunk_size), t, device=device),
+ }
+ model_in = {k: v.to(mdt) for k, v in samples.items()}
+ if ctx_uc is None: # guidance 1.0 on every stream: a single conditional pass
+ ctx, ctx_ids = ctx_c
+ pred = self.dit(
+ **model_in,
+ **fixed,
+ **timesteps,
+ ctx=ctx,
+ ctx_ids=ctx_ids,
+ timesteps_ctx=torch.zeros(ctx.shape[:2], device=device),
+ )
+ pred = {k: pred[k] for k in model_in}
+ else:
+ pred = sampling.cfg_two_pass(self.dit, model_in, fixed, timesteps, ctx_uc, ctx_c, guidance)
+ return {k: v.float() for k, v in pred.items()}
+
+ if cfg.sampler == "cosmos_unipc":
+ out = sampling.cosmos_unipc_order2(
+ flow, predict, n_steps=cfg.num_inference_steps, shift=cfg.sampler_shift
+ )
+ else:
+ out = sampling.euler(flow, predict, n_steps=cfg.num_inference_steps, alpha=cfg.sampler_shift)
+ return out[ak][0].float() / cfg.action_scale
+
+ def _prepared_text(self, caption: str, ctx: tuple[Tensor, Tensor], vector: Tensor):
+ cached = self._prepared_text_cache.get(caption)
+ if cached is None:
+ cached = self.dit.prepare_text(ctx[0], ctx[1], vector)
+ self._prepared_text_cache[caption] = cached
+ return cached
+
+ def _sample_prepared(
+ self,
+ *,
+ flow: dict[str, Tensor],
+ fixed: dict[str, Tensor],
+ caption: str,
+ ctx_c: tuple[Tensor, Tensor],
+ ctx_uc: tuple[Tensor, Tensor] | None,
+ guidance: dict[str, float],
+ ) -> dict[str, Tensor]:
+ """Run the existing solver over an optimized prepared DROID DiT."""
+ cfg, model = self.config, self.dit
+ action_key = f"x_{self.modality}"
+ cond_key = f"{action_key}_cond"
+ vector = fixed["vector"]
+
+ def prepare(caption_key: str, ctx: tuple[Tensor, Tensor]):
+ text = self._prepared_text(caption_key, ctx, vector)
+ return model.prepare_observation(
+ text,
+ video_ids=fixed["x_video_ids"],
+ video_cond=fixed["x_video_cond"],
+ video_cond_ids=fixed["x_video_cond_ids"],
+ action_ids=fixed[f"{action_key}_ids"],
+ action_cond=fixed[cond_key],
+ action_cond_ids=fixed[f"{cond_key}_ids"],
+ )
+
+ request = prepare(caption, ctx_c)
+ negative_request = prepare("", ctx_uc) if ctx_uc is not None else None
+ _, ticks = sampling.cosmos_unipc_schedule(cfg.num_inference_steps, cfg.sampler_shift)
+ times = ticks.to(device=self.device, dtype=torch.float32) / 1000.0
+ steps = model.prepare_steps(request, times, times)
+ phase = 0
+
+ def predict(samples: dict[str, Tensor], _t) -> dict[str, Tensor]:
+ nonlocal phase
+ inputs = {
+ "video": samples["x_video"].to(torch.bfloat16),
+ "action": samples[action_key].to(torch.bfloat16),
+ }
+ if negative_request is None:
+ result = model.forward_prepared(request, steps[phase], **inputs).as_dict()
+ else:
+ negative = model.forward_prepared(negative_request, steps[phase], **inputs).as_dict()
+ positive = model.forward_prepared(request, steps[phase], **inputs).as_dict()
+ result = {
+ key: negative[key] + guidance[key] * (positive[key] - negative[key]) for key in flow
+ }
+ phase += 1
+ return {key: value.float() for key, value in result.items()}
+
+ return sampling.cosmos_unipc_order2(
+ flow,
+ predict,
+ n_steps=cfg.num_inference_steps,
+ shift=cfg.sampler_shift,
+ )
+
+ @torch.no_grad()
+ def training_targets(self, batch: dict[str, Any]) -> Tensor:
+ """The normalized targets a training window carries, ``(B, chunk_size, action_dim)``: flip, deltas from
+ ``action_prev`` under ``joint_delta``, range normalization. Comparable to :meth:`predict_normalized_targets`."""
+ cfg = self.config
+ actions = self._flip(batch[ACTION].float())
+ if actions.ndim != 3 or actions.shape[1:] != (cfg.chunk_size, cfg.action_dim):
+ raise ValueError(
+ f"actions must be (B, {cfg.chunk_size}, {cfg.action_dim}), got {tuple(actions.shape)}"
+ )
+ previous = (
+ batch["command_history"][:, -1] if cfg.inference_profile == "history" else batch.get(ACTION_PREV)
+ )
+ return self._action_targets(actions, previous)
+
+ @torch.no_grad()
+ def predict_normalized_targets(self, batch: dict[str, Any]) -> Tensor:
+ """Observation batch -> ``(B, chunk_size, action_dim)`` predicted targets in the trained action space:
+ normalized, deltas under ``joint_delta``, before denormalization and integration."""
+ self.config.validate_inference()
+ if self._inference_prepared and self.dit._compiled_hot is not None:
+ torch.compiler.cudagraph_mark_step_begin()
+ if self.training:
+ # Prediction enters eval once; validation callers may resume training.
+ self.eval()
+ if self.config.inference_profile == "history":
+ batch = history.observation_window(batch, self.config)
+ cams = self._cameras(batch)
+ state, commands = batch["state"], batch["command_history"]
+ if cams.shape[0] != state.shape[0] or cams.device != state.device:
+ raise ValueError("state and cameras must have the same batch size and device")
+ return torch.stack(
+ [
+ self._sample(
+ history.pack_conditioning(
+ self.video_vae, cams[i], state[i : i + 1], commands[i : i + 1], self.config
+ ),
+ caption,
+ self.config.inference_seed,
+ )
+ for i, caption in enumerate(self._captions(batch, state.shape[0]))
+ ]
+ )
+ cams = self._cameras(batch)[:, :, :1] # the current frame (index 0 of a window)
+ state = self._flip(self._state(batch)) # (B, D) in dataset units
+ b = state.shape[0]
+ assert cams.shape[0] == b and cams.device == state.device, "observation batch mismatch"
+ captions = self._captions(batch, b)
+ token = self._normalize_state(state)
+ targets = []
+ for i in range(b):
+ cond = self._encode_observation(cams[i], token[i : i + 1])
+ targets.append(self._sample(cond, captions[i], self.config.inference_seed))
+ return torch.stack(targets)
+
+ @torch.no_grad()
+ def actions_from_targets(self, targets: Tensor, state: Tensor) -> Tensor:
+ """Normalized targets ``(B, chunk_size, action_dim)`` and the observed ``state (B, action_dim)`` in dataset
+ units -> absolute commands in dataset units (gripper as stored)."""
+ flipped = self._flip(state.float())
+ chunks = [self._targets_to_actions(t, s.to(t.device)) for t, s in zip(targets, flipped, strict=True)]
+ return self._flip(torch.stack(chunks)).float()
+
+ @torch.no_grad()
+ def predict_action_chunk(self, batch: dict[str, Any], **kwargs: Any) -> Tensor:
+ """Observation batch -> ``(B, chunk_size, action_dim)`` absolute commands in the dataset's action units.
+
+ Normalization is undone and, under ``joint_delta``, the predicted deltas are integrated onto the
+ observed state, so the result is what the dataset's action column holds (gripper as stored).
+ """
+ if kwargs:
+ raise NotImplementedError("FLUX Action does not implement RTC inference arguments yet")
+ if self.config.inference_profile == "history":
+ batch = history.observation_window(batch, self.config)
+ targets = self.predict_normalized_targets(batch)
+ return self.actions_from_targets(targets, batch["command_history"][:, -1])
+ targets = self.predict_normalized_targets(batch)
+ return self.actions_from_targets(targets, self._state(batch))
+
+ @torch.no_grad()
+ def predict_from_composite(
+ self, composite: Tensor, state: Tensor, task: str, *, seed: int | None = None
+ ) -> Tensor:
+ """DROID composite view -> ``(chunk_size, action_dim)`` actions in the dataset's conventions.
+
+ ``composite``: the 540x640 view a RoboLab or Cosmos client sends (wrist on top, the two
+ exteriors at half resolution below), uint8 ``(H, W, 3)`` or float ``(3, H, W)`` in ``[0, 1]``.
+ ``state``: ``(action_dim,)`` in the dataset's conventions (gripper as stored); the gripper
+ flip happens here on the way in and out, as in training. Placement on the canvas equals the
+ three-camera path, so a composite built like the training composite gives identical actions.
+ """
+ cfg = self.config
+ assert cfg.camera_layout == "droid", "composite inference requires DROID layout"
+ self.config.validate_inference()
+ if self._inference_prepared and self.dit._compiled_hot is not None:
+ torch.compiler.cudagraph_mark_step_begin()
+ if self.training:
+ # Prediction enters eval once; validation callers may resume training.
+ self.eval()
+ if composite.dtype == torch.uint8:
+ assert composite.ndim == 3 and composite.shape[-1] == 3, "invalid uint8 composite"
+ composite = composite.permute(2, 0, 1).float().div_(255.0)
+ else:
+ assert composite.ndim == 3 and composite.shape[0] == 3, "invalid float composite"
+ assert composite.is_floating_point(), "expected float composite"
+ device = self.device
+ canvas = packing.pad_composite(composite[None].to(device), cfg.canvas_hw) # (3, 1, Hc, Wc)
+ flipped = self._flip(state.float().reshape(1, -1)).to(device)
+ assert flipped.shape[1] == cfg.action_dim, "invalid state width"
+ cond = self._encode_canvas(canvas, self._normalize_state(flipped))
+ chunk = self._sample(cond, task, cfg.inference_seed if seed is None else seed)
+ return self._flip(self._targets_to_actions(chunk, flipped[0].to(chunk.device))).float()
+
+ @torch.no_grad()
+ def select_action(self, batch: dict[str, Any], **kwargs: Any) -> Tensor:
+ """One absolute command per call from a queue of ``n_action_steps`` predictions (open loop; a
+ ``joint_delta`` policy continues from its last returned command, initially the observed state).
+
+ Reset between episodes or interventions. Measured state still conditions every new prediction.
+ """
+ if kwargs:
+ raise NotImplementedError("FLUX Action does not implement RTC inference arguments yet")
+ if self.config.inference_profile == "history":
+ window = self._observation_history.append(batch, self.config, self._last_command)
+ if not self._action_queue:
+ targets = self.predict_normalized_targets(window)[:, : self.config.n_action_steps]
+ self._action_queue.extend(targets.transpose(0, 1))
+ target = self._action_queue.popleft()
+ action = self.actions_from_targets(target[:, None], window["command_history"][:, -1])[:, 0]
+ self._last_command = action.detach().clone()
+ return action
+ if len(self._action_queue) == 0:
+ if self.config.action_parameterization == "joint_delta":
+ targets = self.predict_normalized_targets(batch)
+ anchor = self._state(batch) if self._last_command is None else self._last_command
+ actions = self.actions_from_targets(targets, anchor)
+ else:
+ actions = self.predict_action_chunk(batch)
+ self._action_queue.extend(actions[:, : self.config.n_action_steps].transpose(0, 1))
+ action = self._action_queue.popleft()
+ if self.config.action_parameterization == "joint_delta":
+ self._last_command = action.detach().clone()
+ return action
diff --git a/flux-umi/src/flux_action/processing/__init__.py b/flux-umi/src/flux_action/processing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7168bb55431ff0544d74009ee58606c5e9daa7d
--- /dev/null
+++ b/flux-umi/src/flux_action/processing/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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/flux-umi/src/flux_action/processing/batched_preprocess.py b/flux-umi/src/flux_action/processing/batched_preprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ec63437dd478ac79999be9319eebc7c91a7d774
--- /dev/null
+++ b/flux-umi/src/flux_action/processing/batched_preprocess.py
@@ -0,0 +1,319 @@
+"""Batched, bit-exact replacement for the per-window ``packing.materialize_video`` path (grid layouts).
+
+Production (``FluxActionPolicy._encode_windows``) runs per window: pageable H2D copy of the window's
+uint8 cameras, ``float()/255``, torchvision crop + antialiased resize + ColorJitter (per-window random op
+order and factors), ``compose_grid`` (one antialiased resize per camera into its cell) and ``*2-1``.
+That is ~80 kernel launches and a ~40 ms blocking pageable copy per window (~7.5 s host per 128 windows).
+
+This module produces ``torch.equal`` canvases for all windows of a batch with ~1 % of the launches:
+
+* H2D: each camera tensor of the pinned DataLoader batch is copied with ``non_blocking=True`` into a
+ contiguous slice of one camera-major GPU buffer (pure DMA, no CPU stack).
+* Crop: all per-window offsets at once through an ``unfold`` view + one advanced-index gather on uint8
+ (the gather happens before the float conversion; elementwise ops commute with gathers exactly).
+* ``float().div_(255.0)``, the antialiased bilinear resize and the colour ops run on
+ ``[n_windows, n_cams*T, 3, H, W]`` tensors with per-window broadcast factor tensors. Windows are
+ grouped by their ``color_fn_order`` permutation (<= 24 groups) so the op order is preserved.
+ Every elementwise op uses the same ATen kernel as torchvision's eager path (torchvision's private
+ ``_rgb_to_hsv``/``_hsv_to_rgb`` are reused), hence identical float32 rounding.
+ Two ops cannot be batched across windows and stay per-window (1 launch per window each, on the window's
+ contiguous slice, exact by construction): ``_blend``'s ``add_(other, alpha=1-ratio)``, which ATen compiles
+ to an FMA that no tensor-alpha formulation reproduces (``addcmul`` / ``a + s*b`` round twice), and the
+ contrast mean, whose fp32 reduction tree ATen picks from the per-call shape (``[M, 1, H, W]`` -> M outputs;
+ a ``[n, M, 1, H, W]`` mean with n*M outputs uses another tree once ``H*W >= 131072`` or ``M < 16``, e.g.
+ 360x640 frames or T=5, and is off by 1 fp32 ulp).
+* Compose: the per-camera 256->256 antialiased resize of ``compose_grid`` is the identity for
+ scale 1 (weights (1, 0)); it is skipped when cell size == camera size and run batched otherwise.
+ ``canvas.mul_(2).sub_(1)`` is fused into ``addcmul(-1, x, 2)`` (``2x`` is exact in float32, so one or
+ two roundings give the same result) writing straight into the output canvas (or a bf16 output).
+"""
+
+from __future__ import annotations
+
+import math
+from collections import OrderedDict
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from torch import Tensor
+
+GRAY_LEVEL = 128 # policy.GRAY_LEVEL: the flat tile a dropped camera turns into
+
+
+def grid_shape(n_cams: int) -> tuple[int, int]:
+ """Same as ``packing.grid_shape``."""
+ cols = math.ceil(math.sqrt(n_cams))
+ return math.ceil(n_cams / cols), cols
+
+
+# ---------------------------------------------------------------- colour ops (torchvision arithmetic)
+def _gray(x: Tensor) -> Tensor:
+ """torchvision ``_rgb_to_grayscale_image(..., preserve_dtype=False)``: ``[..., 3, H, W] -> [..., 1, H, W]``."""
+ r, g, b = x.unbind(dim=-3)
+ return r.mul(0.2989).add_(g, alpha=0.587).add_(b, alpha=0.114).unsqueeze(dim=-3)
+
+
+def _blend(x: Tensor, other: Tensor, ratios: list[float], ratio_t: Tensor) -> Tensor:
+ """torchvision ``_blend`` with a ratio per window. ``x``: ``[n, M, 3, H, W]`` float in [0, 1]; ``ratio_t`` holds
+ the same ratios as a device tensor ``[n, 1, 1, 1, 1]`` (fp32 rounding of the python floats, as the scalar kernel)."""
+ out = x.mul(ratio_t) # same fp32 product as image.mul(python_float): the kernel casts the scalar to fp32
+ # ATen's add-with-alpha is `a + alpha * b` compiled to one FMA; keep the scalar-alpha kernel per window.
+ for j, ratio in enumerate(ratios):
+ out[j].add_(other[j], alpha=(1.0 - ratio))
+ return out.clamp_(0, 1.0)
+
+
+def _brightness(x: Tensor, factors: list[float], f_t: Tensor) -> Tensor:
+ return x.mul(f_t).clamp_(0, 1.0)
+
+
+def _contrast(x: Tensor, factors: list[float], f_t: Tensor) -> Tensor:
+ # torchvision: ``torch.mean(gray, dim=(-3, -2, -1), keepdim=True)`` on the window's ``[M, 1, H, W]`` grayscale.
+ # ATen chooses the fp32 reduction tree from the output count and the per-output size, so the mean must be
+ # launched per window on the same ``[M, 1, H, W]`` contiguous slice: one ``[n, M, 1, H, W]`` reduction (n*M
+ # outputs) differs by 1 ulp for H*W >= 131072 or M < 16 (see the module docstring).
+ gray = _gray(x)
+ mean = torch.stack([torch.mean(g, dim=(-3, -2, -1), keepdim=True) for g in gray.unbind(0)])
+ return _blend(x, mean, factors, f_t)
+
+
+def _saturation(x: Tensor, factors: list[float], f_t: Tensor) -> Tensor:
+ return _blend(x, _gray(x), factors, f_t)
+
+
+_SELECT_TABLE = {}
+
+
+def _select_table(device: torch.device) -> Tensor:
+ """torchvision's vpqt -> rgb mapping; cached per device (torchvision rebuilds it per call: a pageable H2D copy)."""
+ t = _SELECT_TABLE.get(device)
+ if t is None:
+ t = torch.tensor([[0, 2, 1, 1, 3, 0], [3, 0, 0, 2, 1, 1], [1, 1, 3, 0, 0, 2]], dtype=torch.long, device=device)
+ _SELECT_TABLE[device] = t
+ return t
+
+
+def _rgb_to_hsv(image: Tensor) -> Tensor:
+ """Verbatim torchvision.transforms.v2.functional._color._rgb_to_hsv (0.25)."""
+ r, g, _ = image.unbind(dim=-3)
+ minc, maxc = torch.aminmax(image, dim=-3)
+ eqc = maxc == minc
+ channels_range = maxc - minc
+ ones = torch.ones_like(maxc)
+ s = channels_range / torch.where(eqc, ones, maxc)
+ channels_range_divisor = torch.where(eqc, ones, channels_range).unsqueeze_(dim=-3)
+ rc, gc, bc = ((maxc.unsqueeze(dim=-3) - image) / channels_range_divisor).unbind(dim=-3)
+ mask_maxc_neq_r = maxc != r
+ mask_maxc_eq_g = maxc == g
+ hg = rc.add(2.0).sub_(bc).mul_(mask_maxc_eq_g & mask_maxc_neq_r)
+ hr = bc.sub_(gc).mul_(~mask_maxc_neq_r)
+ hb = gc.add_(4.0).sub_(rc).mul_(mask_maxc_neq_r.logical_and_(mask_maxc_eq_g.logical_not_()))
+ h = hr.add_(hg).add_(hb)
+ h = h.mul_(1.0 / 6.0).add_(1.0).fmod_(1.0)
+ return torch.stack((h, s, maxc), dim=-3)
+
+
+def _hsv_to_rgb(img: Tensor) -> Tensor:
+ """torchvision._hsv_to_rgb (0.25) with the cached select table; arithmetic unchanged."""
+ h, s, v = img.unbind(dim=-3)
+ h6 = h.mul(6)
+ i = torch.floor(h6)
+ f = h6.sub_(i)
+ i = i.to(dtype=torch.int32)
+ sxf = s * f
+ one_minus_s = 1.0 - s
+ q = (1.0 - sxf).mul_(v).clamp_(0.0, 1.0)
+ t = sxf.add_(one_minus_s).mul_(v).clamp_(0.0, 1.0)
+ p = one_minus_s.mul_(v).clamp_(0.0, 1.0)
+ i.remainder_(6)
+ vpqt = torch.stack((v, p, q, t), dim=-3)
+ select = _select_table(img.device)[:, i]
+ if select.ndim > 3:
+ select = select.moveaxis(0, -3)
+ return vpqt.gather(-3, select)
+
+
+def _hue(x: Tensor, hue_t: Tensor) -> Tensor:
+ """torchvision adjust_hue_image with a per-window hue tensor ``[n, 1, 1, 1]``."""
+ hsv = _rgb_to_hsv(x)
+ h = hsv.select(-3, 0) # [n, M, H, W]; the in-place add/remainder update ``hsv`` itself
+ h.add_(hue_t).remainder_(1.0)
+ # torchvision re-stacks (h, s, v) here; h, s, v are views of hsv already holding the result (pure copy, skipped)
+ return _hsv_to_rgb(hsv)
+
+
+_COLOR_OPS = {
+ 0: ("brightness_factor", _brightness),
+ 1: ("contrast_factor", _contrast),
+ 2: ("saturation_factor", _saturation),
+ 3: ("hue_factor", _hue),
+}
+
+
+_FACTOR_KEYS = ("brightness_factor", "contrast_factor", "saturation_factor", "hue_factor")
+
+
+def _augment_group(x: Tensor, augs: list[dict], factors: Tensor, hw: tuple[int, int]) -> Tensor:
+ """``x`` uint8/float ``[n, n_cams, T, 3, crop_h, crop_w]`` (already cropped) -> float ``[n, n_cams*T, 3, H, W]``.
+
+ ``factors``: device fp32 ``[n, 4]`` = (brightness, contrast, saturation, hue) of these windows."""
+ n, n_cams, t, c, crop_h, crop_w = x.shape
+ h, w = hw
+ x = x.reshape(n, n_cams * t, c, crop_h, crop_w)
+ x = x.float().div_(255.0) if not x.is_floating_point() else x.float()
+ if (crop_h, crop_w) != (h, w): # torchvision resize_image: identity early-return when sizes match
+ x = F.interpolate(
+ x.view(n * n_cams * t, c, crop_h, crop_w), size=[h, w], mode="bilinear", align_corners=False, antialias=True
+ ).view(n, n_cams * t, c, h, w)
+ for fn in augs[0]["color_fn_order"]:
+ key, op = _COLOR_OPS[fn]
+ f_t = factors[:, fn].view(-1, 1, 1, 1) if fn == 3 else factors[:, fn].view(-1, 1, 1, 1, 1)
+ x = op(x, [a[key] for a in augs], f_t) if fn != 3 else op(x, f_t)
+ return x
+
+
+def _group_key(a: dict | None):
+ if a is None:
+ return None
+ return (tuple(a["color_fn_order"]), int(a["crop_height"]), int(a["crop_width"]))
+
+
+# ---------------------------------------------------------------- public entry point
+@torch.no_grad()
+def materialize_videos_batched(
+ cams,
+ augmentations: list[dict | None],
+ dropped: list[list[int]] | None,
+ device: torch.device | str,
+ layout: str = "grid",
+ canvas_hw: tuple[int, int] = (512, 512),
+ *,
+ out_dtype: torch.dtype = torch.float32,
+ max_group_windows: int = 32,
+ windows: list[int] | None = None,
+) -> Tensor:
+ """Canvases ``[N, 3, T, Hc, Wc]`` equal to ``torch.stack([materialize_video(drop(cams[i]), aug[i]) ...])``.
+
+ ``cams``: list of ``n_cams`` tensors ``[N, T, 3, H, W]`` (uint8, ideally pinned: the DataLoader output per
+ camera key) or one tensor ``[N, n_cams, T, 3, H, W]`` (CPU or CUDA). ``augmentations[i]`` is
+ ``packing.sample_augmentation(...)`` for window ``i`` (``None`` = no augmentation); draw them in window
+ order on the host exactly as before. ``dropped[i]`` lists the cameras of window ``i`` replaced by the gray
+ tile (``policy._drop_cameras``). ``out_dtype=torch.bfloat16`` returns ``result.to(bfloat16)`` exactly, with
+ half the output memory (the VAE consumes bf16). ``max_group_windows`` bounds the transient memory
+ (~0.9 GB per window for the colour ops).
+ """
+ if layout not in ("grid", "single", "side_by_side"):
+ raise NotImplementedError(f"layout {layout!r}: only the antialiased grid-style layouts are batched here")
+ device = torch.device(device)
+ # -- 1. stage the uint8 frames on the device: one contiguous DMA per camera, no CPU stack
+ if isinstance(cams, (list, tuple)):
+ n_cams = len(cams)
+ n, t, c, h, w = cams[0].shape
+ buf = torch.empty((n_cams, n, t, c, h, w), dtype=cams[0].dtype, device=device)
+ for k, cam in enumerate(cams):
+ if cam.shape != (n, t, c, h, w):
+ raise ValueError("all cameras must share (N, T, 3, H, W) for the batched path")
+ buf[k].copy_(cam, non_blocking=True)
+ u8 = buf.transpose(0, 1) # [N, n_cams, T, 3, H, W] view (camera-major storage)
+ owned = True
+ else:
+ if cams.ndim != 6:
+ raise ValueError(f"cams must be (N, n_cams, T, 3, H, W), got {tuple(cams.shape)}")
+ owned = cams.device != device
+ u8 = cams.to(device, non_blocking=True)
+ n, n_cams, t, c, h, w = u8.shape
+ if len(augmentations) != n:
+ raise ValueError("one augmentation entry per window")
+ windows = list(range(n)) if windows is None else [int(i) for i in windows]
+ n_out = len(windows)
+ if layout == "single" and n_cams != 1 or layout == "side_by_side" and n_cams != 2:
+ raise ValueError(f"layout {layout!r} needs {1 if layout == 'single' else 2} cameras, got {n_cams}")
+ if dropped and any(dropped):
+ if not owned:
+ u8 = u8.clone()
+ for i, cameras in enumerate(dropped):
+ for k in cameras:
+ u8[i, k].fill_(GRAY_LEVEL if u8.dtype == torch.uint8 else GRAY_LEVEL / 255.0)
+
+ # -- 2. output canvas; cells without a camera and remainder strips are black (-1 after *2-1)
+ ch, cw = canvas_hw
+ rows, cols = (1, 1) if layout == "single" else (1, 2) if layout == "side_by_side" else grid_shape(n_cams)
+ cell_h, cell_w = ch // rows, cw // cols
+ out = torch.empty((n_out, c, t, ch, cw), dtype=out_dtype, device=device)
+ for idx in range(n_cams, rows * cols):
+ r, k = divmod(idx, cols)
+ out[:, :, :, r * cell_h : (r + 1) * cell_h, k * cell_w : (k + 1) * cell_w].fill_(-1.0)
+ if rows * cell_h != ch:
+ out[:, :, :, rows * cell_h :, :].fill_(-1.0)
+ if cols * cell_w != cw:
+ out[:, :, :, :, cols * cell_w :].fill_(-1.0)
+
+ # -- 3. windows grouped by colour-op order (and crop size); each group is one batched pass
+ groups: OrderedDict = OrderedDict() # key -> output positions (ascending)
+ for j, i in enumerate(windows):
+ groups.setdefault(_group_key(augmentations[i]), []).append(j)
+ chunks = []
+ for key, idx in groups.items():
+ for s in range(0, len(idx), max_group_windows):
+ chunks.append((key, idx[s : s + max_group_windows]))
+
+ # one small host->device copy carries every per-window parameter in group order (no stream syncs later):
+ # columns: window index, crop_top, crop_left (int64 view) | brightness, contrast, saturation, hue (fp32 view)
+ order = [j for _, idx in chunks for j in idx] # output positions in processing order
+ ints = torch.empty((n_out, 3), dtype=torch.int64)
+ floats = torch.empty((n_out, 4), dtype=torch.float32)
+ for pos_j, j in enumerate(order):
+ i = windows[j]
+ a = augmentations[i]
+ ints[pos_j, 0] = i # source window
+ ints[pos_j, 1] = int(a["crop_top"]) if a else 0
+ ints[pos_j, 2] = int(a["crop_left"]) if a else 0
+ for k, key in enumerate(_FACTOR_KEYS):
+ floats[pos_j, k] = float(a[key]) if a else 0.0
+ out_pos = torch.tensor(order, dtype=torch.int64).pin_memory().to(device, non_blocking=True)
+ ints_d = ints.pin_memory().to(device, non_blocking=True)
+ floats_d = floats.pin_memory().to(device, non_blocking=True)
+ consts = torch.tensor([-1.0, 2.0], dtype=torch.float32).pin_memory().to(device, non_blocking=True)
+ neg_one, two = consts[0], consts[1]
+ view = None
+ pos = 0
+ for key, idx in chunks: # idx: output positions of this chunk; source windows = ints_d[sl, 0]
+ sl = slice(pos, pos + len(idx))
+ pos += len(idx)
+ src = [windows[j] for j in idx]
+ contiguous = idx == list(range(idx[0], idx[0] + len(idx))) # contiguous output rows -> direct out= write
+ idx_t = None if contiguous else out_pos[sl]
+ if key is None:
+ x = u8[src[0] : src[0] + len(src)] if src == list(range(src[0], src[0] + len(src))) else u8[ints_d[sl, 0]]
+ x = x.reshape(len(idx), n_cams * t, c, h, w)
+ x = x.float().div_(255.0) if not x.is_floating_point() else x.float()
+ else:
+ augs = [augmentations[i] for i in src]
+ crop_h, crop_w = key[1], key[2]
+ tops = [int(a["crop_top"]) for a in augs]
+ lefts = [int(a["crop_left"]) for a in augs]
+ if min(tops) < 0 or min(lefts) < 0 or max(tops) + crop_h > h or max(lefts) + crop_w > w:
+ raise NotImplementedError("crops outside the frame (torchvision zero padding) are not batched")
+ if view is None or view.shape[-2:] != (crop_h, crop_w):
+ view = u8.unfold(4, crop_h, 1).unfold(5, crop_w, 1) # [N, n_cams, T, 3, H-ch+1, W-cw+1, ch, cw]
+ x = view[ints_d[sl, 0], :, :, :, ints_d[sl, 1], ints_d[sl, 2]] # [n, n_cams, T, 3, crop_h, crop_w]
+ x = _augment_group(x, augs, floats_d[sl], (h, w))
+ # -- 4. compose: cells into the canvas with the fused *2-1 (and the optional bf16 cast)
+ cells = x.view(len(idx), n_cams, t, c, h, w)
+ for k in range(n_cams):
+ r, q = divmod(k, cols)
+ cell = cells[:, k] # [n, T, 3, H, W]
+ if (cell_h, cell_w) != (h, w):
+ cell = F.interpolate(
+ cell.reshape(len(idx) * t, c, h, w), size=(cell_h, cell_w), mode="bilinear",
+ align_corners=False, antialias=True,
+ ).view(len(idx), t, c, cell_h, cell_w)
+ cell = cell.permute(0, 2, 1, 3, 4) # [n, 3, T, cell_h, cell_w]
+ region = out[:, :, :, r * cell_h : (r + 1) * cell_h, q * cell_w : (q + 1) * cell_w]
+ if idx_t is None:
+ torch.addcmul(neg_one, cell, two, out=region[idx[0] : idx[0] + len(idx)])
+ else:
+ tmp = torch.empty(cell.shape, dtype=out_dtype, device=device)
+ torch.addcmul(neg_one, cell, two, out=tmp)
+ region[idx_t] = tmp
+ return out
diff --git a/flux-umi/src/flux_action/processing/history.py b/flux-umi/src/flux_action/processing/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3004b276eeaf69f57a38650a15f7d3fa48fc6eb
--- /dev/null
+++ b/flux-umi/src/flux_action/processing/history.py
@@ -0,0 +1,183 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Shared history packing for training and synchronous inference."""
+
+from collections import deque
+from typing import TYPE_CHECKING
+
+import torch
+from torch import Tensor
+
+from ..models.positional import batched_prc_action, batched_prc_vid, times_to_ids
+from . import normalization, packing
+
+if TYPE_CHECKING:
+ from ..config import PolicyConfig
+
+
+class ObservationHistory:
+ """Record each control tick, including ticks served from the action queue."""
+
+ def __init__(self, length: int):
+ self.observations = deque(maxlen=length)
+ self.commands = deque(maxlen=length)
+
+ def append(self, batch: dict, config: "PolicyConfig", last_command: Tensor | None) -> dict:
+ state = batch["state"]
+ if state.ndim == 3 and state.shape[1] == 1:
+ state = state[:, 0]
+ if state.ndim != 2 or state.shape[-1] != config.action_dim:
+ raise ValueError("select_action needs one measured state per tick; reset between episodes")
+ current = {"state": state.detach().clone()}
+ for key in config.camera_keys:
+ image = batch[key]
+ if image.ndim == 5 and image.shape[1] == 1:
+ image = image[:, 0]
+ if image.ndim != 4 or image.shape[0] != state.shape[0]:
+ raise ValueError("select_action needs one image per camera and tick")
+ current[key] = image.detach().clone()
+ if self.observations:
+ for key, value in current.items():
+ previous = self.observations[-1][key]
+ if previous.shape != value.shape or previous.device != value.device:
+ raise ValueError(
+ "observation shape/device changed; reset before starting another episode"
+ )
+ command = state if last_command is None else last_command
+ repeats = config.n_obs_steps if not self.observations else 1
+ for _ in range(repeats):
+ self.observations.append(current)
+ self.commands.append(command.detach().clone())
+ return {
+ **batch,
+ **{key: torch.stack([item[key] for item in self.observations], 1) for key in current},
+ "command_history": torch.stack(list(self.commands), 1),
+ }
+
+
+def observation_window(batch: dict, config: "PolicyConfig") -> dict:
+ """Explicit offline window, or a fresh episode padded with its first observation."""
+ state = batch["state"]
+ if state.ndim == 2 or (state.ndim == 3 and state.shape[1] == 1 and "command_history" not in batch):
+ return ObservationHistory(config.n_obs_steps).append(batch, config, None)
+ if state.ndim != 3 or state.shape[1:] != (config.n_obs_steps, config.action_dim):
+ raise ValueError("prediction needs exactly n_obs_steps measured states")
+ commands = batch.get("command_history")
+ if commands is None or commands.shape != state.shape or commands.device != state.device:
+ raise ValueError("offline history prediction needs matching absolute command_history")
+ return batch
+
+
+def pack_conditioning(vae, cameras: Tensor, states: Tensor, commands: Tensor, config: "PolicyConfig"):
+ """One window: independent visual snapshots, normalized states and optional past commands."""
+ if cameras.shape[1] != config.n_obs_steps:
+ raise ValueError("history prediction needs exactly n_obs_steps camera observations")
+ if cameras.dtype == torch.uint8:
+ cameras = (cameras.cpu().float() / 255).to(states.device)
+ canvas = packing.materialize_video(
+ cameras, None, states.device, layout=config.camera_layout, canvas_hw=config.canvas_hw
+ )
+ indices = snapshot_indices(config)
+ tokens, positions = [], []
+ with torch.autocast("cuda", dtype=torch.bfloat16, enabled=states.device.type == "cuda"):
+ for index in indices:
+ latent = packing.encode_single_frame(vae, canvas[:, index], config.latent_hw, single_frame=True)
+ token, ids = batched_prc_vid(
+ latent, times_to_ids(torch.full((1, 1), index / config.video_position_fps))
+ )
+ tokens.append(token)
+ positions.append(ids)
+ action = pack_actions(conditioning_values(states, commands, config), None, config)
+ return {
+ "x_video_cond": torch.cat(tokens, 1),
+ "x_video_cond_ids": torch.cat(positions, 1),
+ **action,
+ }
+
+
+def snapshot_indices(config: "PolicyConfig") -> list[int]:
+ return (
+ [config.n_obs_steps - 1]
+ if config.history_snapshots == 1
+ else [
+ round(i * (config.n_obs_steps - 1) / (config.history_snapshots - 1))
+ for i in range(config.history_snapshots)
+ ]
+ )
+
+
+def conditioning_values(states: Tensor, commands: Tensor, config: "PolicyConfig") -> Tensor:
+ """Raw measured states and preceding absolute commands -> unscaled conditioning channels."""
+ if states.ndim != 3 or states.shape[1:] != (config.n_obs_steps, config.action_dim):
+ raise ValueError("history conditioning needs exactly n_obs_steps measured states")
+ if commands.shape != states.shape:
+ raise ValueError("history conditioning needs matching absolute command_history")
+ values = normalization.normalize(states.float(), config.state_normalization, config.normalization_clip)
+ if config.condition_on_past_actions:
+ past = commands[:, 1:].float()
+ if config.action_parameterization == "joint_delta":
+ past = normalization.deltas(past, commands[:, 0].float(), config.absolute_action_dims)
+ past = normalization.normalize(past, config.action_normalization, config.normalization_clip)
+ past = torch.cat([torch.zeros_like(commands[:, :1]), past], 1)
+ values = torch.cat([past, values], -1)
+ return values
+
+
+def pack_actions(values: Tensor, actions: Tensor | None, config: "PolicyConfig") -> dict[str, Tensor]:
+ b = values.shape[0]
+ times = (torch.arange(config.n_obs_steps).float() - (config.n_obs_steps - 1)) / config.fps
+ cond, ids = batched_prc_action(
+ values.transpose(1, 2),
+ times_to_ids(times[None].expand(b, -1)),
+ torch.full((b, 1), -1, dtype=torch.long),
+ )
+ result = {f"x_{config.action_modality}_cond": cond, f"x_{config.action_modality}_cond_ids": ids}
+ if actions is not None:
+ tok, pos = batched_prc_action(
+ (actions * config.action_scale).transpose(1, 2),
+ times_to_ids((torch.arange(config.chunk_size).float() / config.fps)[None].expand(b, -1)),
+ )
+ result.update(
+ {f"x_{config.action_modality}": tok.to(torch.bfloat16), f"x_{config.action_modality}_ids": pos}
+ )
+ return result
+
+
+@torch.no_grad()
+def encode_windows(vae, videos: Tensor, config: "PolicyConfig") -> Tensor:
+ """Encode each snapshot and the future independently, as in collab's task packer."""
+ clips = [videos[:, :, i : i + 1] for i in snapshot_indices(config)]
+ clips.append(videos[:, :, config.n_obs_steps :])
+ # Per-window VAE calls preserve the native task path's numerical contract.
+ latents = [
+ torch.cat([vae.encode_task(v[None].to(torch.bfloat16)).clone() for v in clip]) for clip in clips
+ ]
+ return torch.cat(latents, 2)[..., : config.latent_hw[0], : config.latent_hw[1]]
+
+
+def pack_video(latents: Tensor, config: "PolicyConfig") -> dict[str, Tensor]:
+ b = latents.shape[0]
+ times = torch.tensor(snapshot_indices(config)).float()[None].expand(b, -1) / config.video_position_fps
+ cond, cond_ids = batched_prc_vid(latents[:, :, : config.history_snapshots], times_to_ids(times))
+ future = latents[:, :, config.history_snapshots :]
+ tok, ids = batched_prc_vid(
+ future,
+ packing.video_time_ids(
+ future.shape[2],
+ packing.latent_frames(config.n_obs_steps),
+ b,
+ fps=config.video_position_fps,
+ ),
+ )
+ return {"x_video_cond": cond, "x_video_cond_ids": cond_ids, "x_video": tok, "x_video_ids": ids}
diff --git a/flux-umi/src/flux_action/processing/normalization.py b/flux-umi/src/flux_action/processing/normalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d1c8708a1331b013e8c063c459975ced5dfcf39
--- /dev/null
+++ b/flux-umi/src/flux_action/processing/normalization.py
@@ -0,0 +1,80 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Range normalization and the joint-delta parameterization of the SO-101 recipe.
+
+``normalize`` maps a channel's 1st / 99th percentile to -1 / 1 and clips: ``x_norm = clip(2 (x - q01) / span -
+1, -clip, clip)`` with ``span = q99 - q01``, or 1 where the bounds coincide (a gripper that never moved).
+``denormalize`` inverts it inside the clip range. ``deltas`` turns a window's absolute commands into the
+per-frame differences the recipe trains on (the command before the window supplies the first one), and
+``integrate`` adds predicted deltas onto the observed state. Both keep ``absolute_dims`` unchanged.
+"""
+
+from __future__ import annotations
+
+import torch
+from torch import Tensor
+
+DEGENERATE_SPAN = 1e-6
+
+
+def bounds_tensors(stats: dict[str, list[float]], like: Tensor) -> tuple[Tensor, Tensor]:
+ """``(q01, span)`` as tensors on ``like``'s device and dtype."""
+ q01 = torch.as_tensor(stats["q01"], dtype=like.dtype, device=like.device)
+ q99 = torch.as_tensor(stats["q99"], dtype=like.dtype, device=like.device)
+ span = q99 - q01
+ span = torch.where(span > DEGENERATE_SPAN, span, torch.ones_like(span))
+ return q01, span
+
+
+def normalize(x: Tensor, stats: dict[str, list[float]] | None, clip: float) -> Tensor:
+ """``(..., D)`` in dataset units -> normalized; ``stats=None`` is the identity."""
+ if stats is None:
+ return x
+ q01, span = bounds_tensors(stats, x)
+ return (2.0 * (x - q01) / span - 1.0).clamp_(-clip, clip)
+
+
+def denormalize(x: Tensor, stats: dict[str, list[float]] | None) -> Tensor:
+ """Inverse of :func:`normalize` (exact inside the clip range)."""
+ if stats is None:
+ return x
+ q01, span = bounds_tensors(stats, x)
+ return (x + 1.0) * span / 2.0 + q01
+
+
+def deltas(actions: Tensor, previous: Tensor, absolute_dims: tuple[int, ...]) -> Tensor:
+ """``actions (B, K, D)`` and the command before the window ``previous (B, D)`` -> ``a[t] - a[t-1]`` per
+ frame, with ``absolute_dims`` copied from ``actions`` unchanged."""
+ if previous.shape != (actions.shape[0], actions.shape[2]):
+ raise ValueError(
+ f"previous command must be (B, D) = {(actions.shape[0], actions.shape[2])}, got {tuple(previous.shape)}"
+ )
+ shifted = torch.cat([previous[:, None], actions[:, :-1]], dim=1)
+ out = actions - shifted
+ if absolute_dims:
+ dims = list(absolute_dims)
+ out[..., dims] = actions[..., dims]
+ return out
+
+
+def integrate(targets: Tensor, state: Tensor, absolute_dims: tuple[int, ...]) -> Tensor:
+ """``targets (K, D)`` deltas and the observed ``state (D,)`` -> absolute commands ``state + cumsum``;
+ ``absolute_dims`` are taken from ``targets`` as they are."""
+ if state.shape != (targets.shape[-1],):
+ raise ValueError(f"state must be ({targets.shape[-1]},), got {tuple(state.shape)}")
+ out = state[None] + torch.cumsum(targets, dim=0)
+ if absolute_dims:
+ dims = list(absolute_dims)
+ out[..., dims] = targets[..., dims]
+ return out
diff --git a/flux-umi/src/flux_action/processing/packing.py b/flux-umi/src/flux_action/processing/packing.py
new file mode 100644
index 0000000000000000000000000000000000000000..465a69fb3b0c39f2821c06d68a20e2271c541135
--- /dev/null
+++ b/flux-umi/src/flux_action/processing/packing.py
@@ -0,0 +1,839 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Observation window -> the exact DiT inputs, plus the flow-matching loss.
+
+DROID defaults and reusable token construction. The policy config overrides camera layout, canvas,
+action dimensions, chunk length, frame rate and representation scale. Recipe fidelity and limits are described
+in the upstream DROID fine-tuning guide.
+
+Pipeline for one training window (``chunk + 1`` frames: 1 conditioning + ``chunk`` predicted):
+
+ cameras uint8 (n_cams, T, 3, H, W)
+ -> materialize_video (augment, compose one canvas, [-1, 1])
+ -> encode_videos (video VAE, pad to 45 frames, crop the latent to the content)
+ -> pack_video (latent frame 0 = x_video_cond, frames 1.. = x_video)
+ state[s], action[s .. s+chunk-1]
+ -> pack_actions (x action_scale, audio-style ids on the shared 10 ms clock)
+ caption
+ -> text context (see text_encoder.text_context), pack_text
+ -> sample_timesteps + add_noise (one t per sample, shared by video and action)
+ -> build_forward_kwargs / flow_loss
+
+The steps above are batched over the windows of a micro-batch ``(B, ...)``. ``pack_windows`` then
+concatenates the ``B`` windows into one sequence of batch size 1 with per-window token counts, the
+form the DiT consumes in training (``JointSingleSeq.forward(seqlens=...)``): one forward per
+micro-batch, attention confined to each window, captions of any length side by side.
+"""
+
+from __future__ import annotations
+
+import math
+
+import torch
+import torch.nn.functional as F # noqa: N812
+from einops import rearrange, repeat
+from torch import Tensor
+
+from flux_action.models.positional import batched_prc_action, batched_prc_txt, batched_prc_vid, times_to_ids
+
+# ---- DROID reference recipe constants -------------------------------------------------------
+FPS = 15.0
+CHUNK = 32 # predicted actions per window
+CAMERA_HW = (360, 640) # DROID cameras
+COMPOSITE_HW = (540, 640) # wrist full-res on top, two exteriors half-res below
+CANVAS_HW = (544, 736) # Cosmos 480p 4:3 bucket; reflect-pad right 96 / bottom 4
+LATENT_HW = (17, 20) # post-VAE crop for the DROID composite (padded latent columns dropped)
+LATENT_CHANNELS = 96
+SPATIAL_DOWNSAMPLE = 32
+TEMPORAL_DOWNSAMPLE = 4
+VAE_CHUNK_FRAMES = 45 # the video VAE encodes 45-frame chunks
+VAE_PAD_VALUE = -1.0 # short clips are padded with black to the chunk length
+ACTION_DIM = 8 # DROID: 7 joints + gripper
+ACTION_SCALE = 2.0 # representation scale, applied before BOTH action embedders
+TIMESTEP_WIDTH = 0.75 # logit-logistic scale
+TIMESTEP_SHIFT = 42.0 # rational time shift ("alpha") of the training timestep distribution
+VIDEO_LOSS_WEIGHT = 1.0
+# Joint token mean: ONE mean over all target tokens of a window (2720 video + 32 action for DROID),
+# with this weight on the action tokens. The base value 100 undoes the dilution of 32 action tokens
+# among 2752 (2720 / 32 = 85, rounded up to tilt toward actions) and is divided once by the
+# representation scale. Effective per-modality ratio: 32 * 50 / 2720 = 0.588. A per-modality-pooled
+# loss would need 0.588 here, not 50.
+ACTION_LOSS_WEIGHT = 100.0 / ACTION_SCALE
+TEXT_PAD_MULTIPLE = 80
+VEC_DIM = 768
+AUG_CROP_FRACTION = 0.95
+AUG_BRIGHTNESS, AUG_CONTRAST, AUG_SATURATION, AUG_HUE = 0.3, 0.4, 0.5, 0.08
+
+CAMERA_LAYOUTS = ("droid", "single", "side_by_side", "grid")
+
+assert math.isclose(ACTION_LOSS_WEIGHT, 50.0), ACTION_LOSS_WEIGHT
+
+
+def latent_frames(num_frames: int, temporal_downsample: int = TEMPORAL_DOWNSAMPLE) -> int:
+ return 1 + (num_frames - 1) // temporal_downsample
+
+
+def padded_chunk_length(num_frames: int, chunk: int, overlap: int = 1) -> int:
+ """Smallest ``T' >= num_frames`` satisfying ``T' = chunk + n * (chunk - overlap)``."""
+ stride = chunk - overlap
+ n = max(0, -(-(num_frames - chunk) // stride)) # ceil division
+ return chunk + n * stride
+
+
+def content_hw(layout: str, canvas_hw: tuple[int, int]) -> tuple[int, int]:
+ """Pixels of the canvas that carry image content (the rest is reflect padding)."""
+ if layout == "droid":
+ return COMPOSITE_HW
+ if layout in ("single", "side_by_side", "grid"):
+ return tuple(canvas_hw)
+ raise ValueError(f"unknown camera layout {layout!r}; choose from {CAMERA_LAYOUTS}")
+
+
+def latent_hw(layout: str, canvas_hw: tuple[int, int]) -> tuple[int, int]:
+ """Latent grid kept after the VAE: ceil(content / 32); DROID composite 540x640 -> 17x20."""
+ h, w = content_hw(layout, canvas_hw)
+ return (-(-h // SPATIAL_DOWNSAMPLE), -(-w // SPATIAL_DOWNSAMPLE))
+
+
+# ---- 1. pixels ------------------------------------------------------------------------------
+def sample_augmentation(
+ generator: torch.Generator | None = None, camera_hw: tuple[int, int] = CAMERA_HW
+) -> dict:
+ """Draw the Cosmos crop + color-jitter parameters for one window.
+
+ One draw is shared by all cameras and all frames (so the model cannot read the augmentation as
+ motion). Draw order mirrors torchvision's ColorJitter: crop top, crop left, function permutation,
+ then the factors.
+ """
+ h, w = camera_hw
+ crop_h, crop_w = int(h * AUG_CROP_FRACTION), int(w * AUG_CROP_FRACTION)
+ top = int(torch.randint(0, h - crop_h + 1, (), generator=generator))
+ left = int(torch.randint(0, w - crop_w + 1, (), generator=generator))
+ order = [int(i) for i in torch.randperm(4, generator=generator).tolist()]
+
+ def uniform(lo: float, hi: float) -> float:
+ return float(torch.empty(1).uniform_(lo, hi, generator=generator).item())
+
+ return {
+ "crop_top": top,
+ "crop_left": left,
+ "crop_height": crop_h,
+ "crop_width": crop_w,
+ "color_fn_order": order,
+ "brightness_factor": uniform(max(0.0, 1 - AUG_BRIGHTNESS), 1 + AUG_BRIGHTNESS),
+ "contrast_factor": uniform(max(0.0, 1 - AUG_CONTRAST), 1 + AUG_CONTRAST),
+ "saturation_factor": uniform(max(0.0, 1 - AUG_SATURATION), 1 + AUG_SATURATION),
+ "hue_factor": uniform(-AUG_HUE, AUG_HUE),
+ }
+
+
+def apply_augmentation(x: Tensor, a: dict) -> Tensor:
+ """``x`` float ``(N, 3, H, W)`` in ``[0, 1]`` -> same shape, cropped/resized back + color jitter."""
+ import torchvision.transforms.v2.functional as tvf
+
+ h, w = x.shape[-2:]
+ x = tvf.crop(x, top=a["crop_top"], left=a["crop_left"], height=a["crop_height"], width=a["crop_width"])
+ x = tvf.resize(x, size=[h, w], antialias=True)
+ for fn in a["color_fn_order"]:
+ if fn == 0:
+ x = tvf.adjust_brightness(x, a["brightness_factor"])
+ elif fn == 1:
+ x = tvf.adjust_contrast(x, a["contrast_factor"])
+ elif fn == 2:
+ x = tvf.adjust_saturation(x, a["saturation_factor"])
+ else:
+ x = tvf.adjust_hue(x, a["hue_factor"])
+ return x
+
+
+def grid_shape(n_cams: int) -> tuple[int, int]:
+ """Near-square ``(rows, cols)``, wider than tall: 1 -> 1x1, 2 -> 1x2, 3 and 4 -> 2x2, 5 and 6 -> 2x3."""
+ cols = math.ceil(math.sqrt(n_cams))
+ return math.ceil(n_cams / cols), cols
+
+
+def compose_grid(cams: Tensor, canvas_hw: tuple[int, int]) -> Tensor:
+ """Any number of cameras, each resized into one cell of a near-square grid (row-major); unused cells black.
+
+ The generic layout for camera setups outside the validated ones. It runs for any count and resolution,
+ but no checkpoint was trained on it, so finetune quality away from the named layouts is unmeasured.
+ """
+ n_cams, t, c = cams.shape[:3]
+ ch, cw = canvas_hw
+ rows, cols = grid_shape(n_cams)
+ cell_h, cell_w = ch // rows, cw // cols
+ canvas = cams.new_zeros(t, c, ch, cw)
+ for i, cam in enumerate(cams.unbind(0)):
+ r, k = divmod(i, cols)
+ cell = F.interpolate(cam, size=(cell_h, cell_w), mode="bilinear", align_corners=False, antialias=True)
+ canvas[:, :, r * cell_h : (r + 1) * cell_h, k * cell_w : (k + 1) * cell_w] = cell
+ return canvas
+
+
+def compose_canvas(cams: Tensor, layout: str, canvas_hw: tuple[int, int] = CANVAS_HW) -> Tensor:
+ """``cams`` float ``(n_cams, T, 3, H, W)`` in ``[0, 1]`` -> canvas ``(3, T, Hc, Wc)`` in ``[-1, 1]``.
+
+ ``droid``: three 360x640 cameras [wrist, left, right] -> wrist full-res on top, exteriors half-res
+ side by side below (540x640) -> reflect-pad right/bottom to the canvas.
+ ``single``: one camera, resized to the canvas. ``side_by_side``: two cameras, each half the width.
+ ``grid``: any number of cameras in a near-square grid (:func:`compose_grid`).
+ What binds a checkpoint is that training and deployment use the same layout and canvas.
+ """
+ n_cams, _, _, h, w = cams.shape
+ ch, cw = canvas_hw
+ if layout == "droid":
+ if n_cams != 3 or (h, w) != CAMERA_HW:
+ raise ValueError(f"droid layout needs 3 cameras of {CAMERA_HW}, got {n_cams} of {(h, w)}")
+ wrist, left, right = cams.unbind(0)
+ half = (h // 2, w // 2)
+ left = F.interpolate(left, size=half, mode="bilinear", align_corners=False)
+ right = F.interpolate(right, size=half, mode="bilinear", align_corners=False)
+ composite = torch.cat([wrist, torch.cat([left, right], dim=-1)], dim=-2) # (T, 3, 540, 640)
+ return pad_composite(composite, canvas_hw)
+ elif layout == "single":
+ if n_cams != 1:
+ raise ValueError(f"single layout needs exactly one camera, got {n_cams}")
+ canvas = F.interpolate(cams[0], size=(ch, cw), mode="bilinear", align_corners=False, antialias=True)
+ elif layout == "side_by_side":
+ if n_cams != 2 or cw % 2:
+ raise ValueError(f"side_by_side layout needs two cameras and an even canvas width, got {n_cams}")
+ canvas = torch.cat(
+ [
+ F.interpolate(cam, size=(ch, cw // 2), mode="bilinear", align_corners=False, antialias=True)
+ for cam in cams
+ ],
+ dim=-1,
+ )
+ elif layout == "grid":
+ canvas = compose_grid(cams, canvas_hw)
+ else:
+ raise ValueError(f"unknown camera layout {layout!r}; choose from {CAMERA_LAYOUTS}")
+ return canvas.permute(1, 0, 2, 3).contiguous().mul_(2.0).sub_(1.0)
+
+
+def pad_composite(composite: Tensor, canvas_hw: tuple[int, int] = CANVAS_HW) -> Tensor:
+ """DROID composite ``(T, 3, 540, 640)`` in ``[0, 1]`` -> canvas ``(3, T, Hc, Wc)`` in ``[-1, 1]``.
+
+ Reflect-pads right and bottom, the placement the three-camera path and the RoboLab/Cosmos
+ composite input share (wrist on top, the two exteriors at half resolution below).
+ """
+ if composite.ndim != 4 or composite.shape[1] != 3 or tuple(composite.shape[-2:]) != COMPOSITE_HW:
+ raise ValueError(
+ f"composite must be (T, 3, {COMPOSITE_HW[0]}, {COMPOSITE_HW[1]}), got {tuple(composite.shape)}"
+ )
+ ch, cw = canvas_hw
+ pad_right, pad_bottom = cw - composite.shape[-1], ch - composite.shape[-2]
+ if pad_right < 0 or pad_bottom < 0:
+ raise ValueError(f"canvas {canvas_hw} smaller than the DROID composite {COMPOSITE_HW}")
+ canvas = F.pad(composite.float(), (0, pad_right, 0, pad_bottom), mode="reflect")
+ return canvas.permute(1, 0, 2, 3).contiguous().mul_(2.0).sub_(1.0)
+
+
+def materialize_video(
+ cameras: Tensor,
+ augmentation: dict | None,
+ device: torch.device | str,
+ *,
+ layout: str = "droid",
+ canvas_hw: tuple[int, int] = CANVAS_HW,
+) -> Tensor:
+ """``cameras`` uint8 or float ``(n_cams, T, 3, H, W)`` -> canvas ``(3, T, Hc, Wc)`` in ``[-1, 1]``.
+
+ Deterministic given ``augmentation`` (None = no augmentation, the inference path). uint8 is
+ scaled by 255; float input is taken as already in ``[0, 1]``.
+ """
+ if cameras.ndim != 5:
+ raise ValueError(f"cameras must be (n_cams, T, 3, H, W), got {tuple(cameras.shape)}")
+ n_cams, t, c, h, w = cameras.shape
+ x = cameras.to(device=device, non_blocking=True).reshape(-1, c, h, w)
+ x = x.float().div_(255.0) if cameras.dtype == torch.uint8 else x.float()
+ if augmentation is not None:
+ x = apply_augmentation(x, augmentation)
+ return compose_canvas(x.reshape(n_cams, t, c, h, w), layout, canvas_hw)
+
+
+# ---- 2. video VAE ---------------------------------------------------------------------------
+@torch.no_grad()
+def encode_videos(
+ vae,
+ videos: Tensor,
+ latent_hw: tuple[int, int] = LATENT_HW,
+ *,
+ chunk_frames: int = VAE_CHUNK_FRAMES,
+ pad_value: float = VAE_PAD_VALUE,
+ trim_causal_tail: bool = False,
+) -> Tensor:
+ """``(B, 3, T, Hc, Wc)`` in ``[-1, 1]`` -> latents ``(B, 96, latent_frames(T), *latent_hw)``.
+
+ Each clip is padded at the END with black to the VAE's 45-frame chunk, the whole padded canvas is
+ encoded (the VAE sees the mirrored borders), then the padded latent frames and the padded latent
+ columns/rows are dropped. The VAE treats the ``B`` clips independently; batching them only saves
+ kernel launches. ``trim_causal_tail`` opts into the validated 33-frame causal
+ prefix path; returned latent cropping and storage ownership stay the same.
+ """
+ b, c, t, h, w = videos.shape
+ if trim_causal_tail:
+ params = getattr(getattr(vae, "module", None), "params", None)
+ if (t != 33 or chunk_frames != 45 or not getattr(params, "enc_causal", False)
+ or not callable(getattr(vae, "encode_task", None))):
+ raise ValueError("trim_causal_tail requires a causal VAE with encode_task and 33-to-45 padding")
+ lat = vae.encode_task(videos.to(torch.bfloat16))
+ else:
+ total = chunk_frames if t < chunk_frames else padded_chunk_length(t, chunk_frames)
+ if total > t:
+ pad = torch.full((b, c, total - t, h, w), pad_value, dtype=videos.dtype, device=videos.device)
+ videos = torch.cat([videos, pad], dim=2)
+ lat = vae.encode(videos.to(torch.bfloat16)) # (B, 96, latent_frames(total), H/32, W/32)
+ lat = lat[:, :, : latent_frames(t), : latent_hw[0], : latent_hw[1]]
+ return lat.clone() # leave the VAE's inference_mode so autograd may consume it
+
+
+def encode_video(
+ vae,
+ video: Tensor,
+ latent_hw: tuple[int, int] = LATENT_HW,
+ *,
+ chunk_frames: int = VAE_CHUNK_FRAMES,
+ pad_value: float = VAE_PAD_VALUE,
+) -> Tensor:
+ """One clip ``(3, T, Hc, Wc)`` -> ``(1, 96, latent_frames(T), *latent_hw)``; see :func:`encode_videos`."""
+ return encode_videos(vae, video[None], latent_hw, chunk_frames=chunk_frames, pad_value=pad_value)
+
+
+@torch.no_grad()
+def encode_single_frame(
+ vae, frame: Tensor, latent_hw: tuple[int, int] = LATENT_HW, *, single_frame: bool = False
+) -> Tensor:
+ """``(3, Hc, Wc)`` -> ``(1, 96, 1, *latent_hw)``: the inference-time conditioning latent.
+
+ Only the current frame is supplied. By default the VAE repeats it to a 45-frame chunk, encodes that chunk
+ and retains its first latent frame (the reference inference behavior). ``single_frame=True`` encodes the
+ frame alone through ``vae.encode_frame`` when the VAE has one: about 0.5% relative difference in the
+ latent, a fifth of the time.
+ """
+ x = frame[None, :, None].to(torch.bfloat16) # (1, 3, 1, H, W)
+ if single_frame and hasattr(vae, "encode_frame"):
+ lat = vae.encode_frame(x[:, :, 0])
+ else:
+ lat = vae.encode(x) # (1, 96, 1, H/32, W/32)
+ return lat[..., : latent_hw[0], : latent_hw[1]].clone()
+
+
+# ---- 3. token packing (position ids on one 10 ms clock) -------------------------------------
+def video_time_ids(
+ n_latent: int,
+ first_latent: int,
+ batch: int,
+ *,
+ fps: float = FPS,
+ temporal_downsample: int = TEMPORAL_DOWNSAMPLE,
+) -> Tensor:
+ """Latent frame ``i`` sits at time ``i * 4 / fps`` s (frame ``i*4`` of the window)."""
+ seconds = torch.arange(first_latent, first_latent + n_latent).float() * temporal_downsample / fps
+ return times_to_ids(repeat(seconds, "t -> b t", b=batch))
+
+
+def pack_video(latents: Tensor, *, fps: float = FPS) -> dict[str, Tensor]:
+ """``(B, 96, n, h, w)`` -> ``x_video_cond`` (frame 0) + ``x_video`` (frames 1..) with ids."""
+ b, _, n, _, _ = latents.shape
+ latents = latents.to(torch.bfloat16)
+ cond, ids_c = batched_prc_vid(latents[:, :, :1], video_time_ids(1, 0, b, fps=fps))
+ pred, ids_p = batched_prc_vid(latents[:, :, 1:], video_time_ids(n - 1, 1, b, fps=fps))
+ return {"x_video_cond": cond, "x_video_cond_ids": ids_c, "x_video": pred, "x_video_ids": ids_p}
+
+
+def pack_actions(
+ state: Tensor,
+ actions: Tensor,
+ action_times_s: Tensor,
+ modality: str,
+ *,
+ scale: float = ACTION_SCALE,
+) -> dict[str, Tensor]:
+ """``state (B, 1, D)``, ``actions (B, K, D)``, ``times (B, K)`` s since the frame -> scaled tokens + ids.
+
+ Audio-style packing: ids ``(t, 0, 0, 0)``. The state token sits at ``t = 0``, each action at the
+ frame it produces (DROID: ``k / 15`` s -> ids 6, 13, 20, 26, ...).
+ """
+ b = state.shape[0]
+ x_cond, ids_cond = batched_prc_action(
+ (state * scale).transpose(1, 2), times_to_ids(torch.zeros(b, 1, device=state.device))
+ )
+ x_act, ids_act = batched_prc_action(
+ (actions * scale).transpose(1, 2), times_to_ids(action_times_s.to(actions.device))
+ )
+ return {
+ f"x_{modality}_cond": x_cond.float(),
+ f"x_{modality}_cond_ids": ids_cond,
+ f"x_{modality}": x_act.to(torch.bfloat16),
+ f"x_{modality}_ids": ids_act,
+ }
+
+
+def default_action_times(batch: int, chunk: int = CHUNK, fps: float = FPS) -> Tensor:
+ """Action ``k`` (0-based) produces frame ``k + 1``: times ``(k + 1) / fps``."""
+ return repeat((torch.arange(chunk).float() + 1) / fps, "t -> b t", b=batch)
+
+
+def pack_text(ctx: Tensor, vec_dim: int = VEC_DIM) -> dict[str, Tensor]:
+ """``ctx (B, L, 20480)`` -> ctx ids on the l axis (t = h = w = 0), zero ctx timesteps, zero vector."""
+ _, ctx_ids = batched_prc_txt(ctx)
+ b = ctx.shape[0]
+ return {
+ "ctx": ctx,
+ "ctx_ids": ctx_ids.to(ctx.device),
+ "timesteps_ctx": torch.zeros(ctx.shape[:2], device=ctx.device),
+ "vector": torch.zeros(b, vec_dim, device=ctx.device),
+ }
+
+
+# ---- 4. flow matching -----------------------------------------------------------------------
+def rational_time_shift(t: Tensor, shift: float) -> Tensor:
+ return shift * t / (1.0 + (shift - 1.0) * t)
+
+
+def sample_timesteps(
+ batch: int,
+ generator: torch.Generator | None = None,
+ width: float = TIMESTEP_WIDTH,
+ shift: float = TIMESTEP_SHIFT,
+) -> Tensor:
+ """Training timestep: ``logit(t) ~ Logistic(0, width)``, then the rational shift.
+
+ ONE ``t`` per sample, shared by the video tokens and the action tokens.
+ """
+ eps = torch.finfo(torch.float32).eps
+ u = torch.rand(batch, generator=generator).clamp(eps, 1 - eps)
+ t = torch.sigmoid(width * (torch.log(u) - torch.log1p(-u)))
+ return rational_time_shift(t, shift)
+
+
+def draw_noise(shape, dtype: torch.dtype, generator: torch.Generator | None = None) -> Tensor:
+ """The noise :func:`add_noise` draws for a tensor of ``shape``/``dtype``: fp32 CPU normals rounded to ``dtype``
+ on the CPU (exactly what ``randn(...).to(device, dtype)`` does), so it can be drawn ahead and moved asynchronously."""
+ return torch.randn(shape, generator=generator, dtype=torch.float32).to(dtype)
+
+
+def add_noise(
+ x0: Tensor, t: Tensor, generator: torch.Generator | None = None, *, noise: Tensor | None = None
+) -> tuple[Tensor, Tensor]:
+ """``x_t = t * eps + (1 - t) * x0``; velocity target ``eps - x0``. ``t`` is ``(B,)``.
+
+ Everything is computed in ``x0.dtype`` after rounding ``t`` and ``eps`` to it: the reference packs
+ latents, noise and timesteps in bfloat16 and noises in that dtype, so a bf16 window sees ``t`` on
+ the bf16 grid (spacing 2^-8 just below 1; ``t > 1 - 2^-9`` becomes exactly 1). ``noise`` may carry a
+ pre-drawn :func:`draw_noise` result (same values, drawn earlier).
+ """
+ if noise is None:
+ eps_ = torch.randn(x0.shape, generator=generator, dtype=torch.float32).to(
+ device=x0.device, dtype=x0.dtype
+ )
+ else:
+ if tuple(noise.shape) != tuple(x0.shape):
+ raise ValueError(f"pre-drawn noise {tuple(noise.shape)} does not match {tuple(x0.shape)}")
+ eps_ = noise.to(device=x0.device, dtype=x0.dtype)
+ tt = t.to(device=x0.device, dtype=x0.dtype).view(-1, *([1] * (x0.ndim - 1)))
+ x_t = tt * eps_ + (1 - tt) * x0
+ return x_t, eps_ - x0
+
+
+def build_forward_kwargs(
+ video: dict[str, Tensor],
+ action: dict[str, Tensor],
+ text: dict[str, Tensor],
+ t: Tensor,
+ modality: str,
+ generator: torch.Generator | None = None,
+ *,
+ action_timesteps: Tensor | None = None,
+ conditioning_noise_max: float = 0.0,
+ drawn: dict[str, Tensor] | None = None,
+) -> tuple[dict[str, Tensor], dict[str, Tensor], dict[str, Tensor]]:
+ """Assemble one training call: ``(forward_kwargs, flow_targets, clean_latents)``.
+
+ Conditioning streams (``x_video_cond``, ``x__cond``) stay clean at timestep 0. Predicted
+ streams use ``t`` and optionally separate ``action_timesteps``, rounded to their latent dtype.
+ Optional conditioning noise applies only to visual snapshots; state/command history stays clean.
+ The timesteps handed to the model are fp32 tensors holding the rounded values. ``drawn`` may hold the
+ random values of :func:`draw_training_randomness` for this batch (``video``, ``action`` and, with
+ conditioning noise, ``cond_t``/``cond`` noise), drawn earlier in the same order.
+ """
+ ak = f"x_{modality}"
+ drawn = drawn or {}
+ xv, tv = add_noise(video["x_video"], t, generator, noise=drawn.get("video"))
+ t_action = t if action_timesteps is None else action_timesteps
+ xa, ta = add_noise(action[ak], t_action, generator, noise=drawn.get("action"))
+ dev = xv.device
+ tt = t.to(device=dev, dtype=xv.dtype).float() # the rounded value the noising used
+ tt_action = t_action.to(device=dev, dtype=xa.dtype).float()
+ kw = {
+ "x_video": xv,
+ "x_video_ids": video["x_video_ids"].to(dev),
+ "x_video_timesteps": tt[:, None] * torch.ones(xv.shape[:2], device=dev),
+ ak: xa,
+ f"{ak}_ids": action[f"{ak}_ids"].to(dev),
+ f"{ak}_timesteps": tt_action[:, None] * torch.ones(xa.shape[:2], device=dev),
+ "x_video_cond": video["x_video_cond"],
+ "x_video_cond_ids": video["x_video_cond_ids"].to(dev),
+ "x_video_cond_timesteps": torch.zeros(video["x_video_cond"].shape[:2], device=dev),
+ f"{ak}_cond": action[f"{ak}_cond"],
+ f"{ak}_cond_ids": action[f"{ak}_cond_ids"].to(dev),
+ f"{ak}_cond_timesteps": torch.zeros(action[f"{ak}_cond"].shape[:2], device=dev),
+ **text,
+ }
+ if conditioning_noise_max:
+ cond_t = drawn["cond_t"] if "cond_t" in drawn else torch.rand(t.shape, generator=generator)
+ cond_t = cond_t * conditioning_noise_max
+ kw["x_video_cond"], _ = add_noise(video["x_video_cond"], cond_t, generator, noise=drawn.get("cond"))
+ cond_tt = cond_t.to(device=dev, dtype=kw["x_video_cond"].dtype).float()
+ kw["x_video_cond_timesteps"] = cond_tt[:, None].expand(video["x_video_cond"].shape[:2])
+ targets = {"x_video": tv, ak: ta}
+ clean = {"x_video": video["x_video"], ak: action[ak]}
+ return kw, targets, clean
+
+
+def draw_training_randomness(
+ n: int,
+ *,
+ n_video_tokens: int,
+ n_cond_tokens: int,
+ chunk: int,
+ action_dim: int,
+ width: float,
+ shift: float,
+ separate_timesteps: bool = False,
+ video_logit_mean: float = 0.0,
+ video_logit_std: float = 1.0,
+ conditioning_noise: bool = False,
+ latent_dtype: torch.dtype = torch.bfloat16,
+) -> dict[str, Tensor]:
+ """Draw, from the global CPU generator and in the exact order the training forward consumes them, the
+ timesteps and noise of one micro-batch of ``n`` windows: ``t`` (``sample_timesteps``), optionally the
+ separate video timesteps, the video noise ``(n, n_video_tokens, 96)``, the action noise
+ ``(n, chunk, action_dim)`` and, with conditioning noise, ``cond_t`` and the conditioning-frame noise.
+ Lets the trainer draw a step's randomness ahead of its forward without changing any random stream."""
+ out = {"t": sample_timesteps(n, None, width, shift)}
+ if separate_timesteps:
+ out["t_video"] = torch.sigmoid(torch.randn(n) * video_logit_std + video_logit_mean)
+ out["video"] = draw_noise((n, n_video_tokens, LATENT_CHANNELS), latent_dtype)
+ out["action"] = draw_noise((n, chunk, action_dim), latent_dtype)
+ if conditioning_noise:
+ out["cond_t"] = torch.rand(n)
+ out["cond"] = draw_noise((n, n_cond_tokens, LATENT_CHANNELS), latent_dtype)
+ return out
+
+
+def pack_windows(
+ kwargs: dict[str, Tensor], ctxs: list[Tensor], vec_dim: int = VEC_DIM
+) -> tuple[dict[str, Tensor], dict[str, list[int]]]:
+ """``B`` windows -> one DiT call of batch size 1 plus the per-window token counts it needs.
+
+ ``kwargs`` are the stream tensors of :func:`build_forward_kwargs` for ``B`` windows (``(B, L, ...)``:
+ the windows share every stream length), ``ctxs`` their text contexts ``(1, L_i, ctx_dim)`` of any
+ lengths. Streams become ``(1, B * L, ...)`` with window ``i`` at ``[i * L, (i + 1) * L)``; the contexts
+ are concatenated with their own position ids (``l`` restarts at 0 in every window). ``seqlens``
+ (``"ctx"`` and each ``x_`` -> ``B`` token counts) is what ``JointSingleSeq.forward`` takes.
+ """
+ b = len(ctxs)
+ if b == 0:
+ raise ValueError("pack_windows needs at least one window")
+ packed: dict[str, Tensor] = {}
+ seqlens: dict[str, list[int]] = {}
+ for key, value in kwargs.items():
+ if value.shape[0] != b:
+ raise ValueError(f"{key}: expected {b} windows, got {value.shape[0]}")
+ packed[key] = value.reshape(1, b * value.shape[1], *value.shape[2:])
+ if not key.endswith(("_ids", "_timesteps")):
+ seqlens[key] = [int(value.shape[1])] * b
+ if any(c.ndim != 3 or c.shape[0] != 1 for c in ctxs):
+ raise ValueError("each context must be (1, L_i, ctx_dim)")
+ ctx = torch.cat(ctxs, dim=1)
+ ctx_ids = torch.cat([batched_prc_txt(c)[1].to(ctx.device) for c in ctxs], dim=1)
+ packed.update(
+ ctx=ctx,
+ ctx_ids=ctx_ids,
+ timesteps_ctx=torch.zeros(ctx.shape[:2], device=ctx.device),
+ vector=torch.zeros(1, vec_dim, device=ctx.device),
+ )
+ seqlens["ctx"] = [int(c.shape[1]) for c in ctxs]
+ return packed, seqlens
+
+
+# ---- 3b. layout cache: the same packed inputs without the host-bound prologue ----------------
+def _to_device_async(x: Tensor, device: torch.device) -> Tensor:
+ """``x.to(device)`` for a host tensor that never blocks the host on queued GPU work: a CUDA destination is fed
+ from pinned memory with a non-blocking copy (the caching host allocator keeps the staging block alive until the
+ copy has executed); any other destination is a plain move."""
+ if device.type == "cuda":
+ return x.contiguous().pin_memory().to(device, non_blocking=True)
+ return x.to(device)
+
+
+class PackCache:
+ """:func:`pack_video` + :func:`pack_actions` + :func:`build_forward_kwargs` + :func:`pack_windows` for the default
+ training profile -- same values, dtypes and shapes -- without the host-bound prologue of the eager path.
+
+ The eager path rebuilds the position ids of every window with ``cartesian_prod`` (640 calls, ~3400 kernel launches
+ for 128 windows) and moves the per-window time coordinates and the timesteps with pageable ``.to(device)`` copies,
+ each of which synchronizes the stream (261 per step), while every stream of the GPU idles. Here
+
+ * everything that is a pure function of the token layout -- the int64 position ids of the video, conditioning and
+ action streams, the zero timesteps of the conditioning streams, the ``ones`` the predicted streams' timesteps are
+ broadcast with, the zero ``vector`` -- is built once per layout key (device, window count, latent grid, frame
+ rate, chunk length) with the eager helpers on the same device, and reused;
+ * the context ids are built once per distinct context length and concatenated per step (the caption-dropout
+ pattern changes every step, the per-length pieces do not);
+ * the timesteps are rounded to the latent dtype on the host exactly where :func:`add_noise` and
+ :func:`build_forward_kwargs` round them today, then uploaded once from pinned memory asynchronously and reused
+ for both noising calls and both timestep streams (one copy instead of four blocking ones);
+ * the per-window ``rearrange`` + ``stack`` of the tokens becomes one batched ``rearrange`` (pure data movement).
+
+ The cached tensors are shared between steps; the DiT only reads its inputs.
+ """
+
+ MAX_LAYOUTS = 8
+
+ def __init__(self) -> None:
+ self._layouts: dict[tuple, dict[str, Tensor]] = {}
+ self._ctx_ids: dict[tuple, Tensor] = {}
+ self.layout_builds = 0 # cache misses (for tests and diagnostics)
+
+ def clear(self) -> None:
+ self._layouts.clear()
+ self._ctx_ids.clear()
+
+ # -- layout-only tensors ------------------------------------------------------------------
+ def _layout(
+ self, device: torch.device, b: int, n_latent: int, h: int, w: int, fps: float, chunk: int, vec_dim: int
+ ) -> dict[str, Tensor]:
+ key = (str(device), b, n_latent, h, w, float(fps), chunk, vec_dim)
+ hit = self._layouts.get(key)
+ if hit is None:
+ if len(self._layouts) >= self.MAX_LAYOUTS:
+ self._layouts.clear()
+ hit = self._layouts[key] = self._build_layout(device, b, n_latent, h, w, fps, chunk, vec_dim)
+ self.layout_builds += 1
+ return hit
+
+ @staticmethod
+ def _build_layout(
+ device: torch.device, b: int, n_latent: int, h: int, w: int, fps: float, chunk: int, vec_dim: int
+ ) -> dict[str, Tensor]:
+ # The eager helpers, fed tokens with zero channels (only their shapes enter the ids) and time coordinates that
+ # are already on the device, so the per-window ``.to(device)`` inside them is a no-op: no pageable copy, no sync.
+ def vid(t: int) -> Tensor:
+ return torch.empty(b, 0, t, h, w, device=device)
+
+ def act(t: int) -> Tensor:
+ return torch.empty(b, 0, t, device=device)
+
+ _, ids_cond = batched_prc_vid(vid(1), _to_device_async(video_time_ids(1, 0, b, fps=fps), device))
+ _, ids_video = batched_prc_vid(
+ vid(n_latent - 1), _to_device_async(video_time_ids(n_latent - 1, 1, b, fps=fps), device)
+ )
+ _, ids_act_cond = batched_prc_action(act(1), times_to_ids(torch.zeros(b, 1, device=device)))
+ _, ids_act = batched_prc_action(
+ act(chunk), times_to_ids(_to_device_async(default_action_times(b, chunk, fps), device))
+ )
+ return {
+ "x_video_cond_ids": ids_cond,
+ "x_video_ids": ids_video,
+ "action_cond_ids": ids_act_cond,
+ "action_ids": ids_act,
+ "video_ones": torch.ones(b, (n_latent - 1) * h * w, device=device),
+ "action_ones": torch.ones(b, chunk, device=device),
+ "video_cond_zeros": torch.zeros(b, h * w, device=device),
+ "action_cond_zeros": torch.zeros(b, 1, device=device),
+ "vector": torch.zeros(1, vec_dim, device=device),
+ }
+
+ def _ctx_ids_of(self, device: torch.device, length: int) -> Tensor:
+ key = (str(device), length)
+ hit = self._ctx_ids.get(key)
+ if hit is None:
+ if len(self._ctx_ids) >= 256:
+ self._ctx_ids.clear()
+ hit = self._ctx_ids[key] = batched_prc_txt(torch.empty(1, length, 0, device=device))[1]
+ return hit
+
+ # -- per step ------------------------------------------------------------------------------
+ def pack_training_windows(
+ self,
+ latents: Tensor,
+ state: Tensor,
+ actions: Tensor,
+ ctxs: list[Tensor],
+ drawn: dict[str, Tensor],
+ modality: str,
+ *,
+ fps: float = FPS,
+ chunk: int = CHUNK,
+ scale: float = ACTION_SCALE,
+ separate_timesteps: bool = False,
+ conditioning_noise_max: float = 0.0,
+ vec_dim: int = VEC_DIM,
+ ) -> tuple[dict[str, Tensor], dict[str, list[int]], dict[str, Tensor]]:
+ """One training call for ``B`` windows: ``(packed DiT kwargs, seqlens, flow targets)``, equal to::
+
+ video = pack_video(latents, fps=fps)
+ action = pack_actions(state, actions, default_action_times(B, chunk, fps), modality, scale=scale)
+ kw, targets, _ = build_forward_kwargs(video, action, {}, t_video, modality, action_timesteps=t,
+ conditioning_noise_max=conditioning_noise_max, drawn=drawn)
+ packed, seqlens = pack_windows(kw, ctxs, vec_dim)
+
+ ``latents`` ``(B, 96, n, h, w)``, ``state`` ``(B, 1, D)``, ``actions`` ``(B, chunk, D)``, ``ctxs`` the windows'
+ text contexts ``(1, L_i, ctx_dim)``. ``drawn`` holds this batch's randomness in the layout of
+ :func:`draw_training_randomness`: ``t`` (host fp32), ``t_video`` with separate timesteps, the ``video`` and
+ ``action`` noise (host or device, in the latent dtype) and, with conditioning noise, ``cond_t`` and ``cond``.
+ """
+ if latents.ndim != 5:
+ raise ValueError(f"latents must be (B, C, n, h, w), got {tuple(latents.shape)}")
+ b, _, n_latent, h, w = latents.shape
+ if len(ctxs) != b:
+ raise ValueError(f"{len(ctxs)} contexts for {b} windows")
+ if tuple(state.shape[:2]) != (b, 1) or tuple(actions.shape[:2]) != (b, chunk):
+ raise ValueError(f"state {tuple(state.shape)} / actions {tuple(actions.shape)} do not match {b} windows")
+ if any(c.ndim != 3 or c.shape[0] != 1 for c in ctxs):
+ raise ValueError("each context must be (1, L_i, ctx_dim)")
+ device = latents.device
+ layout = self._layout(device, b, n_latent, h, w, fps, chunk, vec_dim)
+ ak = f"x_{modality}"
+ # Tokens: the eager per-window ``rearrange`` + ``stack``, batched (pure data movement), then the same casts.
+ latents = latents.to(torch.bfloat16)
+ x_video_cond = rearrange(latents[:, :, :1], "b c t h w -> b (t h w) c")
+ x_video = rearrange(latents[:, :, 1:], "b c t h w -> b (t h w) c")
+ x_action_cond = (state * scale).float()
+ x_action = (actions * scale).to(torch.bfloat16)
+ # Timesteps: rounded to the latent dtype on the host as ``add_noise`` does, uploaded once, asynchronously.
+ t = drawn["t"]
+ t_video = drawn["t_video"] if separate_timesteps else t
+ t_dev = _to_device_async(t.to(x_action.dtype), device)
+ if t_video is t and x_video.dtype == x_action.dtype:
+ tv_dev = t_dev
+ else:
+ tv_dev = _to_device_async(t_video.to(x_video.dtype), device)
+ xv, target_video = add_noise(x_video, tv_dev, noise=drawn["video"])
+ xa, target_action = add_noise(x_action, t_dev, noise=drawn["action"])
+ tt, tt_action = tv_dev.float(), t_dev.float() # the rounded values the noising used
+ kw = {
+ "x_video": xv,
+ "x_video_ids": layout["x_video_ids"],
+ "x_video_timesteps": tt[:, None] * layout["video_ones"],
+ ak: xa,
+ f"{ak}_ids": layout["action_ids"],
+ f"{ak}_timesteps": tt_action[:, None] * layout["action_ones"],
+ "x_video_cond": x_video_cond,
+ "x_video_cond_ids": layout["x_video_cond_ids"],
+ "x_video_cond_timesteps": layout["video_cond_zeros"],
+ f"{ak}_cond": x_action_cond,
+ f"{ak}_cond_ids": layout["action_cond_ids"],
+ f"{ak}_cond_timesteps": layout["action_cond_zeros"],
+ }
+ if conditioning_noise_max:
+ cond_t = drawn["cond_t"] * conditioning_noise_max # host fp32, as in build_forward_kwargs
+ cond_t_dev = _to_device_async(cond_t.to(x_video_cond.dtype), device)
+ kw["x_video_cond"], _ = add_noise(x_video_cond, cond_t_dev, noise=drawn["cond"])
+ kw["x_video_cond_timesteps"] = cond_t_dev.float()[:, None].expand(b, h * w)
+ packed: dict[str, Tensor] = {}
+ seqlens: dict[str, list[int]] = {}
+ for key, value in kw.items():
+ packed[key] = value.reshape(1, b * value.shape[1], *value.shape[2:])
+ if not key.endswith(("_ids", "_timesteps")):
+ seqlens[key] = [int(value.shape[1])] * b
+ lens = [int(c.shape[1]) for c in ctxs]
+ ctx = torch.cat(ctxs, dim=1)
+ packed.update(
+ ctx=ctx,
+ ctx_ids=torch.cat([self._ctx_ids_of(device, n) for n in lens], dim=1),
+ timesteps_ctx=torch.zeros(1, ctx.shape[1], device=device),
+ vector=layout["vector"],
+ )
+ seqlens["ctx"] = lens
+ return packed, seqlens, {"x_video": target_video, ak: target_action}
+
+
+def flatten_windows(tensors: dict[str, Tensor]) -> dict[str, Tensor]:
+ """``(B, L, ...)`` -> ``(1, B * L, ...)`` for every entry, the layout of :func:`pack_windows` outputs."""
+ return {k: v.reshape(1, v.shape[0] * v.shape[1], *v.shape[2:]) for k, v in tensors.items()}
+
+
+def flow_loss(
+ pred: dict[str, Tensor],
+ targets: dict[str, Tensor],
+ modality: str,
+ action_weight: float = ACTION_LOSS_WEIGHT,
+ video_weight: float = VIDEO_LOSS_WEIGHT,
+ *,
+ action_mask: Tensor | None = None,
+ reduction: str = "joint_tokens",
+ channel_weights: list[float] | None = None,
+) -> dict[str, Tensor]:
+ """Joint-token mean (DROID) or weighted per-modality means (history), with optional channel weights.
+
+ The default action weight (50) applies to joint-token pooling. Channel weights are squared and
+ normalized by their mean, matching collab's task loss. Per-modality
+ MSEs are returned for logging. Over the windows of a micro-batch (batched or packed, see
+ :func:`pack_windows`) this equals the mean of the per-window losses, since every window holds the
+ same number of video and action tokens.
+
+ ``action_mask`` ``(n, D)`` (1 = trained dim) restricts the per-token action MSE to the given dims of each
+ window, for a head shared by embodiments of different action widths (padded dims carry no loss). The
+ action tokens are laid out window-major in the packed sequence, ``n`` windows x ``K`` tokens each.
+ """
+ ak = f"x_{modality}"
+ video = ((pred["x_video"].float() - targets["x_video"].float()) ** 2).mean(-1) # (B, Nv)
+ sq = (pred[ak].float() - targets[ak].float()) ** 2 # (B, Na, D): batched (n, K, D) or packed (1, n*K, D)
+ if action_mask is None:
+ action = sq.mean(-1) # (B, Na)
+ else:
+ n = action_mask.shape[0]
+ m = action_mask.float() # (n, D)
+ if sq.shape[0] == n: # batched: one mask row per window
+ m = m[:, None, :].expand_as(sq)
+ else: # packed: window-major tokens, n windows x K tokens each
+ m = m.repeat_interleave(sq.shape[1] // n, dim=0).reshape(sq.shape)
+ action = (sq * m).sum(-1) / m.sum(-1).clamp_min(1.0)
+ weighted_action = action
+ if channel_weights is not None:
+ weights = torch.tensor(channel_weights, device=sq.device, dtype=torch.float32).square()
+ weights = weights / weights.mean()
+ weighted_action = (
+ (sq * weights).mean(-1)
+ if action_mask is None
+ else (sq * weights * m).sum(-1) / m.sum(-1).clamp_min(1.0)
+ )
+ if reduction == "modalities":
+ total = video_weight * video.mean() + action_weight * weighted_action.mean()
+ elif reduction == "joint_tokens":
+ total = (video_weight * video.sum() + action_weight * weighted_action.sum()) / (
+ video.numel() + action.numel()
+ )
+ else:
+ raise ValueError(f"unknown loss reduction {reduction!r}")
+ return {"loss": total, "video_mse": video.mean().detach(), "action_mse": action.mean().detach()}
+
+
+def token_budget(
+ chunk: int = CHUNK, latent_hw: tuple[int, int] = LATENT_HW, text_tokens: int = TEXT_PAD_MULTIPLE
+) -> dict[str, int]:
+ """Token counts of one window (for sanity checks and batch sizing)."""
+ hw = latent_hw[0] * latent_hw[1]
+ n_pred = latent_frames(chunk + 1) - 1
+ return {
+ "x_video_cond": hw,
+ "x_video": n_pred * hw,
+ "x_action_cond": 1,
+ "x_action": chunk,
+ "ctx_min": text_tokens,
+ }
diff --git a/flux-umi/src/flux_action/serving/__init__.py b/flux-umi/src/flux_action/serving/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..342261cad3f7addcae7ef51aab1d0df8fb0c8f59
--- /dev/null
+++ b/flux-umi/src/flux_action/serving/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Serving FLUX Action policies to simulator and robot clients."""
diff --git a/flux-umi/src/flux_action/serving/protocol.py b/flux-umi/src/flux_action/serving/protocol.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b36c41d0464203366ac9227aed44cdf780c0d40
--- /dev/null
+++ b/flux-umi/src/flux_action/serving/protocol.py
@@ -0,0 +1,48 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""OpenPI's msgpack + NumPy wire format, as ``openpi_client.msgpack_numpy`` 0.1.0 defines it.
+
+Reimplemented (same dictionary layout, byte keys and dtype strings) so a server needs only
+``msgpack``; the RoboLab client packs and unpacks with the original module. Object, void and
+complex arrays are rejected, as in the original.
+"""
+
+import functools
+
+import msgpack
+import numpy as np
+
+
+def pack_array(obj):
+ if isinstance(obj, (np.ndarray, np.generic)) and obj.dtype.kind in ("V", "O", "c"):
+ raise ValueError(f"Unsupported dtype: {obj.dtype}")
+ if isinstance(obj, np.ndarray):
+ return {b"__ndarray__": True, b"data": obj.tobytes(), b"dtype": obj.dtype.str, b"shape": obj.shape}
+ if isinstance(obj, np.generic):
+ return {b"__npgeneric__": True, b"data": obj.item(), b"dtype": obj.dtype.str}
+ return obj
+
+
+def unpack_array(obj):
+ if b"__ndarray__" in obj:
+ return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
+ if b"__npgeneric__" in obj:
+ return np.dtype(obj[b"dtype"]).type(obj[b"data"])
+ return obj
+
+
+Packer = functools.partial(msgpack.Packer, default=pack_array)
+packb = functools.partial(msgpack.packb, default=pack_array)
+Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
+unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
diff --git a/flux-umi/src/flux_action/serving/robolab.py b/flux-umi/src/flux_action/serving/robolab.py
new file mode 100644
index 0000000000000000000000000000000000000000..efbda59b8e6be21a0ac94dbc06adeece9b652a65
--- /dev/null
+++ b/flux-umi/src/flux_action/serving/robolab.py
@@ -0,0 +1,345 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""RoboLab policy adapter and WebSocket server (OpenPI protocol).
+
+Request keys (the RoboLab Cosmos client): ``observation/image`` uint8 ``(540, 640, 3)`` composite
+(wrist on top, the two exteriors at half resolution below), or the three RoBoArena views
+``observation/wrist_image_left``, ``observation/exterior_image_1_left``,
+``observation/exterior_image_2_left`` which are composed the same way; ``observation/joint_position``
+``(7,)`` (the last row of a history); ``observation/gripper_position`` scalar or ``(1,)``, in the
+dataset's convention (the policy flips it internally, as in training and in the source server);
+``prompt``. Response: ``{"action": float32 (32, 8)}`` plus ``server_timing``.
+
+Protocol (OpenPI ``WebsocketPolicyServer``): on connection the server sends the packed metadata
+dict; every following client frame is one packed observation and gets one packed response. On an
+exception the traceback is sent as a text frame and the connection closes with code 1011.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+import traceback
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+
+from ..config import PolicyConfig
+from ..models.transformer import JointSingleSeq
+from . import protocol
+
+COMPOSITE_HW = (540, 640)
+IMAGE_KEY = "observation/image"
+VIEW_KEYS = (
+ "observation/wrist_image_left",
+ "observation/exterior_image_1_left",
+ "observation/exterior_image_2_left",
+)
+INTERNAL_ERROR = 1011
+
+
+def _rgb_uint8(value: Any, key: str) -> np.ndarray:
+ image = np.asarray(value)
+ assert image.ndim == 3 and image.shape[-1] == 3, "image shape"
+ if image.dtype != np.uint8:
+ image = np.clip(image, 0, 255).astype(np.uint8)
+ # msgpack arrays view immutable bytes; torch.from_numpy requires writable storage.
+ return np.require(image, requirements=["C", "W"])
+
+
+def _resize_uint8(image: np.ndarray, size: tuple[int, int]) -> np.ndarray:
+ """Cosmos server resize: bilinear on float, back to uint8 by truncation."""
+ tensor = torch.from_numpy(image).permute(2, 0, 1)[None].float()
+ resized = F.interpolate(tensor, size=size, mode="bilinear", align_corners=False)
+ return resized[0].permute(1, 2, 0).numpy().astype(np.uint8)
+
+
+def compose_views(wrist: np.ndarray, left: np.ndarray, right: np.ndarray) -> np.ndarray:
+ """RoBoArena views -> the 540x640 composite, as the Cosmos RoboLab server composes them."""
+ half = (wrist.shape[0] // 2, wrist.shape[1] // 2)
+ bottom = np.concatenate([_resize_uint8(left, half), _resize_uint8(right, half)], axis=1)
+ return np.concatenate([wrist, bottom], axis=0)
+
+
+def observation_image(obs: dict[str, Any]) -> np.ndarray:
+ if IMAGE_KEY in obs:
+ image = _rgb_uint8(obs[IMAGE_KEY], IMAGE_KEY)
+ elif all(key in obs for key in VIEW_KEYS):
+ image = compose_views(*(_rgb_uint8(obs[key], key) for key in VIEW_KEYS))
+ else:
+ raise KeyError(IMAGE_KEY)
+ assert image.shape[:2] == COMPOSITE_HW, "composite size"
+ return image
+
+
+def observation_state(obs: dict[str, Any], action_dim: int) -> np.ndarray:
+ """``[joint_position (7), gripper_position (1)]`` from the last history row, in dataset units."""
+ joints = np.asarray(obs["observation/joint_position"], dtype=np.float32)
+ if joints.ndim == 2:
+ joints = joints[-1]
+ gripper = np.asarray(obs["observation/gripper_position"], dtype=np.float32).reshape(-1)
+ assert gripper.size > 0, "gripper required"
+ state = np.concatenate([joints.reshape(-1), gripper[-1:]])
+ assert state.shape == (action_dim,) and np.isfinite(state).all(), "invalid state"
+ return state
+
+
+class RoboLabPolicy:
+ """``infer(obs)`` for the OpenPI server; wraps a FluxActionPolicy on its device."""
+
+ def __init__(self, policy, *, log_dir=None, seed_base: int = 0):
+ self.policy = policy
+ self.log_dir = Path(log_dir) if log_dir else None
+ self.seed_base = seed_base
+ self.queries = 0
+ self.chunk_size = policy.config.chunk_size
+ self.action_dim = policy.config.action_dim
+
+ def infer(self, obs: dict[str, Any], *, seed: int | None = None) -> dict[str, Any]:
+ image = observation_image(obs)
+ state = observation_state(obs, self.action_dim)
+ prompt = str(obs.get("prompt", "") or "")
+ self.queries += 1
+ query_seed = self.seed_base + self.queries if seed is None else seed
+ started = time.perf_counter()
+ actions = self.policy.predict_from_composite(
+ torch.from_numpy(image), torch.from_numpy(state), prompt, seed=query_seed
+ )
+ actions = actions.detach().cpu().numpy().astype(np.float32)
+ elapsed = time.perf_counter() - started
+ if actions.shape != (self.chunk_size, self.action_dim):
+ raise RuntimeError(f"policy returned {actions.shape}")
+ if not np.isfinite(actions).all():
+ raise RuntimeError("policy returned non-finite actions")
+ if self.log_dir is not None:
+ self._log(image, state, prompt, query_seed, actions, elapsed)
+ return {"action": actions}
+
+ def _log(self, image, state, prompt, seed, actions, elapsed) -> None:
+ self.log_dir.mkdir(parents=True, exist_ok=True)
+ stem = self.log_dir / f"query_{self.queries:06d}"
+ np.savez(
+ stem.with_suffix(".npz"),
+ **{
+ IMAGE_KEY: image,
+ "observation/joint_position": state[:-1],
+ "observation/gripper_position": state[-1:],
+ },
+ )
+ stem.with_suffix(".json").write_text(
+ json.dumps(
+ {
+ "prompt": prompt,
+ "seed": seed,
+ "predicted_actions": actions.tolist(),
+ "inference_time_s": elapsed,
+ "serving_setup": self.policy.serving_setup,
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+
+
+def prepare_serving_policy(
+ policy,
+ *,
+ device="cuda",
+ dtype: str = "keep",
+ settings: dict[str, Any] | None = None,
+ compile_dit: bool = True,
+ offload_text_encoder: bool = False,
+ warmup: int = 1,
+):
+ """Apply explicit sampler overrides and the serve-time knobs of ``inference.precision`` to a policy
+ that still sits on the CPU, then move it to ``device``.
+
+ Published sampler settings remain unchanged unless ``settings`` explicitly overrides them. The optimized
+ inference backend is installed after placement and compiled by default; ``warmup`` requests go through
+ :meth:`FluxActionPolicy.predict_from_composite` exactly as :meth:`RoboLabPolicy.infer` does, so the cached
+ compiled paths are the ones serving uses. ``policy.serving_setup`` records what was applied."""
+ from ..inference.precision import prepare_for_serving
+
+ assert dtype in ("keep", "bfloat16", "float32"), "serving dtype"
+ prepared = policy._inference_prepared
+ requested_dtype = (
+ str(next(policy.dit.parameters()).dtype).removeprefix("torch.") if dtype == "keep" else dtype
+ )
+ assert not prepared or requested_dtype == policy.config.torch_dtype, "prepared dtype mismatch"
+ values = dict(settings or {})
+ values["torch_dtype"] = requested_dtype
+ policy.config = PolicyConfig(**{**policy.config.to_dict(), **values})
+ policy.config.validate_inference()
+ target_dtype = getattr(torch, requested_dtype)
+ current_dtype = next(policy.dit.parameters()).dtype
+ if dtype != "keep" and target_dtype != current_dtype:
+ assert isinstance(policy.dit, JointSingleSeq), "cannot recast packed inference weights"
+ # Frozen encoders manage their own precision (including fp32 buffers).
+ policy.dit.to(dtype=target_dtype) # CPU cast before GPU placement and inference preparation
+ policy.set_compute_dtype(None)
+ policy.reset()
+
+ def warm_request():
+ image = torch.zeros((*COMPOSITE_HW, 3), dtype=torch.uint8)
+ state = torch.zeros(policy.config.action_dim, dtype=torch.float32)
+ policy.predict_from_composite(image, state, "warm-up request", seed=0)
+
+ policy.serving_setup = prepare_for_serving(
+ policy,
+ device=device,
+ compile_dit=compile_dit,
+ offload_text_encoder=offload_text_encoder,
+ warmup=warmup,
+ warmup_fn=warm_request,
+ )
+ policy.reset() # the warm-up caption and queue state must not leak into the first request
+ return policy
+
+
+def load_serving_policy(
+ checkpoint, *, revision: str | None = None, subfolder: str | None = None, device="cuda", **kwargs
+):
+ """Restore an export on the CPU and :func:`prepare_serving_policy` it for ``device`` (same keywords)."""
+ from ..policy import FluxActionPolicy
+
+ return prepare_serving_policy(
+ FluxActionPolicy.from_pretrained(checkpoint, revision=revision, subfolder=subfolder, device="cpu"),
+ device=device,
+ **kwargs,
+ )
+
+
+async def _handle(websocket, adapter: RoboLabPolicy, metadata: dict[str, Any]) -> None:
+ import websockets
+
+ packer = protocol.Packer()
+ await websocket.send(packer.pack(metadata))
+ prev_total = None
+ while True:
+ try:
+ started = time.monotonic()
+ obs = protocol.unpackb(await websocket.recv())
+ infer_started = time.monotonic()
+ response = adapter.infer(obs)
+ response["server_timing"] = {"infer_ms": (time.monotonic() - infer_started) * 1000}
+ if prev_total is not None:
+ response["server_timing"]["prev_total_ms"] = prev_total * 1000
+ await websocket.send(packer.pack(response))
+ prev_total = time.monotonic() - started
+ except websockets.ConnectionClosed:
+ break
+ except Exception:
+ await websocket.send(traceback.format_exc())
+ await websocket.close(
+ code=INTERNAL_ERROR, reason="Internal server error. Traceback included in previous frame."
+ )
+ raise
+
+
+async def serve_async(
+ adapter: RoboLabPolicy, *, host: str = "0.0.0.0", port: int = 8000, metadata=None, ready=None
+):
+ """Serve until cancelled; ``ready`` (an ``asyncio.Event``) is set once the port is bound."""
+ import websockets.asyncio.server
+
+ async def handler(websocket):
+ await _handle(websocket, adapter, metadata or {})
+
+ async with websockets.asyncio.server.serve(
+ handler, host, port, compression=None, max_size=None
+ ) as server:
+ if ready is not None:
+ ready.set()
+ await server.serve_forever()
+
+
+def serve(adapter: RoboLabPolicy, *, host: str = "0.0.0.0", port: int = 8000, metadata=None) -> None:
+ asyncio.run(serve_async(adapter, host=host, port=port, metadata=metadata))
+
+
+def collection_entries(path) -> list[dict[str, Any]]:
+ """Fixture entries from a ``collection.json`` or from a directory of server query logs.
+
+ Query logs (``query_NNNNNN.npz`` + ``.json`` + ``_actions.json``, the format the source server
+ and this adapter write) get the query index as seed, which is what the source server used.
+ """
+ path = Path(path)
+ if path.is_dir():
+ entries = []
+ for npz in sorted(path.glob("query_*.npz")):
+ meta = json.loads(npz.with_suffix(".json").read_text())
+ actions = npz.with_name(npz.stem + "_actions.json")
+ if not actions.is_file():
+ actions = npz.with_suffix(".json") # this adapter stores the actions in the same json
+ entries.append(
+ {
+ "id": npz.stem,
+ "fixture": npz.name,
+ "expected_actions": actions.name,
+ "prompt": meta.get("prompt", ""),
+ "seed": int(meta.get("seed", int(npz.stem.split("_")[-1]))),
+ }
+ )
+ assert entries, "empty fixture collection"
+ return entries
+ collection = json.loads(path.read_text())
+ assert collection.get("kind") == "policy-fixture-collection", "fixture collection kind"
+ return list(collection["fixtures"])
+
+
+def replay_collection(
+ collection_path, adapter: RoboLabPolicy, output_dir, *, atol: float = 1e-3
+) -> dict[str, Any]:
+ """Run recorded fixtures and compare the actions with the recorded ones.
+
+ Each entry names ``fixture`` (npz with the observation keys), ``expected_actions`` (json with
+ ``predicted_actions``), ``prompt`` and ``seed``. Reports per-fixture max absolute and relative
+ L2 differences; ``passed`` means every fixture stays within ``atol``.
+ """
+ collection_path, output_dir = Path(collection_path), Path(output_dir)
+ base = collection_path if collection_path.is_dir() else collection_path.parent
+ output_dir.mkdir(parents=True, exist_ok=True)
+ cases = []
+ for entry in collection_entries(collection_path):
+ fixture = base / entry["fixture"]
+ expected_path = base / entry["expected_actions"]
+ expected = np.asarray(json.loads(expected_path.read_text())["predicted_actions"], dtype=np.float32)
+ with np.load(fixture, allow_pickle=False) as arrays:
+ obs = {key: arrays[key] for key in arrays.files}
+ obs["prompt"] = entry.get("prompt", "")
+ actions = adapter.infer(obs, seed=int(entry["seed"]))["action"]
+ diff = np.abs(actions - expected)
+ rel = float(np.linalg.norm(actions - expected) / max(np.linalg.norm(expected), 1e-12))
+ case = {
+ "id": entry["id"],
+ "max_abs": float(diff.max()),
+ "rel_l2": rel,
+ "passed": bool(diff.max() <= atol),
+ }
+ (output_dir / f"{entry['id']}.json").write_text(
+ json.dumps({**case, "predicted_actions": actions.tolist()}, indent=2) + "\n"
+ )
+ cases.append(case)
+ report = {
+ "collection": str(collection_path),
+ "atol": atol,
+ "passed": all(c["passed"] for c in cases),
+ "cases": cases,
+ }
+ (output_dir / "report.json").write_text(json.dumps(report, indent=2) + "\n")
+ return report
diff --git a/flux-umi/src/flux_action/training/__init__.py b/flux-umi/src/flux_action/training/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..84123d4b4b111608029176b143cd65c98b6b0d53
--- /dev/null
+++ b/flux-umi/src/flux_action/training/__init__.py
@@ -0,0 +1,14 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Training components of the DROID recipe: schedules, power EMA and (later) the trainer."""
diff --git a/flux-umi/src/flux_action/training/activation_offload.py b/flux-umi/src/flux_action/training/activation_offload.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5504b441f9b028578e473c3ad4ea5dbf4b7bc0a
--- /dev/null
+++ b/flux-umi/src/flux_action/training/activation_offload.py
@@ -0,0 +1,709 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Asynchronous CPU offload of checkpoint-held activations (FSDP2 + non-reentrant selective checkpointing).
+
+Why
+---
+With per-block selective checkpointing every block keeps its *input* (for the recompute) and its saved op outputs
+(SDPA, mlp_out, ...) on the GPU from the forward until its own backward: on the G2 joint model that is 33 heavy
+blocks x 1.77 GiB per saved tensor, so GPU memory, not compute, bounds how many recompute GEMMs can be skipped.
+This module moves those tensors to page-locked host memory while the forward runs and brings them back one or two
+blocks ahead of their backward, so the GPU memory they occupied can hold more selective-checkpoint saves instead.
+It is pure data movement: the backward consumes bit-identical values.
+
+Hook points
+-----------
+* Tier ``"inputs"``: the non-reentrant checkpoint frame keeps the block inputs through
+ ``_NoopSaveInputs.save_for_backward``, which runs *before* the frame installs its own saved-tensor hooks. An outer
+ ``torch.autograd.graph.saved_tensors_hooks`` around the checkpointed call therefore sees exactly those inputs and
+ nothing saved inside the frame (the innermost hooks win there). :class:`OffloadCheckpointWrapper` installs that
+ context around ``CheckpointWrapper.forward``. Its unpack hook is also the earliest point of a block's backward
+ (the recompute starts by reading the saved inputs) and doubles as the prefetch / slot-release trigger.
+* SAC tiers (``"sdpa"``, ``"mlp_out"``, ``"attn_out"``, ``"qkv"``, ``"mlp_in"``): the selective-checkpoint forward
+ mode stores saved op outputs as ``_VersionWrapper`` entries that the recompute mode pops with ``get_val()``;
+ :class:`_OffloadCachingMode` (a ``_CachingTorchDispatchMode``) replaces the large entries of the requested kinds
+ (classified by the policy's ``kind``) with :class:`_LazyEntry` objects whose ``get_val()`` returns the prefetched
+ GPU copy with the original shape, strides and dtype.
+
+Streams and events
+------------------
+Two dedicated streams per rank. D2H: an event recorded on the producing (compute) stream orders the copy on the
+``d2h`` stream; the item keeps a reference to the source tensor until the copy's event has completed (polled
+without blocking at every pack and at the start of the backward), so the GPU memory goes back to the allocator
+only after the copy and no ``record_stream`` bookkeeping is involved. H2D: into a ring of GPU staging slots. A
+slot is rewritten only after an event recorded on the compute stream at a point where the block that consumed it
+has had its whole backward issued (see below), and every consumer orders the compute stream after the copy's event
+(stream waits only, never the host). All copies run under ``torch.no_grad`` on strided views with the source
+layout, so each is a single ``cudaMemcpyAsync`` (including the BSHD layout of the cuDNN / efficient SDPA output).
+
+Prefetch trigger
+----------------
+Autograd executes nodes in decreasing sequence number, so when block ``b``'s backward starts (first unpack of its
+saved inputs by the recompute) every node of blocks ``> b`` has already been issued on the compute stream. That
+unpack (1) records the release event for the staging slots of blocks ``> b`` and (2) issues the H2D copies of the
+``prefetch`` nearest offloaded blocks below ``b`` into free slots. With ``prefetch=1`` the ring holds two blocks
+of items (the one being consumed and the one being staged). No hooks on block outputs are needed (FSDP2 wraps and
+re-registers those) and the recompute entry needs no knowledge of the graph beyond the wrapped blocks' forward
+order, which is learned per pass from the order in which the wrapped blocks are called (the DiT runs its mode blocks
+depth-major while modules enumerate modality-major). The last ``keep_last`` blocks in forward order stay resident
+(their backward comes first, before any prefetch could have been triggered); with ``keep_last=0`` the last
+``prefetch`` offloaded blocks are staged when the last wrapped block's forward returns.
+
+Host throttle
+-------------
+The training host issues the whole DiT forward far ahead of the GPU (command-buffer backpressure only stops it
+later, in the encoder launches), so without a bound every offloaded tensor would still be allocated when the
+forward ends and the offload would free nothing in the forward. ``max_inflight_bytes`` bounds the bytes whose D2H
+copy has not completed yet: beyond it the pack hook waits on the oldest copy's event. This is the only host wait;
+the compute stream keeps ``max_inflight_bytes / bytes-per-block`` blocks of queued work, so the GPU does not idle
+because of it, and the waiting time is taken from launch-queue stalls the host would otherwise spend later.
+``FLUX_ACTION_AC_OFFLOAD_INFLIGHT_GIB`` overrides the default (32 GiB); ``FLUX_ACTION_AC_OFFLOAD_LOG=1`` prints a
+JSON line of counters per forward/backward pass on rank 0.
+"""
+
+from __future__ import annotations
+
+import collections
+import contextlib
+import dataclasses
+import json
+import os
+import threading
+import time
+from collections.abc import Callable, Iterator
+from typing import Any
+
+import torch
+from torch import nn
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, CheckpointWrapper
+from torch.utils._pytree import tree_map
+from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode, _VersionWrapper
+
+INPUT_TIER = "inputs"
+SAC_TIERS = ("sdpa", "mlp_out", "attn_out", "qkv", "mlp_in")
+TIERS = (INPUT_TIER, *SAC_TIERS)
+GIB = 1 << 30
+
+
+def _env_int(name: str, default: int) -> int:
+ value = os.environ.get(name)
+ return int(value) if value not in (None, "") else default
+
+
+@dataclasses.dataclass(frozen=True)
+class OffloadPlan:
+ """What to offload and how far ahead to bring it back.
+
+ ``tiers``: ``"inputs"`` (the checkpoint frame's block inputs) and/or selective-checkpoint save kinds (see
+ ``distributed._SacPolicy``: ``sdpa``, ``mlp_out``, ``attn_out``, ``qkv``, ``mlp_in``) whose saved outputs are
+ offloaded; a SAC tier is only effective for kinds the policy actually saves. ``keep_last``: the last N wrapped
+ blocks in forward order keep everything resident. ``prefetch``: how many offloaded blocks ahead of the backward
+ the H2D copies are issued (ring size = prefetch + 1 blocks). ``min_bytes``: smaller tensors stay resident (the
+ 20 tiny text / state / action blocks, position tables, modulation rows). ``max_inflight_bytes``: bound on the
+ source bytes whose D2H copy is still running (0 = unbounded, see the module docstring).
+ """
+
+ tiers: tuple[str, ...] = (INPUT_TIER, "sdpa", "mlp_out")
+ keep_last: int = 2
+ prefetch: int = 1
+ min_bytes: int = GIB
+ max_inflight_bytes: int = dataclasses.field(
+ default_factory=lambda: _env_int("FLUX_ACTION_AC_OFFLOAD_INFLIGHT_GIB", 32) * GIB
+ )
+ log: bool = dataclasses.field(default_factory=lambda: os.environ.get("FLUX_ACTION_AC_OFFLOAD_LOG", "0") == "1")
+
+ def __post_init__(self):
+ tiers = tuple(dict.fromkeys(t.strip() for t in self.tiers if t.strip()))
+ object.__setattr__(self, "tiers", tiers)
+ if not tiers:
+ raise ValueError("OffloadPlan needs at least one tier")
+ for tier in tiers:
+ if tier not in TIERS:
+ raise ValueError(f"unknown offload tier {tier!r}; choose from {TIERS}")
+ if self.keep_last < 0 or self.prefetch < 1 or self.min_bytes < 1 or self.max_inflight_bytes < 0:
+ raise ValueError("keep_last and max_inflight_bytes must be >= 0, prefetch and min_bytes >= 1")
+
+ @classmethod
+ def from_spec(cls, spec: str | None, *, keep_last: int = 2, prefetch: int = 1) -> OffloadPlan | None:
+ """``"off"`` / ``""`` -> ``None``; otherwise a comma-separated tier list such as ``"inputs,sdpa,mlp_out"``."""
+ spec = (spec or "off").strip().lower()
+ if spec in ("off", "none", "0", "false"):
+ return None
+ return cls(tiers=tuple(spec.split(",")), keep_last=keep_last, prefetch=prefetch)
+
+ @property
+ def sac_tiers(self) -> tuple[str, ...]:
+ return tuple(t for t in self.tiers if t != INPUT_TIER)
+
+
+# ------------------------------------------------------------------------------------------------ handles
+
+class _Resident:
+ """Pack-hook result for a tensor that stays on the GPU; its unpack still delivers the block-start signal."""
+
+ __slots__ = ("value", "block")
+
+ def __init__(self, value, block: int):
+ self.value, self.block = value, block
+
+
+class _Item:
+ """One offloaded tensor: host slot, source (held until the D2H event), staging slot (until consumed)."""
+
+ __slots__ = ("block", "tier", "ordinal", "shape", "stride", "dtype", "nbytes", "host", "src", "ev_d2h",
+ "slot", "staged", "ev_h2d", "fetched")
+
+ def __init__(self, block: int, tier: str, ordinal: int, t: torch.Tensor):
+ self.block, self.tier, self.ordinal = block, tier, ordinal
+ self.shape, self.stride, self.dtype = tuple(t.shape), tuple(t.stride()), t.dtype
+ self.nbytes = t.numel() * t.element_size()
+ self.host = self.src = self.ev_d2h = self.slot = self.staged = self.ev_h2d = None
+ self.fetched = False
+
+
+class _LazyEntry:
+ """Stands in for ``_VersionWrapper`` in the SAC storage; the recompute mode calls ``get_val``."""
+
+ __slots__ = ("item", "offloader")
+
+ def __init__(self, item: _Item, offloader: ActivationOffloader):
+ self.item, self.offloader = item, offloader
+
+ def get_val(self, allow_cache_entry_mutation): # the mutation check needs the source, which is gone
+ return self.offloader._fetch(self.item)
+
+
+def _is_dense(t: torch.Tensor) -> bool:
+ """Non-overlapping and dense (a permutation of a contiguous layout): one memcpy covers exactly its elements."""
+ try:
+ from torch._prims_common import is_non_overlapping_and_dense
+
+ return bool(is_non_overlapping_and_dense(t))
+ except Exception: # noqa: BLE001 - private helper; be conservative
+ return t.is_contiguous()
+
+
+# ------------------------------------------------------------------------------------------------ host pool
+
+def _numa_cpus_for_device(device: torch.device) -> list[int] | None:
+ """CPUs of the NUMA node the GPU's PCIe root belongs to (None when sysfs does not tell)."""
+ try:
+ props = torch.cuda.get_device_properties(device)
+ bus = f"{props.pci_domain_id:04x}:{props.pci_bus_id:02x}:{props.pci_device_id:02x}.0"
+ with open(f"/sys/bus/pci/devices/{bus}/numa_node") as f:
+ node = int(f.read().strip())
+ if node < 0:
+ return None
+ with open(f"/sys/devices/system/node/node{node}/cpulist") as f:
+ cpus: list[int] = []
+ for part in f.read().strip().split(","):
+ lo, _, hi = part.partition("-")
+ cpus.extend(range(int(lo), int(hi or lo) + 1))
+ return cpus or None
+ except (OSError, ValueError, AttributeError):
+ return None
+
+
+@contextlib.contextmanager
+def _cpu_affinity(cpus: list[int] | None) -> Iterator[None]:
+ """Run the first touch of host pages on the GPU's NUMA node so they are allocated there."""
+ if not cpus or not hasattr(os, "sched_setaffinity"):
+ yield
+ return
+ previous = os.sched_getaffinity(0)
+ wanted = set(cpus) & previous
+ if not wanted:
+ yield
+ return
+ try:
+ os.sched_setaffinity(0, wanted)
+ except OSError:
+ yield
+ return
+ try:
+ yield
+ finally:
+ os.sched_setaffinity(0, previous)
+
+
+def _cuda_ok(err) -> bool:
+ return err == 0 or getattr(err, "value", None) == 0 or getattr(err, "name", None) == "success"
+
+
+class _HostPool:
+ """Page-locked host slots keyed by ``(block, tier, ordinal)``.
+
+ Exact-size buffers registered with ``cudaHostRegister`` (torch's pinned allocator rounds every request up to a
+ power of two, i.e. 2 GiB for a 1.77 GiB tensor), first-touched on the GPU's NUMA node. Slots are allocated on
+ first use (the first training step) and reused by every later step; a larger request for an existing key
+ replaces the slot.
+ """
+
+ def __init__(self, device: torch.device):
+ self.device = device
+ self.slots: dict[tuple, torch.Tensor] = {}
+ self.cpus = _numa_cpus_for_device(device)
+ self.bytes = 0
+ self.seconds = 0.0
+ self.registered = 0
+ self.fallback = 0
+ self._registered_ptrs: set[int] = set()
+
+ def get(self, key: tuple, nbytes: int) -> torch.Tensor:
+ buf = self.slots.get(key)
+ if buf is not None and buf.numel() >= nbytes:
+ return buf
+ if buf is not None:
+ self._drop(buf)
+ began = time.perf_counter()
+ buf = self._alloc(nbytes)
+ self.slots[key] = buf
+ self.bytes += buf.numel()
+ self.seconds += time.perf_counter() - began
+ return buf
+
+ def _alloc(self, nbytes: int) -> torch.Tensor:
+ buf = torch.empty(nbytes, dtype=torch.uint8)
+ with _cpu_affinity(self.cpus):
+ buf.zero_() # first touch: physical pages on the local node
+ err = torch.cuda.cudart().cudaHostRegister(buf.data_ptr(), nbytes, 0)
+ if _cuda_ok(err) and buf.is_pinned():
+ self.registered += 1
+ self._registered_ptrs.add(buf.data_ptr())
+ return buf
+ self.fallback += 1
+ return torch.empty(nbytes, dtype=torch.uint8, pin_memory=True)
+
+ def _drop(self, buf: torch.Tensor) -> None:
+ self.bytes -= buf.numel()
+ if buf.data_ptr() in self._registered_ptrs:
+ self._registered_ptrs.discard(buf.data_ptr())
+ torch.cuda.cudart().cudaHostUnregister(buf.data_ptr())
+
+ def close(self) -> None:
+ """Unregister every slot (registered pages must not be freed while still mapped for DMA)."""
+ for buf in self.slots.values():
+ self._drop(buf)
+ self.slots.clear()
+
+ def __del__(self):
+ try:
+ if self.slots and torch.cuda.is_available():
+ torch.cuda.synchronize(self.device) # no copy may still target the pages
+ self.close()
+ except Exception: # noqa: BLE001 - interpreter shutdown
+ pass
+
+
+# ------------------------------------------------------------------------------------------------ staging ring
+
+class _Slot:
+ __slots__ = ("buf", "busy", "ev_release")
+
+ def __init__(self, buf: torch.Tensor, ev_release: torch.cuda.Event | None):
+ self.buf, self.busy, self.ev_release = buf, True, ev_release
+
+
+class _Ring:
+ """GPU staging buffers for prefetched items; grows on demand to (prefetch + 1) blocks of items.
+
+ A slot is written by the ``h2d`` stream only after ``ev_release``, an event recorded on the compute stream once
+ its previous consumer's backward has been fully issued (or, for a fresh allocation, at allocation time: the
+ allocator may hand out memory the compute stream has only just stopped using).
+ """
+
+ def __init__(self, device: torch.device, h2d: torch.cuda.Stream):
+ self.device, self.h2d = device, h2d
+ self.slots: list[_Slot] = []
+ self.bytes = 0
+ self.grown = 0
+
+ def acquire(self, nbytes: int) -> _Slot:
+ best = None
+ for slot in self.slots:
+ if not slot.busy and slot.buf.numel() >= nbytes and (best is None or slot.buf.numel() < best.buf.numel()):
+ best = slot
+ if best is not None:
+ best.busy = True
+ return best
+ for slot in self.slots: # a free slot that is too small: let its memory go before growing
+ if not slot.busy:
+ slot.buf.record_stream(self.h2d)
+ self.bytes -= slot.buf.numel()
+ self.slots.remove(slot)
+ break
+ ev = torch.cuda.Event()
+ ev.record(torch.cuda.current_stream(self.device))
+ slot = _Slot(torch.empty(nbytes, dtype=torch.uint8, device=self.device), ev)
+ self.slots.append(slot)
+ self.bytes += nbytes
+ self.grown += 1
+ return slot
+
+ def release(self, slot: _Slot, ev_release: torch.cuda.Event) -> None:
+ slot.busy, slot.ev_release = False, ev_release
+
+
+# ------------------------------------------------------------------------------------------------ engine
+
+class ActivationOffloader:
+ """Per-rank offload engine shared by all wrapped blocks of one model (see the module docstring).
+
+ Thread-safety: pack hooks run on the training thread during the forward, unpack hooks on the autograd thread
+ during the backward; a re-entrant lock serializes the bookkeeping.
+ """
+
+ def __init__(self, plan: OffloadPlan, device: torch.device | None = None):
+ self.plan = plan
+ if device is None:
+ device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
+ elif device.type == "cuda" and device.index is None:
+ device = torch.device("cuda", torch.cuda.current_device())
+ self.device = device
+ cuda = device.type == "cuda"
+ self.d2h = torch.cuda.Stream(device) if cuda else None
+ self.h2d = torch.cuda.Stream(device) if cuda else None
+ self.host = _HostPool(device) if cuda else None
+ self.ring = _Ring(device, self.h2d) if cuda else None
+ self._lock = threading.RLock()
+ self.n_blocks = 0
+ self._groups: list[list[_Item]] = [] # items per forward position of the current pass
+ self._order: list[int] = [] # wrapper index of each forward position (learned every pass)
+ self._cur_pos = -1
+ self._phase = "idle" # idle | forward | backward
+ self._inflight: collections.deque[_Item] = collections.deque()
+ self._inflight_bytes = 0
+ self._signalled: set[int] = set()
+ self._prefetched: set[int] = set()
+ self._fetched = 0
+ self._total_items = 0
+ self._wait_seconds = 0.0
+ self._pass = 0
+ self._rank = int(os.environ.get("RANK", "0"))
+ self.stats: collections.Counter = collections.Counter()
+ self.last_pass: dict[str, Any] = {}
+ self.peaks: dict[str, float] = {}
+
+ def __deepcopy__(self, memo): # a deep-copied model (e.g. an EMA clone) shares the engine; it is never run
+ return self
+
+ def __reduce__(self):
+ raise TypeError("ActivationOffloader holds CUDA streams and page-locked memory and cannot be pickled")
+
+ # ---------------------------------------------------------------------------------------- wrapping
+ def wrap(self, module: nn.Module, index: int, sac_policy_factory: Callable[[], Any] | None = None) -> OffloadCheckpointWrapper:
+ """Checkpoint-wrap ``module`` (``index`` identifies the wrapper; the forward position is learned per pass);
+ ``sac_policy_factory`` (fresh selective-checkpoint policy per call) enables the SAC tiers for it."""
+ return OffloadCheckpointWrapper(module, self, index, sac_policy_factory)
+
+ def finalize(self, n_blocks: int) -> None:
+ """Number of wrapped blocks; ``keep_last`` counts back from the last forward position."""
+ self.n_blocks = n_blocks
+ self._groups = [[] for _ in range(n_blocks)]
+
+ def resident_block(self, pos: int) -> bool:
+ """Blocks at the last ``keep_last`` forward positions (their backward comes first) keep everything resident.
+
+ Positions are assigned in the order the wrapped blocks are called in the current pass (the module enumeration
+ order is modality-major while the DiT forward is depth-major, so the static wrapper index is not usable)."""
+ return pos < 0 or pos >= self.n_blocks - self.plan.keep_last
+
+ def tier_enabled(self, tier: str | None) -> bool:
+ return tier is not None and tier in self.plan.tiers
+
+ def offloadable(self, t) -> bool:
+ return (
+ isinstance(t, torch.Tensor)
+ and t.device == self.device
+ and t.layout == torch.strided
+ and t.numel() * t.element_size() >= self.plan.min_bytes
+ and _is_dense(t)
+ )
+
+ @staticmethod
+ def classify(policy, func, args) -> str | None:
+ """The policy's save kind of an op (``_SacPolicy.kind``); None for policies without classification."""
+ kind = getattr(policy, "kind", None)
+ return kind(func, args, False) if callable(kind) else None
+
+ # ---------------------------------------------------------------------------------------- forward side
+ def block_forward_begin(self, index: int) -> None:
+ with self._lock:
+ if self._phase == "backward" or (self._order and len(self._order) >= self.n_blocks):
+ self._end_pass()
+ self._phase = "forward"
+ self._cur_pos = len(self._order)
+ self._order.append(index)
+ while len(self._groups) <= self._cur_pos:
+ self._groups.append([])
+
+ def block_forward_end(self, index: int) -> None:
+ with self._lock:
+ pos, self._cur_pos = self._cur_pos, -1
+ if pos == self.n_blocks - 1 and self.plan.keep_last == 0 and self.d2h is not None:
+ self._prefetch_below(self.n_blocks) # nothing precedes the first backward: stage the tail now
+
+ def _pack_input(self, t):
+ pos = self._cur_pos
+ if self.tier_enabled(INPUT_TIER) and not self.resident_block(pos) and self.offloadable(t):
+ return self._offload(t, pos, INPUT_TIER)
+ if isinstance(t, torch.Tensor) and not self.resident_block(pos) and self.tier_enabled(INPUT_TIER) \
+ and t.device == self.device and t.numel() * t.element_size() >= self.plan.min_bytes:
+ self.stats["resident_non_dense"] += 1
+ return _Resident(t, pos)
+
+ def _unpack_input(self, handle):
+ if isinstance(handle, _Item):
+ self._backward_signal(handle.block)
+ return self._fetch(handle)
+ self._backward_signal(handle.block)
+ return handle.value
+
+ def _maybe_lazy(self, entry, kind: str):
+ pos = self._cur_pos
+ if isinstance(entry, _VersionWrapper) and not self.resident_block(pos) and self.offloadable(entry.val):
+ return _LazyEntry(self._offload(entry.val, pos, kind), self)
+ return entry
+
+ def _offload(self, t: torch.Tensor, block: int, tier: str) -> _Item:
+ with self._lock, torch.no_grad():
+ self._throttle()
+ group = self._groups[block]
+ item = _Item(block, tier, sum(1 for it in group if it.tier == tier), t)
+ host = self.host.get((block, tier, item.ordinal), item.nbytes)
+ item.host = host[: item.nbytes].view(item.dtype).as_strided(item.shape, item.stride)
+ produced = torch.cuda.Event()
+ produced.record(torch.cuda.current_stream(self.device))
+ self.d2h.wait_event(produced)
+ with torch.cuda.stream(self.d2h):
+ item.host.copy_(t, non_blocking=True)
+ item.ev_d2h = torch.cuda.Event()
+ item.ev_d2h.record(self.d2h)
+ item.src = t # released once ev_d2h has completed (polled, never waited on except by the throttle)
+ group.append(item)
+ self._inflight.append(item)
+ self._inflight_bytes += item.nbytes
+ self.stats["items"] += 1
+ self.stats[f"items_{tier}"] += 1
+ self.stats["d2h_bytes"] += item.nbytes
+ return item
+
+ def _poll_inflight(self) -> None:
+ while self._inflight and self._inflight[0].ev_d2h.query():
+ item = self._inflight.popleft()
+ item.src = None
+ self._inflight_bytes -= item.nbytes
+
+ def release_completed(self) -> int:
+ """Drop the GPU sources of all completed D2H copies (called automatically; public for tests). Returns the
+ bytes still in flight."""
+ with self._lock:
+ self._poll_inflight()
+ return self._inflight_bytes
+
+ def _throttle(self) -> None:
+ self._poll_inflight()
+ limit = self.plan.max_inflight_bytes
+ while limit and self._inflight_bytes > limit and self._inflight:
+ began = time.perf_counter()
+ self._inflight[0].ev_d2h.synchronize()
+ self._wait_seconds += time.perf_counter() - began
+ self.stats["throttle_waits"] += 1
+ self._poll_inflight()
+
+ # ---------------------------------------------------------------------------------------- backward side
+ def _backward_signal(self, block: int) -> None:
+ with self._lock:
+ if self._phase != "backward":
+ self._phase = "backward"
+ self._total_items = sum(len(g) for g in self._groups)
+ self._poll_inflight()
+ if block < 0 or block in self._signalled:
+ return
+ self._signalled.add(block)
+ ev_release = None
+ for j in range(block + 1, len(self._groups)): # their backward is fully issued once block's starts
+ for item in self._groups[j]:
+ if item.slot is not None:
+ if ev_release is None:
+ ev_release = torch.cuda.Event()
+ ev_release.record(torch.cuda.current_stream(self.device))
+ self.ring.release(item.slot, ev_release)
+ item.slot = item.staged = None
+ if not item.fetched:
+ self.stats["never_fetched"] += 1
+ self._prefetch_below(block)
+ self._poll_inflight()
+
+ def _prefetch_below(self, block: int) -> None:
+ want, j = self.plan.prefetch, block - 1
+ while j >= 0 and want > 0:
+ if self._groups[j]:
+ if j not in self._prefetched:
+ self._prefetched.add(j)
+ for item in self._groups[j]:
+ self._prefetch_item(item)
+ want -= 1
+ j -= 1
+
+ def _prefetch_item(self, item: _Item) -> None:
+ with torch.no_grad():
+ slot = self.ring.acquire(item.nbytes)
+ if slot.ev_release is not None:
+ self.h2d.wait_event(slot.ev_release)
+ self.h2d.wait_event(item.ev_d2h)
+ with torch.cuda.stream(self.h2d):
+ staged = slot.buf[: item.nbytes].view(item.dtype).as_strided(item.shape, item.stride)
+ staged.copy_(item.host, non_blocking=True)
+ item.ev_h2d = torch.cuda.Event()
+ item.ev_h2d.record(self.h2d)
+ item.slot, item.staged = slot, staged
+ self.stats["h2d_bytes"] += item.nbytes
+
+ def _fetch(self, item: _Item) -> torch.Tensor:
+ with self._lock:
+ if item.staged is None:
+ if item.fetched:
+ raise RuntimeError("offloaded activation requested again after its staging slot was released")
+ self.stats["late_prefetch"] += 1
+ self._prefetch_item(item)
+ torch.cuda.current_stream(self.device).wait_event(item.ev_h2d)
+ if not item.fetched:
+ item.fetched = True
+ self._fetched += 1
+ if self._fetched == self._total_items:
+ self._sample_peaks()
+ return item.staged
+
+ # ---------------------------------------------------------------------------------------- pass boundary
+ def _sample_peaks(self) -> None:
+ try:
+ stats = torch.cuda.memory_stats(self.device)
+ self.peaks = {k: round(stats.get(f"{k}_bytes.all.peak", 0) / GIB, 2) for k in ("allocated", "active", "reserved")}
+ except Exception: # noqa: BLE001 - diagnostics only
+ self.peaks = {}
+
+ def _end_pass(self) -> None:
+ if self.d2h is not None:
+ ev = torch.cuda.Event()
+ ev.record(torch.cuda.current_stream(self.device))
+ for group in self._groups:
+ for item in group:
+ if item.slot is not None:
+ self.ring.release(item.slot, ev)
+ item.slot = item.staged = None
+ if not item.fetched:
+ self.stats["never_fetched"] += 1
+ self.d2h.wait_stream(self.h2d) # host slots are rewritten only after (possibly unconsumed) H2D reads
+ self._poll_inflight()
+ if self._inflight: # cannot happen after a completed backward; keep the host slots consistent anyway
+ self._inflight[-1].ev_d2h.synchronize()
+ self._poll_inflight()
+ self.stats["end_pass_sync"] += 1
+ self.last_pass = self.summary()
+ if self.plan.log and self._rank == 0 and self.stats.get("items"):
+ print(json.dumps({"event": "activation_offload", "pass": self._pass, **self.last_pass}), flush=True)
+ self._groups = [[] for _ in range(self.n_blocks)]
+ self._order = []
+ self._signalled.clear()
+ self._prefetched.clear()
+ self._fetched = self._total_items = 0
+ self._wait_seconds = 0.0
+ self.stats = collections.Counter()
+ self.peaks = {}
+ self._pass += 1
+ self._phase = "idle"
+
+ def summary(self) -> dict[str, Any]:
+ """Counters of the current pass (bytes, items per tier, throttle waits, ring / host pool sizes, peaks)."""
+ out: dict[str, Any] = {k: 0 for k in ("items", "d2h_bytes", "h2d_bytes", "late_prefetch", "never_fetched",
+ "throttle_waits", "resident_non_dense")}
+ out.update(self.stats)
+ out["throttle_wait_s"] = round(self._wait_seconds, 3)
+ out["inflight_bytes"] = self._inflight_bytes
+ if self.ring is not None:
+ out["ring_slots"], out["ring_gib"] = len(self.ring.slots), round(self.ring.bytes / GIB, 2)
+ if self.host is not None:
+ out["host_slots"], out["host_gib"] = len(self.host.slots), round(self.host.bytes / GIB, 2)
+ out["host_pin_s"], out["host_registered"], out["host_fallback"] = round(self.host.seconds, 2), self.host.registered, self.host.fallback
+ out["host_numa_cpus"] = len(self.host.cpus) if self.host.cpus else 0
+ out["peak_gib"] = dict(self.peaks)
+ return out
+
+
+# ------------------------------------------------------------------------------------------------ hooks
+
+class _OffloadCachingMode(_CachingTorchDispatchMode):
+ """Selective-checkpoint forward mode whose large saved entries of the offloaded kinds become lazy."""
+
+ def __init__(self, policy_fn, storage, offloader: ActivationOffloader):
+ super().__init__(policy_fn, storage)
+ self.offloader = offloader
+
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
+ before = len(self.storage[func]) if func in self.storage else 0
+ out = super().__torch_dispatch__(func, types, args, kwargs)
+ entries = self.storage.get(func)
+ if entries is not None and len(entries) > before:
+ kind = self.offloader.classify(self.policy_fn, func, args)
+ if self.offloader.tier_enabled(kind):
+ entries[-1] = tree_map(lambda e: self.offloader._maybe_lazy(e, kind), entries[-1])
+ return out
+
+
+def _sac_offload_context_fn(offloader: ActivationOffloader, policy_factory: Callable[[], Any]):
+ def context_fn():
+ policy = policy_factory()
+ storage: dict = collections.defaultdict(list)
+ return _OffloadCachingMode(policy, storage, offloader), _CachedTorchDispatchMode(policy, storage, False)
+
+ return context_fn
+
+
+class OffloadCheckpointWrapper(CheckpointWrapper):
+ """``CheckpointWrapper`` (non-reentrant, no RNG stashing) whose forward runs under the offload engine's
+ saved-tensor hooks; state-dict names keep the usual ``_checkpoint_wrapped_module.`` prefix."""
+
+ def __init__(self, module: nn.Module, offloader: ActivationOffloader, index: int, sac_policy_factory=None):
+ kwargs = {}
+ if sac_policy_factory is not None:
+ kwargs["context_fn"] = _sac_offload_context_fn(offloader, sac_policy_factory)
+ super().__init__(module, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False, **kwargs)
+ self._offloader = offloader
+ self._offload_index = index
+
+ def forward(self, *args, **kwargs):
+ offloader, index = self._offloader, self._offload_index
+ offloader.block_forward_begin(index)
+ try:
+ with torch.autograd.graph.saved_tensors_hooks(offloader._pack_input, offloader._unpack_input):
+ return super().forward(*args, **kwargs)
+ finally:
+ offloader.block_forward_end(index)
+
+
+def install(blocks: list[nn.Module], plan: OffloadPlan, *, sac_policy_factories=None,
+ device: torch.device | None = None) -> tuple[ActivationOffloader, list[OffloadCheckpointWrapper]]:
+ """Wrap ``blocks`` (forward order) for checkpointing with offload; returns the engine and the wrappers.
+
+ ``sac_policy_factories`` (optional, one per block, ``None`` entries for plain full recompute) enable the SAC
+ tiers. ``apply_activation_checkpointing`` in ``training/distributed.py`` performs the same steps in place.
+ """
+ offloader = ActivationOffloader(plan, device)
+ factories = list(sac_policy_factories) if sac_policy_factories is not None else [None] * len(blocks)
+ if len(factories) != len(blocks):
+ raise ValueError("one selective-checkpoint policy factory (or None) per block is required")
+ wrapped = [offloader.wrap(block, i, factory) for i, (block, factory) in enumerate(zip(blocks, factories, strict=True))]
+ offloader.finalize(len(wrapped))
+ return offloader, wrapped
diff --git a/flux-umi/src/flux_action/training/checkpoint.py b/flux-umi/src/flux_action/training/checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..2753f3d0cafcfd2a7d925babdd6d9b3897307e23
--- /dev/null
+++ b/flux-umi/src/flux_action/training/checkpoint.py
@@ -0,0 +1,343 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Resumable training checkpoints on ``torch.distributed.checkpoint``.
+
+``/step-/`` is written after ``N`` optimizer updates, the reference's naming, and holds
+
+* ``model/`` DCP: the policy's DiT parameters (dense or FSDP shards, resharded on load)
+* ``optimizer/`` DCP: AdamW state keyed by parameter name
+* ``ema_0p10/``, ``ema_0p05/`` DCP: the power-EMA shadow tensors of each profile
+* ``state.json`` rank 0: :class:`TrainState` (step, seeds, world size, EMA steps, loader position)
+* ``config.json`` rank 0: the ``PolicyConfig``, so :func:`export_policy` rebuilds the model without the run
+* ``rng/rank-.pt`` per-rank torch / CUDA / ``random`` / numpy generator states
+* ``COMPLETE`` rank 0, after every rank finished: :func:`latest_checkpoint` ignores directories without it
+
+The learning-rate scheduler is not stored. Rebuild it from the configuration and call
+``resume_lr_scheduler(scheduler, state.step)``. Generator states are restored only when
+reseeding is off and the world size is unchanged; the reference drew a fresh seed on every
+resume, which :func:`resume_seed` reproduces deterministically from the run seed.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import random
+import shutil
+import warnings
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import torch
+import torch.distributed.checkpoint as dcp
+from torch import Tensor, nn
+from torch.distributed.checkpoint.state_dict import (
+ get_model_state_dict,
+ get_optimizer_state_dict,
+ set_model_state_dict,
+ set_optimizer_state_dict,
+)
+
+from ..config import PolicyConfig
+from .distributed import barrier, rank_world
+from .ema import PowerEMA
+
+STATE_FORMAT = 1
+COMPLETE_MARKER = "COMPLETE"
+_SINGLE_PROCESS_WARNING = "torch.distributed is disabled, unavailable or uninitialized"
+
+
+def ema_folder(sigma_rel: float) -> str:
+ """``0.10 -> ema_0p10``; the profile is part of the folder name."""
+ return "ema_" + f"{sigma_rel:.2f}".replace(".", "p")
+
+
+@dataclass
+class TrainState:
+ step: int = 0 # completed optimizer updates
+ run_seed: int = 42
+ seed_history: list[int] = field(default_factory=list) # seeds in effect, in order; [0] is run_seed
+ world_size: int = 1
+ emas: dict[str, dict[str, Any]] = field(default_factory=dict) # folder -> {sigma_rel, last_step}
+ data: dict[str, Any] = field(default_factory=dict) # loader position, owned by the data path
+ extra: dict[str, Any] = field(default_factory=dict)
+
+ def __post_init__(self):
+ if not self.seed_history:
+ self.seed_history = [self.run_seed]
+
+ @property
+ def seed(self) -> int:
+ """The seed in effect for the current segment of the run."""
+ return self.seed_history[-1]
+
+ def to_json(self) -> str:
+ return json.dumps({"format": STATE_FORMAT, **asdict(self)}, indent=2) + "\n"
+
+ @classmethod
+ def from_json(cls, text: str) -> TrainState:
+ data = json.loads(text)
+ if data.pop("format", None) != STATE_FORMAT:
+ raise ValueError("unsupported training state format")
+ return cls(**data)
+
+
+def resume_seed(run_seed: int, resume_index: int) -> int:
+ """Seed of the ``resume_index``-th resume (1-based): distinct from the run seed, reproducible."""
+ if resume_index < 1:
+ raise ValueError("resume_index counts resumes from one")
+ digest = hashlib.sha256(f"{run_seed}:{resume_index}".encode()).digest()
+ return int.from_bytes(digest[:4], "big") % (2**31 - 1) + 1
+
+
+def seed_everything(seed: int) -> None:
+ random.seed(seed)
+ np.random.seed(seed % (2**32))
+ torch.manual_seed(seed)
+
+
+def cpu_rng_state() -> dict[str, Any]:
+ """The host-side generator states (torch CPU, python ``random``, numpy) as weights_only-loadable values."""
+ version, keys, gauss = random.getstate()
+ np_name, np_keys, np_pos, np_has_gauss, np_gauss = np.random.get_state()
+ return {
+ "torch": torch.get_rng_state(),
+ "python": {"version": version, "keys": list(keys), "gauss": gauss},
+ "numpy": {
+ "name": np_name,
+ "keys": torch.from_numpy(np.asarray(np_keys).copy()),
+ "pos": int(np_pos),
+ "has_gauss": int(np_has_gauss),
+ "gauss": float(np_gauss),
+ },
+ }
+
+
+def rng_state(cpu: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Generator states of this process; everything is a tensor, int or list so it loads with weights_only.
+
+ ``cpu`` replaces the live host-side states with an earlier :func:`cpu_rng_state` snapshot: the trainer passes
+ the snapshot taken when the pending (prefetched) micro-batch was prepared, so that a resumed run, which prepares
+ that batch again, draws the same values and continues the same random stream.
+ """
+ return {**(cpu if cpu is not None else cpu_rng_state()),
+ "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []}
+
+
+def set_rng_state(state: dict[str, Any]) -> None:
+ torch.set_rng_state(state["torch"])
+ if state["cuda"] and torch.cuda.is_available():
+ torch.cuda.set_rng_state_all(state["cuda"])
+ py = state["python"]
+ random.setstate((py["version"], tuple(py["keys"]), py["gauss"]))
+ npy = state["numpy"]
+ np.random.set_state((npy["name"], npy["keys"].numpy(), npy["pos"], npy["has_gauss"], npy["gauss"]))
+
+
+def _dcp_save(state_dict: dict[str, Any], path: Path) -> None:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", message=_SINGLE_PROCESS_WARNING)
+ dcp.save(state_dict, checkpoint_id=str(path))
+
+
+def _dcp_load(state_dict: dict[str, Any], path: Path, *, partial: bool = False) -> None:
+ """Load in place; ``partial`` leaves template entries the checkpoint lacks untouched."""
+ from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", message=_SINGLE_PROCESS_WARNING)
+ planner = DefaultLoadPlanner(allow_partial_load=True) if partial else None
+ dcp.load(state_dict, checkpoint_id=str(path), planner=planner)
+
+
+def checkpoint_dir(root: str | Path, step: int) -> Path:
+ return Path(root) / f"step-{step}"
+
+
+def complete_checkpoints(root: str | Path) -> list[tuple[int, Path]]:
+ """All complete ``step-`` directories under ``root``, sorted by step."""
+ root = Path(root)
+ if not root.is_dir():
+ return []
+ steps = []
+ for entry in root.iterdir():
+ if entry.is_dir() and entry.name.startswith("step-") and (entry / COMPLETE_MARKER).exists():
+ try:
+ steps.append((int(entry.name.removeprefix("step-")), entry))
+ except ValueError:
+ continue
+ return sorted(steps)
+
+
+def latest_checkpoint(root: str | Path) -> Path | None:
+ """The complete checkpoint with the highest step, or ``None``."""
+ steps = complete_checkpoints(root)
+ return steps[-1][1] if steps else None
+
+
+def prune_checkpoints(root: str | Path, *, keep_last: int, keep_every: int | None, protect: int) -> list[int]:
+ """Delete complete checkpoints except the newest ``keep_last``, every ``keep_every``-th step and
+ ``protect`` (the step just written). Call on one rank only. Returns the removed steps."""
+ if keep_last < 1:
+ raise ValueError("keep_last must be positive")
+ steps = complete_checkpoints(root)
+ keep = {step for step, _ in steps[-keep_last:]} | {protect}
+ if keep_every:
+ keep |= {step for step, _ in steps if step % keep_every == 0}
+ removed = []
+ for step, path in steps:
+ if step not in keep:
+ shutil.rmtree(path)
+ removed.append(step)
+ return removed
+
+
+def save_checkpoint(
+ root: str | Path,
+ *,
+ step: int,
+ model: nn.Module,
+ optimizer: torch.optim.Optimizer,
+ emas: dict[str, PowerEMA],
+ state: TrainState,
+ config: PolicyConfig,
+ rng: dict[str, Any] | None = None,
+) -> Path:
+ """Write ``/step-``; every rank calls this. Existing directories are replaced.
+
+ ``rng`` overrides the generator states written for this rank (see :func:`rng_state`); default = the live states.
+ """
+ rank, world_size = rank_world()
+ path = checkpoint_dir(root, step)
+ if rank == 0 and path.exists():
+ shutil.rmtree(path)
+ barrier()
+ path.mkdir(parents=True, exist_ok=True)
+ state.step = step
+ state.world_size = world_size
+ state.emas = {
+ name: {"sigma_rel": ema.sigma_rel, "last_step": ema.last_step, "n_tensors": len(ema.names)}
+ for name, ema in emas.items()
+ }
+ _dcp_save({"model": get_model_state_dict(model)}, path / "model")
+ _dcp_save({"optimizer": get_optimizer_state_dict(model, optimizer)}, path / "optimizer")
+ for name, ema in emas.items():
+ _dcp_save({"tensors": ema.state_dict()["tensors"]}, path / name)
+ (path / "rng").mkdir(exist_ok=True)
+ torch.save(rng if rng is not None else rng_state(), path / "rng" / f"rank-{rank:04d}.pt")
+ if rank == 0:
+ (path / "state.json").write_text(state.to_json())
+ (path / "config.json").write_text(json.dumps(config.to_dict(), indent=2) + "\n")
+ barrier()
+ if rank == 0:
+ (path / COMPLETE_MARKER).write_text(f"{step}\n")
+ barrier()
+ return path
+
+
+def load_checkpoint(
+ path: str | Path,
+ *,
+ model: nn.Module,
+ optimizer: torch.optim.Optimizer | None = None,
+ emas: dict[str, PowerEMA] | None = None,
+) -> TrainState:
+ """Restore model, optimizer and EMA tensors in place (resharding as needed) and return the state."""
+ path = Path(path)
+ if not (path / COMPLETE_MARKER).exists():
+ raise FileNotFoundError(f"{path} is not a complete checkpoint")
+ state = TrainState.from_json((path / "state.json").read_text())
+ model_sd = {"model": get_model_state_dict(model)}
+ _dcp_load(model_sd, path / "model")
+ set_model_state_dict(model, model_sd["model"])
+ if optimizer is not None:
+ optim_sd = {"optimizer": get_optimizer_state_dict(model, optimizer)}
+ _dcp_load(optim_sd, path / "optimizer")
+ set_optimizer_state_dict(model, optimizer, optim_sd["optimizer"])
+ for name, ema in (emas or {}).items():
+ meta = state.emas.get(name)
+ if meta is None:
+ raise ValueError(f"checkpoint has no EMA profile {name!r}; found {sorted(state.emas)}")
+ if float(meta["sigma_rel"]) != ema.sigma_rel:
+ raise ValueError(f"{name}: checkpoint sigma_rel {meta['sigma_rel']} differs from {ema.sigma_rel}")
+ _dcp_load({"tensors": dict(zip(ema.names, ema.shadow, strict=True))}, path / name)
+ ema.last_step = meta["last_step"]
+ return state
+
+
+def restore_rng(path: str | Path, state: TrainState) -> bool:
+ """Restore this rank's generator states when the world size is unchanged; ``False`` otherwise."""
+ rank, world_size = rank_world()
+ if state.world_size != world_size:
+ return False
+ file = Path(path) / "rng" / f"rank-{rank:04d}.pt"
+ if not file.exists():
+ return False
+ set_rng_state(torch.load(file, weights_only=True))
+ return True
+
+
+def export_policy(
+ path: str | Path, output: str | Path, *, profile: str = "model", dtype: str | None = None
+) -> dict[str, Any]:
+ """Write a standalone inference export from a checkpoint's ``model`` or an EMA profile folder.
+
+ Runs in one process on the CPU regardless of how many ranks wrote the checkpoint. Tensors that a
+ profile does not average (frozen streams and conditioning heads) come from ``model/``.
+
+ ``dtype`` casts the exported weights; ``None`` keeps the checkpoint's dtype. The checkpoint holds fp32
+ masters and an export is served in the dtype it was written in: ``"bfloat16"`` for serving, ``None`` to keep
+ the masters for further training or diffing.
+ """
+ from ..models.transformer import JointSingleSeqParams
+ from ..models.wiring import action_dit_params, build_action_dit, restrict_content_streams
+ from ..policy import write_policy_export
+
+ path = Path(path)
+ if not (path / COMPLETE_MARKER).exists():
+ raise FileNotFoundError(f"{path} is not a complete checkpoint")
+ state = TrainState.from_json((path / "state.json").read_text())
+ if profile != "model" and profile not in state.emas:
+ raise ValueError(f"unknown profile {profile!r}; choose 'model' or one of {sorted(state.emas)}")
+ config = PolicyConfig(**json.loads((path / "config.json").read_text()))
+ dit = build_action_dit(
+ action_dit_params(
+ restrict_content_streams(JointSingleSeqParams(**config.dit_config), config.content_streams),
+ config.action_modality,
+ config.action_dim,
+ attn_mode=config.attn_mode,
+ conditioning_channels=config.conditioning_channels,
+ ),
+ None,
+ modality=config.action_modality,
+ dtype=getattr(torch, config.torch_dtype),
+ )
+ tensors: dict[str, Tensor] = {f"dit.{k}": v for k, v in dit.state_dict().items()}
+ _dcp_load({"model": tensors}, path / "model")
+ if profile != "model":
+ averaged = {f"dit.{k}": v for k, v in dit.named_parameters()}
+ _dcp_load({"tensors": averaged}, path / profile, partial=True)
+ if dtype is not None:
+ target = getattr(torch, dtype)
+ tensors = {k: (v.to(target) if v.is_floating_point() else v) for k, v in tensors.items()}
+ write_policy_export(output, config, tensors, weight_profile=profile)
+ return {
+ "checkpoint": str(path),
+ "step": state.step,
+ "profile": profile,
+ "output": str(output),
+ "tensors": len(tensors),
+ }
diff --git a/flux-umi/src/flux_action/training/data.py b/flux-umi/src/flux_action/training/data.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a0d50f8d20232abe7ab4ab52fcdfb0b62655326
--- /dev/null
+++ b/flux-umi/src/flux_action/training/data.py
@@ -0,0 +1,405 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Streaming training windows over an indexed dataset: deterministic order, one window per episode visit.
+
+The manifest comes from ``flux-action index-droid`` (the compact Cosmos3-DROID layout: three 360x640
+cameras, 8-dimensional state and action) or ``flux-action index-lerobot`` (a LeRobot dataset: the
+manifest names its camera streams, row widths and native camera sizes, and windows start at frame 1 so the
+command before the window, ``action_prev``, exists for the joint-delta parameterization). Frames are
+decoded at the manifest's native size and, for LeRobot cameras, rescaled to ``frame_hw``.
+
+A visit of episode ``e`` in epoch ``k`` of a run with seed ``s`` draws its window start, caption
+paraphrase and ``window_seed`` (the seed of the policy's augmentation and caption-dropout draws for that
+window) from ``Random(f"{s}:{k}:{e}")``, so the set of windows of an epoch and their augmentations do not
+depend on how many ranks or workers share it, nor on when the policy encodes the window; only the
+assignment does. Episodes are shuffled per epoch,
+split ``[rank::world_size]`` across ranks and ``[worker::num_workers]`` across loader workers.
+``DataLoader`` batches ``windows_per_rank`` consecutive windows of one worker and serves workers in
+order, so batch ``i`` comes from worker ``i % num_workers``.
+
+An epoch has the same number of batches on every rank, a multiple of the accumulation steps:
+``batches_per_rank = (n_episodes // (world_size * num_workers * windows_per_rank)) * num_workers``
+rounded down to the accumulation multiple; the leftover episodes of the epoch are skipped. Ranks
+therefore run in lockstep (FSDP collectives, epoch boundaries, ``max_epochs``) and one recorded
+:class:`DataPosition` describes all of them. On an exact resume the dataset skips the consumed batches
+and rotates the worker assignment so the loader, which always starts with worker 0, continues the
+original order.
+
+Frames stay uint8 until the policy moves them to the accelerator (2.2 GB per 32-window batch
+instead of 8.7 GB as float32).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import multiprocessing
+import sys
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from random import Random
+from typing import Any
+
+import numpy as np
+import torch
+from torch.utils.data import DataLoader, IterableDataset, get_worker_info
+
+from ..data.droid import index as droid_index
+from ..data.droid.episodes import CAMERAS, select_caption
+from ..data.droid.video import FRAME_HW, decode_window
+from ..data.lerobot import index as lerobot_index
+from ..data.windows import select_window_start, valid_window_spans
+
+DROID_STATE_DIM = DROID_ACTION_DIM = 8
+GRAY_LEVEL = 128 # the flat tile of a camera stream the index declared absent
+
+
+def load_manifest(path) -> dict:
+ """A DROID or LeRobot manifest, validated by its own loader (``kind`` tells them apart)."""
+ manifest = json.loads(Path(path).read_text())
+ if manifest.get("kind") == lerobot_index.KIND:
+ return lerobot_index.load_manifest(path)
+ return droid_index.load_manifest(path)
+
+
+def manifest_dims(manifest: dict) -> tuple[int, int]:
+ """``(state_dim, action_dim)`` of the rows array; DROID manifests predate the fields."""
+ return int(manifest.get("state_dim", DROID_STATE_DIM)), int(manifest.get("action_dim", DROID_ACTION_DIM))
+
+
+@dataclass
+class DataPosition:
+ """Loader position of one rank; exact only for the recorded topology."""
+
+ epoch: int = 0
+ batches_consumed: int = 0
+ world_size: int = 1
+ num_workers: int = 1
+ windows_per_rank: int = 1
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> DataPosition:
+ return cls(**data)
+
+ def matches(self, *, world_size: int, num_workers: int, windows_per_rank: int) -> bool:
+ return (self.world_size, self.num_workers, self.windows_per_rank) == (
+ world_size,
+ num_workers,
+ windows_per_rank,
+ )
+
+
+def epoch_order(n_episodes: int, seed: int, epoch: int) -> list[int]:
+ order = list(range(n_episodes))
+ Random(f"{seed}:{epoch}").shuffle(order)
+ return order
+
+
+class WindowDataset(IterableDataset):
+ """Windows of an indexed dataset (``load_manifest``): ``images.`` uint8 ``(chunk + 1, 3, H, W)``
+ per camera, ``state`` ``(S,)`` at the window's first frame, ``action`` ``(chunk, A)`` commands, and, when
+ the manifest provides it, ``action_prev`` ``(A,)``: the command before the window.
+
+ With ``n_obs_steps=H``, the start is the current control tick: images span
+ ``[start-H+1, start+chunk]``, states span ``[start-H+1, start]``, and
+ ``command_history`` spans ``[start-H, start-1]``. Actions still start at ``start``.
+ Only complete histories within a valid episode range are sampled.
+ """
+
+ def __init__(
+ self,
+ manifest: dict,
+ source_root,
+ rows_path,
+ *,
+ seed: int,
+ epoch: int = 0,
+ rank: int = 0,
+ world_size: int = 1,
+ num_workers: int = 1,
+ windows_per_rank: int = 1,
+ skip_batches: int = 0,
+ grad_accumulation: int = 1,
+ decoder: str = "ffmpeg",
+ frame_hw: tuple[int, int] = FRAME_HW,
+ visits_per_epoch: int = 1,
+ split: str | None = "train",
+ n_obs_steps: int | None = None,
+ ):
+ if not 0 <= rank < world_size:
+ raise ValueError("rank must lie in [0, world_size)")
+ if num_workers < 1 or windows_per_rank < 1 or skip_batches < 0 or grad_accumulation < 1:
+ raise ValueError(
+ "num_workers, windows_per_rank and grad_accumulation must be positive, skip_batches non-negative"
+ )
+ if visits_per_epoch < 1:
+ raise ValueError("visits_per_epoch must be positive")
+ if n_obs_steps is not None and (n_obs_steps < 1 or not manifest.get("action_prev")):
+ raise ValueError("history windows need positive n_obs_steps and an index with previous commands")
+ self.n_obs_steps = n_obs_steps
+ self.manifest = manifest
+ # episodes carry a split when the index held some out (LeRobot ``--val-episodes``); None takes all
+ self.episodes = [e for e in manifest["episodes"] if split is None or e.get("split", "train") == split]
+ # Episodes that cannot supply one complete history window (n_obs_steps observed ticks plus the
+ # chunk inside one keep range) are excluded; the count is kept for diagnostics.
+ self.episodes_without_history = 0
+ if n_obs_steps is not None:
+ eligible = [
+ e
+ for e in self.episodes
+ if valid_window_spans(e["n_frames"], self._valid_ranges(e), manifest["chunk_size"])
+ ]
+ self.episodes_without_history = len(self.episodes) - len(eligible)
+ self.episodes = eligible
+ self.split, self.visits_per_epoch = split, visits_per_epoch
+ self.source_root = source_root
+ self.rows_path = rows_path
+ self.fps = int(manifest["fps"])
+ self.chunk_size = int(manifest["chunk_size"])
+ self.total_frames = int(manifest["total_frames"])
+ self.state_dim, self.action_dim = manifest_dims(manifest)
+ self.cameras = tuple(manifest.get("camera_order", CAMERAS))
+ self.action_prev = bool(manifest.get("action_prev", False))
+ self.seed, self.epoch = seed, epoch
+ self.rank, self.world_size = rank, world_size
+ self.num_workers, self.windows_per_rank = num_workers, windows_per_rank
+ self.skip_batches = skip_batches
+ self.decoder, self.frame_hw = decoder, tuple(frame_hw)
+ # LeRobot manifests record the native size of every camera; frames of another size are rescaled to
+ # frame_hw. DROID manifests do not, and their frames must already have frame_hw (never rescaled).
+ native = manifest.get("camera_hw") or {}
+ self.resize = {
+ camera: native.get(camera) is not None and tuple(native[camera]) != self.frame_hw
+ for camera in self.cameras
+ }
+ self._rows = None
+ self.batches_per_rank = self.epoch_batches(grad_accumulation)
+ if self.batches_per_rank == 0:
+ history = (
+ f" ({self.episodes_without_history} more episodes were dropped because they are too short "
+ f"for {n_obs_steps} observed ticks plus {manifest['chunk_size']} actions inside one keep range)"
+ if self.episodes_without_history
+ else ""
+ )
+ raise ValueError(
+ f"{len(self.episodes)} episodes x {visits_per_epoch} visits cannot fill one update on "
+ f"{world_size} ranks x {num_workers} workers x {windows_per_rank} windows x {grad_accumulation} "
+ f"accumulation steps{history}; raise visits_per_epoch or shrink the update"
+ )
+ if skip_batches > self.batches_per_rank:
+ raise ValueError(
+ f"skip_batches {skip_batches} exceeds the {self.batches_per_rank} batches of an epoch"
+ )
+
+ def epoch_batches(self, grad_accumulation: int) -> int:
+ per_worker = self.n_positions // (self.world_size * self.num_workers * self.windows_per_rank)
+ return (per_worker * self.num_workers // grad_accumulation) * grad_accumulation
+
+ @property
+ def rows(self) -> np.ndarray:
+ if self._rows is None: # opened lazily so the memmap is created inside each worker
+ rows = np.load(self.rows_path, mmap_mode="r")
+ expected = (self.total_frames, self.state_dim + self.action_dim)
+ if rows.dtype != np.float32 or rows.shape != expected:
+ raise ValueError(f"rows array must be float32 {expected}, got {rows.dtype} {rows.shape}")
+ self._rows = rows
+ return self._rows
+
+ @property
+ def n_positions(self) -> int:
+ """Episode visits per epoch: position ``p`` is episode ``p % n_episodes``, visit ``p // n_episodes``."""
+ return len(self.episodes) * self.visits_per_epoch
+
+ def rank_order(self) -> list[int]:
+ return epoch_order(self.n_positions, self.seed, self.epoch)[self.rank :: self.world_size]
+
+ def worker_batches(self, worker_id: int) -> int:
+ """Batches worker ``worker_id`` contributes to the epoch (batch ``i`` comes from worker ``i % n``)."""
+ remaining = self.batches_per_rank - worker_id
+ return -(-remaining // self.num_workers) if remaining > 0 else 0 # ceil division
+
+ def worker_positions(self, worker_id: int) -> list[int]:
+ """Episode positions logical worker ``worker_id`` yields after skipping its consumed batches."""
+ mine = self.rank_order()[worker_id :: self.num_workers]
+ produced = 0
+ if self.skip_batches > worker_id:
+ produced = -(-(self.skip_batches - worker_id) // self.num_workers)
+ return mine[produced * self.windows_per_rank : self.worker_batches(worker_id) * self.windows_per_rank]
+
+ def logical_worker(self, physical_worker: int) -> int:
+ """The loader serves physical workers from 0; after ``skip_batches`` the next batch is due from
+ logical worker ``skip_batches % num_workers``, so the assignment rotates by that amount."""
+ return (physical_worker + self.skip_batches) % self.num_workers
+
+ def __iter__(self):
+ info = get_worker_info()
+ worker_id, workers = (info.id, info.num_workers) if info is not None else (0, 1)
+ if workers != self.num_workers:
+ raise RuntimeError(f"dataset built for {self.num_workers} workers but the loader runs {workers}")
+ for position in self.worker_positions(self.logical_worker(worker_id)):
+ yield self.window(position)
+
+ def _valid_ranges(self, episode: dict) -> list:
+ # The index permits one preceding command outside each range. Extend that
+ # requirement to a complete command/state/image history; never pad it.
+ shift = (self.n_obs_steps or 1) - 1
+ return [[lo + shift, hi] for lo, hi in episode["valid_ranges"] if lo + shift < hi]
+
+ def window(self, position: int) -> dict[str, Any]:
+ """The window of visit ``position`` (see :attr:`n_positions`) for this seed and epoch."""
+ episode = self.episodes[position % len(self.episodes)]
+ visit = position // len(self.episodes)
+ key = f"{self.seed}:{self.epoch}:{episode['episode_index']}" # visit 0: the DROID loader's key
+ rng = Random(key if visit == 0 else f"{key}:{visit}")
+ start = select_window_start(episode["n_frames"], self._valid_ranges(episode), rng, self.chunk_size)
+ if start is None:
+ raise ValueError(f"episode {episode['episode_id']} has no valid window")
+ task = select_caption(episode["caption"], rng)
+ return self.window_at(
+ position % len(self.episodes), start, task=task, window_seed=rng.getrandbits(63)
+ )
+
+ def valid_starts(self, episode_position: int) -> list[int]:
+ """Every allowed window start of an episode, in order (evaluation picks from these)."""
+ episode = self.episodes[episode_position]
+ spans = valid_window_spans(episode["n_frames"], self._valid_ranges(episode), self.chunk_size)
+ return [s for first, count in spans for s in range(first, first + count)]
+
+ def window_at(
+ self, episode_position: int, start: int, *, task: str | None = None, window_seed: int = 0
+ ) -> dict[str, Any]:
+ """The window of episode ``episode_position`` starting at frame ``start`` (must be an allowed start);
+ ``task`` defaults to the caption's first paraphrase."""
+ episode = self.episodes[episode_position]
+ if start not in self.valid_starts(episode_position):
+ raise ValueError(f"episode {episode['episode_id']}: {start} is not an allowed window start")
+ if task is None:
+ task = select_caption(episode["caption"])
+ first = episode["from_index"] + start
+ before = self.n_obs_steps or (
+ 1 if self.action_prev else 0
+ ) # the row before the window (start >= 1 by the manifest)
+ if start - before < 0:
+ raise ValueError(f"episode {episode['episode_id']}: window at {start} has no previous command")
+ rows = np.array(self.rows[first - before : first + self.chunk_size + 1])
+ if not np.isfinite(rows).all():
+ raise ValueError(f"episode {episode['episode_id']}: rows missing from the rows array")
+ s = self.state_dim
+ item: dict[str, Any] = {
+ "state": torch.from_numpy(rows[before, :s].copy()),
+ "action": torch.from_numpy(rows[before : before + self.chunk_size, s:].copy()),
+ "task": task,
+ "episode_index": episode["episode_index"],
+ "start": start,
+ "window_seed": window_seed,
+ }
+ if self.action_prev:
+ item["action_prev"] = torch.from_numpy(rows[before - 1, s:].copy())
+ frame_start, frame_count = start, self.chunk_size + 1
+ if self.n_obs_steps is not None:
+ item["state"] = torch.from_numpy(rows[1 : before + 1, :s].copy())
+ item["command_history"] = torch.from_numpy(rows[:before, s:].copy())
+ frame_start = start - before + 1
+ frame_count = before + self.chunk_size
+ for camera in self.cameras:
+ video = episode["videos"][camera]
+ if video is None: # a stream the index declared gray (no such camera in the dataset)
+ item[f"images.{camera}"] = torch.full(
+ (frame_count, 3, *self.frame_hw), GRAY_LEVEL, dtype=torch.uint8
+ )
+ continue
+ frames = decode_window(
+ f"{self.source_root}/{video['file']}",
+ video["first_frame"] + frame_start,
+ frame_count,
+ fps=self.fps,
+ frame_hw=self.frame_hw,
+ decoder=self.decoder,
+ resize=self.resize[camera],
+ )
+ item[f"images.{camera}"] = torch.from_numpy(frames).permute(0, 3, 1, 2).contiguous()
+ return item
+
+
+DroidWindowDataset = WindowDataset # the name the DROID trainer and its tests were written against
+
+
+def collate_windows(items: list[dict[str, Any]]) -> dict[str, Any]:
+ batch: dict[str, Any] = {"task": [it["task"] for it in items]}
+ for key in items[0]:
+ if key == "task":
+ continue
+ values = [it[key] for it in items]
+ batch[key] = torch.stack(values) if isinstance(values[0], torch.Tensor) else torch.tensor(values)
+ return batch
+
+
+def epoch_loader_state(epoch: int, skip_batches: int):
+ """Atomic epoch/position shared with persistent worker processes."""
+ context = multiprocessing.get_context("forkserver" if sys.platform.startswith("linux") else "spawn")
+ return context.Array("q", [epoch, skip_batches], lock=True)
+
+
+def set_epoch_loader_state(state, epoch: int, skip_batches: int) -> None:
+ with state.get_lock():
+ state[0], state[1] = epoch, skip_batches
+
+
+def get_epoch_loader_state(state) -> tuple[int, int]:
+ with state.get_lock():
+ return int(state[0]), int(state[1])
+
+
+def build_dataloader(
+ dataset: WindowDataset,
+ *,
+ prefetch_factor: int = 2,
+ pin_memory: bool = False,
+ in_process: bool = False,
+ persistent_workers: bool = False,
+) -> DataLoader:
+ """Fixed ``windows_per_rank`` per batch, workers served in order, incomplete tail dropped.
+
+ ``in_process`` runs the dataset in the calling process (tests, CPU runs); it needs ``num_workers == 1``.
+ The loader gets its own generator seeded from the run seed, epoch and rank, so creating it never
+ touches the global RNG (which an exact resume restores from the checkpoint).
+ """
+ if in_process and dataset.num_workers != 1:
+ raise ValueError("in-process loading needs a dataset built for one worker")
+ if in_process and persistent_workers:
+ raise ValueError("persistent workers need multiprocessing")
+ generator = torch.Generator().manual_seed(
+ int.from_bytes(
+ hashlib.sha256(f"{dataset.seed}:{dataset.epoch}:{dataset.rank}".encode()).digest()[:8], "big"
+ )
+ % (2**63 - 1)
+ )
+ kwargs: dict[str, Any] = {"generator": generator}
+ if not in_process:
+ kwargs.update(num_workers=dataset.num_workers, prefetch_factor=prefetch_factor, in_order=True,
+ persistent_workers=persistent_workers)
+ if sys.platform.startswith("linux"):
+ # workers start after CUDA/NCCL initialization; a forked child inheriting that state can deadlock
+ kwargs["multiprocessing_context"] = "forkserver"
+ return DataLoader(
+ dataset,
+ batch_size=dataset.windows_per_rank,
+ drop_last=True,
+ collate_fn=collate_windows,
+ pin_memory=pin_memory,
+ **kwargs,
+ )
diff --git a/flux-umi/src/flux_action/training/distributed.py b/flux-umi/src/flux_action/training/distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0bcb05ab476e5d39c947243678335ad35a63cd5
--- /dev/null
+++ b/flux-umi/src/flux_action/training/distributed.py
@@ -0,0 +1,397 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Process group, device mesh and FSDP2 sharding of the DiT, following the reference layout.
+
+The reference sharded every transformer block and the root with ``bfloat16`` parameters for
+compute, ``float32`` gradient reduction, ``reshard_after_forward=True`` and full activation
+checkpointing per block (``preserve_rng_state=False``). Master weights stay in float32 inside
+FSDP; the optimizer and the EMAs see float32 DTensor shards.
+
+Group layout as in the reference: block groups cast their forward inputs to the compute dtype (the
+rotary tables enter attention in bfloat16), ``time_in`` is its own group in the master precision, and
+the root casts nothing (the policy feeds streams and context in the compute dtype and fp32 timesteps
+that already sit on the bf16 grid).
+"""
+
+from __future__ import annotations
+
+import math
+import os
+from collections.abc import Iterable
+from datetime import timedelta
+
+import torch
+import torch.distributed as dist
+from torch import nn
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
+from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
+from torch.distributed.tensor import DeviceMesh, init_device_mesh
+
+CHECKPOINT_WRAPPED = "_checkpoint_wrapped_module."
+
+
+def init_distributed(backend: str | None = None) -> tuple[int, int, torch.device]:
+ """``(rank, world_size, device)`` from the torchrun environment; single process without it."""
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
+ rank = int(os.environ.get("RANK", "0"))
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
+ if torch.cuda.is_available():
+ device = torch.device("cuda", local_rank)
+ torch.cuda.set_device(device)
+ else:
+ device = torch.device("cpu")
+ if world_size > 1 and not dist.is_initialized():
+ backend = backend or ("nccl" if device.type == "cuda" else "gloo")
+ kwargs = {"device_id": device} if device.type == "cuda" else {}
+ # Collectives wait this long before failing (default 10 min); checkpoint writes from many ranks to
+ # shared storage and slow container starts need more. FLUX_ACTION_PG_TIMEOUT_MINUTES overrides.
+ timeout = timedelta(minutes=float(os.environ.get("FLUX_ACTION_PG_TIMEOUT_MINUTES", "30")))
+ dist.init_process_group(backend, rank=rank, world_size=world_size, timeout=timeout, **kwargs)
+ return rank, world_size, device
+
+
+def rank_world() -> tuple[int, int]:
+ if dist.is_available() and dist.is_initialized():
+ return dist.get_rank(), dist.get_world_size()
+ return 0, 1
+
+
+def barrier() -> None:
+ if dist.is_available() and dist.is_initialized():
+ dist.barrier()
+
+
+def all_reduce_mean(value: float, device: torch.device) -> float:
+ if not (dist.is_available() and dist.is_initialized()):
+ return float(value)
+ tensor = torch.tensor(float(value), device=device if device.type == "cuda" else "cpu")
+ dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
+ return float(tensor.item() / dist.get_world_size())
+
+
+def all_reduce_means(values: torch.Tensor) -> list[float]:
+ """Reduce detached metrics together, synchronizing with the host once per update."""
+ if dist.is_available() and dist.is_initialized():
+ values = values.float()
+ dist.all_reduce(values, op=dist.ReduceOp.SUM)
+ values /= dist.get_world_size()
+ return values.tolist()
+
+
+def all_reduce_sum_async(values: torch.Tensor) -> torch.Tensor:
+ """``all_reduce_means`` without the host round trip: the reduced fp32 means stay on the device."""
+ if dist.is_available() and dist.is_initialized():
+ values = values.float()
+ dist.all_reduce(values, op=dist.ReduceOp.SUM)
+ values /= dist.get_world_size()
+ return values
+
+
+def global_grad_norm_tensor(module: nn.Module, device: torch.device, replicas: int = 1) -> torch.Tensor:
+ """:func:`global_grad_norm` as a 0-dim fp64 device tensor (no host synchronization): the same fp32 sum of
+ squared shard norms and all-reduce, then ``sqrt(total / replicas)`` in fp64 exactly like the host computation."""
+ from torch.distributed.tensor import DTensor
+
+ grads = []
+ for param in module.parameters():
+ grad = param.grad
+ if grad is None:
+ continue
+ grads.append((grad.to_local() if isinstance(grad, DTensor) else grad).detach())
+ if grads:
+ total = torch.stack([n.float() for n in torch._foreach_norm(grads)]).pow(2).sum()
+ else:
+ total = torch.zeros((), dtype=torch.float32, device=device if device.type == "cuda" else "cpu")
+ total = total.to(device if device.type == "cuda" else "cpu")
+ if dist.is_available() and dist.is_initialized():
+ dist.all_reduce(total, op=dist.ReduceOp.SUM)
+ return (total.double() / max(replicas, 1)).sqrt()
+
+
+def global_grad_norm(module: nn.Module, device: torch.device, replicas: int = 1) -> float:
+ """L2 norm of all gradients across ranks, ``inf``/``nan`` if any shard is non-finite.
+
+ Sharded gradients (DTensors) contribute their local shard; ``replicas`` is the number of HSDP replica
+ groups holding identical shards, so their sum is divided out. One collective per call.
+ """
+ from torch.distributed.tensor import DTensor
+
+ grads = []
+ for param in module.parameters():
+ grad = param.grad
+ if grad is None:
+ continue
+ grads.append((grad.to_local() if isinstance(grad, DTensor) else grad).detach())
+ if grads:
+ total = torch.stack([n.float() for n in torch._foreach_norm(grads)]).pow(2).sum()
+ else:
+ total = torch.zeros((), dtype=torch.float32)
+ total = total.to(device if device.type == "cuda" else "cpu")
+ if dist.is_available() and dist.is_initialized():
+ dist.all_reduce(total, op=dist.ReduceOp.SUM)
+ value = float(total.item())
+ return math.sqrt(value / max(replicas, 1)) if math.isfinite(value) else value
+
+
+def build_mesh(world_size: int, shard_size: int | None, device_type: str) -> DeviceMesh:
+ """``shard_size`` ranks shard each parameter (FSDP); ``world_size // shard_size`` replicas (HSDP).
+
+ Reference: replicate 16 x shard 4 on GB200 (one node per shard group).
+ """
+ shard = shard_size or world_size
+ if shard < 1 or world_size % shard:
+ raise ValueError(f"shard_size {shard} must divide the world size {world_size}")
+ replicate = world_size // shard
+ if replicate == 1:
+ return init_device_mesh(device_type, (shard,), mesh_dim_names=("shard",))
+ return init_device_mesh(device_type, (replicate, shard), mesh_dim_names=("replicate", "shard"))
+
+
+def dit_blocks(dit: nn.Module) -> Iterable[tuple[nn.ModuleList, int]]:
+ """Every transformer block of the DiT as ``(container, index)`` so it can be replaced in place."""
+ for kind in ("content_mode_blocks", "late_content_mode_blocks"):
+ for blocks in getattr(dit, kind, {}).values():
+ for i in range(len(blocks)):
+ yield blocks, i
+ for kind in ("txt_mode_blocks", "single_blocks", "late_txt_mode_blocks"):
+ blocks = getattr(dit, kind, None)
+ if blocks is not None:
+ for i in range(len(blocks)):
+ yield blocks, i
+
+
+SAC_SAVE_KINDS = ("sdpa", "mlp_out", "attn_out", "qkv", "mlp_in", "out_stage")
+
+
+def _sdpa_ops():
+ aten = torch.ops.aten
+ return {
+ aten._scaled_dot_product_cudnn_attention.default,
+ aten._scaled_dot_product_flash_attention.default,
+ aten._scaled_dot_product_efficient_attention.default,
+ }
+
+
+def _out_stage_op():
+ """``flux::out_stage`` (models.dit_out_stage) when its CUDA/Triton stack is importable, else None."""
+ try:
+ from flux_action.models.dit_out_stage import OP
+ except Exception: # pragma: no cover - CPU-only environments without Triton
+ return None
+ return OP
+
+
+def _out_stage_enabled() -> bool:
+ try:
+ from flux_action.models import dit_mod_rows
+ except Exception: # pragma: no cover
+ return False
+ return bool(dit_mod_rows.Config.out_stage)
+
+
+class _SacPolicy:
+ """Selective-checkpoint policy for one block forward (a fresh instance per checkpointed call).
+
+ ``save`` names the ops whose outputs are kept instead of recomputed: ``sdpa`` (the attention kernel), and the
+ block GEMMs identified by the shape ``[K, N]`` of their transposed weight (``aten.mm(x, w_t)`` / ``addmm``):
+ ``mlp_in`` [hidden, mlp_in], ``mlp_out`` [mlp_hidden, hidden], and the [hidden, hidden] projections, which are
+ ``qkv`` before the attention kernel of the same pass and ``attn_out`` after it. Everything else is recomputed.
+ Ranked by recomputation avoided per saved byte (joint block, 309k tokens, 1.9 GB per hidden-width tensor):
+ mlp_out (~15 ms GEMM / 1.9 GB) > sdpa (~7 ms / 1.9 GB) > attn_out (~5 ms / 1.9 GB) >= qkv, mlp_in (same ratio
+ but 5.7 / 11.4 GB). Numerically identical to full recomputation (the saved values are the forward's own).
+ With ``PolicyConfig.dit_out_stage`` the output stage is the single op ``flux::out_stage`` (kind ``out_stage``,
+ outputs ``(y, s)``: the block output, kept anyway, plus one hidden-width tensor, i.e. the ``mlp_out`` price);
+ saving it skips attn_out GEMM + mlp_out GEMM + add + gate kernel in the recompute (~18 ms per joint block), and the
+ ``mlp_out`` / ``attn_out`` kinds no longer exist (the GEMMs run inside the op).
+ """
+
+ def __init__(self, save, hidden: int, mlp_in: int, mlp_hidden: int):
+ self.save = frozenset(save)
+ self.hidden, self.mlp_in, self.mlp_hidden = hidden, mlp_in, mlp_hidden
+ self.seen_sdpa = {False: False, True: False} # per phase (forward / recompute)
+ self.sdpa_ops = _sdpa_ops()
+ self.out_stage_op = _out_stage_op() if "out_stage" in self.save else None
+ aten = torch.ops.aten
+ self.mm_ops = {aten.mm.default: 1, aten.addmm.default: 2} # index of the transposed weight argument
+
+ def kind(self, op, args, recompute: bool):
+ if op in self.sdpa_ops:
+ self.seen_sdpa[recompute] = True
+ return "sdpa"
+ if self.out_stage_op is not None and op is self.out_stage_op:
+ return "out_stage"
+ idx = self.mm_ops.get(op)
+ if idx is None or len(args) <= idx or args[idx].ndim != 2:
+ return None
+ k, n = args[idx].shape
+ if k == self.hidden and n == self.mlp_in:
+ return "mlp_in"
+ if k == self.mlp_hidden and n == self.hidden:
+ return "mlp_out"
+ if k == self.hidden and n == self.hidden:
+ return "attn_out" if self.seen_sdpa[recompute] else "qkv"
+ return None
+
+ def __call__(self, ctx, op, *args, **kwargs):
+ from torch.utils.checkpoint import CheckpointPolicy
+
+ if self.kind(op, args, bool(ctx.is_recompute)) in self.save:
+ return CheckpointPolicy.MUST_SAVE
+ return CheckpointPolicy.PREFER_RECOMPUTE
+
+
+def _block_dims(block: nn.Module) -> tuple[int, int, int]:
+ mlp_in = block.mlp_in.weight.shape # [mlp_in_width, hidden]
+ mlp_out = block.mlp_out.weight.shape # [hidden, mlp_hidden]
+ return int(mlp_in[1]), int(mlp_in[0]), int(mlp_out[1])
+
+
+def _sac_context_fn(save, dims):
+ from torch.utils.checkpoint import create_selective_checkpoint_contexts
+
+ def context_fn():
+ return create_selective_checkpoint_contexts(_SacPolicy(save, *dims))
+
+ return context_fn
+
+
+def apply_activation_checkpointing(
+ dit: nn.Module,
+ *,
+ mode: str = "full",
+ save_mlp_blocks: int = 0,
+ skip_last: int = 0,
+ sac_save=("sdpa",),
+ sac_extra_save=(),
+ sac_extra_blocks: int = 0,
+ offload=None,
+) -> int:
+ """Non-reentrant checkpointing of every block (the reference's ``AC_MODE=full``) with memory-for-speed variants
+ that are numerically identical to full recomputation (the same kernels run on the same values):
+
+ * ``mode="sac"``: selective checkpointing keeping the outputs named in ``sac_save`` (see :class:`_SacPolicy`) in
+ every block, plus ``sac_extra_save`` in ``sac_extra_blocks`` blocks: the joint ``single_blocks`` first (the
+ largest activations), then the remaining blocks in :func:`dit_blocks` order;
+ * ``mode="sac_attn"``: the campaign-2 spelling of ``sac_save=("sdpa",)``; ``save_mlp_blocks`` additionally keeps
+ the ``mlp_in`` GEMM output of ``sac_extra_blocks`` blocks in the same order;
+ * ``skip_last``: the last N single-stream blocks are not checkpointed at all;
+ * ``offload`` (an ``activation_offload.OffloadPlan``): the checkpoint-held block inputs and/or the selectively
+ saved outputs are copied to pinned host memory during the forward and prefetched back ahead of each block's
+ backward (``activation_offload.OffloadCheckpointWrapper``); pure data movement, same values.
+ """
+ if mode not in ("full", "sac", "sac_attn"):
+ raise ValueError(f"unknown activation checkpointing mode {mode!r}")
+ if mode == "sac_attn":
+ sac_save, sac_extra_save, sac_extra_blocks = ("sdpa",), ("mlp_in",), save_mlp_blocks
+ for name in (*sac_save, *sac_extra_save):
+ if name not in SAC_SAVE_KINDS:
+ raise ValueError(f"unknown selective-checkpoint save kind {name!r}; choose from {SAC_SAVE_KINDS}")
+ if mode != "full":
+ kinds = set(sac_save) | set(sac_extra_save)
+ fused = _out_stage_enabled()
+ if "out_stage" in kinds and not fused:
+ raise ValueError("selective-checkpoint save kind 'out_stage' needs the fused output stage (PolicyConfig.dit_out_stage)")
+ if fused and kinds & {"mlp_out", "attn_out"}:
+ raise ValueError("with dit_out_stage the attn_out / mlp_out GEMMs run inside flux::out_stage: save 'out_stage' instead")
+ entries = list(dit_blocks(dit))
+ single = getattr(dit, "single_blocks", None)
+ skipped = {id(single[i]) for i in range(max(0, len(single) - skip_last), len(single))} if single is not None and skip_last else set()
+ extra_order = [id(b[i]) for b, i in entries if b is single] + [id(b[i]) for b, i in entries if b is not single]
+ extra = set(extra_order[:sac_extra_blocks])
+ offloader = None
+ if offload is not None:
+ from .activation_offload import ActivationOffloader
+
+ offloader = ActivationOffloader(offload)
+ n = 0
+ for blocks, i in entries:
+ if id(blocks[i]) in skipped:
+ continue
+ kwargs = {}
+ save = None
+ if mode != "full":
+ save = sorted(set(sac_save) | (set(sac_extra_save) if id(blocks[i]) in extra else set()))
+ kwargs["context_fn"] = _sac_context_fn(save, _block_dims(blocks[i]))
+ if offloader is not None:
+ policy_factory = (lambda save=save, dims=_block_dims(blocks[i]): _SacPolicy(save, *dims)) if save is not None else None
+ blocks[i] = offloader.wrap(blocks[i], n, policy_factory)
+ else:
+ blocks[i] = checkpoint_wrapper(
+ blocks[i], checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False, **kwargs
+ )
+ n += 1
+ if offloader is not None:
+ offloader.finalize(n)
+ dit.__dict__["_flux_activation_offloader"] = offloader # reachable for tests / diagnostics
+ return n
+
+
+def shard_dit(
+ dit: nn.Module,
+ mesh: DeviceMesh,
+ *,
+ param_dtype: torch.dtype = torch.bfloat16,
+ reduce_dtype: torch.dtype = torch.float32,
+ reshard_after_forward: bool = True,
+ activation_checkpointing: bool = True,
+ ac_mode: str = "full",
+ ac_save_mlp_blocks: int = 0,
+ ac_skip_last: int = 0,
+ ac_sac_save=("sdpa",),
+ ac_sac_extra_save=(),
+ ac_sac_extra_blocks: int = 0,
+ ac_offload=None,
+ comm_memory_from_pg: bool = False,
+) -> nn.Module:
+ """Wrap the DiT in place the way the reference trainer does: blocks, ``time_in``, then the root.
+
+ Blocks compute in ``param_dtype`` and cast their inputs to it (so the fp32 rotary tables enter the
+ attention in ``param_dtype``, as in the reference). ``time_in`` keeps the precision of its stored
+ parameters, the reference's "high precision for t_embedder" group; ``JointSingleSeq.embed_timesteps``
+ feeds it in that dtype and casts the result for the modulations. The root casts nothing: the policy
+ hands it streams in the compute dtype and fp32 timesteps (already on the bf16 grid, see
+ ``packing.add_noise``).
+ """
+ if activation_checkpointing:
+ apply_activation_checkpointing(
+ dit, mode=ac_mode, save_mlp_blocks=ac_save_mlp_blocks, skip_last=ac_skip_last, sac_save=ac_sac_save,
+ sac_extra_save=ac_sac_extra_save, sac_extra_blocks=ac_sac_extra_blocks, offload=ac_offload,
+ )
+ block_policy = MixedPrecisionPolicy(
+ param_dtype=param_dtype, reduce_dtype=reduce_dtype, cast_forward_inputs=True
+ )
+ for blocks, i in dit_blocks(dit):
+ fully_shard(blocks[i], mesh=mesh, mp_policy=block_policy, reshard_after_forward=reshard_after_forward)
+ # The blocks cast their fp32 inputs (the RoPE tables) to param_dtype; the row-modulation forward pre-casts them once.
+ dit.__dict__["_flux_pe_cast_dtype"] = param_dtype
+ time_policy = MixedPrecisionPolicy(
+ param_dtype=next(dit.time_in.parameters()).dtype, reduce_dtype=reduce_dtype, cast_forward_inputs=False
+ )
+ fully_shard(dit.time_in, mesh=mesh, mp_policy=time_policy, reshard_after_forward=reshard_after_forward)
+ root_policy = MixedPrecisionPolicy(
+ param_dtype=param_dtype, reduce_dtype=reduce_dtype, cast_forward_inputs=False
+ )
+ fully_shard(dit, mesh=mesh, mp_policy=root_policy, reshard_after_forward=reshard_after_forward)
+ if comm_memory_from_pg:
+ # NCCL-registered (symmetric / user-buffer) staging buffers for the all-gather / reduce-scatter copies:
+ # fewer SMs per collective and zero-copy on NVLink / IB SHARP (needs NCCL >= 2.27; scheduling-only change).
+ for module in dit.modules():
+ if hasattr(module, "set_allocate_memory_from_process_group_for_comm"):
+ module.set_allocate_memory_from_process_group_for_comm(True)
+ return dit
+
+
+def clean_name(name: str) -> str:
+ """Parameter name without activation-checkpoint wrapper segments."""
+ return name.replace(CHECKPOINT_WRAPPED, "")
diff --git a/flux-umi/src/flux_action/training/ema.py b/flux-umi/src/flux_action/training/ema.py
new file mode 100644
index 0000000000000000000000000000000000000000..c99969981ce4a54d88bc410d52ffe37d288bb394
--- /dev/null
+++ b/flux-umi/src/flux_action/training/ema.py
@@ -0,0 +1,144 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Karras power-function EMA, ported from the reference trainer's averaging callback.
+
+Profile: ``sigma_rel`` maps to ``gamma``, the largest real root of
+``g^3 + 7 g^2 + (16 - sigma_rel^-2) g + (12 - sigma_rel^-2)`` (EDM2 ``solve_gamma``; equivalently
+``sigma_rel^2 = (g + 1) / ((g + 2)^2 (g + 3))``). The update after optimizer update ``g``
+(zero-based; the reference passes its ``global_step`` before incrementing it) uses
+``beta = (1 - 1 / (g + 1)) ** (gamma + 1)`` in ``ema = beta * ema + (1 - beta) * model``;
+``g == 0`` copies the model instead. ``beta`` depends only on the global step, so a resumed run
+continues the same profile.
+
+The reference kept every EMA as a second FSDP-sharded module with the model's structure.
+:class:`PowerEMA` keeps a shadow tensor per parameter in FP32 with the parameter's device and
+(DTensor) placement, so no rank holds a full copy; :meth:`PowerEMA.consolidated` gathers full
+tensors for export. Buffers are not averaged; the reference copied them from the model.
+"""
+
+from collections.abc import Iterable, Sequence
+
+import numpy as np
+import torch
+from torch import Tensor, nn
+
+from .distributed import clean_name
+
+DROID_POWER_EMA_SIGMA_RELS = (0.10, 0.05)
+SIGMA_REL_UPPER = 12**-0.5
+
+
+def sigma_rel_to_gamma(sigma_rel: float) -> float:
+ """Reference ``power_ema_sigma_rel_to_gamma``: largest real root of the EDM2 cubic."""
+ sigma_rel = float(sigma_rel)
+ if not 0.0 < sigma_rel < SIGMA_REL_UPPER:
+ raise ValueError(f"sigma_rel must lie in (0, 1 / sqrt(12)), got {sigma_rel}")
+ t = sigma_rel**-2
+ return float(np.roots([1, 7, 16 - t, 12 - t]).real.max())
+
+
+def power_ema_beta(gamma: float, step: int) -> float:
+ """Reference ``power_ema_decay``: zero at update 0 (copy), ``(1 - 1 / (step + 1)) ** (gamma + 1)`` after."""
+ if step < 0:
+ raise ValueError(f"step must be non-negative, got {step}")
+ if step == 0:
+ return 0.0
+ return (1 - 1 / (step + 1)) ** (gamma + 1)
+
+
+def _copy_each(targets: Sequence[Tensor], sources: Sequence[Tensor]) -> None:
+ """Per-tensor ``copy_`` as in the reference; ``_foreach_copy_`` has no DTensor sharding rule."""
+ for target, source in zip(targets, sources, strict=True):
+ target.copy_(source)
+
+
+class PowerEMA:
+ """Shadow copies of named tensors, updated with the power-function schedule."""
+
+ def __init__(self, named_tensors: Iterable[tuple[str, Tensor]], sigma_rel: float):
+ self.sigma_rel = float(sigma_rel)
+ self.gamma = sigma_rel_to_gamma(sigma_rel)
+ names, shadow = [], []
+ for name, tensor in named_tensors:
+ if not tensor.is_floating_point():
+ raise TypeError(f"{name}: power EMA averages floating-point tensors only")
+ names.append(name)
+ shadow.append(tensor.detach().to(dtype=torch.float32, copy=True))
+ if not names:
+ raise ValueError("no tensors to average")
+ self.names: tuple[str, ...] = tuple(names)
+ self.shadow: list[Tensor] = shadow
+ self.last_step: int | None = None
+
+ @classmethod
+ def from_module(cls, module: nn.Module, sigma_rel: float) -> "PowerEMA":
+ """Average every trainable parameter of ``module`` (frozen encoders stay out).
+
+ Names drop activation-checkpoint wrapper segments so they match the plain model's keys.
+ """
+ return cls(((clean_name(n), p) for n, p in module.named_parameters() if p.requires_grad), sigma_rel)
+
+ @torch.no_grad()
+ def update(self, tensors: Sequence[Tensor], step: int) -> float:
+ """Fold the current ``tensors`` in after optimizer update ``step``; returns the beta used."""
+ if len(tensors) != len(self.shadow):
+ raise ValueError(f"expected {len(self.shadow)} tensors, got {len(tensors)}")
+ current = [t.detach().float() for t in tensors]
+ beta = power_ema_beta(self.gamma, step)
+ if step == 0:
+ _copy_each(self.shadow, current)
+ else:
+ torch._foreach_lerp_(self.shadow, current, 1 - beta)
+ self.last_step = step
+ return beta
+
+ def update_from_module(self, module: nn.Module, step: int) -> float:
+ params = {clean_name(n): p for n, p in module.named_parameters()}
+ return self.update([params[n] for n in self.names], step)
+
+ @torch.no_grad()
+ def copy_to(self, tensors: Sequence[Tensor]) -> None:
+ """Write the averaged values into ``tensors`` (evaluation swap or export into a model)."""
+ if len(tensors) != len(self.shadow):
+ raise ValueError(f"expected {len(self.shadow)} tensors, got {len(tensors)}")
+ _copy_each([t.detach() for t in tensors], self.shadow)
+
+ def state_dict(self) -> dict[str, object]:
+ """Local shadow tensors (shards for DTensors) plus the profile and last step."""
+ return {
+ "sigma_rel": self.sigma_rel,
+ "last_step": self.last_step,
+ "tensors": dict(zip(self.names, self.shadow, strict=True)),
+ }
+
+ def load_state_dict(self, state: dict[str, object]) -> None:
+ if float(state["sigma_rel"]) != self.sigma_rel:
+ raise ValueError(
+ f"checkpoint profile sigma_rel={state['sigma_rel']} differs from {self.sigma_rel}"
+ )
+ tensors = state["tensors"]
+ if set(tensors) != set(self.names):
+ raise ValueError("checkpoint tensor names differ from the averaged tensors")
+ with torch.no_grad():
+ _copy_each(self.shadow, [tensors[n] for n in self.names])
+ self.last_step = state["last_step"]
+
+ @torch.no_grad()
+ def consolidated(self) -> dict[str, Tensor]:
+ """Full tensors on the CPU, gathering DTensor shards; every rank must call this."""
+ out = {}
+ for name, tensor in zip(self.names, self.shadow, strict=True):
+ full = tensor.full_tensor() if hasattr(tensor, "full_tensor") else tensor
+ out[name] = full.detach().cpu().contiguous()
+ return out
diff --git a/flux-umi/src/flux_action/training/schedule.py b/flux-umi/src/flux_action/training/schedule.py
new file mode 100644
index 0000000000000000000000000000000000000000..36f60b2ac8436629858725721430afa91548ab8c
--- /dev/null
+++ b/flux-umi/src/flux_action/training/schedule.py
@@ -0,0 +1,203 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Learning-rate schedules of the DROID recipe, ported from the reference trainer.
+
+Call order, pinned to the reference on 2026-09-12: a factor is evaluated at the zero-based index
+``g`` of the optimizer update it applies to. ``LambdaLR`` primes ``factor(0)`` when it is built,
+``optimizer.step()`` consumes that value for update 0, and ``scheduler.step()`` runs once after
+every optimizer update, so update ``g`` uses ``factor(g)``. A checkpoint written after ``N``
+updates resumes through :func:`resume_lr_scheduler`, the reference's ``last_epoch = N - 1`` plus
+one ``step()``, so update ``N`` uses ``factor(N)`` with or without the interruption.
+
+The trunk factor is exactly zero through update 1000. The reference keeps the trunk in the
+optimizer during that phase: AdamW moments and step counts advance at learning rate zero.
+Express freezing through the factor, never by skipping the parameter group.
+
+The reference ran the cooldown as a second launch that replaced both schedules at step 25000.
+:class:`CooldownFrom` reproduces that inside one schedule so a single run can cool down from
+any step; the arithmetic is identical.
+"""
+
+import warnings
+from collections.abc import Callable, Sequence
+
+from torch.optim import Optimizer
+from torch.optim.lr_scheduler import LambdaLR
+
+LRLambda = Callable[[int], float]
+
+# Reference recipe (GB200 runs 936673 / 938134 / 941584). LR_SCALE 0.96 is folded into the
+# peak learning rates of PolicyConfig, so the factors below peak at exactly one.
+DROID_FROZEN_STEPS = 1000
+DROID_TRUNK_WARMUP_STEPS = 2000
+DROID_HEADS_WARMUP_STEPS = 1000
+DROID_COOLDOWN_START = 25000
+DROID_COOLDOWN_STEPS = 5000
+
+
+class FrozenThenLinearWarmup:
+ """Zero through ``frozen_steps``, linear to ``lr_scale`` at ``frozen_steps + warmup_steps``, then flat.
+
+ Reference ``bfl.modules.lr_scheduler.FrozenThenLinearWarmup``: the boundary step itself is
+ still zero and the first non-zero factor is ``1 / warmup_steps``.
+ """
+
+ def __init__(self, frozen_steps: int, warmup_steps: int, lr_scale: float = 1.0):
+ if frozen_steps < 0:
+ raise ValueError(f"frozen_steps must be non-negative, got {frozen_steps}")
+ if warmup_steps <= 0:
+ raise ValueError(f"warmup_steps must be positive, got {warmup_steps}")
+ self.frozen_steps = frozen_steps
+ self.warmup_steps = warmup_steps
+ self.lr_scale = lr_scale
+
+ def __call__(self, step: int) -> float:
+ if step <= self.frozen_steps:
+ return 0.0
+ progress = (step - self.frozen_steps) / self.warmup_steps
+ return max(0.0, min(progress, 1.0)) * self.lr_scale
+
+
+class LinearWarmupLinearDecay:
+ """Reference ``bfl.modules.lr_scheduler.LinearWarmupLinearDecay`` (torchtitan lineage).
+
+ Relative to ``start_step``: warmup returns ``(step + 1) / (warmup_steps + 1)`` (so the first
+ update is not at zero), an optional constant phase returns one, the decay returns
+ ``1 - (step - offset) / decay_steps`` and raises one step past its end. Steps before
+ ``start_step`` return ``lr_scale``. Every phase is optional through ``None``.
+ """
+
+ def __init__(
+ self,
+ warmup_steps: int | None,
+ decay_steps: int | None,
+ constant_steps: int | None = None,
+ lr_scale: float = 1.0,
+ start_step: int = 0,
+ ):
+ for name, value in (
+ ("warmup_steps", warmup_steps),
+ ("decay_steps", decay_steps),
+ ("constant_steps", constant_steps),
+ ):
+ if value is not None and value < 0:
+ raise ValueError(f"{name} must be non-negative or None, got {value}")
+ if start_step < 0:
+ raise ValueError(f"start_step must be non-negative, got {start_step}")
+ self.warmup_steps = warmup_steps
+ self.warmup_offset = 0 if warmup_steps is None else warmup_steps
+ self.constant_steps = constant_steps
+ self.constant_offset = (
+ self.warmup_offset if constant_steps is None else self.warmup_offset + constant_steps
+ )
+ self.decay_steps = decay_steps
+ self.lr_scale = lr_scale
+ self.start_step = start_step
+
+ def __call__(self, step: int) -> float:
+ effective = step - self.start_step
+ if effective < 0:
+ return self.lr_scale
+ if self.warmup_steps is not None and effective < self.warmup_steps:
+ factor = (effective + 1) / (self.warmup_steps + 1)
+ elif self.constant_steps is not None and effective < self.constant_steps + self.warmup_offset:
+ factor = 1.0
+ elif self.decay_steps is not None:
+ if effective > self.decay_steps + self.constant_offset:
+ raise RuntimeError(
+ f"step {step} (effective {effective}) lies past the scheduled end "
+ f"{self.start_step + self.constant_offset + self.decay_steps}"
+ )
+ factor = 1 - (effective - self.constant_offset) / self.decay_steps
+ else:
+ factor = 1.0
+ return max(min(factor, 1.0), 0.0) * self.lr_scale
+
+
+class CooldownFrom:
+ """``base`` before ``start_step``; from there the reference cooldown overlay.
+
+ The overlay is ``LinearWarmupLinearDecay(None, decay_steps, start_step=start_step)``: it
+ returns ``lr_scale`` at ``start_step`` and reaches zero at ``start_step + decay_steps``. With
+ the recipe's constant phase both sides of the boundary equal ``lr_scale``. Relaunching the
+ reference with its cooldown overlay at ``start_step`` yields the same factors.
+ """
+
+ def __init__(self, base: LRLambda, start_step: int, decay_steps: int, lr_scale: float = 1.0):
+ if decay_steps <= 0:
+ raise ValueError(f"decay_steps must be positive, got {decay_steps}")
+ self.base = base
+ self.start_step = start_step
+ self.decay_steps = decay_steps
+ self.cooldown = LinearWarmupLinearDecay(None, decay_steps, start_step=start_step, lr_scale=lr_scale)
+
+ def __call__(self, step: int) -> float:
+ return self.base(step) if step < self.start_step else self.cooldown(step)
+
+
+def droid_lr_lambdas(
+ *,
+ cooldown_start: int | None = DROID_COOLDOWN_START,
+ cooldown_steps: int = DROID_COOLDOWN_STEPS,
+ lr_scale: float = 1.0,
+ frozen_steps: int = DROID_FROZEN_STEPS,
+ trunk_warmup_steps: int = DROID_TRUNK_WARMUP_STEPS,
+ heads_warmup_steps: int = DROID_HEADS_WARMUP_STEPS,
+) -> tuple[LRLambda, LRLambda]:
+ """Factors for ``FluxActionPolicy.get_optim_params()`` in its order: ``(trunk, heads)``.
+
+ Trunk: zero through ``frozen_steps``, linear to one over ``trunk_warmup_steps``, constant. Heads:
+ ``(g + 1) / (heads_warmup_steps + 1)`` for the first ``heads_warmup_steps`` updates, then constant.
+ Defaults are the DROID recipe (1000 / 2000 / 1000); a short finetune passes smaller phases or its trunk
+ never trains. ``cooldown_start=None`` leaves both constant (the reference's open-ended base launch); the
+ default cools both down from 25000 to zero at 30000.
+ """
+ trunk: LRLambda = (
+ LinearWarmupLinearDecay(trunk_warmup_steps, None, lr_scale=lr_scale)
+ if frozen_steps == 0
+ else FrozenThenLinearWarmup(frozen_steps, trunk_warmup_steps, lr_scale)
+ )
+ heads: LRLambda = LinearWarmupLinearDecay(heads_warmup_steps, None, lr_scale=lr_scale)
+ if cooldown_start is not None:
+ trunk = CooldownFrom(trunk, cooldown_start, cooldown_steps, lr_scale)
+ heads = CooldownFrom(heads, cooldown_start, cooldown_steps, lr_scale)
+ return trunk, heads
+
+
+def build_lr_scheduler(optimizer: Optimizer, lr_lambdas: Sequence[LRLambda]) -> LambdaLR:
+ """One ``LambdaLR`` with one factor per parameter group.
+
+ The factors are wrapped in plain functions, as in the reference, so ``state_dict()`` does not
+ serialize them: a resumed run always uses the schedule of its current configuration.
+ """
+ if len(lr_lambdas) != len(optimizer.param_groups):
+ raise ValueError(f"{len(optimizer.param_groups)} parameter groups but {len(lr_lambdas)} schedules")
+ return LambdaLR(optimizer, lr_lambda=[lambda step, f=f: f(step) for f in lr_lambdas])
+
+
+def resume_lr_scheduler(scheduler: LambdaLR, step: int) -> None:
+ """Reference resume after ``step`` completed updates.
+
+ Loading the optimizer state restores stale ``lr`` values; stepping once from ``step - 1``
+ makes update ``step`` use ``factor(step)``. A fresh run (``step == 0``) needs nothing.
+ """
+ if step < 0:
+ raise ValueError(f"step must be non-negative, got {step}")
+ if step == 0:
+ return
+ scheduler.last_epoch = step - 1
+ with warnings.catch_warnings():
+ # The fresh optimizer has not stepped yet; the reference performs the same priming step.
+ warnings.filterwarnings("ignore", message="Detected call of `lr_scheduler.step\\(\\)`")
+ scheduler.step()
diff --git a/flux-umi/src/flux_action/training/timing.py b/flux-umi/src/flux_action/training/timing.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b920c43bc5eecb7d80842a578b140ccb347261a
--- /dev/null
+++ b/flux-umi/src/flux_action/training/timing.py
@@ -0,0 +1,83 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Optional training phase timings without synchronizing between CUDA streams.
+
+CUDA events measure elapsed time between markers on the stream that records each
+section. They can include stream idle gaps while the host enqueues work, and omit host
+work that occurs before the start marker executes. Host durations measure the Python
+call interval; they do not wait for queued GPU work. The caller must synchronize the
+device once before reading :meth:`StepTimings.seconds`. Sections on the encoder and
+training streams can overlap, so their durations are not additive.
+
+Set ``FLUX_ACTION_NVTX=1`` alongside ``--timing-breakdown`` to publish the same
+section names as NVTX push/pop ranges for Nsight Compute kernel selection.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+import torch
+
+
+class StepTimings:
+ def __init__(self, device: torch.device):
+ self.device = device
+ # NCU can select a phase by name without inspecting every Python launch stack.
+ # This is opt-in because NVTX markers add overhead to each profiled section.
+ self._nvtx_enabled = device.type == "cuda" and os.environ.get("FLUX_ACTION_NVTX") == "1"
+ self._events: dict[str, list[tuple[torch.cuda.Event, torch.cuda.Event]]] = {}
+ self._host_seconds: dict[str, float] = {}
+
+ @contextmanager
+ def section(self, name: str) -> Iterator[None]:
+ if self._nvtx_enabled:
+ torch.cuda.nvtx.range_push(name)
+ try:
+ host_started = time.perf_counter()
+ if self.device.type == "cuda":
+ stream = torch.cuda.current_stream(self.device)
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record(stream)
+ try:
+ yield
+ finally:
+ end.record(stream)
+ self._events.setdefault(name, []).append((start, end))
+ self._host_seconds[name] = self._host_seconds.get(name, 0.0) + time.perf_counter() - host_started
+ else:
+ try:
+ yield
+ finally:
+ self._host_seconds[name] = self._host_seconds.get(name, 0.0) + time.perf_counter() - host_started
+ finally:
+ if self._nvtx_enabled:
+ torch.cuda.nvtx.range_pop()
+
+ def seconds(self) -> dict[str, float]:
+ """Stream event intervals on CUDA, or synchronous host intervals on CPU."""
+ if self.device.type != "cuda":
+ return self._host_seconds.copy()
+ totals = {}
+ for name, events in self._events.items():
+ totals[name] = sum(start.elapsed_time(end) for start, end in events) / 1000
+ return totals
+
+ def host_seconds(self) -> dict[str, float]:
+ """Python call intervals, excluding asynchronous GPU completion."""
+ return self._host_seconds.copy()
diff --git a/flux-umi/src/flux_action/training/trainer.py b/flux-umi/src/flux_action/training/trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fe30ef796f53a27711a837b809225cec666a614
--- /dev/null
+++ b/flux-umi/src/flux_action/training/trainer.py
@@ -0,0 +1,1176 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Training loop of the DROID recipe, also driving the SO-101 recipe over an indexed LeRobot dataset.
+
+Fixed ``windows_per_rank`` windows per rank per micro-step, gradient accumulation to the global
+batch, fused AdamW (0.9, 0.99) with the reference schedules on the trunk and head groups, optional
+global gradient-norm clipping, two power EMAs, checkpoints every ``checkpoint_every`` updates, resume
+with the reference's reseeding or an exact continuation. One process on CPU or GPU, or ``torchrun``
+with FSDP2/HSDP over the DiT. The index (``index_dir``) decides the data path: a DROID manifest streams
+the compact Cosmos3 layout, a LeRobot manifest streams that dataset and its ``statistics.json`` fixes
+the policy's action parameterization and normalization bounds.
+
+Update ``g`` (zero-based) consumes ``factor(g)`` and then feeds the EMAs with index ``g``; the
+checkpoint after ``N`` updates is ``step-N``. Ranks seed their generators with ``seed + rank`` so
+timesteps and noise differ across ranks; the data order uses the shared seed.
+
+The encoders run one micro-batch ahead: while the DiT trains on micro-batch ``i``, ``policy.prepare``
+(augmentation, video VAE, text encoder; frozen, no gradients) already runs for micro-batch ``i + 1`` on
+a side CUDA stream, so their time hides behind the backward pass instead of adding to the step. The
+loop therefore reads one batch ahead of the update it is on. Augmentation and caption dropout draw from
+the loader's per-window seeds, so running ahead changes no random stream and an exact resume stays exact.
+"""
+
+from __future__ import annotations
+
+import gc
+import hashlib
+import importlib
+import json
+import math
+import time
+from contextlib import nullcontext
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Callable
+
+import torch
+import torch.distributed as dist
+from torch import nn
+
+from ..config import PolicyConfig
+from ..data.droid.index import ROWS_FILENAME
+from ..data.lerobot import index as lerobot_index
+from .checkpoint import (
+ TrainState,
+ ema_folder,
+ latest_checkpoint,
+ load_checkpoint,
+ prune_checkpoints,
+ restore_rng,
+ resume_seed,
+ rng_state,
+ save_checkpoint,
+ seed_everything,
+)
+from .data import (
+ DataPosition, WindowDataset, build_dataloader, epoch_loader_state, load_manifest, manifest_dims,
+)
+from .distributed import (
+ all_reduce_means,
+ all_reduce_sum_async,
+ global_grad_norm_tensor,
+ apply_activation_checkpointing,
+ build_mesh,
+ global_grad_norm,
+ init_distributed,
+ shard_dit,
+)
+from .ema import DROID_POWER_EMA_SIGMA_RELS, PowerEMA
+from .schedule import (
+ DROID_COOLDOWN_START,
+ DROID_COOLDOWN_STEPS,
+ DROID_FROZEN_STEPS,
+ DROID_HEADS_WARMUP_STEPS,
+ DROID_TRUNK_WARMUP_STEPS,
+ build_lr_scheduler,
+ droid_lr_lambdas,
+ resume_lr_scheduler,
+)
+from .timing import StepTimings
+
+PolicyFactory = Callable[[PolicyConfig], nn.Module]
+
+TIMING_PHASES = (
+ "prepare_total",
+ "prepare_total_host",
+ "text_context",
+ "text_context_host",
+ "video_preprocess",
+ "video_preprocess_host",
+ "video_vae",
+ "video_vae_host",
+ "encode_wait",
+ "forward_total",
+ "forward_pack",
+ "dit_forward",
+ "loss",
+ "backward",
+ "metrics",
+ "gradient_check",
+ "grad_reduce_norm",
+ "grad_clip",
+ "optimizer",
+ "scheduler",
+ "ema",
+ "zero_grad",
+)
+
+
+@dataclass
+class TrainConfig:
+ source_root: str
+ index_dir: str
+ output_dir: str
+ # Dataset plug. ``"index"`` (default) streams the manifest in ``index_dir`` (DROID or LeRobot). Any other
+ # value is ``"pkg.module:callable"``; the callable receives this config and the loader keyword arguments
+ # (seed, epoch, rank, world_size, num_workers, windows_per_rank, skip_batches, grad_accumulation) and
+ # returns an iterable dataset of training windows with ``batches_per_rank``. ``index_dir`` is then unused.
+ dataset: str = "index"
+ sampling_contract: str | None = None # custom sampler's versioned exact-resume contract
+ sampling_manifest_sha256: str | None = None
+ sampling_legal_starts: int | None = None
+ policy: dict[str, Any] = field(
+ default_factory=dict
+ ) # PolicyConfig fields: trunk_weights, encoder ids, ...
+ steps: int = 30000
+ cooldown_start: int | None = DROID_COOLDOWN_START
+ cooldown_steps: int = DROID_COOLDOWN_STEPS
+ # LR phases of ``droid_lr_lambdas``: trunk frozen for ``frozen_steps``, then warmed over
+ # ``trunk_warmup_steps``; heads warmed over ``heads_warmup_steps``. The DROID values (1000 / 2000 / 1000)
+ # were sized for a 30k-step recipe; a few-thousand-step finetune never trains the trunk unless these shrink.
+ frozen_steps: int = DROID_FROZEN_STEPS
+ trunk_warmup_steps: int = DROID_TRUNK_WARMUP_STEPS
+ heads_warmup_steps: int = DROID_HEADS_WARMUP_STEPS
+ seed: int = 42
+ reseed_on_resume: bool = True
+ windows_per_rank: int = 32
+ grad_accumulation: int = 1
+ num_workers: int = 8
+ prefetch_factor: int = 2
+ in_process_loader: bool = False
+ reuse_epoch_loader: bool = False
+ prefetch_next_epoch: bool = False
+ decoder: str = "ffmpeg"
+ frame_hw: tuple[int, int] = (360, 640)
+ shard_size: int | None = None # ranks per shard group; None = all ranks
+ param_dtype: str = "float32"
+ compute_dtype: str = "bfloat16"
+ reduce_dtype: str = "float32"
+ activation_checkpointing: bool = True
+ # Memory-for-speed variants of activation checkpointing (numerically identical to full recompute):
+ # ac_mode "sac_attn" keeps the attention outputs; ac_save_mlp_blocks also keeps the mlp_in GEMM output of the
+ # first N blocks; ac_skip_last leaves the last N single-stream blocks without checkpointing.
+ ac_mode: str = "full"
+ ac_save_mlp_blocks: int = 0
+ ac_skip_last: int = 0
+ # ac_mode "sac": keep the outputs named in ac_sac_save (sdpa, mlp_out, attn_out, qkv, mlp_in) in every block and
+ # ac_sac_extra_save additionally in the first ac_sac_extra_blocks blocks (see distributed._SacPolicy).
+ ac_sac_save: tuple[str, ...] = ("sdpa",)
+ ac_sac_extra_save: tuple[str, ...] = ()
+ ac_sac_extra_blocks: int = 0
+ # Asynchronous CPU offload of checkpoint-held activations (training/activation_offload.py): "off" or a
+ # comma-separated list of tiers among inputs (the block inputs kept for the recompute) and the selective-
+ # checkpoint kinds in ac_sac_save / ac_sac_extra_save (sdpa, mlp_out, ...). The last ac_offload_keep_last
+ # blocks stay resident; H2D prefetch runs ac_offload_prefetch blocks ahead of the backward.
+ ac_offload: str = "off"
+ ac_offload_keep_last: int = 2
+ ac_offload_prefetch: int = 1
+ reshard_after_forward: bool = True
+ # FSDP2 collectives stage through process-group (NCCL-registered) memory; scheduling-only, needs NCCL >= 2.27.
+ fsdp_comm_memory_from_pg: bool = False
+ # Disable the cyclic garbage collector during training and collect generation 1 every N steps (0 = automatic GC).
+ manual_gc_every: int = 0
+ # Keep the step's host synchronizations off the critical path: the grad-clip coefficient is computed on the device
+ # (bit-identical fp64 arithmetic), the optimizer step is launched before the metrics are read back, and the
+ # per-step device synchronize is dropped (the non-finite check still happens before anything is checkpointed).
+ async_step_end: bool = False
+ betas: tuple[float, float] = (0.9, 0.99)
+ eps: float = 1e-8
+ weight_decay: float = 0.05
+ fused_optimizer: bool = True
+ # Global gradient-norm clipping (torch.nn.utils.clip_grad_norm_ semantics, over all ranks). None = off,
+ # the DROID recipe; the SO-101 recipe clips at 1.0. The logged grad_norm is the norm before clipping.
+ max_grad_norm: float | None = None
+ # Windows drawn per episode per epoch. One (DROID) means an epoch is one window per episode, so a small
+ # dataset cannot fill an update: ranks x num_workers x windows_per_rank x grad_accumulation windows are
+ # needed per epoch. The SO-101 corpus builder took up to 35 windows per episode; several visits draw
+ # independent starts and captions from the run seed, the epoch, the episode and the visit number.
+ visits_per_epoch: int = 1
+ ema_sigma_rels: tuple[float, ...] = DROID_POWER_EMA_SIGMA_RELS
+ # Content streams of the trunk that receive no loss here and are not shipped: frozen, not trained.
+ frozen_streams: tuple[str, ...] = ("image", "image_cond", "audio", "audio_cond")
+ checkpoint_every: int = 1000
+ # Retention: keep the newest ``keep_checkpoints`` complete checkpoints plus every ``keep_every``-th
+ # step (None keeps everything, as the source run did). A checkpoint is 4x the fp32 model size.
+ keep_checkpoints: int | None = None
+ keep_every: int | None = 5000
+ log_every: int = 10
+ resume: str = "auto" # auto | none | path of a step directory
+ initialize_from: str | None = None # model weights only; new optimizer, EMA and step zero
+ # A resumed run must keep windows_per_rank x ranks x grad_accumulation unless explicitly allowed.
+ allow_global_batch_change: bool = False
+ # A resumed run must carry the checkpoint's run seed unless explicitly allowed (branching a new run).
+ allow_seed_change: bool = False
+ max_epochs: int | None = None
+ # Run ``policy.prepare`` of the next micro-batch in a helper thread while the current backward runs, so the
+ # encoder stream and the training stream are fed concurrently (the CUDA launch queue otherwise serializes
+ # them). Same work, same RNG streams (per-window generators); CUDA only.
+ prepare_async: bool = False
+
+ def __post_init__(self):
+ self.frame_hw = tuple(self.frame_hw)
+ self.betas = tuple(self.betas)
+ self.ema_sigma_rels = tuple(self.ema_sigma_rels)
+ self.frozen_streams = tuple(self.frozen_streams)
+ if self.steps < 1 or self.windows_per_rank < 1 or self.grad_accumulation < 1 or self.num_workers < 1:
+ raise ValueError("steps, windows_per_rank, grad_accumulation and num_workers must be positive")
+ if self.cooldown_start is not None and self.cooldown_start + self.cooldown_steps < self.steps:
+ raise ValueError(
+ "steps must not exceed cooldown_start + cooldown_steps (the schedule ends there)"
+ )
+ if self.checkpoint_every < 1 or self.log_every < 1:
+ raise ValueError("checkpoint_every and log_every must be positive")
+ if (self.keep_checkpoints is not None and self.keep_checkpoints < 1) or (
+ self.keep_every is not None and self.keep_every < 1
+ ):
+ raise ValueError("keep_checkpoints and keep_every must be positive when set")
+ if self.initialize_from is not None and self.resume not in ("auto", "none"):
+ raise ValueError("initialize_from cannot be combined with an explicit resume checkpoint")
+ if self.in_process_loader and self.num_workers != 1:
+ raise ValueError("in_process_loader needs num_workers == 1")
+ if self.reuse_epoch_loader and (
+ self.dataset not in ("flux_action.data.umi.all_windows:build",)
+ or self.in_process_loader
+ ):
+ raise ValueError("reuse_epoch_loader requires a multi-process all-windows dataset")
+ if self.prefetch_next_epoch and not self.reuse_epoch_loader:
+ raise ValueError("prefetch_next_epoch requires reuse_epoch_loader")
+ if self.prefetch_next_epoch and (self.max_epochs is None or self.max_epochs < 1):
+ raise ValueError("prefetch_next_epoch requires a finite positive max_epochs")
+ if self.max_grad_norm is not None and not (
+ math.isfinite(self.max_grad_norm) and self.max_grad_norm > 0
+ ):
+ raise ValueError("max_grad_norm must be a finite positive number or None")
+ if self.visits_per_epoch < 1:
+ raise ValueError("visits_per_epoch must be positive")
+ if self.ac_mode not in ("full", "sac", "sac_attn") or self.ac_save_mlp_blocks < 0 or self.ac_skip_last < 0:
+ raise ValueError("ac_mode must be full, sac or sac_attn; ac_save_mlp_blocks / ac_skip_last must be non-negative")
+ from .distributed import SAC_SAVE_KINDS
+
+ for name in (*self.ac_sac_save, *self.ac_sac_extra_save):
+ if name not in SAC_SAVE_KINDS:
+ raise ValueError(f"unknown ac_sac_save kind {name!r}; choose from {SAC_SAVE_KINDS}")
+ if self.ac_sac_extra_blocks < 0 or self.manual_gc_every < 0:
+ raise ValueError("ac_sac_extra_blocks and manual_gc_every must be non-negative")
+ if self.ac_offload_keep_last < 0 or self.ac_offload_prefetch < 1:
+ raise ValueError("ac_offload_keep_last must be non-negative and ac_offload_prefetch positive")
+ if self.ac_offload != "off":
+ from .activation_offload import INPUT_TIER, TIERS
+
+ tiers = [t.strip() for t in self.ac_offload.split(",") if t.strip()]
+ if not tiers or any(t not in TIERS for t in tiers) or not self.activation_checkpointing:
+ raise ValueError(f"ac_offload must be 'off' or tiers from {TIERS} with activation_checkpointing on")
+ saved = set(self.ac_sac_save) | set(self.ac_sac_extra_save)
+ if any(t != INPUT_TIER and (self.ac_mode != "sac" or t not in saved) for t in tiers):
+ raise ValueError("ac_offload SAC tiers need ac_mode='sac' and the kind in ac_sac_save / ac_sac_extra_save")
+
+ @classmethod
+ def from_file(cls, path, overrides: tuple[str, ...] | list[str] = ()) -> TrainConfig:
+ """JSON file plus ``key=value`` overrides (``policy.key=value`` reaches the policy fields)."""
+ data = json.loads(Path(path).read_text())
+ for item in overrides:
+ key, _, raw = item.partition("=")
+ if not _:
+ raise ValueError(f"override {item!r} is not key=value")
+ try:
+ value = json.loads(raw)
+ except json.JSONDecodeError:
+ value = raw
+ if key.startswith("policy."):
+ data.setdefault("policy", {})[key.removeprefix("policy.")] = value
+ else:
+ data[key] = value
+ return cls(**data)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ def global_batch(self, world_size: int) -> int:
+ return world_size * self.windows_per_rank * self.grad_accumulation
+
+
+class Trainer:
+ def __init__(
+ self,
+ config: TrainConfig,
+ *,
+ policy_factory: PolicyFactory | None = None,
+ stop_after_steps: int | None = None,
+ timing_breakdown: bool = False,
+ ):
+ if stop_after_steps is not None and (type(stop_after_steps) is not int or stop_after_steps < 1):
+ raise ValueError("stop_after_steps must be a positive integer")
+ self.config = config
+ self.stop_after_steps = stop_after_steps
+ self.timing_breakdown = timing_breakdown
+ self._run_stop_step = config.steps
+ self.rank, self.world_size, self.device = init_distributed()
+ self.sharded = self.world_size > 1
+ self.param_dtype = getattr(torch, config.param_dtype)
+ self.compute_dtype = getattr(torch, config.compute_dtype)
+ self.policy_factory = policy_factory
+ self.output_dir = Path(config.output_dir)
+ self.step = 0
+ self.epoch_losses: list[float] = []
+ self.encode_stream = torch.cuda.Stream(self.device) if self.device.type == "cuda" else None
+ self._prepared: Any = None # PreparedWindows of the next micro-batch, encoded ahead of its update
+
+ # ------------------------------------------------------------------ construction
+ def build(self) -> Trainer:
+ cfg = self.config
+ seed_everything(cfg.seed + self.rank)
+ index = Path(cfg.index_dir)
+ if cfg.dataset == "index":
+ self.manifest = load_manifest(index / "manifest.json")
+ self.rows_path = index / ROWS_FILENAME
+ if not self.rows_path.is_file():
+ raise FileNotFoundError(
+ f"{self.rows_path} missing; run flux-action index-droid or flux-action index-lerobot"
+ )
+ self._build_dataset = None
+ else:
+ self.manifest = self.rows_path = None
+ self._build_dataset = _import_dataset_builder(cfg.dataset)
+ # fresh heads are drawn from the run seed (rank-independent), not from the per-rank RNG seeded above
+ fields = {"head_init_seed": cfg.seed, **cfg.policy, "torch_dtype": cfg.param_dtype}
+ self._resume_path = (
+ latest_checkpoint(self.output_dir)
+ if cfg.resume == "auto"
+ else (None if cfg.resume == "none" else Path(cfg.resume))
+ )
+ self._initialization_path = Path(cfg.initialize_from) if cfg.initialize_from and self._resume_path is None else None
+ source_config = self._resume_path or self._initialization_path
+ if source_config is not None and fields.get("content_streams") is None:
+ saved = json.loads((source_config / "config.json").read_text())
+ fields["content_streams"] = saved.get("content_streams")
+ if self.manifest is not None:
+ fields = self._reconcile_with_index(fields, index)
+ policy_config = PolicyConfig(**fields)
+ policy_config.validate_training()
+ with torch.random.fork_rng(devices=[]):
+ # every rank builds identical tensors on the CPU; only the CPU generator is touched and restored,
+ # so the per-rank seeding above keeps governing training randomness on every device
+ torch.default_generator.manual_seed(cfg.seed)
+ policy = (
+ self.policy_factory(policy_config) if self.policy_factory else _default_policy(policy_config)
+ )
+ frozen = policy.freeze_streams(cfg.frozen_streams) + policy.freeze_conditioning_heads()
+ self._log_line(
+ {
+ "event": "frozen",
+ "streams": list(cfg.frozen_streams),
+ "tensors": len(frozen),
+ "frozen_numel": sum(p.numel() for p in policy.parameters() if not p.requires_grad),
+ "trainable_numel": sum(p.numel() for p in policy.parameters() if p.requires_grad),
+ }
+ )
+ from .activation_offload import OffloadPlan
+
+ ac_offload = OffloadPlan.from_spec(cfg.ac_offload, keep_last=cfg.ac_offload_keep_last, prefetch=cfg.ac_offload_prefetch)
+ if self.sharded:
+ mesh = build_mesh(self.world_size, cfg.shard_size, self.device.type)
+ shard_dit(
+ policy.dit,
+ mesh,
+ param_dtype=self.compute_dtype,
+ reduce_dtype=getattr(torch, cfg.reduce_dtype),
+ reshard_after_forward=cfg.reshard_after_forward,
+ activation_checkpointing=cfg.activation_checkpointing,
+ ac_mode=cfg.ac_mode,
+ ac_save_mlp_blocks=cfg.ac_save_mlp_blocks,
+ ac_skip_last=cfg.ac_skip_last,
+ ac_sac_save=tuple(cfg.ac_sac_save),
+ ac_sac_extra_save=tuple(cfg.ac_sac_extra_save),
+ ac_sac_extra_blocks=cfg.ac_sac_extra_blocks,
+ ac_offload=ac_offload,
+ comm_memory_from_pg=cfg.fsdp_comm_memory_from_pg,
+ )
+ else:
+ if cfg.activation_checkpointing:
+ apply_activation_checkpointing(
+ policy.dit, mode=cfg.ac_mode, save_mlp_blocks=cfg.ac_save_mlp_blocks, skip_last=cfg.ac_skip_last,
+ sac_save=tuple(cfg.ac_sac_save), sac_extra_save=tuple(cfg.ac_sac_extra_save),
+ sac_extra_blocks=cfg.ac_sac_extra_blocks, offload=ac_offload,
+ )
+ policy.dit.to(self.device)
+ for component in (getattr(policy.video_vae, "module", policy.video_vae), policy.text_encoder):
+ if isinstance(component, nn.Module):
+ component.to(self.device)
+ policy.set_compute_dtype(self.compute_dtype if self.compute_dtype != self.param_dtype else None)
+ policy.train()
+ self.policy = policy
+ self._initialize_weights()
+ self.optimizer = torch.optim.AdamW(
+ policy.get_optim_params(),
+ betas=cfg.betas,
+ eps=cfg.eps,
+ weight_decay=cfg.weight_decay,
+ fused=cfg.fused_optimizer and self.device.type == "cuda",
+ )
+ self.scheduler = build_lr_scheduler(
+ self.optimizer,
+ droid_lr_lambdas(
+ cooldown_start=cfg.cooldown_start,
+ cooldown_steps=cfg.cooldown_steps,
+ frozen_steps=cfg.frozen_steps,
+ trunk_warmup_steps=cfg.trunk_warmup_steps,
+ heads_warmup_steps=cfg.heads_warmup_steps,
+ ),
+ )
+ self.emas = {ema_folder(s): PowerEMA.from_module(policy, s) for s in cfg.ema_sigma_rels}
+ self.state = TrainState(run_seed=cfg.seed, world_size=self.world_size)
+ self.state.extra["train_config"] = cfg.to_dict()
+ self.state.extra["global_batch"] = cfg.global_batch(self.world_size)
+ self.state.extra["data_contract"] = self._data_contract()
+ if self._initialization_path is not None:
+ self.state.extra["initialization"] = self._initialization_record
+ self.position = DataPosition(
+ world_size=self.world_size, num_workers=cfg.num_workers, windows_per_rank=cfg.windows_per_rank
+ )
+ self._resume()
+ return self
+
+ def _reconcile_with_index(self, fields: dict[str, Any], index: Path) -> dict[str, Any]:
+ """The policy's action space must be the indexed dataset's.
+
+ The rows array's action width must equal ``action_dim`` (the state token has the same width). For a
+ LeRobot index, its ``statistics.json`` fixes the action parameterization and the normalization
+ bounds: empty policy fields take them, set fields must agree with them (a config that carries one
+ dataset's bounds is wrong for another dataset, so a mismatch is an error, not a warning).
+ """
+ chunk = fields.get("chunk_size", PolicyConfig.chunk_size)
+ if chunk != self.manifest["chunk_size"]:
+ raise ValueError(
+ f"policy.chunk_size {chunk} disagrees with index chunk_size {self.manifest['chunk_size']}; re-index with --chunk-size {chunk}"
+ )
+ state_dim, action_dim = manifest_dims(self.manifest)
+ wanted = int(fields.get("action_dim", PolicyConfig.action_dim))
+ if wanted != action_dim or state_dim != action_dim:
+ raise ValueError(
+ f"policy.action_dim {wanted} but the index holds {action_dim}-dimensional actions and "
+ f"{state_dim}-dimensional states; the state token needs action_dim values"
+ )
+ statistics_path = index / lerobot_index.STATISTICS_FILENAME
+ if self.manifest.get("kind") != lerobot_index.KIND:
+ return fields
+ if not statistics_path.is_file():
+ raise FileNotFoundError(f"LeRobot training requires normalization statistics: {statistics_path}")
+ statistics = lerobot_index.load_statistics(statistics_path)
+ fields = dict(fields)
+ indexed = statistics["action"]["parameterization"]
+ absolute = tuple(statistics["action"]["absolute_dims"])
+ parameterization = fields.setdefault("action_parameterization", indexed)
+ if "absolute_action_dims" in fields:
+ configured = lerobot_index.normalize_dims(fields["absolute_action_dims"], action_dim)
+ else:
+ configured = absolute if indexed == "joint_delta" else ()
+ fields["absolute_action_dims"] = list(configured)
+ if parameterization != indexed or (indexed == "joint_delta" and configured != absolute):
+ raise ValueError(
+ f"the index statistics describe {indexed!r} targets with absolute dims {list(absolute)}, the "
+ f"policy config {parameterization!r} with {list(configured)}; re-index with "
+ "--action-parameterization / --absolute-action-dims or change the policy fields"
+ )
+ adopted = []
+ for field_name, block in (("action_normalization", "action"), ("state_normalization", "state")):
+ bounds = {k: [float(v) for v in statistics[block][k]] for k in ("q01", "q99")}
+ current = fields.get(field_name)
+ if current is None:
+ fields[field_name] = bounds
+ adopted.append(field_name)
+ continue
+ same = all(
+ len(current[k]) == len(bounds[k])
+ and all(math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-9) for a, b in zip(current[k], bounds[k]))
+ for k in ("q01", "q99")
+ )
+ if not same:
+ raise ValueError(
+ f"policy.{field_name} disagrees with {statistics_path}; remove the field to take the "
+ "index's bounds, or index the dataset the checkpoint was normalized against"
+ )
+ clip = float(statistics["clip"])
+ if fields.setdefault("normalization_clip", clip) != clip:
+ raise ValueError(
+ f"policy.normalization_clip {fields['normalization_clip']} but the index used {clip}"
+ )
+ self._log_line(
+ {
+ "event": "normalization",
+ "statistics": str(statistics_path),
+ "adopted": adopted,
+ "action_parameterization": indexed,
+ "absolute_action_dims": list(absolute),
+ }
+ )
+ return fields
+
+ def _data_contract(self) -> str:
+ # The manifest includes row hashes, dataset identity, cameras and episode ranges.
+ # Hash its semantic contents so moving an index or reformatting JSON is harmless.
+ data = {"dataset": self.config.dataset, "manifest": self.manifest}
+ if self.manifest is None:
+ data["source_root"] = self.config.source_root
+ return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
+
+ def _validate_resume_contract(self, path: Path) -> None:
+ saved = PolicyConfig(**json.loads((path / "config.json").read_text())).to_dict()
+ current = self.policy.config.to_dict()
+ fields = (
+ "action_dim",
+ "action_modality",
+ "content_streams",
+ "camera_layout",
+ "camera_keys",
+ "canvas_hw",
+ "chunk_size",
+ "fps",
+ "action_scale",
+ "gripper_flip_dims",
+ "action_parameterization",
+ "absolute_action_dims",
+ "action_normalization",
+ "state_normalization",
+ "normalization_clip",
+ "inference_profile",
+ "n_obs_steps",
+ "history_snapshots",
+ "condition_on_past_actions",
+ "video_position_fps",
+ "text_fixed_length",
+ "separate_timesteps",
+ "video_logit_mean",
+ "video_logit_std",
+ "conditioning_noise_max",
+ "loss_reduction",
+ "action_channel_weights",
+ "action_loss_weight",
+ "video_loss_weight",
+ "train_timestep_width",
+ "train_timestep_shift",
+ "state_dropout",
+ )
+ changed = [name for name in fields if saved.get(name) != current.get(name)]
+ extra = json.loads((path / "state.json").read_text()).get("extra", {})
+ if extra.get("data_contract", self._data_contract()) != self._data_contract():
+ changed.append("dataset/index")
+ previous = extra.get("train_config", {})
+ if previous.get("sampling_contract") != self.config.sampling_contract:
+ changed.append("sampling_contract")
+ if self.config.sampling_contract:
+ # Versioned full-window samplers promise continuation, not a silent fresh epoch.
+ for name in ("num_workers", "windows_per_rank", "grad_accumulation", "visits_per_epoch",
+ "sampling_manifest_sha256", "sampling_legal_starts", "shard_size"):
+ if previous.get(name) != getattr(self.config, name):
+ changed.append(name)
+ if extra.get("global_batch") != self.config.global_batch(self.world_size):
+ changed.append("sampler topology")
+ for name in ("dataset", "frame_hw", "decoder"):
+ if name in previous and previous[name] != json.loads(json.dumps(self.config.to_dict()[name])):
+ changed.append(name)
+ if changed:
+ raise ValueError(
+ f"resume changes the saved policy/data contract: {', '.join(changed)}; "
+ "start a separate fine-tuning run instead of restoring optimizer state"
+ )
+
+ def _initialize_weights(self) -> None:
+ path = self._initialization_path
+ if path is None:
+ return
+ source, output = path.resolve(), self.output_dir.resolve()
+ if source == output or source.is_relative_to(output) or output.is_relative_to(source):
+ raise ValueError("initialization checkpoint and output must be separate")
+ saved = PolicyConfig(**json.loads((path / "config.json").read_text())).to_dict()
+ current = self.policy.config.to_dict()
+ fields = (
+ "action_dim", "action_modality", "dit_config", "content_streams", "camera_layout", "camera_keys",
+ "canvas_hw", "chunk_size", "fps", "action_scale", "gripper_flip_dims", "action_parameterization",
+ # Normalization is excluded: a post-training run normalizes with its own data statistics.
+ "absolute_action_dims", "normalization_clip",
+ "inference_profile", "n_obs_steps", "history_snapshots", "condition_on_past_actions",
+ "video_position_fps", "text_fixed_length", "conditioning_noise_max", "separate_timesteps",
+ )
+ changed = [name for name in fields if saved[name] != current[name]]
+ if changed:
+ raise ValueError("weight initialization changes policy contract: " + ", ".join(changed))
+ source_state = load_checkpoint(path, model=self.policy)
+ self._initialization_record = {
+ "checkpoint": str(path), "source_step": source_state.step, "profile": "model",
+ "config_sha256": hashlib.sha256((path / "config.json").read_bytes()).hexdigest(),
+ "state_sha256": hashlib.sha256((path / "state.json").read_bytes()).hexdigest(),
+ "optimizer_restored": False, "ema_restored": False, "new_step": 0,
+ }
+ self._log_line({"event": "initialize_weights", **self._initialization_record})
+
+ def _resume(self) -> None:
+ cfg = self.config
+ path = self._resume_path
+ if path is None:
+ return
+ self._validate_resume_contract(path)
+ self.state = load_checkpoint(path, model=self.policy, optimizer=self.optimizer, emas=self.emas)
+ self.state.extra["data_contract"] = self._data_contract()
+ self.step = self.state.step
+ if cfg.seed != self.state.run_seed and not cfg.allow_seed_change:
+ raise ValueError(
+ f"checkpoint {path} belongs to run seed {self.state.run_seed}, config seed is {cfg.seed}; "
+ "use the checkpoint's seed (or a new output_dir), or set allow_seed_change"
+ )
+ previous, current = self.state.extra.get("global_batch"), cfg.global_batch(self.world_size)
+ if (
+ previous is None and "train_config" in self.state.extra
+ ): # checkpoints written before the field existed
+ saved = self.state.extra["train_config"]
+ previous = self.state.world_size * saved["windows_per_rank"] * saved["grad_accumulation"]
+ if previous is not None and previous != current and not cfg.allow_global_batch_change:
+ raise ValueError(
+ f"the checkpoint was trained with {previous} windows per update, this launch gives {current}; "
+ "adjust windows_per_rank or grad_accumulation, or set allow_global_batch_change"
+ )
+ self.state.extra["global_batch"] = current
+ resume_lr_scheduler(self.scheduler, self.step)
+ recorded = self.state.data.get("position")
+ recorded = DataPosition.from_dict(recorded) if recorded else None
+ topology = dict(
+ world_size=self.world_size, num_workers=cfg.num_workers, windows_per_rank=cfg.windows_per_rank
+ )
+ exact = (
+ not cfg.reseed_on_resume
+ and recorded is not None
+ and recorded.matches(**topology)
+ and restore_rng(path, self.state)
+ )
+ if exact:
+ self.position = recorded
+ mode = "exact"
+ else:
+ if cfg.reseed_on_resume:
+ self.state.seed_history.append(resume_seed(self.state.run_seed, len(self.state.seed_history)))
+ seed_everything(self.state.seed + self.rank)
+ next_epoch = recorded.epoch + 1 if recorded else 0
+ if recorded and cfg.sampling_contract and recorded.batches_consumed == 0:
+ next_epoch = recorded.epoch
+ self.position = DataPosition(epoch=next_epoch, **topology)
+ mode = "reseeded" if cfg.reseed_on_resume else "fresh_epoch"
+ self.state.world_size = self.world_size
+ self.state.extra.setdefault("resumes", []).append(
+ {"from": str(path), "step": self.step, "mode": mode}
+ )
+ self.state.extra["train_config"] = cfg.to_dict()
+ self._log_line(
+ {"event": "resume", "from": str(path), "step": self.step, "mode": mode, "seed": self.state.seed}
+ )
+
+ def _rank_max(self, values: list[float]) -> list[float]:
+ """Return the per-field critical rank without a collective in single-process runs."""
+ if self.world_size == 1:
+ return values
+ tensor = torch.tensor(values, device=self.device, dtype=torch.float64)
+ dist.all_reduce(tensor, op=dist.ReduceOp.MAX)
+ return tensor.cpu().tolist()
+
+ # ------------------------------------------------------------------ loop
+ def run(self) -> dict[str, Any]:
+ started = time.perf_counter()
+ self.build()
+ if self.timing_breakdown:
+ seconds = time.perf_counter() - started
+ seconds_max = self._rank_max([seconds])[0]
+ self._log_line({"event": "build_timing", "seconds": seconds, "seconds_rank_max": seconds_max})
+ self._log_line(
+ {
+ "event": "timing_info",
+ "unit": "seconds",
+ "phase_scope": "maximum across ranks, calculated separately for each phase",
+ "prepare_attribution": "encodings launched during this update; early updates prepare a later batch",
+ "overlap": "encoder and training streams overlap; phase durations cannot be summed",
+ "source": "CUDA event intervals on each stream, or synchronous perf_counter intervals on CPU",
+ "cuda_event_limit": "stream intervals are not complete host wall time or pure GPU kernel time",
+ "host_fields": "*_host is Python call time and excludes queued GPU completion",
+ }
+ )
+ return self.train()
+
+ def train(self) -> dict[str, Any]:
+ cfg = self.config
+ self._run_stop_step = min(
+ cfg.steps,
+ self.step + self.stop_after_steps if self.stop_after_steps is not None else cfg.steps,
+ )
+ self._written = self.step if latest_checkpoint(self.output_dir) is not None and self.step > 0 else -1
+ if cfg.manual_gc_every:
+ # Deterministic collection points instead of random pauses on the launch thread (stragglers at scale).
+ gc.disable()
+ gc.collect()
+ loader = None
+ loader_iter = None
+ batches = None
+ try:
+ while self.step < self._run_stop_step and (cfg.max_epochs is None or self.position.epoch < cfg.max_epochs):
+ loader_started = time.perf_counter()
+ if loader is None or not cfg.reuse_epoch_loader:
+ loader_kwargs = dict(
+ seed=self.state.seed,
+ epoch=self.position.epoch,
+ rank=self.rank,
+ world_size=self.world_size,
+ num_workers=cfg.num_workers,
+ windows_per_rank=cfg.windows_per_rank,
+ skip_batches=self.position.batches_consumed,
+ grad_accumulation=cfg.grad_accumulation,
+ )
+ if self._build_dataset is not None:
+ dataset = self._build_dataset(cfg, **loader_kwargs)
+ else:
+ dataset = WindowDataset(
+ self.manifest,
+ cfg.source_root,
+ self.rows_path,
+ **loader_kwargs,
+ decoder=cfg.decoder,
+ frame_hw=cfg.frame_hw,
+ visits_per_epoch=cfg.visits_per_epoch,
+ split="train",
+ n_obs_steps=self.policy.config.n_obs_steps
+ if self.policy.config.inference_profile == "history"
+ else None,
+ )
+ self._epoch_batches_per_rank = dataset.batches_per_rank
+ if cfg.reuse_epoch_loader:
+ dataset.set_loader_state(epoch_loader_state(self.position.epoch, self.position.batches_consumed))
+ if cfg.prefetch_next_epoch:
+ if dataset.batches_per_rank < cfg.grad_accumulation + 2:
+ raise ValueError("next-epoch prefetch needs at least two updates per epoch")
+ dataset.set_continuous_end(cfg.max_epochs * dataset.batches_per_rank)
+ loader = build_dataloader(
+ dataset,
+ prefetch_factor=cfg.prefetch_factor,
+ pin_memory=self.device.type == "cuda",
+ in_process=cfg.in_process_loader,
+ persistent_workers=cfg.reuse_epoch_loader,
+ )
+ if cfg.prefetch_next_epoch:
+ loader_iter = iter(loader)
+ reused = False
+ else:
+ if not cfg.prefetch_next_epoch:
+ dataset.start_epoch(self.position.epoch, self.position.batches_consumed)
+ reused = True
+ if self.rank == 0 and self.position.batches_consumed == 0:
+ self._log_line(
+ {
+ "event": "epoch",
+ "epoch": self.position.epoch,
+ "batches_per_rank": dataset.batches_per_rank,
+ }
+ )
+ loader_seconds = time.perf_counter() - loader_started
+ loader_seconds_max = self._rank_max([loader_seconds])[0] if self.timing_breakdown else None
+ if self.rank == 0:
+ self._log_line({"event": "epoch_loader", "epoch": self.position.epoch,
+ "reused": reused, "seconds": round(loader_seconds, 3),
+ **({"seconds_rank_max": loader_seconds_max} if self.timing_breakdown else {})})
+ accum = cfg.grad_accumulation
+ pending: list[dict[str, Any]] = [] # the update's micro-batches plus one batch of lookahead
+ exhausted = True
+ waited_since = time.perf_counter()
+ data_wait = 0.0
+ first_batch = True
+ self._prepared = None
+ if cfg.prefetch_next_epoch:
+ batches = (next(loader_iter) for _ in range(
+ dataset.batches_per_rank - self.position.batches_consumed
+ ))
+ else:
+ batches = loader
+ for batch in batches:
+ batch_time = time.perf_counter()
+ data_wait += batch_time - waited_since
+ if first_batch:
+ first_batch_wait = batch_time - waited_since
+ first_batch_wait_max = (
+ self._rank_max([first_batch_wait])[0] if self.timing_breakdown else None
+ )
+ if self.rank == 0:
+ self._log_line({"event": "epoch_first_batch", "epoch": self.position.epoch,
+ "seconds": round(first_batch_wait, 3),
+ **({"seconds_rank_max": first_batch_wait_max} if self.timing_breakdown else {})})
+ first_batch = False
+ pending.append(batch)
+ if len(pending) == accum and self.step + 1 == self._run_stop_step:
+ # No lookahead is needed for the final update. Do not request another
+ # batch from the loader (its workers may already have prefetched it).
+ self._train_update(pending, None, data_wait)
+ exhausted = False
+ break
+ if len(pending) <= accum:
+ waited_since = time.perf_counter()
+ continue
+ stop = self._train_update(pending[:accum], pending[accum], data_wait)
+ pending = pending[accum:]
+ waited_since = time.perf_counter()
+ data_wait = 0.0
+ if stop:
+ exhausted = False
+ break
+ if exhausted:
+ # the epoch's last update has no lookahead batch
+ if len(pending) == accum:
+ stop = self._train_update(pending, None, data_wait)
+ if stop:
+ break
+ self.position.epoch += 1
+ self.position.batches_consumed = 0
+ if self.position.batches_consumed == getattr(self, "_epoch_batches_per_rank", None):
+ self.position.epoch += 1
+ self.position.batches_consumed = 0
+ if self._written != self.step:
+ self._checkpoint()
+ return {
+ "step": self.step,
+ "epoch": self.position.epoch,
+ "seed": self.state.seed,
+ "output_dir": str(self.output_dir),
+ }
+ finally:
+ if cfg.manual_gc_every:
+ gc.enable()
+ if batches is not None and batches is not loader and hasattr(batches, "close"):
+ batches.close()
+ batches = None
+ loader_iter = None
+ loader = None
+
+ def _train_update(
+ self, micro: list[dict[str, Any]], next_batch: dict[str, Any] | None, data_wait: float
+ ) -> bool:
+ """One update on ``micro`` (``next_batch`` is the following update's first batch, encoded ahead);
+ logs, checkpoints, advances the position. Returns True at this invocation's step limit."""
+ cfg = self.config
+ # The final update still consumes both micro-batches, but has no use for the next update's encoding.
+ metrics = self._update(micro, next_batch if self.step + 1 < self._run_stop_step else None)
+ metrics["data_wait"] = data_wait
+ if self.timing_breakdown:
+ local = metrics.pop("_timing_local")
+ names = (*TIMING_PHASES, "data_wait", "step_time")
+ values = self._rank_max([local.get(name, metrics.get(name, 0.0)) for name in names])
+ metrics["timing_breakdown_s"] = {
+ "scope": "rank_max",
+ **dict(zip(names, values, strict=True)),
+ }
+ self.position.batches_consumed += cfg.grad_accumulation
+ self.step += 1
+ if cfg.manual_gc_every and self.step % cfg.manual_gc_every == 0:
+ gc.collect(1)
+ metrics.update(step=self.step, epoch=self.position.epoch)
+ self.epoch_losses.append(metrics["loss"])
+ if self.rank == 0 and (
+ self.timing_breakdown or self.step % cfg.log_every == 0 or self.step == self._run_stop_step
+ ):
+ self._log_line(metrics)
+ if self.step % cfg.checkpoint_every == 0 or self.step == cfg.steps:
+ self._checkpoint()
+ self._written = self.step
+ return self.step >= self._run_stop_step
+
+ def _prepare(self, batch: dict[str, Any], timings: StepTimings | None = None) -> Any:
+ """``policy.prepare`` on the side stream, with an event the consumer waits for."""
+ if timings is not None:
+ from ..policy import FluxActionPolicy
+
+ def encode():
+ if timings is not None and isinstance(self.policy, FluxActionPolicy):
+ return self.policy.prepare(batch, timings=timings)
+ return self.policy.prepare(batch)
+
+ section = timings.section("prepare_total") if timings else nullcontext()
+ if self.encode_stream is None:
+ with section:
+ return encode()
+ with torch.cuda.stream(self.encode_stream):
+ with section:
+ prepared = encode()
+ prepared.event = torch.cuda.Event()
+ prepared.event.record(self.encode_stream)
+ return prepared
+
+ def _update(
+ self, micro: list[dict[str, Any]], next_batch: dict[str, Any] | None = None
+ ) -> dict[str, Any]:
+ cfg = self.config
+ started = time.perf_counter()
+ timings = StepTimings(self.device) if self.timing_breakdown else None
+ if self.device.type == "cuda":
+ torch.cuda.reset_peak_memory_stats(self.device)
+ accum = len(micro)
+ # FP64 matches the previous Python-float accumulation without per-microbatch host waits.
+ metrics = torch.zeros(3, device=self.device, dtype=torch.float64)
+ windows = 0
+ autocast = torch.autocast(
+ self.device.type,
+ dtype=self.compute_dtype,
+ enabled=not self.sharded
+ and self.compute_dtype != self.param_dtype
+ and self.device.type == "cuda",
+ )
+ for i, batch in enumerate(micro):
+ if self.sharded:
+ self.policy.dit.set_requires_gradient_sync(i == accum - 1)
+ prepared = self._prepared if self._prepared is not None else self._prepare(batch, timings)
+ self._prepared = None
+ if timings is not None:
+ if self.device.type == "cuda" and prepared.event is not None:
+ # The policy will repeat this wait for tensor lifetime tracking. Timing it here
+ # keeps the encoder dependency out of the forward sections below.
+ with timings.section("encode_wait"):
+ torch.cuda.current_stream(self.device).wait_event(prepared.event)
+ if hasattr(prepared, "timings"):
+ prepared.timings = timings
+ with timings.section("forward_total") if timings else nullcontext():
+ with autocast:
+ loss, info = self.policy(batch, prepared=prepared)
+ following = micro[i + 1] if i + 1 < accum else next_batch
+ prepare_thread = None
+ # Invariant behind exact resumes: ``prepare`` snapshots the host generators when it starts
+ # (PreparedWindows.rng_before) and nothing between that point and the checkpoint write -- the backward,
+ # optimizer, EMAs -- may draw from the global CPU RNG (activation checkpointing runs with
+ # preserve_rng_state=False and the models hold no dropout), also when prepare runs on the helper thread.
+ if following is not None: # its encoders overlap this micro-batch's backward pass
+ if cfg.prepare_async and self.device.type == "cuda":
+ prepare_thread = _PrepareThread(self, following, timings)
+ else:
+ self._prepared = self._prepare(following, timings)
+ with timings.section("backward") if timings else nullcontext():
+ (loss / accum).backward()
+ if prepare_thread is not None:
+ self._prepared = prepare_thread.result()
+ with timings.section("metrics") if timings else nullcontext():
+ metrics += (
+ torch.stack(
+ [
+ loss.detach().double(),
+ torch.as_tensor(info["video_mse"], device=self.device, dtype=torch.float64),
+ torch.as_tensor(info["action_mse"], device=self.device, dtype=torch.float64),
+ ]
+ )
+ / accum
+ )
+ windows += int(info["n_valid_windows"])
+ if self.sharded:
+ self.policy.dit.set_requires_gradient_sync(True)
+ if self.step == 0:
+ with timings.section("gradient_check") if timings else nullcontext():
+ self._check_gradients()
+ replicas = self.world_size // (self.config.shard_size or self.world_size) if self.sharded else 1
+ clipped = {}
+ if cfg.async_step_end and self.device.type == "cuda":
+ # Device-side reductions; the host reads them back only after the optimizer step has been launched.
+ with timings.section("grad_reduce_norm") if timings else nullcontext():
+ means_dev = all_reduce_sum_async(metrics)
+ norm_dev = global_grad_norm_tensor(self.policy, self.device, replicas)
+ coef_dev = None
+ if self.config.max_grad_norm is not None:
+ with timings.section("grad_clip") if timings else nullcontext():
+ # min(1, max_norm / (norm + 1e-6)) in fp64 on the device == the host formula; multiplying by a
+ # 0-dim fp64 tensor rounds exactly like multiplying by the Python float (same opmath cast).
+ numer = torch.full((), float(self.config.max_grad_norm), dtype=torch.float64, device=norm_dev.device)
+ coef_dev = torch.clamp(numer / (norm_dev + 1e-6), max=1.0)
+ for param in self.policy.parameters():
+ if param.grad is not None:
+ param.grad.mul_(coef_dev)
+ consumed = [group["lr"] for group in self.optimizer.param_groups]
+ with timings.section("optimizer") if timings else nullcontext():
+ self.optimizer.step()
+ # one host round trip for everything the step logs (the GPU keeps executing the optimizer meanwhile)
+ readback = torch.cat([means_dev.double().reshape(-1), norm_dev.reshape(1),
+ (coef_dev if coef_dev is not None else norm_dev.new_ones(())).reshape(1)])
+ loss_mean, video, action, grad_norm, coefficient = readback.tolist()
+ if self.config.max_grad_norm is not None:
+ clipped = {"grad_clip": coefficient}
+ if not (math.isfinite(loss_mean) and math.isfinite(grad_norm)):
+ # The update was already applied (it is never checkpointed: this raise precedes the write).
+ raise RuntimeError(
+ f"non-finite update at step {self.step + 1}: loss {loss_mean}, grad_norm {grad_norm}; "
+ "resume from the last complete checkpoint"
+ )
+ else:
+ # Abort on all ranks before anything is mutated: a non-finite update would poison the parameters,
+ # the optimizer moments and both EMAs, then be written as a complete checkpoint.
+ with timings.section("grad_reduce_norm") if timings else nullcontext():
+ loss_mean, video, action = all_reduce_means(metrics)
+ grad_norm = global_grad_norm(self.policy, self.device, replicas)
+ if not (math.isfinite(loss_mean) and math.isfinite(grad_norm)):
+ raise RuntimeError(
+ f"non-finite update at step {self.step + 1}: loss {loss_mean}, grad_norm {grad_norm}; "
+ "nothing was applied, resume from the last complete checkpoint"
+ )
+ if self.config.max_grad_norm is not None:
+ with timings.section("grad_clip") if timings else nullcontext():
+ # clip_grad_norm_ semantics on the global norm: every rank scales its shards by the same factor
+ coefficient = min(1.0, self.config.max_grad_norm / (grad_norm + 1e-6))
+ if coefficient < 1.0:
+ for param in self.policy.parameters():
+ if param.grad is not None:
+ param.grad.mul_(coefficient)
+ clipped = {"grad_clip": coefficient}
+ consumed = [group["lr"] for group in self.optimizer.param_groups] # factor(step) for this update
+ with timings.section("optimizer") if timings else nullcontext():
+ self.optimizer.step()
+ with timings.section("scheduler") if timings else nullcontext():
+ self.scheduler.step()
+ betas = {}
+ if self.emas:
+ with timings.section("ema") if timings else nullcontext():
+ betas = {name: ema.update_from_module(self.policy, self.step) for name, ema in self.emas.items()}
+ with timings.section("zero_grad") if timings else nullcontext():
+ self.optimizer.zero_grad(set_to_none=True)
+ peak = {}
+ if self.device.type == "cuda":
+ if not cfg.async_step_end or timings is not None:
+ # the CUDA-event timing breakdown needs completed events; without it the step end stays asynchronous
+ torch.cuda.synchronize(self.device)
+ peak = {"peak_mem_gb": round(torch.cuda.max_memory_allocated(self.device) / 2**30, 1)}
+ step_time = time.perf_counter() - started
+ timing_local = {}
+ if timings is not None:
+ timing_local = timings.seconds()
+ host = timings.host_seconds()
+ for phase in ("prepare_total", "text_context", "video_preprocess", "video_vae"):
+ timing_local[f"{phase}_host"] = host.get(phase, 0.0)
+ return {
+ "loss": loss_mean,
+ "video_mse": video,
+ "action_mse": action,
+ "grad_norm": grad_norm,
+ **clipped,
+ "windows": windows * self.world_size,
+ "lr_trunk": consumed[0],
+ "lr_heads": consumed[1] if len(consumed) > 1 else None,
+ **{f"beta_{name}": beta for name, beta in betas.items()},
+ "step_time": step_time,
+ **({"_timing_local": timing_local} if timings else {}),
+ **peak,
+ }
+
+ def _check_gradients(self) -> None:
+ """Every trainable parameter must take part in the loss; otherwise freeze it explicitly.
+
+ Parameters without gradients would hold no optimizer state and make the checkpoint
+ incomplete; the trunk's image and audio streams are frozen through ``frozen_streams`` and
+ the conditioning final layers through ``freeze_conditioning_heads``.
+ """
+ missing = [n for n, p in self.policy.named_parameters() if p.requires_grad and p.grad is None]
+ if missing:
+ raise RuntimeError(
+ f"{len(missing)} trainable parameters received no gradient, e.g. {missing[:4]}; "
+ "add their streams to frozen_streams"
+ )
+
+ # ------------------------------------------------------------------ side effects
+ def _checkpoint(self) -> None:
+ started = time.perf_counter()
+ position = self.position.to_dict()
+ if position["batches_consumed"] == getattr(self, "_epoch_batches_per_rank", None):
+ position.update(epoch=position["epoch"] + 1, batches_consumed=0)
+ self.state.data["position"] = position
+ # A micro-batch prepared ahead of its update (``self._prepared``) already consumed the global generators
+ # (timesteps/noise with ``prefetch_randomness``, dropout/augmentation without window seeds). The resumed run
+ # prepares that batch again, so the checkpoint stores the generator states from before that prepare.
+ pending = getattr(self._prepared, "rng_before", None) if self._prepared is not None else None
+ path = save_checkpoint(
+ self.output_dir,
+ step=self.step,
+ model=self.policy,
+ optimizer=self.optimizer,
+ emas=self.emas,
+ state=self.state,
+ config=self.policy.config,
+ rng=rng_state(cpu=pending) if pending is not None else None,
+ )
+ seconds = time.perf_counter() - started
+ seconds_max = self._rank_max([seconds])[0] if self.timing_breakdown else None
+ if self.rank == 0:
+ self._log_line(
+ {
+ "event": "checkpoint",
+ "step": self.step,
+ "path": str(path),
+ "seconds": round(seconds, 1),
+ **({"seconds_rank_max": seconds_max} if self.timing_breakdown else {}),
+ }
+ )
+ if self.config.keep_checkpoints is not None:
+ removed = prune_checkpoints(
+ self.output_dir,
+ keep_last=self.config.keep_checkpoints,
+ keep_every=self.config.keep_every,
+ protect=self.step,
+ )
+ if removed:
+ self._log_line({"event": "prune", "removed_steps": removed})
+
+ def _log_line(self, record: dict[str, Any]) -> None:
+ if self.rank != 0:
+ return
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+ line = json.dumps({"time": time.time(), **record})
+ with (self.output_dir / "metrics.jsonl").open("a") as stream:
+ stream.write(line + "\n")
+ print(line, flush=True)
+
+
+class _PrepareThread:
+ """``trainer._prepare(batch)`` on a helper thread (CUDA device and encoder stream are thread-local).
+
+ The main thread meanwhile drives the backward pass, so kernel launches of both streams interleave in the
+ CUDA launch queue instead of the host blocking on one stream at a time. Exceptions propagate on
+ :meth:`result`."""
+
+ def __init__(self, trainer: Trainer, batch: dict[str, Any], timings: StepTimings | None):
+ import threading
+
+ self._trainer, self._batch, self._timings = trainer, batch, timings
+ self._result: Any = None
+ self._error: BaseException | None = None
+ self._thread = threading.Thread(target=self._run, name="prepare-next", daemon=True)
+ self._thread.start()
+
+ def _run(self) -> None:
+ try:
+ torch.cuda.set_device(self._trainer.device)
+ self._result = self._trainer._prepare(self._batch, self._timings)
+ except BaseException as error: # noqa: BLE001 - re-raised on the main thread
+ self._error = error
+
+ def result(self) -> Any:
+ self._thread.join()
+ if self._error is not None:
+ raise self._error
+ return self._result
+
+
+def _default_policy(config: PolicyConfig) -> nn.Module:
+ from ..policy import FluxActionPolicy
+
+ return FluxActionPolicy(config)
+
+
+def _import_dataset_builder(spec: str) -> Callable[..., Any]:
+ """Resolve "pkg.module:callable" (TrainConfig.dataset) to the callable."""
+ if ":" not in spec:
+ raise ValueError(f"dataset must be 'index' or 'pkg.module:callable', got {spec!r}")
+ module_name, attr = spec.split(":", 1)
+ return getattr(importlib.import_module(module_name), attr)
diff --git a/flux-umi/tests/conftest.py b/flux-umi/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..87399781f964d0b4ba4b690880789cca28bb4080
--- /dev/null
+++ b/flux-umi/tests/conftest.py
@@ -0,0 +1,98 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+import pytest
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from flux_action.config import PolicyConfig
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+
+TINY_DIT = {
+ "hidden_size": 64,
+ "num_heads": 2,
+ "depth": 1,
+ "depth_single_blocks": 1,
+ "axes_dim": [8, 8, 8, 8],
+ "context_in_dim": 32,
+}
+
+
+class FakeVideoVAE(nn.Module):
+ """Shape-only CPU fixture; does not establish real VAE parity."""
+
+ def __init__(self):
+ super().__init__()
+ self.register_buffer("proj", torch.randn(96, 3, generator=torch.Generator().manual_seed(0)) * 0.1)
+
+ def encode(self, video):
+ b, c, t, h, w = video.shape
+ x = video.float()[:, :, ::4]
+ tp = x.shape[2]
+ x = F.avg_pool2d(x.transpose(1, 2).reshape(-1, c, h, w), 32)
+ x = torch.einsum("nchw,oc->nohw", x, self.proj.float())
+ return x.reshape(b, tp, 96, h // 32, w // 32).transpose(1, 2)
+
+ def encode_task(self, video):
+ return self.encode(video)
+
+ def encode_frame(self, frame):
+ """The single-frame path of the real VAE; counted so tests can assert which path ran."""
+ self.frame_calls = getattr(self, "frame_calls", 0) + 1
+ return self.encode(frame[:, :, None])
+
+
+def tiny_config(**kwargs):
+ values = dict(
+ camera_layout="single",
+ camera_keys=("images.top",),
+ canvas_hw=(64, 96),
+ action_dim=6,
+ gripper_flip_dims=(),
+ dit_config=TINY_DIT,
+ torch_dtype="float32",
+ sampler="euler",
+ num_inference_steps=2,
+ guidance_scale=1.0,
+ sampler_shift=5.0,
+ augment=False,
+ )
+ values.update(kwargs)
+ return PolicyConfig(**values)
+
+
+def make_policy(config=None):
+ return FluxActionPolicy(
+ config or tiny_config(), video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+
+
+@pytest.fixture
+def batch():
+ rng = torch.Generator().manual_seed(42)
+ return {
+ "images.top": torch.rand(1, 33, 3, 64, 96, generator=rng),
+ "state": torch.rand(1, 6, generator=rng),
+ "action": torch.rand(1, 32, 6, generator=rng),
+ "task": ["move the object"],
+ }
+
+
+@pytest.fixture(autouse=True, scope="session")
+def cpu_threads():
+ previous = torch.get_num_threads()
+ torch.set_num_threads(2)
+ yield
+ torch.set_num_threads(previous)
diff --git a/flux-umi/tests/fixtures/so101_history/README.md b/flux-umi/tests/fixtures/so101_history/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..794aed88b1d121b8e75570b4b3c4a56e72d2fff3
--- /dev/null
+++ b/flux-umi/tests/fixtures/so101_history/README.md
@@ -0,0 +1,13 @@
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+SO-101历史输入测试包:8次观测、两张视觉快照和历史命令,预测42步、执行32步。权重与分位数由测试合成生成,不含已发布模型权重。
+
+---
+
+
+
+SO-101 history package schema: eight observations, two visual snapshots, past commands, predict 42 / execute 32. Model weights and quantiles are synthetic and generated by tests; no released model weights are included.
diff --git a/flux-umi/tests/fixtures/so101_history/config.json b/flux-umi/tests/fixtures/so101_history/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..221c06705efddeea8b82670001bc491d36dd5d4b
--- /dev/null
+++ b/flux-umi/tests/fixtures/so101_history/config.json
@@ -0,0 +1,131 @@
+{
+ "type": "flux3",
+ "n_obs_steps": 8,
+ "input_features": {
+ "observation.images.scene": {
+ "type": "VISUAL",
+ "shape": [
+ 3,
+ 256,
+ 256
+ ]
+ },
+ "observation.images.wrist": {
+ "type": "VISUAL",
+ "shape": [
+ 3,
+ 256,
+ 256
+ ]
+ },
+ "observation.state": {
+ "type": "STATE",
+ "shape": [
+ 6
+ ]
+ }
+ },
+ "output_features": {
+ "action": {
+ "type": "ACTION",
+ "shape": [
+ 6
+ ]
+ }
+ },
+ "device": "cuda",
+ "use_amp": false,
+ "use_peft": false,
+ "push_to_hub": false,
+ "repo_id": null,
+ "private": null,
+ "tags": null,
+ "license": null,
+ "pretrained_path": null,
+ "pretrained_revision": null,
+ "conditioning": "history",
+ "packer": null,
+ "condition_on_past_actions": true,
+ "action_representation": "delta",
+ "delta_absolute_dims": [
+ -1
+ ],
+ "text_fixed_length": 320,
+ "video_position_fps": 24.0,
+ "history_snapshots": 2,
+ "normalization_stats": null,
+ "normalization_clip": 6.0,
+ "separate_timesteps": true,
+ "video_logit_mean": 1.08,
+ "video_logit_std": 1.0,
+ "conditioning_noise_max": 0.2,
+ "loss_reduction": "modalities",
+ "action_channel_weights": [
+ 1.0,
+ 1.0,
+ 1.0,
+ 1.0,
+ 1.0,
+ 2.0
+ ],
+ "gradient_checkpointing": true,
+ "chunk_size": 42,
+ "n_action_steps": 32,
+ "fps": 30.0,
+ "camera_layout": "side_by_side",
+ "camera_keys": [
+ "observation.images.scene",
+ "observation.images.wrist"
+ ],
+ "canvas_hw": [
+ 256,
+ 512
+ ],
+ "action_modality": "action",
+ "action_scale": 2.0,
+ "gripper_flip_dims": [],
+ "use_relative_actions": false,
+ "relative_exclude_joints": [
+ "gripper"
+ ],
+ "action_feature_names": null,
+ "normalization_mapping": {
+ "VISUAL": "IDENTITY",
+ "STATE": "IDENTITY",
+ "ACTION": "IDENTITY"
+ },
+ "trunk_weights": null,
+ "video_vae_id": "video_vae.safetensors",
+ "text_encoder_id": "text_encoder",
+ "dit_config": null,
+ "attn_mode": "torch",
+ "dtype": "bfloat16",
+ "compile_model": false,
+ "sampler": "euler",
+ "num_inference_steps": 4,
+ "guidance_scale": 3.0,
+ "guidance_scale_action": null,
+ "sampler_shift": 6.93,
+ "inference_seed": 42,
+ "head_init_seed": 0,
+ "train_timestep_width": 0.75,
+ "train_timestep_shift": 42.0,
+ "action_loss_weight": 0.5,
+ "video_loss_weight": 1.0,
+ "caption_dropout": 0.1,
+ "augment": false,
+ "optimizer_lr": 0.0001,
+ "optimizer_lr_heads_multiplier": 5.0,
+ "optimizer_betas": [
+ 0.9,
+ 0.999
+ ],
+ "optimizer_eps": 1e-08,
+ "optimizer_weight_decay": 0.0,
+ "optimizer_grad_clip_norm": 1.0,
+ "scheduler_freeze_backbone_steps": 0,
+ "scheduler_warmup_steps": 0,
+ "scheduler_warmup_steps_heads": 0,
+ "scheduler_decay_steps": 0,
+ "scheduler_cooldown_steps": 0
+}
diff --git a/flux-umi/tests/fixtures/so101_history/policy_postprocessor.json b/flux-umi/tests/fixtures/so101_history/policy_postprocessor.json
new file mode 100644
index 0000000000000000000000000000000000000000..4169920c937ced96f0825cd042d04ed7a6981a75
--- /dev/null
+++ b/flux-umi/tests/fixtures/so101_history/policy_postprocessor.json
@@ -0,0 +1,24 @@
+{
+ "name": "policy_postprocessor",
+ "steps": [
+ {
+ "registry_name": "flux3_action_history_unnormalizer",
+ "config": {
+ "action_dim": 6,
+ "action_representation": "delta",
+ "absolute_dims": [
+ -1
+ ],
+ "normalization_clip": 6.0
+ },
+ "state_file": "policy_postprocessor_step_0_flux3_action_history_unnormalizer.safetensors"
+ },
+ {
+ "registry_name": "device_processor",
+ "config": {
+ "device": "cpu",
+ "float_dtype": null
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/flux-umi/tests/fixtures/so101_history/policy_preprocessor.json b/flux-umi/tests/fixtures/so101_history/policy_preprocessor.json
new file mode 100644
index 0000000000000000000000000000000000000000..b94d85b8648112b26880b07e683c201709f55278
--- /dev/null
+++ b/flux-umi/tests/fixtures/so101_history/policy_preprocessor.json
@@ -0,0 +1,65 @@
+{
+ "name": "policy_preprocessor",
+ "steps": [
+ {
+ "registry_name": "rename_observations_processor",
+ "config": {
+ "rename_map": {}
+ }
+ },
+ {
+ "registry_name": "to_batch_processor",
+ "config": {}
+ },
+ {
+ "registry_name": "device_processor",
+ "config": {
+ "device": "cuda",
+ "float_dtype": null
+ }
+ },
+ {
+ "registry_name": "flux3_observation_history_normalizer",
+ "config": {
+ "action_dim": 6,
+ "action_representation": "delta",
+ "absolute_dims": [
+ -1
+ ],
+ "normalization_clip": 6.0,
+ "n_obs_steps": 8,
+ "chunk_size": 42,
+ "camera_keys": [
+ "observation.images.scene",
+ "observation.images.wrist"
+ ],
+ "condition_on_past_actions": true
+ },
+ "state_file": "policy_preprocessor_step_3_flux3_observation_history_normalizer.safetensors"
+ },
+ {
+ "registry_name": "flux3_action_target_normalizer",
+ "config": {
+ "action_dim": 6,
+ "action_representation": "delta",
+ "absolute_dims": [
+ -1
+ ],
+ "normalization_clip": 6.0,
+ "n_obs_steps": 8,
+ "chunk_size": 42
+ },
+ "state_file": "policy_preprocessor_step_4_flux3_action_target_normalizer.safetensors"
+ },
+ {
+ "registry_name": "flux3_camera_resize",
+ "config": {
+ "camera_keys": [
+ "observation.images.scene",
+ "observation.images.wrist"
+ ],
+ "camera_layout": "side_by_side"
+ }
+ }
+ ]
+}
diff --git a/flux-umi/tests/synthetic_droid.py b/flux-umi/tests/synthetic_droid.py
new file mode 100644
index 0000000000000000000000000000000000000000..2028ded2df3ce9da84f0812212903bc09c85a990
--- /dev/null
+++ b/flux-umi/tests/synthetic_droid.py
@@ -0,0 +1,145 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Synthetic compact Cosmos3-DROID layout with real AV1 clips for the data-path tests."""
+
+import json
+from fractions import Fraction
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from flux_action.data.droid.cosmos import CAMERA_FEATURES, filter_key
+
+pa = pytest.importorskip("pyarrow") # the data extra; skip these tests without it
+pq = pytest.importorskip("pyarrow.parquet")
+
+FRAME_HW = (32, 64)
+FPS = 15
+
+
+def frame_image(episode: int, frame: int, camera: int, frame_hw=FRAME_HW) -> np.ndarray:
+ """Flat colors that survive AV1: red = episode, green = frame index, blue = camera."""
+ img = np.empty((*frame_hw, 3), np.uint8)
+ img[..., 0] = 30 + 50 * episode
+ img[..., 1] = (6 * frame) % 250
+ img[..., 2] = 60 + 60 * camera
+ return img
+
+
+def write_av1_clip(path, frames: np.ndarray, fps: int = FPS) -> None:
+ """Encode uint8 ``(N, H, W, 3)`` frames as AV1 with a keyframe every second frame."""
+ av = pytest.importorskip("av") # the data extra
+
+ n, h, w, _ = frames.shape
+ with av.open(str(path), "w") as container:
+ stream = container.add_stream("libsvtav1", rate=fps)
+ stream.width, stream.height, stream.pix_fmt = w, h, "yuv420p"
+ stream.options = {"g": "2", "preset": "12"}
+ for i in range(n):
+ frame = av.VideoFrame.from_ndarray(np.ascontiguousarray(frames[i]), format="rgb24").reformat(
+ format="yuv420p"
+ )
+ frame.pts, frame.time_base = i, Fraction(1, fps)
+ for packet in stream.encode(frame):
+ container.mux(packet)
+ for packet in stream.encode(None):
+ container.mux(packet)
+ with av.open(str(path)) as container: # the fixture must carry exact frame timestamps
+ stream = container.streams.video[0]
+ indices = [round(float(f.pts * stream.time_base) * fps) for f in container.decode(stream)]
+ assert indices == list(range(n)), indices[:5]
+
+
+def build_compact_dataset(root, episodes, frame_hw=FRAME_HW):
+ """``episodes``: dicts with ``n_frames``, ``caption`` and ``keep`` (list of [a, b) ranges or None).
+
+ Writes info.json, tasks/episodes/data parquet files, three concatenated AV1 files and the
+ keep-ranges filter. Returns the filter path.
+ """
+ root = Path(root)
+ for sub in ("success/meta/episodes/chunk-000", "success/data/chunk-000"):
+ (root / sub).mkdir(parents=True, exist_ok=True)
+ total = sum(e["n_frames"] for e in episodes)
+ info = {
+ "codebase_version": "v3.0",
+ "fps": FPS,
+ "total_episodes": len(episodes),
+ "total_frames": total,
+ "chunks_size": 1000,
+ "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet",
+ "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4",
+ }
+ (root / "success/meta/info.json").write_text(json.dumps(info))
+ captions = sorted({e["caption"] for e in episodes})
+ pq.write_table(
+ pa.Table.from_pylist([{"task_index": i, "task": c} for i, c in enumerate(captions)]),
+ root / "success/meta/tasks.parquet",
+ )
+ episode_rows, data_rows, keep, cursor = [], [], {}, 0
+ for e, episode in enumerate(episodes):
+ n, caption = episode["n_frames"], episode["caption"]
+ row = {
+ "episode_index": e,
+ "episode_id": f"lab/episode-{e}",
+ "tasks": [caption],
+ "length": n,
+ "data/chunk_index": 0,
+ "data/file_index": 0,
+ "dataset_from_index": cursor,
+ "dataset_to_index": cursor + n,
+ }
+ for feature in CAMERA_FEATURES.values():
+ row[f"videos/{feature}/chunk_index"] = 0
+ row[f"videos/{feature}/file_index"] = 0
+ row[f"videos/{feature}/from_timestamp"] = cursor / FPS
+ row[f"videos/{feature}/to_timestamp"] = (cursor + n) / FPS
+ episode_rows.append(row)
+ for i in range(n):
+ data_rows.append(
+ {
+ "episode_index": e,
+ "frame_index": i,
+ "index": cursor + i,
+ "timestamp": np.float32(i) / np.float32(FPS),
+ "task_index": captions.index(caption),
+ "action.joint_position": [float(e) + 100 + i / 1000] * 7,
+ "action.gripper_position": [0.75],
+ "observation.state.joint_positions": [float(e) + i / 1000] * 7,
+ "observation.state.gripper_position": [0.25],
+ }
+ )
+ if episode.get("keep") is not None:
+ keep[filter_key(row["episode_id"])] = episode["keep"]
+ cursor += n
+ pq.write_table(
+ pa.Table.from_pylist(episode_rows), root / "success/meta/episodes/chunk-000/file-000.parquet"
+ )
+ table = pa.Table.from_pylist(data_rows)
+ table = table.set_column(
+ table.schema.get_field_index("timestamp"),
+ "timestamp",
+ pa.array(table["timestamp"].to_numpy(), pa.float32()),
+ )
+ pq.write_table(table, root / "success/data/chunk-000/file-000.parquet")
+ for c, feature in enumerate(CAMERA_FEATURES.values()):
+ frames = np.stack(
+ [frame_image(e, i, c, frame_hw) for e, ep in enumerate(episodes) for i in range(ep["n_frames"])]
+ )
+ path = root / f"success/videos/{feature}/chunk-000/file-000.mp4"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ write_av1_clip(path, frames)
+ filter_path = root / "keep_ranges.json"
+ filter_path.write_text(json.dumps(keep))
+ return filter_path
diff --git a/flux-umi/tests/synthetic_lerobot.py b/flux-umi/tests/synthetic_lerobot.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b89c6b9955a347b6afb0ebb056dfc51293938cb
--- /dev/null
+++ b/flux-umi/tests/synthetic_lerobot.py
@@ -0,0 +1,217 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Synthetic LeRobot datasets (v2.1 and v3.0 layouts) with real AV1 clips for the data-path tests.
+
+Two cameras of different native sizes (``top`` 48x64, ``wrist`` 32x48), 6-dimensional state and action at
+30 Hz. Frame ``i`` of episode ``e`` holds ``state = e + i / 1000`` on the joints, ``action = state + 100 +
+i / 100`` (so consecutive deltas are ``0.011``), a constant gripper state 20 and a gripper command ``30 + i``.
+"""
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+from synthetic_droid import frame_image, write_av1_clip
+
+pa = pytest.importorskip("pyarrow") # the data extra; skip these tests without it
+pq = pytest.importorskip("pyarrow.parquet")
+
+FPS = 30
+DIM = 6
+CAMERAS = {"top": "observation.images.top", "wrist": "observation.images.front"}
+CAMERA_HW = {"top": (48, 64), "wrist": (32, 48)}
+JOINT_NAMES = [
+ "shoulder_pan.pos",
+ "shoulder_lift.pos",
+ "elbow_flex.pos",
+ "wrist_flex.pos",
+ "wrist_roll.pos",
+ "gripper.pos",
+]
+
+
+def _motion_frame(frame: int, spec: dict | None) -> tuple[float, float]:
+ """``(joint offset, gripper offset)`` of a frame: the default slow drift (1/1000 per frame), or, with a
+ spec, ``stride`` per frame up to ``freeze_from`` and constant afterwards (a dead stretch)."""
+ spec = spec or {}
+ effective = min(frame, spec["freeze_from"]) if "freeze_from" in spec else frame
+ return effective * spec.get("stride", 1 / 1000), float(effective)
+
+
+def state_row(episode: int, frame: int, spec: dict | None = None) -> list[float]:
+ joints, _ = _motion_frame(frame, spec)
+ return [float(episode) + joints] * (DIM - 1) + [20.0]
+
+
+def action_row(episode: int, frame: int, spec: dict | None = None) -> list[float]:
+ joints, gripper = _motion_frame(frame, spec)
+ return [float(episode) + 100 + joints + gripper / 100] * (DIM - 1) + [30.0 + gripper]
+
+
+def _features() -> dict:
+ features = {
+ "action": {"dtype": "float32", "shape": [DIM], "names": JOINT_NAMES},
+ "observation.state": {"dtype": "float32", "shape": [DIM], "names": JOINT_NAMES},
+ }
+ for stream, feature in CAMERAS.items():
+ h, w = CAMERA_HW[stream]
+ features[feature] = {
+ "dtype": "video",
+ "shape": [h, w, 3],
+ "names": ["height", "width", "channels"],
+ "info": {"video.height": h, "video.width": w, "video.codec": "av1", "video.fps": FPS},
+ }
+ for name in ("timestamp", "frame_index", "episode_index", "index", "task_index"):
+ features[name] = {"dtype": "float32" if name == "timestamp" else "int64", "shape": [1], "names": None}
+ return features
+
+
+def _data_rows(episodes, first_index=0, first_episode=0):
+ rows, cursor = [], first_index
+ for e, episode in enumerate(episodes, start=first_episode):
+ for i in range(episode["n_frames"]):
+ rows.append(
+ {
+ "action": action_row(e, i, episode),
+ "observation.state": state_row(e, i, episode),
+ "timestamp": np.float32(i) / np.float32(FPS),
+ "frame_index": i,
+ "episode_index": e,
+ "index": cursor + i,
+ "task_index": episode["task_index"],
+ }
+ )
+ cursor += episode["n_frames"]
+ return rows
+
+
+def _table(rows):
+ table = pa.Table.from_pylist(rows)
+ for name in ("action", "observation.state"):
+ column = pa.array([r[name] for r in rows], pa.list_(pa.float32(), DIM))
+ table = table.set_column(table.schema.get_field_index(name), name, column)
+ return table.set_column(
+ table.schema.get_field_index("timestamp"),
+ "timestamp",
+ pa.array(table["timestamp"].to_numpy(), pa.float32()),
+ )
+
+
+def _camera_frames(episodes, stream: str, camera_index: int) -> np.ndarray:
+ return np.stack(
+ [
+ frame_image(e, i, camera_index, CAMERA_HW[stream])
+ for e, episode in enumerate(episodes)
+ for i in range(episode["n_frames"])
+ ]
+ )
+
+
+def build_v3_dataset(root, episodes) -> Path:
+ """``episodes``: dicts with ``n_frames`` and ``caption``. Concatenated data and video files."""
+ root = Path(root)
+ for sub in ("meta/episodes/chunk-000", "data/chunk-000"):
+ (root / sub).mkdir(parents=True, exist_ok=True)
+ captions = sorted({e["caption"] for e in episodes})
+ for episode in episodes:
+ episode["task_index"] = captions.index(episode["caption"])
+ total = sum(e["n_frames"] for e in episodes)
+ info = {
+ "codebase_version": "v3.0",
+ "robot_type": "so101_follower",
+ "fps": FPS,
+ "total_episodes": len(episodes),
+ "total_frames": total,
+ "chunks_size": 1000,
+ "data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet",
+ "video_path": "videos/{video_key}/chunk-{chunk_index:03d}/file-{file_index:03d}.mp4",
+ "features": _features(),
+ }
+ (root / "meta/info.json").write_text(json.dumps(info))
+ pq.write_table(
+ pa.Table.from_pylist([{"task_index": i, "task": c} for i, c in enumerate(captions)]),
+ root / "meta/tasks.parquet",
+ )
+ episode_rows, cursor = [], 0
+ for e, episode in enumerate(episodes):
+ n = episode["n_frames"]
+ row = {
+ "episode_index": e,
+ "tasks": [episode["caption"]],
+ "length": n,
+ "data/chunk_index": 0,
+ "data/file_index": 0,
+ "dataset_from_index": cursor,
+ "dataset_to_index": cursor + n,
+ }
+ for feature in CAMERAS.values():
+ row[f"videos/{feature}/chunk_index"] = 0
+ row[f"videos/{feature}/file_index"] = 0
+ row[f"videos/{feature}/from_timestamp"] = cursor / FPS
+ row[f"videos/{feature}/to_timestamp"] = (cursor + n) / FPS
+ episode_rows.append(row)
+ cursor += n
+ pq.write_table(pa.Table.from_pylist(episode_rows), root / "meta/episodes/chunk-000/file-000.parquet")
+ pq.write_table(_table(_data_rows(episodes)), root / "data/chunk-000/file-000.parquet")
+ for c, (stream, feature) in enumerate(CAMERAS.items()):
+ path = root / f"videos/{feature}/chunk-000/file-000.mp4"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ write_av1_clip(path, _camera_frames(episodes, stream, c), fps=FPS)
+ return root
+
+
+def build_v21_dataset(root, episodes) -> Path:
+ """Same content in the v2.1 layout: one parquet and one mp4 per episode and camera, jsonl metadata."""
+ root = Path(root)
+ (root / "meta").mkdir(parents=True, exist_ok=True)
+ captions = sorted({e["caption"] for e in episodes})
+ for episode in episodes:
+ episode["task_index"] = captions.index(episode["caption"])
+ total = sum(e["n_frames"] for e in episodes)
+ info = {
+ "codebase_version": "v2.1",
+ "robot_type": "so101",
+ "fps": FPS,
+ "total_episodes": len(episodes),
+ "total_frames": total,
+ "total_tasks": len(captions),
+ "chunks_size": 1000,
+ "data_path": "data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
+ "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
+ "features": _features(),
+ }
+ (root / "meta/info.json").write_text(json.dumps(info))
+ (root / "meta/tasks.jsonl").write_text(
+ "".join(json.dumps({"task_index": i, "task": c}) + "\n" for i, c in enumerate(captions))
+ )
+ (root / "meta/episodes.jsonl").write_text(
+ "".join(
+ json.dumps({"episode_index": e, "tasks": [ep["caption"]], "length": ep["n_frames"]}) + "\n"
+ for e, ep in enumerate(episodes)
+ )
+ )
+ cursor = 0
+ for e, episode in enumerate(episodes):
+ rows = _data_rows([episode], first_index=cursor, first_episode=e)
+ path = root / f"data/chunk-000/episode_{e:06d}.parquet"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ pq.write_table(_table(rows), path)
+ for c, (stream, feature) in enumerate(CAMERAS.items()):
+ clip = root / f"videos/chunk-000/{feature}/episode_{e:06d}.mp4"
+ clip.parent.mkdir(parents=True, exist_ok=True)
+ frames = np.stack([frame_image(e, i, c, CAMERA_HW[stream]) for i in range(episode["n_frames"])])
+ write_av1_clip(clip, frames, fps=FPS)
+ cursor += episode["n_frames"]
+ return root
diff --git a/flux-umi/tests/test_cameras.py b/flux-umi/tests/test_cameras.py
new file mode 100644
index 0000000000000000000000000000000000000000..981e845b3d479489df200115726b8e37d661c81e
--- /dev/null
+++ b/flux-umi/tests/test_cameras.py
@@ -0,0 +1,113 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Camera layouts, camera-key hints, weight specs and the frozen components."""
+
+import pytest
+import torch
+import torch.nn.functional as F # noqa: N812
+from conftest import make_policy, tiny_config
+
+from flux_action.models.runtime import _looks_like_local_path, parse_weight_spec, resolve_weights
+from flux_action.processing import packing
+
+
+def test_grid_shape_is_near_square_and_wider_than_tall():
+ assert [packing.grid_shape(n) for n in range(1, 7)] == [(1, 1), (1, 2), (2, 2), (2, 2), (2, 3), (2, 3)]
+
+
+def test_side_by_side_and_grid_canvases():
+ cams = torch.rand(2, 1, 3, 48, 64)
+ canvas = packing.compose_canvas(cams, "side_by_side", (64, 128))
+ assert canvas.shape == (3, 1, 64, 128)
+ left = F.interpolate(cams[0], size=(64, 64), mode="bilinear", align_corners=False, antialias=True)
+ torch.testing.assert_close(canvas[:, :, :, :64].permute(1, 0, 2, 3), left * 2 - 1)
+ three = torch.rand(3, 1, 3, 48, 64)
+ grid = packing.compose_canvas(three, "grid", (64, 128)) # 2x2 grid of 32x64 cells, last cell black
+ assert grid.shape == (3, 1, 64, 128) and (grid[:, :, 32:, 64:] == -1).all()
+ cell = F.interpolate(three[2], size=(32, 64), mode="bilinear", align_corners=False, antialias=True)
+ torch.testing.assert_close(grid[:, :, 32:, :64].permute(1, 0, 2, 3), cell * 2 - 1)
+ assert packing.content_hw("grid", (64, 128)) == (64, 128) and packing.latent_hw(
+ "side_by_side", (64, 128)
+ ) == (2, 4)
+ with pytest.raises(ValueError, match="side_by_side layout needs two cameras"):
+ packing.compose_canvas(three, "side_by_side", (64, 128))
+ with pytest.raises(ValueError, match="unknown camera layout"):
+ packing.compose_canvas(three, "mosaic", (64, 128))
+
+
+def test_grid_policy_takes_mixed_resolutions_and_names_missing_cameras():
+ policy = make_policy(tiny_config(camera_layout="grid", camera_keys=("images.a", "images.b", "images.c")))
+ batch = {
+ "images.a": torch.rand(1, 3, 48, 64),
+ "images.b": (torch.rand(1, 3, 24, 32) * 255).to(torch.uint8),
+ "images.c": torch.rand(1, 3, 40, 40),
+ }
+ cams = policy._cameras(batch)
+ assert cams.shape == (1, 3, 1, 3, 48, 64) and cams.dtype == torch.float32
+ with pytest.raises(KeyError, match=r"images\."):
+ policy._cameras({"images.a": batch["images.a"]})
+ single = make_policy()
+ with pytest.raises(KeyError, match="wrist, left exterior, right exterior"):
+ make_policy(
+ tiny_config(
+ camera_layout="droid", camera_keys=("images.w", "images.l", "images.r"), canvas_hw=(544, 736)
+ )
+ )._cameras({})
+ assert single.config.camera_layout == "single"
+
+
+def test_frozen_components_are_unregistered_and_follow_moves():
+ policy = make_policy()
+ assert policy.frozen.video_vae is policy.video_vae and policy.frozen.text_encoder is policy.text_encoder
+ assert not policy.text_encoder.training and not any(
+ p.requires_grad for p in policy.text_encoder.parameters()
+ )
+ assert not any(k.startswith(("video_vae", "text_encoder", "frozen")) for k in policy.state_dict())
+ policy.train()
+ assert not policy.text_encoder.training # train() cannot reach the unregistered components
+ policy.to(torch.float32) # device / dtype moves are forwarded without error
+
+
+def test_weight_specs(tmp_path):
+ assert parse_weight_spec("org/repo") == ("org/repo", None, None)
+ assert parse_weight_spec("org/repo:temp/dit.safetensors@abc123") == (
+ "org/repo",
+ "temp/dit.safetensors",
+ "abc123",
+ )
+ assert parse_weight_spec("org/repo@main") == ("org/repo", None, "main")
+ with pytest.raises(ValueError, match="weight spec"):
+ parse_weight_spec("@abc")
+ local = tmp_path / "weights@odd:name.safetensors"
+ local.write_bytes(b"")
+ assert resolve_weights(str(local), "dit.safetensors") == str(local) # existing paths are never parsed
+
+
+def test_missing_local_weights_report_the_path_instead_of_a_hub_repo_id(tmp_path, monkeypatch):
+ """The usual first mistake is running a config before downloading its weights."""
+ monkeypatch.chdir(tmp_path) # the relative specs below must not resolve against the repository
+ for spec in (
+ "outputs/weights/flux-3-action-base.safetensors", # the path in configs/droid/train.json
+ str(tmp_path / "video_vae.safetensors"),
+ "./weights",
+ "outputs/weights/text_encoder",
+ ):
+ with pytest.raises(FileNotFoundError, match="no such file or directory"):
+ resolve_weights(spec, "dit.safetensors")
+
+
+def test_hub_specs_are_not_mistaken_for_local_paths():
+ """The guard must not intercept a repo_id that simply is not on disk."""
+ for spec in ("org/repo", "black-forest-labs/FLUX-3-action", "org/repo:temp/dit.safetensors@abc123"):
+ assert not _looks_like_local_path(parse_weight_spec(spec)[0])
diff --git a/flux-umi/tests/test_cosmos.py b/flux-umi/tests/test_cosmos.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a65a3cd4d20af28d20959d7e32aa37d35445c48
--- /dev/null
+++ b/flux-umi/tests/test_cosmos.py
@@ -0,0 +1,125 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+import json
+
+import numpy as np
+import pytest
+
+from flux_action.checkpoints.artifacts import sha256
+from flux_action.data.droid.cosmos import CAMERA_FEATURES, convert_episode, filter_key
+
+pa = pytest.importorskip("pyarrow") # the data extra; skip these tests without it
+pq = pytest.importorskip("pyarrow.parquet")
+
+
+@pytest.fixture
+def compact_source(tmp_path, monkeypatch):
+ root = tmp_path / "source"
+ (root / "success/meta/episodes/chunk-000").mkdir(parents=True)
+ (root / "success/data").mkdir()
+ info = {
+ "codebase_version": "v3.0",
+ "fps": 15,
+ "data_path": "data/rows.parquet",
+ "video_path": "videos/{video_key}.mp4",
+ }
+ (root / "success/meta/info.json").write_text(json.dumps(info))
+ pq.write_table(
+ pa.Table.from_pylist([{"task": "task", "task_index": 0}]), root / "success/meta/tasks.parquet"
+ )
+ row = {
+ "episode_index": 2,
+ "episode_id": "lab/episode",
+ "tasks": ["task"],
+ "length": 34,
+ "data/chunk_index": 0,
+ "data/file_index": 0,
+ "dataset_from_index": 100,
+ "dataset_to_index": 134,
+ }
+ for feature in CAMERA_FEATURES.values():
+ for key, value in [
+ ("chunk_index", 0),
+ ("file_index", 0),
+ ("from_timestamp", 10.0),
+ ("to_timestamp", 10.0 + 34 / 15),
+ ]:
+ row[f"videos/{feature}/{key}"] = value
+ p = root / f"success/videos/{feature}.mp4"
+ p.parent.mkdir(exist_ok=True)
+ p.write_bytes(b"fixture")
+ pq.write_table(pa.Table.from_pylist([row]), root / "success/meta/episodes/chunk-000/file-000.parquet")
+ rows = {
+ "episode_index": [2] * 34,
+ "frame_index": list(range(34)),
+ "index": list(range(100, 134)),
+ "timestamp": pa.array(np.arange(34, dtype=np.float32) / np.float32(15)),
+ "task_index": [0] * 34,
+ "action.joint_position": [[0.2] * 7] * 34,
+ "action.gripper_position": [[0.7]] * 34,
+ "observation.state.joint_positions": [[0.1] * 7] * 34,
+ "observation.state.gripper_position": [[0.3]] * 34,
+ }
+ pq.write_table(pa.table(rows), root / "success/data/rows.parquet")
+ (root / "filter.json").write_text(json.dumps({filter_key("lab/episode"): [[0, 34]]}))
+ lock = {
+ "format_version": 1,
+ "dataset_id": "nvidia/Cosmos3-DROID",
+ "dataset_revision": "a" * 40,
+ "filter_file": "filter.json",
+ "files": {str(p.relative_to(root)): sha256(p) for p in root.rglob("*") if p.is_file()},
+ }
+ path = tmp_path / "lock.json"
+ path.write_text(json.dumps(lock))
+
+ def decode(path, start, length):
+ assert start == 150 and length == 34
+ return np.zeros((length, 360, 640, 3), np.uint8)
+
+ monkeypatch.setattr("flux_action.data.droid.cosmos.decode_frames", decode)
+ return root, path, tmp_path / "output"
+
+
+def test_compact_episode_alignment(compact_source):
+ root, lock, output = compact_source
+ result = convert_episode(root, lock, 2, output)
+ assert result["n_valid_starts"] == 2
+ with np.load(output / "episode.npz") as arrays:
+ np.testing.assert_array_equal(arrays["state"][:, -1], np.full(34, 0.3, np.float32))
+ np.testing.assert_array_equal(arrays["action"][:, -1], np.full(34, 0.7, np.float32))
+ assert json.loads((output / "source.json").read_text())["source_lock_sha256"] == sha256(lock)
+
+
+def test_source_checksum_rejected(compact_source):
+ root, lock, output = compact_source
+ (root / "success/meta/info.json").write_text("{}")
+ with pytest.raises(ValueError, match="checksum"):
+ convert_episode(root, lock, 2, output)
+
+
+def test_missing_source_file_is_named(compact_source):
+ root, lock, output = compact_source
+ (root / "success/meta/info.json").unlink()
+ with pytest.raises(FileNotFoundError, match="success/meta/info.json"):
+ convert_episode(root, lock, 2, output)
+
+
+def test_missing_filter_episode_not_treated_as_valid(compact_source):
+ root, path, output = compact_source
+ (root / "filter.json").write_text("{}")
+ lock = json.loads(path.read_text())
+ lock["files"]["filter.json"] = sha256(root / "filter.json")
+ path.write_text(json.dumps(lock))
+ with pytest.raises(ValueError, match="no complete window"):
+ convert_episode(root, path, 2, output)
diff --git a/flux-umi/tests/test_data.py b/flux-umi/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..a41454bc6abce44f9fe227c632f1f764260e3904
--- /dev/null
+++ b/flux-umi/tests/test_data.py
@@ -0,0 +1,178 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+import json
+from random import Random
+
+import numpy as np
+import pytest
+import torch
+
+from flux_action.data.droid.episodes import (
+ load_window,
+ prepare_episode,
+ select_caption,
+ validate_arrays,
+ validate_episode,
+)
+from flux_action.data.schema import EpisodeMetadata
+from flux_action.data.windows import sample_episode_visits, select_window_start, valid_window_spans
+
+
+@pytest.mark.parametrize(
+ "n,ranges,expected",
+ [
+ (32, [(0, 32)], []),
+ (33, [(0, 33)], [(0, 1)]),
+ (34, [(0, 34)], [(0, 2)]),
+ (100, [(0, 34), (60, 100)], [(0, 2), (60, 8)]),
+ (33, [(-5, 50)], [(0, 1)]),
+ (100, [], []),
+ ],
+)
+def test_valid_boundaries(n, ranges, expected):
+ assert valid_window_spans(n, ranges) == expected
+
+
+def test_selection_weights_valid_starts_not_ranges():
+ # Probe every possible RNG offset: two starts in the first range, eight in the second.
+ class Offset:
+ def __init__(self, value):
+ self.value = value
+
+ def randrange(self, total):
+ assert total == 10
+ return self.value
+
+ assert [select_window_start(100, [(0, 34), (60, 100)], Offset(i)) for i in range(10)] == [
+ 0,
+ 1,
+ *range(60, 68),
+ ]
+
+
+def test_one_window_per_episode_visit_and_rng_resume():
+ short = EpisodeMetadata("short", "test", "train", 33, ((0, 33),), "a")
+ long = EpisodeMetadata("long", "test", "train", 200, ((0, 200),), "b")
+ visits = [short, long] * 4
+ rng = Random(42)
+ saved = rng.getstate()
+ chosen = list(sample_episode_visits(visits, rng))
+ assert [episode.episode_id for episode, _ in chosen] == ["short", "long"] * 4
+ rng.setstate(saved)
+ assert chosen == list(sample_episode_visits(visits, rng))
+
+
+@pytest.mark.parametrize("ranges", [None, [(0.5, 33)], [(False, 33)], [(10, 2)], [(0, 1, 2)]])
+def test_invalid_range_metadata(ranges):
+ with pytest.raises(ValueError):
+ valid_window_spans(33, ranges)
+
+
+def test_schema_rejects_overlap_and_convention():
+ with pytest.raises(ValueError, match="disjoint"):
+ EpisodeMetadata("e", "test", "train", 100, ((0, 50), (40, 90)), "a")
+ with pytest.raises(ValueError, match="closed-fraction"):
+ EpisodeMetadata("e", "test", "train", 33, ((0, 33),), "a", gripper_convention="open_fraction")
+
+
+@pytest.fixture
+def episode_input(tmp_path):
+ n = 34
+ metadata = EpisodeMetadata("fixture", "synthetic-v1", "test", n, ((0, n),), "move")
+ arrays = {
+ name: np.full((n, 360, 640, 3), i * 60, dtype=np.uint8)
+ for i, name in enumerate(("wrist", "left", "right"), 1)
+ }
+ arrays["timestamps"] = np.arange(n, dtype=np.float64) / 15
+ arrays["state"] = np.tile(np.arange(n, dtype=np.float32)[:, None], (1, 8))
+ arrays["action"] = arrays["state"] + 100
+ arrays["state"][:, -1] = 0.2
+ arrays["action"][:, -1] = 0.7
+ metadata_path = tmp_path / "metadata.json"
+ metadata_path.write_text(json.dumps(metadata.to_dict()))
+ arrays_path = tmp_path / "arrays.npz"
+ np.savez_compressed(arrays_path, **arrays)
+ return metadata, arrays, metadata_path, arrays_path
+
+
+def test_prepare_resume_and_alignment(episode_input, tmp_path):
+ metadata, arrays, metadata_path, arrays_path = episode_input
+ out = tmp_path / "prepared"
+ manifest = prepare_episode(metadata_path, arrays_path, out)
+ assert manifest["n_valid_starts"] == 2
+ assert prepare_episode(metadata_path, arrays_path, out) == manifest
+ assert validate_episode(out) == metadata
+ batch = load_window(out, 1)
+ assert batch["images.wrist"].shape == (1, 33, 3, 360, 640)
+ assert batch["images.wrist"][0, 0, 0, 0, 0] == pytest.approx(60 / 255)
+ assert batch["images.left"][0, 0, 0, 0, 0] == pytest.approx(120 / 255)
+ assert batch["images.right"][0, 0, 0, 0, 0] == pytest.approx(180 / 255)
+ assert batch["state"][0, 0] == 1
+ torch.testing.assert_close(batch["action"][0, :, 0], torch.arange(101, 133, dtype=torch.float32))
+ assert batch["state"][0, -1] == pytest.approx(0.2)
+ assert batch["action"][0, 0, -1] == pytest.approx(0.7) # no premature gripper flip
+ with pytest.raises(ValueError, match="valid window"):
+ load_window(out, 2)
+ with (out / "episode.npz").open("ab") as f:
+ f.write(b"corrupt")
+ with pytest.raises(ValueError, match="checksum"):
+ validate_episode(out)
+
+
+def test_caption_paraphrase_selection(episode_input, tmp_path):
+ metadata, _, metadata_path, arrays_path = episode_input
+ metadata_path.write_text(json.dumps({**metadata.to_dict(), "caption": "pick it up | grab it | take it"}))
+ out = tmp_path / "prepared"
+ prepare_episode(metadata_path, arrays_path, out)
+ assert load_window(out, 0)["task"] == ["pick it up"]
+ drawn = {load_window(out, 0, rng=Random(seed))["task"][0] for seed in range(20)}
+ assert drawn == {"pick it up", "grab it", "take it"}
+ assert select_caption("single") == "single"
+
+
+def test_bad_timestamps_and_gripper(episode_input):
+ metadata, arrays, _, _ = episode_input
+ arrays["timestamps"][5] += 0.01
+ with pytest.raises(ValueError, match="timestamps"):
+ validate_arrays(metadata, arrays)
+ arrays["timestamps"] = np.arange(metadata.n_frames) / 15
+ arrays["action"][0, -1] = 1.2
+ with pytest.raises(ValueError, match="gripper"):
+ validate_arrays(metadata, arrays)
+
+
+def test_prepared_droid_window_train_and_infer(episode_input, tmp_path):
+ from conftest import make_policy, tiny_config
+
+ _, _, metadata_path, arrays_path = episode_input
+ out = tmp_path / "prepared"
+ prepare_episode(metadata_path, arrays_path, out)
+ batch = load_window(out, 0)
+ config = tiny_config(
+ camera_layout="droid",
+ camera_keys=("images.wrist", "images.left", "images.right"),
+ canvas_hw=(544, 736),
+ action_dim=8,
+ gripper_flip_dims=(-1,),
+ )
+ policy = make_policy(config).train()
+ loss, info = policy(batch)
+ loss.backward()
+ assert torch.isfinite(loss) and info["n_valid_windows"] == 1
+ observation = {**batch, **{key: batch[key][:, 0] for key in config.camera_keys}}
+ chunk = policy.predict_action_chunk(observation)
+ assert chunk.shape == (1, 32, 8) and torch.isfinite(chunk).all()
+ flipped = policy._flip(batch["action"])
+ torch.testing.assert_close(flipped[..., -1], torch.full((1, 32), 0.3))
+ torch.testing.assert_close(policy._flip(flipped), batch["action"])
diff --git a/flux-umi/tests/test_droid_cli.py b/flux-umi/tests/test_droid_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d3e8b939f83d4bafc50e4d9554f992787770f2f
--- /dev/null
+++ b/flux-umi/tests/test_droid_cli.py
@@ -0,0 +1,157 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""The DROID entry point restores the root package's native config and verified weights."""
+
+import builtins
+import hashlib
+import json
+import sys
+
+import numpy as np
+import pytest
+import torch
+from conftest import FakeVideoVAE, make_policy, tiny_config
+from safetensors.torch import save_file
+
+from flux_action import cli
+from flux_action.config import DROID_INFERENCE_SETTINGS
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+
+
+def test_infer_help_does_not_require_serving_extras(monkeypatch, capsys):
+ original_import = builtins.__import__
+
+ def without_serving(name, *args, **kwargs):
+ if name.startswith(("flux_action.serving", "msgpack", "websockets")):
+ raise ModuleNotFoundError(f"serving extra unavailable: {name}")
+ return original_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", without_serving)
+ monkeypatch.setattr(sys, "argv", ["flux-action", "infer", "--help"])
+ with pytest.raises(SystemExit) as exit_info:
+ cli.main()
+ assert exit_info.value.code == 0
+ assert "--observation" in capsys.readouterr().out
+
+
+def test_delivered_weights_load_strictly_and_predict(tmp_path, monkeypatch):
+ reference = make_policy(
+ tiny_config(
+ **DROID_INFERENCE_SETTINGS,
+ camera_layout="droid",
+ camera_keys=("images.wrist", "images.left", "images.right"),
+ canvas_hw=(544, 736),
+ chunk_size=32,
+ fps=15.0,
+ action_scale=2.0,
+ action_parameterization="absolute",
+ action_normalization=None,
+ state_normalization=None,
+ single_frame_encode=False,
+ inference_seed=0,
+ action_dim=8,
+ action_modality="action_prediction_droid",
+ gripper_flip_dims=(-1,),
+ content_streams=("video", "video_cond"),
+ torch_dtype="bfloat16",
+ )
+ )
+ bundle = tmp_path
+ reference.save_pretrained(bundle)
+ native = bundle / "config.native.json"
+ (bundle / "config.json").rename(native)
+ (bundle / "config.json").write_text('{"type": "flux3"}')
+ manifest_path = bundle / "manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ manifest["sha256"][native.name] = hashlib.sha256(native.read_bytes()).hexdigest()
+ manifest_path.write_text(json.dumps(manifest))
+ weights = bundle / "model.safetensors"
+
+ restore = FluxActionPolicy.from_pretrained
+
+ def tiny_restore(directory, **kwargs):
+ return restore(directory, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32), **kwargs)
+
+ monkeypatch.setattr(FluxActionPolicy, "from_pretrained", tiny_restore)
+ loaded = FluxActionPolicy.from_pretrained(tmp_path)
+ for key, value in reference.state_dict().items():
+ torch.testing.assert_close(loaded.state_dict()[key], value, rtol=0, atol=0)
+ for key, value in DROID_INFERENCE_SETTINGS.items():
+ assert getattr(loaded.config, key) == value
+ for key in (
+ "camera_layout",
+ "camera_keys",
+ "canvas_hw",
+ "chunk_size",
+ "fps",
+ "action_scale",
+ "gripper_flip_dims",
+ "action_parameterization",
+ "action_normalization",
+ "state_normalization",
+ "single_frame_encode",
+ "inference_seed",
+ ):
+ assert getattr(loaded.config, key) == getattr(reference.config, key)
+ observation = tmp_path / "observation.npz"
+ np.savez(
+ observation,
+ **{
+ **{key: np.zeros((360, 640, 3), np.uint8) for key in reference.config.camera_keys},
+ "state": np.zeros(8, np.float32),
+ },
+ )
+ output = tmp_path / "inference"
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "flux-action",
+ "infer",
+ "--checkpoint",
+ str(tmp_path),
+ "--observation",
+ str(observation),
+ "--task",
+ "move",
+ "--output",
+ str(output),
+ "--device",
+ "cpu",
+ ],
+ )
+ cli.main()
+ actions = np.load(output / "actions.npy")
+ assert actions.shape == (1, 32, 8) and actions.dtype == np.float32 and np.isfinite(actions).all()
+ state = reference.state_dict()
+ state.pop(next(iter(state)))
+ save_file(state, weights)
+ manifest["sha256"][weights.name] = hashlib.sha256(weights.read_bytes()).hexdigest()
+ manifest_path.write_text(json.dumps(manifest))
+ with pytest.raises(RuntimeError, match="Missing key"):
+ FluxActionPolicy.from_pretrained(tmp_path)
+
+
+@pytest.mark.parametrize("missing", ["config.json", "manifest.json", "model.safetensors"])
+def test_missing_delivery_files_fail_before_model_loading(tmp_path, monkeypatch, missing):
+ make_policy().save_pretrained(tmp_path)
+ (tmp_path / missing).unlink()
+
+ def unexpected_load(*args, **kwargs):
+ pytest.fail("Must reject incomplete snapshots before loading the model or contacting the Hub")
+
+ monkeypatch.setattr(FluxActionPolicy, "__init__", unexpected_load)
+ with pytest.raises(FileNotFoundError, match=missing):
+ FluxActionPolicy.from_pretrained(tmp_path)
diff --git a/flux-umi/tests/test_history_inference.py b/flux-umi/tests/test_history_inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..2968503917f8d8ab1cbbde78dcecd91128e52391
--- /dev/null
+++ b/flux-umi/tests/test_history_inference.py
@@ -0,0 +1,141 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""History checkpoints: token contract, per-tick command feedback and export/reload."""
+
+import pytest
+import torch
+from conftest import FakeVideoVAE, make_policy, tiny_config
+
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+from flux_action.processing.history import observation_window, pack_conditioning
+
+
+def history_config(**kwargs):
+ return tiny_config(
+ **{
+ "inference_profile": "history",
+ "n_obs_steps": 8,
+ "history_snapshots": 2,
+ "condition_on_past_actions": True,
+ "chunk_size": 42,
+ "n_action_steps": 32,
+ "fps": 30.0,
+ "video_position_fps": 24.0,
+ "action_parameterization": "joint_delta",
+ "absolute_action_dims": (5,),
+ **kwargs,
+ }
+ )
+
+
+def observation(tick=0):
+ return {
+ "images.top": torch.full((1, 3, 64, 96), tick / 255),
+ "state": torch.full((1, 6), float(tick)),
+ "task": "move",
+ }
+
+
+def test_history_tokens_follow_snapshot_and_command_clocks():
+ config = history_config(
+ state_normalization={"q01": [0.0] * 6, "q99": [10.0] * 6},
+ action_normalization={"q01": [-2.0] * 6, "q99": [2.0] * 6},
+ )
+ states = torch.arange(8).float()[None, :, None].expand(1, 8, 6)
+ commands = states + 1
+ cameras = torch.zeros(1, 8, 3, 64, 96)
+ cameras[:, -1] = 1
+ vae = FakeVideoVAE()
+ cond = pack_conditioning(vae, cameras, states, commands, config)
+ assert vae.frame_calls == 2
+ assert cond["x_video_cond"].shape == (1, 12, 96)
+ assert cond["x_video_cond_ids"][0, :, 0].tolist() == [0] * 6 + [29] * 6
+ assert not torch.equal(cond["x_video_cond"][:, :6], cond["x_video_cond"][:, 6:])
+ ids = cond["x_action_cond_ids"][0]
+ assert ids[:, 0].tolist() == [-24, -20, -17, -14, -10, -7, -4, 0]
+ assert ids[:, -1].tolist() == [-1] * 8
+ expected_state = states / 5 - 1
+ torch.testing.assert_close(cond["x_action_cond"][..., 6:], expected_state, rtol=0, atol=0)
+ past = cond["x_action_cond"][..., :6]
+ assert (past[:, 0] == 0).all()
+ assert (past[:, 1:, :5] == 0.5).all() # consecutive command deltas, unscaled
+ torch.testing.assert_close(past[:, 1:, 5], commands[:, 1:, 5] / 2)
+
+
+def test_history_select_records_every_tick_and_only_executed_commands(monkeypatch):
+ policy = make_policy(history_config(n_action_steps=3))
+ windows = []
+
+ def predict(batch):
+ windows.append(
+ {key: value.clone() for key, value in batch.items() if isinstance(value, torch.Tensor)}
+ )
+ return torch.ones(1, 42, 6)
+
+ monkeypatch.setattr(policy, "predict_normalized_targets", predict)
+ for tick in range(7):
+ command = policy.select_action(observation(tick))
+ assert command[0, 0] == tick + 1
+ assert command[0, 5] == 1
+ command.fill_(-999) # callers must not corrupt the command history
+ assert len(windows) == 3
+ assert windows[1]["state"][0, :, 0].tolist() == [0, 0, 0, 0, 0, 1, 2, 3]
+ assert windows[1]["command_history"][0, :, 0].tolist() == [0, 0, 0, 0, 0, 1, 2, 3]
+ assert windows[2]["images.top"][0, :, 0, 0, 0].tolist() == pytest.approx(
+ [0, 0, 1 / 255, 2 / 255, 3 / 255, 4 / 255, 5 / 255, 6 / 255]
+ )
+ assert len(policy._action_queue) == 2 # unexecuted predictions do not enter history
+ policy.reset()
+ assert not policy._observation_history.observations and policy._last_command is None
+ assert policy.select_action(observation(10))[0, 0] == 11
+ assert (windows[-1]["command_history"] == 10).all()
+
+
+def test_history_predict_export_reload_and_explicit_window(tmp_path):
+ policy = make_policy(history_config())
+ assert policy.dit.emb_in["action_cond"].in_features == 12
+ captures = []
+ policy.dit.register_forward_pre_hook(lambda m, args, kwargs: captures.append(kwargs), with_kwargs=True)
+ obs = observation(3)
+ chunk = policy.predict_action_chunk(obs)
+ assert chunk.shape == (1, 42, 6) and torch.isfinite(chunk).all()
+ assert not policy._observation_history.observations # stateless prediction
+ first = captures[0]
+ assert first["x_video"].shape[1] == 11 * 6
+ assert first["x_video_ids"][0, ::6, 0].tolist() == [33, 50, 66, 83, 100, 116, 133, 150, 166, 183, 200]
+ assert first["x_action_ids"][0, :4, 0].tolist() == [0, 3, 6, 10]
+ assert first["ctx"].shape[1] == 320
+ explicit = observation_window(obs, policy.config)
+ torch.testing.assert_close(policy.predict_action_chunk(explicit), chunk, rtol=0, atol=0)
+ del explicit["command_history"]
+ with pytest.raises(ValueError, match="command_history"):
+ policy.predict_action_chunk(explicit)
+ policy.save_pretrained(tmp_path)
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ torch.testing.assert_close(restored.predict_action_chunk(obs), chunk, rtol=0, atol=0)
+ with pytest.raises(ValueError, match="training needs 50 frames"):
+ policy.prepare(obs)
+
+
+def test_history_requires_reset_after_batch_size_changes():
+ policy = make_policy(history_config())
+ policy.select_action(observation())
+ obs = observation()
+ obs["state"] = obs["state"].expand(2, -1)
+ obs["images.top"] = obs["images.top"].expand(2, -1, -1, -1)
+ with pytest.raises(ValueError, match="reset"):
+ policy.select_action(obs)
diff --git a/flux-umi/tests/test_history_training.py b/flux-umi/tests/test_history_training.py
new file mode 100644
index 0000000000000000000000000000000000000000..105e60d0db5e3a9cf1a4c14956bc260388195a6d
--- /dev/null
+++ b/flux-umi/tests/test_history_training.py
@@ -0,0 +1,146 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""History training boundaries, conditioning parity, loss, and backward execution."""
+
+import pytest
+import torch
+from conftest import make_policy, tiny_config
+
+from flux_action.processing import history, packing
+
+
+def history_config(**kwargs):
+ return tiny_config(
+ **{
+ "inference_profile": "history",
+ "n_obs_steps": 8,
+ "history_snapshots": 2,
+ "condition_on_past_actions": True,
+ "chunk_size": 42,
+ "n_action_steps": 32,
+ "fps": 30.0,
+ "action_parameterization": "joint_delta",
+ "absolute_action_dims": (-1,),
+ "caption_dropout": 0.0,
+ "separate_timesteps": True,
+ "conditioning_noise_max": 0.2,
+ "loss_reduction": "modalities",
+ "action_loss_weight": 0.5,
+ "action_channel_weights": [1.0, 1.0, 1.0, 1.0, 1.0, 2.0],
+ **kwargs,
+ }
+ )
+
+
+def batch():
+ rng = torch.Generator().manual_seed(24)
+ commands = torch.randn(2, 50, 6, generator=rng).cumsum(1)
+ return {
+ "images.top": torch.randint(256, (2, 50, 3, 64, 96), dtype=torch.uint8, generator=rng),
+ "state": torch.randn(2, 8, 6, generator=rng),
+ "command_history": commands[:, :8],
+ "action": commands[:, 8:],
+ "task": ["move the object", "move"],
+ "window_seed": torch.tensor([42, 43]),
+ }
+
+
+def test_history_training_matches_inference_conditioning_and_has_no_future_leak(monkeypatch):
+ policy = make_policy(history_config()).eval()
+ data = batch()
+ lengths = []
+ encode = policy.video_vae.encode_task
+ monkeypatch.setattr(
+ policy.video_vae, "encode_task", lambda clip: (lengths.append(clip.shape[2]), encode(clip))[1]
+ )
+ prepared = policy.prepare(data)
+ assert lengths == [1, 1, 1, 1, 42, 42]
+ assert all(ctx.shape[1] == 320 for ctx in prepared.ctxs)
+ streams = {
+ **history.pack_video(prepared.latents, policy.config),
+ **history.pack_actions(prepared.state, prepared.actions, policy.config),
+ }
+ assert streams["x_video"].shape == (2, 66, 96)
+ assert streams["x_video_cond"].shape == (2, 12, 96)
+ assert streams["x_action_cond"].shape == (2, 8, 12)
+ for i in range(2):
+ expected = history.pack_conditioning(
+ policy.video_vae,
+ data["images.top"][i : i + 1, :8],
+ data["state"][i : i + 1],
+ data["command_history"][i : i + 1],
+ policy.config,
+ )
+ for key, value in expected.items():
+ torch.testing.assert_close(streams[key][i : i + 1], value, rtol=0, atol=0)
+ assert streams["x_video_cond_ids"][0, ::6, 0].tolist() == [0, 29]
+ assert streams["x_video_ids"][0, ::6, 0].tolist() == [33, 50, 66, 83, 100, 116, 133, 150, 166, 183, 200]
+ assert streams["x_action_ids"][0, :4, 0].tolist() == [0, 3, 6, 10]
+ torch.testing.assert_close(
+ prepared.actions[:, 0, :5], data["action"][:, 0, :5] - data["command_history"][:, -1, :5]
+ )
+ torch.testing.assert_close(prepared.state[:, 0, :6], torch.zeros(2, 6))
+ altered = {**data, "images.top": data["images.top"].clone(), "action": data["action"] + 100}
+ altered["images.top"][:, 8:] = 255 - altered["images.top"][:, 8:]
+ again = policy.prepare(altered)
+ torch.testing.assert_close(prepared.latents[:, :, :2], again.latents[:, :, :2], rtol=0, atol=0)
+ torch.testing.assert_close(prepared.state, again.state, rtol=0, atol=0)
+ assert not torch.equal(prepared.latents[:, :, 2:], again.latents[:, :, 2:])
+
+
+def test_separate_noise_and_weighted_modality_loss_backward():
+ policy = make_policy(history_config()).train()
+ calls = []
+ policy.dit.register_forward_pre_hook(lambda m, a, k: calls.append(k), with_kwargs=True)
+ loss, metrics = policy(batch())
+ loss.backward()
+ assert torch.isfinite(loss) and metrics["n_valid_windows"] == 2
+ assert len(calls) == 1 and calls[0]["seqlens"]["x_action_cond"] == [8, 8]
+ assert calls[0]["x_video_cond_timesteps"].gt(0).all()
+ assert calls[0]["x_action_cond_timesteps"].eq(0).all()
+ assert calls[0]["x_video_timesteps"][0, 0] != calls[0]["x_action_timesteps"][0, 0]
+ assert policy.dit.final_layer["action"].linear.weight.grad.abs().sum() > 0
+ policy.eval()
+ policy(batch())
+ assert calls[-1]["x_video_cond_timesteps"].eq(0).all()
+
+
+def test_modality_loss_gripper_weight_and_mask():
+ pred = {"x_video": torch.full((1, 2, 96), 2.0), "x_action": torch.tensor([[[1.0, 3.0], [1.0, 3.0]]])}
+ target = {k: torch.zeros_like(v) for k, v in pred.items()}
+ result = packing.flow_loss(
+ pred, target, "action", 0.5, 1.0, reduction="modalities", channel_weights=[1.0, 2.0]
+ )
+ torch.testing.assert_close(result["loss"], torch.tensor(4.0 + 0.5 * (1.0 * 0.4 + 9.0 * 1.6) / 2))
+ torch.testing.assert_close(result["action_mse"], torch.tensor(5.0))
+ masked = packing.flow_loss(
+ pred,
+ target,
+ "action",
+ 0.5,
+ 1.0,
+ reduction="modalities",
+ channel_weights=[1.0, 2.0],
+ action_mask=torch.tensor([[1.0, 0.0]]),
+ )
+ torch.testing.assert_close(masked["loss"], torch.tensor(4.2))
+
+
+@pytest.mark.parametrize(
+ "settings",
+ [{"conditioning_noise_max": 1.1}, {"loss_reduction": "sum"}, {"action_channel_weights": [0.0] * 6}],
+)
+def test_invalid_history_loss_contract(settings):
+ with pytest.raises(ValueError):
+ history_config(**settings)
diff --git a/flux-umi/tests/test_hub.py b/flux-umi/tests/test_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..5380da224b460d8089ce3b7921b57d117998b720
--- /dev/null
+++ b/flux-umi/tests/test_hub.py
@@ -0,0 +1,108 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Pinned, selective downloads and strict native-policy restores from the Hub."""
+
+import fnmatch
+import sys
+from types import SimpleNamespace
+
+import pytest
+import torch
+from conftest import FakeVideoVAE, make_policy
+
+from flux_action.hub import resolve_policy_directory
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+
+
+@pytest.mark.parametrize("subfolder", [None, "variants/gd"])
+def test_hub_restore_downloads_only_the_selected_policy(tmp_path, monkeypatch, subfolder):
+ policy = make_policy()
+ package = tmp_path / subfolder if subfolder else tmp_path
+ policy.save_pretrained(package)
+ prefix = f"{subfolder}/" if subfolder else ""
+ files = [
+ "model.safetensors",
+ "config.native.json",
+ "variants/gd/model.safetensors",
+ "variants/gd/manifest.json",
+ "variants/sd/model.safetensors",
+ "variants/fp8r/model.safetensors",
+ "video_vae.safetensors",
+ "text_encoder/model.safetensors",
+ "policy_preprocessor_step_3_flux3_observation_history_normalizer.safetensors",
+ ]
+
+ def download(**kwargs):
+ assert kwargs["repo_id"] == "org/droid" and kwargs["revision"] == "immutable"
+ selected = {
+ name for name in files if any(fnmatch.fnmatchcase(name, p) for p in kwargs["allow_patterns"])
+ }
+ expected = (
+ {"variants/gd/model.safetensors", "variants/gd/manifest.json"}
+ if subfolder
+ else {files[0], files[1], files[-1]}
+ )
+ assert selected == expected
+ for name in ("model.safetensors", "config.json", "config.native.json", "manifest.json"):
+ assert prefix + name in kwargs["allow_patterns"]
+ return str(tmp_path)
+
+ monkeypatch.setitem(sys.modules, "huggingface_hub", SimpleNamespace(snapshot_download=download))
+ loaded = FluxActionPolicy.from_pretrained(
+ "org/droid",
+ revision="immutable",
+ subfolder=subfolder,
+ video_vae=FakeVideoVAE(),
+ text_encoder=MockTextEncoder(32),
+ )
+ assert loaded.config.to_dict() == policy.config.to_dict()
+ for name, value in policy.state_dict().items():
+ torch.testing.assert_close(value, loaded.state_dict()[name], rtol=0, atol=0)
+ assert resolve_policy_directory(tmp_path, subfolder=subfolder) == package
+
+
+@pytest.mark.parametrize("subfolder", ["../other", "/absolute", "variants/../../other"])
+def test_rejects_subfolders_outside_the_repository(tmp_path, subfolder):
+ with pytest.raises(ValueError, match="subfolder"):
+ resolve_policy_directory(tmp_path, subfolder=subfolder)
+
+
+def test_missing_local_path_and_local_revision_fail_without_hub_access(tmp_path):
+ with pytest.raises(FileNotFoundError):
+ resolve_policy_directory(tmp_path / "missing")
+ with pytest.raises(ValueError, match="revision"):
+ resolve_policy_directory(tmp_path, revision="ignored-revision")
+
+
+@pytest.mark.parametrize(
+ "source", ["outputs/missing-export", "runs/x/export", "export.safetensors", "./nope", "~/nope"]
+)
+def test_path_like_sources_are_missing_files_not_hub_repositories(tmp_path, monkeypatch, source):
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "outputs").mkdir()
+ # huggingface_hub is an optional extra (CI runs without it): stub the module so any Hub lookup fails loudly
+ hub_stub = SimpleNamespace(snapshot_download=lambda **k: pytest.fail("asked the Hub for a path"))
+ monkeypatch.setitem(sys.modules, "huggingface_hub", hub_stub)
+ with pytest.raises(FileNotFoundError, match="no such policy directory"):
+ resolve_policy_directory(source)
+
+
+def test_missing_local_text_encoder_directory_is_a_missing_file(tmp_path, monkeypatch):
+ from flux_action.models.text_encoder import load_text_encoder
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "outputs").mkdir()
+ with pytest.raises(FileNotFoundError, match="no such text encoder directory"):
+ load_text_encoder("outputs/weights/text_encoder")
diff --git a/flux-umi/tests/test_lerobot.py b/flux-umi/tests/test_lerobot.py
new file mode 100644
index 0000000000000000000000000000000000000000..f635932b73b8ae65681abd34a2e315e595c2547f
--- /dev/null
+++ b/flux-umi/tests/test_lerobot.py
@@ -0,0 +1,777 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""LeRobot index (v2.1 and v3.0), window streaming, the joint-delta action space with range normalization,
+camera dropout and the trainer over an indexed LeRobot dataset."""
+
+import json
+import sys
+
+import numpy as np
+import pytest
+import torch
+from conftest import TINY_DIT, FakeVideoVAE
+from synthetic_lerobot import CAMERAS, DIM, action_row, build_v3_dataset, build_v21_dataset, state_row
+
+from flux_action import cli
+from flux_action.config import PolicyConfig
+from flux_action.data.lerobot import index as lerobot_index
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+from flux_action.processing import normalization
+from flux_action.training.checkpoint import export_policy, latest_checkpoint
+from flux_action.training.data import WindowDataset, build_dataloader, load_manifest
+from flux_action.training.trainer import TrainConfig, Trainer
+
+EPISODES = [
+ {"n_frames": 40, "caption": "pick up the cube"},
+ {"n_frames": 38, "caption": "put the cube in the bowl"},
+ {"n_frames": 44, "caption": "pick up the cube"},
+ {"n_frames": 33, "caption": "too short: a window needs frame 1 .. 33"}, # excluded
+ {"n_frames": 41, "caption": "stack the cubes"},
+]
+FRAME_HW = (32, 32)
+TINY_POLICY = dict(
+ camera_layout="side_by_side",
+ camera_keys=["images.top", "images.wrist"],
+ canvas_hw=[64, 128],
+ action_dim=DIM,
+ gripper_flip_dims=[],
+ action_parameterization="joint_delta",
+ absolute_action_dims=[-1],
+ camera_dropout={"images.wrist": 0.2},
+ dit_config=TINY_DIT,
+ augment=False,
+ sampler="euler",
+ num_inference_steps=2,
+ guidance_scale=1.0,
+ sampler_shift=5.0,
+)
+
+
+def tiny_policy(config):
+ return FluxActionPolicy(config, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+def _index(root, builder):
+ source = builder(root / "source", [dict(e) for e in EPISODES])
+ out = root / "index"
+ summary = lerobot_index.index_dataset(source, out, CAMERAS)
+ return source, out, summary
+
+
+@pytest.fixture(scope="module")
+def v3(tmp_path_factory):
+ return _index(tmp_path_factory.mktemp("lerobot_v3"), build_v3_dataset)
+
+
+@pytest.fixture(scope="module")
+def v21(tmp_path_factory):
+ return _index(tmp_path_factory.mktemp("lerobot_v21"), build_v21_dataset)
+
+
+def reference_statistics():
+ """q01 / q99 of the joint-delta targets (first row zero, gripper absolute) and of the states."""
+ targets, states = [], []
+ for e, episode in enumerate(EPISODES):
+ if episode["n_frames"] < 34:
+ continue
+ actions = np.array([action_row(e, i) for i in range(episode["n_frames"])], np.float64)
+ delta = np.zeros_like(actions)
+ delta[1:] = actions[1:] - actions[:-1]
+ delta[:, -1] = actions[:, -1]
+ targets.append(delta)
+ states.append(np.array([state_row(e, i) for i in range(episode["n_frames"])], np.float64))
+ targets, states = np.concatenate(targets), np.concatenate(states)
+ return (
+ np.percentile(targets, 1, axis=0),
+ np.percentile(targets, 99, axis=0),
+ np.percentile(states, 1, axis=0),
+ np.percentile(states, 99, axis=0),
+ )
+
+
+@pytest.mark.parametrize("layout", ["v3", "v21"])
+def test_index_manifest_rows_and_statistics(layout, request):
+ source, out, summary = request.getfixturevalue(layout)
+ manifest = load_manifest(out / "manifest.json")
+ assert manifest["kind"] == "lerobot" and manifest["codebase_version"].startswith(
+ "v3" if layout == "v3" else "v2"
+ )
+ counts = manifest["counts"]
+ assert counts["listed"] == 5 and counts["eligible"] == 4 and counts["no_valid_window"] == 1
+ assert counts["rows_rejected"] == 0 and summary["rows_rejected"] == {}
+ assert [e["episode_index"] for e in manifest["episodes"]] == [0, 1, 2, 4]
+ assert counts["valid_starts_total"] == sum(n - 33 for n in (40, 38, 44, 41))
+ assert manifest["camera_order"] == ["top", "wrist"] and manifest["camera_hw"] == {
+ "top": [48, 64],
+ "wrist": [32, 48],
+ }
+ assert (manifest["state_dim"], manifest["action_dim"]) == (DIM, DIM) and manifest["action_prev"] is True
+ assert manifest["action_names"][-1] == "gripper.pos"
+ for episode, expected_from in zip(manifest["episodes"], [0, 40, 78, 155], strict=True):
+ assert episode["valid_ranges"] == [[1, episode["n_frames"]]]
+ assert episode["from_index"] == expected_from
+ for camera in ("top", "wrist"):
+ assert (source / episode["videos"][camera]["file"]).is_file()
+ assert episode["videos"][camera]["first_frame"] == (expected_from if layout == "v3" else 0)
+ rows = np.load(out / "rows.f32.npy", mmap_mode="r")
+ assert rows.shape == (manifest["total_frames"], 2 * DIM)
+ assert rows[78 + 5, :DIM].tolist() == pytest.approx(state_row(2, 5), rel=1e-6)
+ assert rows[78 + 5, DIM:].tolist() == pytest.approx(action_row(2, 5), rel=1e-6)
+ assert np.isnan(rows[122:155]).all() # the excluded episode's frames are never read
+ statistics = lerobot_index.load_statistics(out / "statistics.json")
+ q01, q99, s01, s99 = reference_statistics()
+ assert statistics["action"]["parameterization"] == "joint_delta"
+ assert statistics["action"]["absolute_dims"] == [DIM - 1] and statistics["clip"] == 6.0
+ # the rows are float32; the float64 reference agrees to that precision
+ assert statistics["action"]["q01"] == pytest.approx(q01.tolist(), rel=1e-3, abs=1e-4)
+ assert statistics["action"]["q99"] == pytest.approx(q99.tolist(), rel=1e-3, abs=1e-4)
+ assert statistics["state"]["q01"] == pytest.approx(s01.tolist(), rel=1e-5, abs=1e-4)
+ assert statistics["state"]["q99"] == pytest.approx(s99.tolist(), rel=1e-5, abs=1e-4)
+ assert statistics["frames"] == 40 + 38 + 44 + 41 and statistics["episodes"] == 4
+
+
+def test_both_layouts_yield_the_same_rows_and_statistics(v3, v21):
+ rows3 = np.load(v3[1] / "rows.f32.npy")
+ rows21 = np.load(v21[1] / "rows.f32.npy")
+ np.testing.assert_array_equal(np.nan_to_num(rows3), np.nan_to_num(rows21))
+ s3, s21 = (json.loads((out / "statistics.json").read_text()) for out in (v3[1], v21[1]))
+ assert s3["action"] == s21["action"] and s3["state"] == s21["state"]
+
+
+@pytest.mark.parametrize("layout", ["v3", "v21"])
+def test_windows_carry_previous_command_and_resized_frames(layout, request):
+ source, out, _ = request.getfixturevalue(layout)
+ manifest = load_manifest(out / "manifest.json")
+ dataset = WindowDataset(manifest, source, out / "rows.f32.npy", seed=3, frame_hw=FRAME_HW, decoder="pyav")
+ windows = list(dataset)
+ assert len(windows) == 4
+ for w in windows:
+ e, s = w["episode_index"], w["start"]
+ assert s >= 1
+ assert w["state"].tolist() == pytest.approx(state_row(e, s), rel=1e-6)
+ assert w["action"].shape == (32, DIM) and w["action"][0].tolist() == pytest.approx(
+ action_row(e, s), rel=1e-6
+ )
+ assert w["action_prev"].tolist() == pytest.approx(action_row(e, s - 1), rel=1e-6)
+ for camera, index in (("top", 0), ("wrist", 1)):
+ frames = w[f"images.{camera}"]
+ assert frames.dtype == torch.uint8 and frames.shape == (33, 3, *FRAME_HW) # both cameras rescaled
+ # flat colors survive AV1 and the rescale: red = episode, blue = camera
+ assert abs(int(frames[:, 0].float().mean()) - (30 + 50 * e)) <= 6
+ assert abs(int(frames[:, 2].float().mean()) - (60 + 60 * index)) <= 6
+ batch = next(iter(build_dataloader(dataset, in_process=True)))
+ assert batch["action_prev"].shape == (1, DIM) and batch["images.wrist"].shape == (1, 33, 3, *FRAME_HW)
+
+
+def test_policy_normalizes_deltas_and_integrates_back(v3):
+ source, out, _ = v3
+ manifest = load_manifest(out / "manifest.json")
+ statistics = lerobot_index.load_statistics(out / "statistics.json")
+ bounds = {k: {b: statistics[k][b] for b in ("q01", "q99")} for k in ("action", "state")}
+ config = PolicyConfig(
+ **{**TINY_POLICY, "action_normalization": bounds["action"], "state_normalization": bounds["state"]}
+ )
+ policy = tiny_policy(config).train()
+ dataset = WindowDataset(
+ manifest, source, out / "rows.f32.npy", seed=1, frame_hw=FRAME_HW, decoder="pyav", windows_per_rank=2
+ )
+ batch = next(iter(build_dataloader(dataset, in_process=True)))
+ prepared = policy.prepare(batch)
+ # reference: deltas from the previous command, gripper absolute, then range normalization with clip 6
+ q01, q99 = (np.array(bounds["action"][k]) for k in ("q01", "q99"))
+ span = np.where(q99 - q01 > 1e-6, q99 - q01, 1.0)
+ actions, previous = (
+ batch["action"].numpy().astype(np.float64),
+ batch["action_prev"].numpy().astype(np.float64),
+ )
+ shifted = np.concatenate([previous[:, None], actions[:, :-1]], axis=1)
+ targets = actions - shifted
+ targets[..., -1] = actions[..., -1]
+ expected = np.clip(2 * (targets - q01) / span - 1, -6, 6)
+ torch.testing.assert_close(prepared.actions.double(), torch.from_numpy(expected), rtol=1e-5, atol=1e-5)
+ s01, s99 = (np.array(bounds["state"][k]) for k in ("q01", "q99"))
+ s_span = np.where(s99 - s01 > 1e-6, s99 - s01, 1.0)
+ expected_state = np.clip(2 * (batch["state"].numpy().astype(np.float64) - s01) / s_span - 1, -6, 6)
+ torch.testing.assert_close(
+ prepared.state.double(), torch.from_numpy(expected_state), rtol=1e-5, atol=1e-5
+ )
+ loss, info = policy(batch, prepared=prepared)
+ assert torch.isfinite(loss) and info["n_valid_windows"] == 2
+ # inference undoes the normalization and integrates the deltas onto the observed state
+ observation = {
+ k: (v[:, 0] if k.startswith("images.") else v) for k, v in batch.items() if k != "action_prev"
+ }
+ policy.eval()
+ known = torch.linspace(-0.5, 0.5, 32 * DIM).reshape(32, DIM)
+ policy._sample = lambda cond, caption, seed: known.clone() # noqa: E731 (the DiT is not under test)
+ predicted = policy.predict_action_chunk(observation)
+ denormalized = (known.double() + 1) * torch.from_numpy(span) / 2 + torch.from_numpy(q01)
+ for i in range(2):
+ state = batch["state"][i].double()
+ expected_abs = state[None] + torch.cumsum(denormalized, dim=0)
+ expected_abs[:, -1] = denormalized[:, -1]
+ torch.testing.assert_close(predicted[i].double(), expected_abs, rtol=1e-5, atol=1e-4)
+ assert predicted.shape == (2, 32, DIM)
+ with pytest.raises(AssertionError, match="action_prev"):
+ policy.train().prepare({k: v for k, v in batch.items() if k != "action_prev"})
+
+
+def test_camera_dropout_is_deterministic_and_gray():
+ policy = tiny_policy(PolicyConfig(**{**TINY_POLICY, "camera_dropout": {"images.wrist": 1.0}}))
+ cams = torch.randint(0, 255, (2, 3, 3, 8, 8), dtype=torch.uint8)
+ dropped = FluxActionPolicy._drop_cameras(cams, [1])
+ assert torch.equal(dropped[0], cams[0]) and (dropped[1] == 128).all()
+ assert FluxActionPolicy._drop_cameras(cams, []) is cams
+ floats = FluxActionPolicy._drop_cameras(cams.float() / 255, [0])
+ assert torch.allclose(floats[0], torch.full_like(floats[0], 128 / 255))
+ # the draw comes from the window seed: same seed, same decision; the gray tile reaches the encoder
+ seen = []
+ policy._encode_windows = lambda cams, idx, device, generators, dropped=None, timings=None: (
+ seen.append(dropped),
+ torch.zeros(len(idx), 96, 9, 2, 4),
+ )[1] # noqa: E731
+ rng = torch.Generator().manual_seed(0)
+ batch = {
+ "images.top": torch.randint(0, 255, (3, 33, 3, 8, 8), dtype=torch.uint8, generator=rng),
+ "images.wrist": torch.randint(0, 255, (3, 33, 3, 8, 8), dtype=torch.uint8, generator=rng),
+ "state": torch.zeros(3, DIM),
+ "action": torch.zeros(3, 32, DIM),
+ "action_prev": torch.zeros(3, DIM),
+ "task": ["a", "b", "c"],
+ "window_seed": torch.tensor([11, 12, 13]),
+ }
+ policy.train().prepare(batch)
+ assert seen[-1] == [[1], [1], [1]]
+ half = tiny_policy(PolicyConfig(**{**TINY_POLICY, "camera_dropout": {"images.wrist": 0.5}}))
+ half._encode_windows = policy._encode_windows
+ half.train().prepare(batch)
+ first = seen[-1]
+ half.prepare(batch)
+ assert seen[-1] == first and any(d == [] for d in first) or seen[-1] == first
+ half.eval()
+ half.prepare(batch)
+ assert seen[-1] == [[], [], []] # no dropout outside training
+
+
+def make_config(source, out, output, **overrides):
+ values = dict(
+ source_root=str(source),
+ index_dir=str(out),
+ output_dir=str(output),
+ policy=TINY_POLICY,
+ steps=4,
+ cooldown_start=None,
+ cooldown_steps=0,
+ windows_per_rank=2,
+ num_workers=1,
+ in_process_loader=True,
+ decoder="pyav",
+ frame_hw=FRAME_HW,
+ param_dtype="float32",
+ compute_dtype="float32",
+ activation_checkpointing=False,
+ checkpoint_every=2,
+ log_every=1,
+ max_grad_norm=1e-3,
+ ema_sigma_rels=(0.10,),
+ reseed_on_resume=False, # the resume test compares an interrupted run with an uninterrupted one
+ )
+ values.update(overrides)
+ return TrainConfig(**values)
+
+
+def records(output):
+ return [json.loads(line) for line in (output / "metrics.jsonl").read_text().splitlines()]
+
+
+def test_trainer_runs_resumes_and_exports_with_the_index_bounds(v3, tmp_path):
+ source, out, _ = v3
+ output = tmp_path / "run"
+ result = Trainer(make_config(source, out, output), policy_factory=tiny_policy).run()
+ assert result["step"] == 4 and latest_checkpoint(output) == output / "step-4"
+ lines = records(output)
+ event = next(r for r in lines if r.get("event") == "normalization")
+ assert set(event["adopted"]) == {"action_normalization", "state_normalization"}
+ assert event["action_parameterization"] == "joint_delta" and event["absolute_action_dims"] == [DIM - 1]
+ steps = [r for r in lines if "loss" in r]
+ assert [r["step"] for r in steps] == [1, 2, 3, 4] and all(np.isfinite(r["loss"]) for r in steps)
+ assert all(0 < r["grad_clip"] < 1 and r["grad_norm"] > 1e-3 for r in steps) # clipped at 1e-3
+ statistics = lerobot_index.load_statistics(out / "statistics.json")
+ saved = json.loads((output / "step-4" / "config.json").read_text())
+ assert saved["action_normalization"]["q99"] == pytest.approx(statistics["action"]["q99"])
+ assert saved["state_normalization"]["q01"] == pytest.approx(statistics["state"]["q01"])
+ assert saved["action_parameterization"] == "joint_delta"
+ assert lerobot_index.normalize_dims(saved["absolute_action_dims"], DIM) == (DIM - 1,)
+ # exact resume reproduces the uninterrupted losses
+ part = tmp_path / "part"
+ Trainer(make_config(source, out, part, steps=2), policy_factory=tiny_policy).run()
+ Trainer(make_config(source, out, part, steps=4), policy_factory=tiny_policy).run()
+ assert [(r["step"], r["loss"]) for r in records(part) if "loss" in r] == [
+ (r["step"], r["loss"]) for r in steps
+ ]
+ # export carries the bounds and predicts absolute commands from a dataset window
+ export = export_policy(output / "step-4", tmp_path / "export", profile="ema_0p10")
+ assert export["profile"] == "ema_0p10"
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "export", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert restored.config.action_normalization["q01"] == pytest.approx(statistics["action"]["q01"])
+ manifest = load_manifest(out / "manifest.json")
+ dataset = WindowDataset(manifest, source, out / "rows.f32.npy", seed=9, frame_hw=FRAME_HW, decoder="pyav")
+ batch = next(iter(build_dataloader(dataset, in_process=True)))
+ observation = {
+ k: (v[:, 0] if k.startswith("images.") else v) for k, v in batch.items() if k != "action_prev"
+ }
+ chunk = restored.predict_action_chunk(observation)
+ assert chunk.shape == (1, 32, DIM) and torch.isfinite(chunk).all()
+ assert torch.equal(restored.select_action(observation), chunk[0, 0][None])
+
+
+def test_trainer_refuses_a_policy_that_disagrees_with_the_index(v3, tmp_path):
+ source, out, _ = v3
+ statistics = lerobot_index.load_statistics(out / "statistics.json")
+ other = {"q01": [0.0] * DIM, "q99": [1.0] * DIM}
+ with pytest.raises(ValueError, match="disagrees"):
+ Trainer(
+ make_config(source, out, tmp_path / "a", policy={**TINY_POLICY, "action_normalization": other}),
+ policy_factory=tiny_policy,
+ ).run()
+ with pytest.raises(ValueError, match="joint_delta"):
+ Trainer(
+ make_config(
+ source,
+ out,
+ tmp_path / "b",
+ policy={**TINY_POLICY, "action_parameterization": "absolute", "absolute_action_dims": []},
+ ),
+ policy_factory=tiny_policy,
+ ).run()
+ with pytest.raises(ValueError, match="absolute dims"):
+ Trainer(
+ make_config(source, out, tmp_path / "c", policy={**TINY_POLICY, "absolute_action_dims": []}),
+ policy_factory=tiny_policy,
+ ).run()
+ with pytest.raises(ValueError, match="action_dim"):
+ Trainer(
+ make_config(source, out, tmp_path / "d", policy={**TINY_POLICY, "action_dim": 8}),
+ policy_factory=tiny_policy,
+ ).run()
+ # the same bounds spelled out explicitly are accepted, and fields left out are taken from the index
+ explicit = {
+ **TINY_POLICY,
+ "action_normalization": {k: statistics["action"][k] for k in ("q01", "q99")},
+ "state_normalization": {k: statistics["state"][k] for k in ("q01", "q99")},
+ }
+ del explicit["absolute_action_dims"]
+ Trainer(
+ make_config(source, out, tmp_path / "e", policy=explicit, steps=1), policy_factory=tiny_policy
+ ).run()
+
+
+def test_policy_normalization_math():
+ cfg = PolicyConfig(
+ action_dim=6, gripper_flip_dims=(), action_normalization={"q01": [0] * 6, "q99": [2] * 6}
+ )
+ assert cfg.action_normalization == {"q01": [0.0] * 6, "q99": [2.0] * 6}
+ x = torch.tensor([[0.0, 1.0, 2.0, 4.0, -4.0, 1.0]])
+ normalized = normalization.normalize(x, cfg.action_normalization, cfg.normalization_clip)
+ assert normalized.tolist() == [[-1.0, 0.0, 1.0, 3.0, -5.0, 0.0]]
+ torch.testing.assert_close(normalization.denormalize(normalized, cfg.action_normalization), x)
+ degenerate = {"q01": [1.0] * 6, "q99": [1.0] * 6} # a channel that never moved keeps span 1
+ assert normalization.normalize(torch.full((1, 6), 1.5), degenerate, 6.0).tolist() == [[0.0] * 6]
+
+
+def test_index_lerobot_command(v3, tmp_path, monkeypatch, capsys):
+ source = v3[0]
+ out = tmp_path / "cli_index"
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "flux-action",
+ "index-lerobot",
+ "--source-root",
+ str(source),
+ "--output-dir",
+ str(out),
+ "--camera",
+ "top=observation.images.top",
+ "--camera",
+ "wrist=observation.images.front",
+ "--dataset-id",
+ "lab/synthetic",
+ ],
+ )
+ cli.main()
+ result = json.loads(capsys.readouterr().out)
+ assert result["counts"]["eligible"] == 4 and result["action"]["parameterization"] == "joint_delta"
+ manifest = load_manifest(out / "manifest.json")
+ assert manifest["dataset_id"] == "lab/synthetic" and (out / "statistics.json").is_file()
+ assert (out / "rows.f32.npy").is_file()
+
+
+MOTION_EPISODES = [
+ {"n_frames": 120, "caption": "moving then still", "stride": 1.0, "freeze_from": 30},
+ {"n_frames": 120, "caption": "never moves", "stride": 0.0},
+ {"n_frames": 200, "caption": "moving throughout", "stride": 1.0},
+ {"n_frames": 80, "caption": "held out", "stride": 1.0},
+]
+
+
+@pytest.fixture(scope="module")
+def curated(tmp_path_factory):
+ root = tmp_path_factory.mktemp("lerobot_curated")
+ source = build_v3_dataset(root / "source", [dict(e) for e in MOTION_EPISODES])
+ out = root / "index"
+ summary = lerobot_index.index_dataset(source, out, CAMERAS, val_episodes=1, strip_dead_windows=0.6)
+ return source, out, summary
+
+
+def test_dead_window_filter_and_validation_split(curated):
+ source, out, summary = curated
+ manifest = load_manifest(out / "manifest.json")
+ counts = manifest["counts"]
+ assert counts["dead_static"] == 1 and counts["dead_long"] == 0 and counts["dead_no_window"] == 0
+ assert [e["episode_index"] for e in manifest["episodes"]] == [0, 2, 3]
+ still, moving, held = manifest["episodes"]
+ # the state freezes at frame 30 (frame 30 itself still moved into place), so frames 31.. are dead; a
+ # 33-frame window from s holds s + 2 dead frames -> s <= 17 keeps at most 60% dead
+ assert still["valid_ranges"] == [[1, 50]] and still["n_valid_starts"] == 17
+ assert moving["valid_ranges"] == [[1, 200]] and moving["n_valid_starts"] == 200 - 33
+ assert counts["dead_starts_removed"] == (120 - 33) - 17
+ assert (still["split"], moving["split"], held["split"]) == ("train", "train", "val")
+ assert counts["train_episodes"] == 2 and counts["val_episodes"] == 1
+ assert manifest["dead_window_filter"]["max_dead_fraction"] == 0.6
+ train = WindowDataset(manifest, source, out / "rows.f32.npy", seed=1, frame_hw=FRAME_HW, decoder="pyav")
+ assert [e["episode_index"] for e in train.episodes] == [0, 2]
+ assert train.valid_starts(0) == list(range(1, 18))
+ for w in train:
+ if w["episode_index"] == 0:
+ assert 1 <= w["start"] <= 17
+ val = WindowDataset(
+ manifest, source, out / "rows.f32.npy", seed=1, frame_hw=FRAME_HW, decoder="pyav", split="val"
+ )
+ assert [e["episode_index"] for e in val.episodes] == [3]
+ everything = WindowDataset(
+ manifest, source, out / "rows.f32.npy", seed=1, frame_hw=FRAME_HW, decoder="pyav", split=None
+ )
+ assert len(everything.episodes) == 3
+ # statistics: over every kept episode (train and val), as the corpus builder computed them
+ statistics = lerobot_index.load_statistics(out / "statistics.json")
+ assert statistics["episodes"] == 3 and statistics["frames"] == 120 + 200 + 80
+ assert statistics["action"]["q99"][0] == pytest.approx(1.01, abs=1e-3) # stride 1 + gripper/100 coupling
+
+
+def test_dead_mask_definition():
+ fps = 30
+ states = np.zeros((300, DIM))
+ states[:100, 0] = np.arange(100) * 1.0 # moving for 100 frames, then holding still for 200 (>= 2 s)
+ states[100:, 0] = 99.0
+ mask, moving = lerobot_index.dead_mask(states, fps)
+ assert moving == pytest.approx(100 / 300) and not mask[:100].any() and mask[100:].all()
+ short = np.zeros((100, DIM))
+ short[::2, 0] = 1.0 # alternating: never still for 2 s
+ mask, _ = lerobot_index.dead_mask(short, fps)
+ assert not mask.any()
+ assert lerobot_index._ranges_of_starts([1, 2, 3, 7, 8], 32) == [[1, 36], [7, 41]]
+
+
+def test_visits_per_epoch_adds_windows_deterministically(v3):
+ source, out, _ = v3
+ manifest = load_manifest(out / "manifest.json")
+ common = dict(seed=5, frame_hw=FRAME_HW, decoder="pyav")
+ once = list(WindowDataset(manifest, source, out / "rows.f32.npy", **common))
+ thrice = WindowDataset(manifest, source, out / "rows.f32.npy", visits_per_epoch=3, **common)
+ assert thrice.n_positions == 12 and thrice.batches_per_rank == 12
+ windows = list(thrice)
+ key = lambda w: (w["episode_index"], w["start"], w["window_seed"]) # noqa: E731
+ assert len(windows) == 12 and {key(w) for w in once} <= {key(w) for w in windows}
+ assert len({key(w) for w in windows}) == 12 # every visit draws its own start and seed
+ again = list(WindowDataset(manifest, source, out / "rows.f32.npy", visits_per_epoch=3, **common))
+ assert [key(w) for w in again] == [key(w) for w in windows]
+ with pytest.raises(ValueError, match="visits_per_epoch"):
+ WindowDataset(manifest, source, out / "rows.f32.npy", windows_per_rank=8, **common)
+ WindowDataset(manifest, source, out / "rows.f32.npy", windows_per_rank=8, visits_per_epoch=2, **common)
+ with pytest.raises(ValueError, match="visits_per_epoch"):
+ TrainConfig(source_root="s", index_dir="i", output_dir="o", visits_per_epoch=0)
+
+
+def test_gray_camera_stream(tmp_path):
+ source = build_v3_dataset(tmp_path / "source", [dict(e) for e in EPISODES[:2]])
+ out = tmp_path / "index"
+ lerobot_index.index_dataset(source, out, {"top": CAMERAS["top"], "wrist": lerobot_index.GRAY})
+ manifest = load_manifest(out / "manifest.json")
+ assert manifest["cameras"] == {"top": CAMERAS["top"], "wrist": "gray"}
+ assert manifest["camera_hw"] == {"top": [48, 64], "wrist": None}
+ assert all(e["videos"]["wrist"] is None for e in manifest["episodes"])
+ dataset = WindowDataset(manifest, source, out / "rows.f32.npy", seed=1, frame_hw=FRAME_HW, decoder="pyav")
+ window = next(iter(dataset))
+ assert window["images.wrist"].shape == (33, 3, *FRAME_HW) and (window["images.wrist"] == 128).all()
+ assert window["images.top"].shape == (33, 3, *FRAME_HW) and not (window["images.top"] == 128).all()
+ policy = tiny_policy(PolicyConfig(**TINY_POLICY)).train()
+ batch = next(iter(build_dataloader(dataset, in_process=True)))
+ loss, info = policy(batch)
+ assert torch.isfinite(loss) and info["n_valid_windows"] == 1
+ with pytest.raises(ValueError, match="at least one camera must be a video"):
+ lerobot_index.build_manifest(source, {"top": lerobot_index.GRAY})
+
+
+def test_evaluate_export_scores_held_out_windows(curated, tmp_path, monkeypatch, capsys):
+ from flux_action.inference.evaluate import evaluate_policy, spread
+
+ assert (
+ spread(10, 4) == [0, 3, 6, 9] and spread(1, 4) == [0] and spread(0, 3) == [] and spread(5, 1) == [0]
+ )
+ source, out, _ = curated
+ statistics = lerobot_index.load_statistics(out / "statistics.json")
+ config = PolicyConfig(
+ **{
+ **TINY_POLICY,
+ "action_normalization": {k: statistics["action"][k] for k in ("q01", "q99")},
+ "state_normalization": {k: statistics["state"][k] for k in ("q01", "q99")},
+ }
+ )
+ policy = tiny_policy(config).eval()
+ policy.save_pretrained(tmp_path / "export")
+ report = evaluate_policy(policy, source, out, windows_per_episode=3, frame_hw=FRAME_HW)
+ assert report["split"] == "val" and report["episodes"] == 1 and report["n_windows"] == 3
+ assert [w["start"] for w in report["windows"]] == [1, 24, 47] # spread over the 47 allowed starts
+ assert np.isfinite(report["action_mse_normalized"]) and np.isfinite(report["action_mse_raw"])
+ assert len(report["action_mse_raw_per_channel"]) == DIM
+ # the recorded targets integrate back onto the command before the window exactly; onto the observed
+ # state (the deployment convention) they carry the state-vs-command offset of the first command
+ manifest = load_manifest(out / "manifest.json")
+ dataset = WindowDataset(
+ manifest, source, out / "rows.f32.npy", seed=0, frame_hw=FRAME_HW, decoder="pyav", split="val"
+ )
+ batch = next(iter(build_dataloader(dataset, in_process=True)))
+ recorded = policy.training_targets(batch)
+ torch.testing.assert_close(
+ policy.actions_from_targets(recorded, batch["action_prev"]),
+ batch["action"].float(),
+ rtol=1e-4,
+ atol=1e-3,
+ )
+ onto_state = policy.actions_from_targets(recorded, batch["state"])
+ offset = (batch["action_prev"] - batch["state"])[:, None, :-1]
+ torch.testing.assert_close(
+ onto_state[..., :-1], batch["action"].float()[..., :-1] - offset, rtol=1e-4, atol=1e-3
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "flux-action",
+ "evaluate",
+ "--checkpoint",
+ str(tmp_path),
+ "--subfolder",
+ "export",
+ "--source-root",
+ str(source),
+ "--index-dir",
+ str(out),
+ "--device",
+ "cpu",
+ "--frame-hw",
+ "32,32",
+ "--windows-per-episode",
+ "2",
+ "--setting",
+ "num_inference_steps=1",
+ "--output",
+ str(tmp_path / "report.json"),
+ ],
+ )
+ restore = FluxActionPolicy.from_pretrained # the module attribute is this very class: keep the original
+ monkeypatch.setattr(
+ "flux_action.inference.evaluate.FluxActionPolicy.from_pretrained",
+ lambda path, video_vae=None, text_encoder=None, device="cpu": restore(
+ path, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32), device=device
+ ),
+ )
+ cli.main()
+ printed = json.loads(capsys.readouterr().out)
+ saved = json.loads((tmp_path / "report.json").read_text())
+ assert (
+ printed["n_windows"] == 2
+ and saved["inference"]["num_inference_steps"] == 1
+ and len(saved["windows"]) == 2
+ )
+ assert saved["checkpoint_manifest"]["kind"] == "policy_export"
+
+
+def test_trainer_requires_statistics_before_model_construction(v3, tmp_path):
+ source, index, _ = v3
+ copied = tmp_path / "index"
+ copied.mkdir()
+ for name in ("manifest.json", "rows.f32.npy"):
+ (copied / name).write_bytes((index / name).read_bytes())
+ with pytest.raises(FileNotFoundError, match="normalization statistics"):
+ Trainer(make_config(source, copied, tmp_path / "run"), policy_factory=tiny_policy).build()
+
+
+@pytest.mark.parametrize("change", ["statistics", "cameras", "dataset"])
+def test_resume_rejects_changed_contract_before_restoring_weights(v3, tmp_path, monkeypatch, change):
+ source, index, _ = v3
+ copied = tmp_path / "index"
+ copied.mkdir()
+ for name in ("manifest.json", "rows.f32.npy", "statistics.json"):
+ (copied / name).write_bytes((index / name).read_bytes())
+ output = tmp_path / "run"
+ Trainer(make_config(source, copied, output, steps=2), policy_factory=tiny_policy).run()
+ config = make_config(source, copied, output)
+ if change == "statistics":
+ path = copied / "statistics.json"
+ data = json.loads(path.read_text())
+ data["action"]["q99"][0] += 10
+ path.write_text(json.dumps(data))
+ elif change == "cameras":
+ config.policy = {**TINY_POLICY, "camera_keys": list(reversed(TINY_POLICY["camera_keys"]))}
+ else:
+ path = copied / "manifest.json"
+ data = json.loads(path.read_text())
+ data["dataset_revision"] = "different-revision"
+ path.write_text(json.dumps(data))
+
+ def unexpected_restore(*args, **kwargs):
+ pytest.fail("contract must be checked before model/optimizer restoration")
+
+ monkeypatch.setattr("flux_action.training.trainer.load_checkpoint", unexpected_restore)
+ with pytest.raises(ValueError, match="policy/data contract"):
+ Trainer(config, policy_factory=tiny_policy).build()
+
+
+@pytest.mark.parametrize("layout", ["v3", "v21"])
+def test_history_windows_align_states_preceding_commands_and_episode_boundaries(layout, request):
+ source, out, _ = request.getfixturevalue(layout)
+ dataset = WindowDataset(
+ load_manifest(out / "manifest.json"),
+ source,
+ out / "rows.f32.npy",
+ seed=3,
+ frame_hw=FRAME_HW,
+ decoder="pyav",
+ n_obs_steps=8,
+ )
+ assert {e["episode_index"] for e in dataset.episodes} == {2, 4} # shorter episodes cannot supply history
+ for position, episode in enumerate(dataset.episodes):
+ assert dataset.valid_starts(position)[0] == 8
+ with pytest.raises(ValueError, match="allowed window start"):
+ dataset.window_at(position, 7)
+ for start in dataset.valid_starts(position):
+ item = dataset.window_at(position, start)
+ e = episode["episode_index"]
+ torch.testing.assert_close(
+ item["state"],
+ torch.tensor([state_row(e, f) for f in range(start - 7, start + 1)], dtype=torch.float32),
+ )
+ torch.testing.assert_close(
+ item["command_history"],
+ torch.tensor([action_row(e, f) for f in range(start - 8, start)], dtype=torch.float32),
+ )
+ torch.testing.assert_close(item["action_prev"], item["command_history"][-1])
+ assert item["action"][0].tolist() == pytest.approx(action_row(e, start), rel=1e-6)
+ assert item["images.top"].shape == (40, 3, *FRAME_HW)
+
+
+def test_history_trainer_resume_and_offline_evaluation(v3, tmp_path, monkeypatch):
+ from flux_action.inference.evaluate import evaluate_policy
+
+ source, out, _ = v3
+ fields = {
+ **TINY_POLICY,
+ "inference_profile": "history",
+ "n_obs_steps": 8,
+ "history_snapshots": 2,
+ "condition_on_past_actions": True,
+ "separate_timesteps": True,
+ "conditioning_noise_max": 0.2,
+ "loss_reduction": "modalities",
+ "action_loss_weight": 0.5,
+ "action_channel_weights": [1.0, 1.0, 1.0, 1.0, 1.0, 2.0],
+ }
+ full = Trainer(make_config(source, out, tmp_path / "full", policy=fields), policy_factory=tiny_policy)
+ full.run()
+ Trainer(
+ make_config(source, out, tmp_path / "split", policy=fields, steps=2), policy_factory=tiny_policy
+ ).run()
+ resumed = Trainer(make_config(source, out, tmp_path / "split", policy=fields), policy_factory=tiny_policy)
+ resumed.run()
+ assert resumed.state.extra["resumes"][-1]["mode"] == "exact"
+ for key, value in full.policy.state_dict().items():
+ torch.testing.assert_close(resumed.policy.state_dict()[key], value, rtol=0, atol=0)
+ for key, ema in full.emas.items():
+ for actual, expected in zip(resumed.emas[key].shadow, ema.shadow, strict=True):
+ torch.testing.assert_close(actual, expected, rtol=0, atol=0)
+ # The export rebuilds the DiT from the saved config: the 12-channel history conditioning head
+ # (state + previous command) must load, and the restored policy must keep the history contract.
+ export = export_policy(
+ latest_checkpoint(tmp_path / "full"), tmp_path / "history-export", profile="ema_0p10"
+ )
+ assert export["profile"] == "ema_0p10"
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "history-export", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert (restored.config.n_obs_steps, restored.config.condition_on_past_actions) == (8, True)
+ assert restored.dit.state_dict()["emb_in.action_cond.weight"].shape[1] == 2 * DIM
+ # A perfect target predictor must reconstruct recorded commands from the last history command,
+ # not from the measured follower state. This checks the offline evaluation input/anchor too.
+ policy = full.policy.eval()
+ dataset = WindowDataset(
+ load_manifest(out / "manifest.json"),
+ source,
+ out / "rows.f32.npy",
+ seed=0,
+ frame_hw=FRAME_HW,
+ decoder="pyav",
+ n_obs_steps=8,
+ )
+ from flux_action.training.data import collate_windows
+
+ samples = [
+ collate_windows([dataset.window_at(i, dataset.valid_starts(i)[0])])
+ for i in range(len(dataset.episodes))
+ ]
+ targets = iter(policy.training_targets(sample) for sample in samples)
+
+ def predict(observation):
+ assert observation["state"].shape == (1, 8, 6)
+ assert observation["images.top"].shape[1] == 8
+ assert observation["command_history"].shape == (1, 8, 6)
+ return next(targets).to(observation["state"].device) # a real predictor answers on the policy device
+
+ monkeypatch.setattr(policy, "predict_normalized_targets", predict)
+ report = evaluate_policy(policy, source, out, split="train", windows_per_episode=1, frame_hw=FRAME_HW)
+ assert report["action_mse_normalized"] == 0.0
+ assert report["action_mse_raw"] < 1e-6
+ with pytest.raises(ValueError, match="policy/data contract"):
+ Trainer(
+ make_config(source, out, tmp_path / "split", policy={**fields, "conditioning_noise_max": 0.1}),
+ policy_factory=tiny_policy,
+ ).build()
+
+
+def test_history_recipe_requires_matching_index_horizon(v3, tmp_path):
+ source, out, _ = v3
+
+ def unexpected(config):
+ pytest.fail("index mismatch must fail before model construction")
+
+ with pytest.raises(ValueError, match="re-index with --chunk-size 42"):
+ Trainer(
+ make_config(source, out, tmp_path / "run", policy={**TINY_POLICY, "chunk_size": 42}),
+ policy_factory=unexpected,
+ ).build()
diff --git a/flux-umi/tests/test_offline.py b/flux-umi/tests/test_offline.py
new file mode 100644
index 0000000000000000000000000000000000000000..9df3b59eb2a97cf60d1d2c2e39f89f7bd3577c3b
--- /dev/null
+++ b/flux-umi/tests/test_offline.py
@@ -0,0 +1,117 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+import json
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+import torch
+from conftest import FakeVideoVAE, make_policy, tiny_config
+
+from flux_action.inference.offline import run_inference
+from flux_action.models.text_encoder import MockTextEncoder, Qwen3VLEmbedder
+from flux_action.policy import FluxActionPolicy
+
+
+def test_recorded_export_inference(tmp_path, monkeypatch):
+ checkpoint = tmp_path / "checkpoint"
+ make_policy().save_pretrained(checkpoint)
+ restore = FluxActionPolicy.from_pretrained
+ monkeypatch.setattr(
+ FluxActionPolicy,
+ "from_pretrained",
+ lambda directory, device: restore(
+ directory, device=device, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ ),
+ )
+ observation = tmp_path / "observation.npz"
+ np.savez(observation, **{"images.top": np.zeros((64, 96, 3), np.uint8), "state": np.zeros(6, np.float32)})
+ first = run_inference(checkpoint, observation, tmp_path / "first", task="pick up", device="cpu")
+ second = run_inference(
+ tmp_path, observation, tmp_path / "second", subfolder="checkpoint", task="pick up", device="cpu"
+ )
+ first_actions = np.load(tmp_path / "first/actions.npy")
+ second_actions = np.load(tmp_path / "second/actions.npy")
+ assert np.isfinite(first_actions).all() and np.isfinite(second_actions).all(), "nonfinite actions"
+ print(f"reload max_abs={np.abs(first_actions - second_actions).max():.9g}")
+ assert second["checkpoint_manifest"] == json.loads((checkpoint / "manifest.json").read_text())
+ assert first["actions_shape"] == [1, 32, 6]
+ assert first["policy_config"]["sampler"] == "euler"
+ assert not first["serving_setup"]["prepared"], "CPU inference uses the reference backend"
+ assert first["gpu_memory_bytes"] == {
+ "peak_during_load": None,
+ "allocated_after_load": None,
+ "peak_during_chunk": None,
+ }
+ assert json.loads((tmp_path / "first/report.json").read_text()) == json.loads(json.dumps(first))
+ with pytest.raises(FileExistsError):
+ run_inference(checkpoint, observation, tmp_path / "first", task="pick up", device="cpu")
+
+
+def test_settings_supply_sampling_for_exports_without_them(tmp_path, monkeypatch):
+ # a training export carries no sampler settings; --setting must supply them and be recorded
+ checkpoint = tmp_path / "checkpoint"
+ make_policy(
+ tiny_config(sampler=None, num_inference_steps=None, guidance_scale=None, sampler_shift=None)
+ ).save_pretrained(checkpoint)
+ restore = FluxActionPolicy.from_pretrained
+ monkeypatch.setattr(
+ FluxActionPolicy,
+ "from_pretrained",
+ lambda directory, device: restore(
+ directory, device=device, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ ),
+ )
+ observation = tmp_path / "observation.npz"
+ np.savez(observation, **{"images.top": np.zeros((64, 96, 3), np.uint8), "state": np.zeros(6, np.float32)})
+ with pytest.raises(AssertionError, match="invalid sampler"):
+ run_inference(checkpoint, observation, tmp_path / "none", task="pick up", device="cpu")
+ settings = {"sampler": "euler", "num_inference_steps": 2, "guidance_scale": 1.0, "sampler_shift": 5.0}
+ report = run_inference(
+ checkpoint, observation, tmp_path / "set", task="pick up", device="cpu", settings=settings
+ )
+ assert report["settings"] == settings and report["policy_config"]["sampler"] == "euler"
+ assert report["actions_shape"] == [1, 32, 6]
+
+
+@pytest.mark.parametrize("length,expected", [(21, 80), (80, 80), (81, 160), (8100, 8160), (9000, 8192)])
+def test_text_bucket_inputs_and_padding_hidden_states(length, expected):
+ calls = []
+
+ def tokenize(text, **kwargs):
+ calls.append(kwargs)
+ real = min(length, kwargs["max_length"])
+ width = kwargs["max_length"] if kwargs["padding"] == "max_length" else real
+ return {
+ "input_ids": torch.ones(1, width, dtype=torch.long),
+ "attention_mask": (torch.arange(width)[None] < real).long(),
+ }
+
+ def model(**kwargs):
+ assert kwargs["use_cache"] is False
+ assert kwargs["attention_mask"].sum() == min(length, 8192)
+ # Preserve padded hidden states: they are part of the reference conditioning.
+ return SimpleNamespace(hidden_states=(torch.ones(1, expected, 2),))
+
+ encoder = Qwen3VLEmbedder.__new__(Qwen3VLEmbedder)
+ torch.nn.Module.__init__(encoder)
+ encoder.model = SimpleNamespace(model=model, device="cpu")
+ encoder.processor = SimpleNamespace(apply_chat_template=lambda *a, **k: "formatted", tokenizer=tokenize)
+ encoder.output_layer = [0]
+ encoder.dtype = torch.bfloat16
+ result = encoder.forward_bucketed("caption")
+ assert result.shape == (1, expected, 2)
+ assert result.sum() == 2 * expected
+ assert calls[0]["max_length"] == 8192
+ assert calls[1]["padding_side"] == "right"
diff --git a/flux-umi/tests/test_packed_windows.py b/flux-umi/tests/test_packed_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ab7bdd9582d982d8f05ee206e4a6d0ca7dcc18e
--- /dev/null
+++ b/flux-umi/tests/test_packed_windows.py
@@ -0,0 +1,255 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Packing the windows of a micro-batch into one DiT forward must equal separate per-window forwards."""
+
+import pytest
+import torch
+from conftest import TINY_DIT, FakeVideoVAE, make_policy, tiny_config
+
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.models.transformer import (
+ JointSingleSeq,
+ JointSingleSeqParams,
+ packed_attention,
+ window_major_order,
+)
+from flux_action.models.wiring import action_dit_params
+from flux_action.processing import packing
+
+MODALITY = "action"
+CTX_DIM = TINY_DIT["context_in_dim"]
+
+
+def tiny_dit(attn_mode="torch", seed=0):
+ params = action_dit_params(JointSingleSeqParams(**TINY_DIT), MODALITY, 6, attn_mode=attn_mode)
+ torch.manual_seed(seed)
+ return JointSingleSeq(params).eval()
+
+
+def window_inputs(n_windows, ctx_lens, latent_frames=3, latent_hw=(2, 3), chunk=8, seed=0):
+ """Per-window DiT kwargs (``B = 1`` each, dense) and the same windows batched (``B = n``) + contexts."""
+ gen = torch.Generator().manual_seed(seed)
+ latents = torch.randn(n_windows, 96, latent_frames, *latent_hw, generator=gen)
+ state = torch.randn(n_windows, 1, 6, generator=gen)
+ actions = torch.randn(n_windows, chunk, 6, generator=gen)
+ t = torch.rand(n_windows, generator=gen)
+ ctxs = [torch.randn(1, n, CTX_DIM, generator=gen) for n in ctx_lens]
+ video = packing.pack_video(latents)
+ action = packing.pack_actions(state, actions, packing.default_action_times(n_windows, chunk), MODALITY)
+ kwargs, targets, _ = packing.build_forward_kwargs(
+ video, action, {}, t, MODALITY, torch.Generator().manual_seed(seed + 1)
+ )
+ kwargs = {k: v.float() if v.is_floating_point() else v for k, v in kwargs.items()}
+ per_window = []
+ for i in range(n_windows):
+ text = packing.pack_text(ctxs[i], 768)
+ per_window.append({**{k: v[i : i + 1] for k, v in kwargs.items()}, **text})
+ return per_window, kwargs, ctxs
+
+
+def unpack(out, n_windows):
+ return {k: v.reshape(n_windows, v.shape[1] // n_windows, v.shape[2]) for k, v in out.items()}
+
+
+@pytest.mark.parametrize("attn_mode", ["torch", "cudnn"])
+@pytest.mark.parametrize("ctx_lens", [[4, 4, 4], [4, 8, 4, 12]])
+def test_packed_forward_matches_per_window_forwards(attn_mode, ctx_lens):
+ dit = tiny_dit(attn_mode)
+ n = len(ctx_lens)
+ per_window, kwargs, ctxs = window_inputs(n, ctx_lens)
+ with torch.no_grad():
+ dense = [dit(**kw) for kw in per_window]
+ packed, seqlens = packing.pack_windows(kwargs, ctxs)
+ out = unpack(dit(**packed, seqlens=seqlens), n)
+ assert set(out) == set(dense[0]) == {"x_video", "x_video_cond", f"x_{MODALITY}", f"x_{MODALITY}_cond"}
+ for name in out:
+ expected = torch.cat([d[name] for d in dense])
+ torch.testing.assert_close(out[name], expected, rtol=1e-4, atol=1e-4)
+
+
+def test_packed_backward_matches_the_mean_of_per_window_losses():
+ dit = tiny_dit()
+ n = 3
+ per_window, kwargs, ctxs = window_inputs(n, [4, 8, 4])
+ targets = {k: torch.randn_like(v) for k, v in per_window[0].items() if k in ("x_video", f"x_{MODALITY}")}
+
+ def loss_of(out, i):
+ return sum(((out[k][0] - targets[k][0]) ** 2).mean() for k in targets) / n
+
+ for p in dit.parameters():
+ p.grad = None
+ sum(loss_of(dit(**kw), 0) for kw in per_window).backward()
+ reference = {name: p.grad.clone() for name, p in dit.named_parameters() if p.grad is not None}
+ for p in dit.parameters():
+ p.grad = None
+ packed, seqlens = packing.pack_windows(kwargs, ctxs)
+ out = unpack(dit(**packed, seqlens=seqlens), n)
+ sum(sum(((out[k][i] - targets[k][0]) ** 2).mean() for k in targets) / n for i in range(n)).backward()
+ assert reference
+ for name, p in dit.named_parameters():
+ if name in reference:
+ torch.testing.assert_close(p.grad, reference[name], rtol=1e-4, atol=1e-5)
+
+
+def test_unequal_stream_lengths_across_windows():
+ """The general grouping path: windows whose content streams differ in length (not produced by the policy)."""
+ dit = tiny_dit()
+ a, _, ctx_a = window_inputs(1, [4], latent_frames=3, seed=1)
+ b, _, ctx_b = window_inputs(1, [8], latent_frames=2, seed=2)
+ dense = [dit(**a[0]), dit(**b[0])]
+ packed, seqlens = {}, {}
+ for key in a[0]:
+ if key in ("vector",):
+ packed[key] = a[0][key]
+ continue
+ packed[key] = torch.cat([a[0][key], b[0][key]], dim=1)
+ if key.startswith("x_") and not key.endswith(("_ids", "_timesteps")):
+ seqlens[key] = [a[0][key].shape[1], b[0][key].shape[1]]
+ seqlens["ctx"] = [4, 8]
+ out = dit(**packed, seqlens=seqlens)
+ for name, value in out.items():
+ expected = torch.cat([dense[0][name], dense[1][name]], dim=1)
+ torch.testing.assert_close(value, expected, rtol=1e-4, atol=1e-4)
+
+
+def test_window_major_order_is_a_permutation_with_inverse():
+ order, inverse, lens = window_major_order([[2, 3], [4, 1], [1, 1]], torch.device("cpu"))
+ assert lens == [7, 5] and order.tolist() == [0, 1, 5, 6, 7, 8, 10, 2, 3, 4, 9, 11]
+ x = torch.arange(12)
+ assert torch.equal(x[order][inverse], x)
+
+
+def test_packed_attention_validates_its_inputs():
+ q = torch.randn(1, 2, 6, 4)
+ with pytest.raises(ValueError):
+ packed_attention(q, q, q, "torch", [4, 4])
+ with pytest.raises(ValueError):
+ packed_attention(torch.randn(2, 2, 6, 4), q, q, "torch", [3, 3])
+ dit = tiny_dit()
+ per_window, kwargs, ctxs = window_inputs(2, [4, 4])
+ packed, seqlens = packing.pack_windows(kwargs, ctxs)
+ with pytest.raises(ValueError):
+ dit(**packed, seqlens={**seqlens, "ctx": [4, 3]})
+
+
+class VariableLengthMock(MockTextEncoder):
+ """Caption buckets of 4 or 8 tokens, so a batch mixes context lengths as DROID captions do."""
+
+ def forward_bucketed(self, text):
+ return self.encode(1, n_tokens=8 if len(text) > 12 else 4, seed=len(text))[0]
+
+
+def test_policy_trains_a_mixed_caption_batch_in_one_dit_forward():
+ calls = []
+ policy = make_policy(tiny_config(vae_batch_windows=2)).train()
+ policy.frozen.text_encoder = VariableLengthMock(CTX_DIM) # the encoders live in FrozenComponents
+ policy.dit.register_forward_pre_hook(
+ lambda m, args, kwargs: calls.append(kwargs["ctx"].shape), with_kwargs=True
+ )
+ rng = torch.Generator().manual_seed(0)
+ batch = {
+ "images.top": torch.rand(3, 33, 3, 64, 96, generator=rng),
+ "state": torch.rand(3, 6, generator=rng),
+ "action": torch.rand(3, 32, 6, generator=rng),
+ "task": ["short", "a much longer caption", "short"],
+ }
+ loss, info = policy(batch)
+ assert torch.isfinite(loss) and info["n_valid_windows"] == 3
+ assert calls == [(1, 4 + 8 + 4, CTX_DIM)] # one forward, contexts concatenated unpadded
+ loss.backward()
+ assert all(p.grad is not None for p in policy.dit.emb_in[MODALITY].parameters())
+ assert len(policy._ctx_cache) == 2 # the repeated caption was encoded once
+
+
+def test_batched_contexts_match_single_encodes_and_are_cached():
+ encoder = MockTextEncoder(CTX_DIM)
+ singles = [encoder.forward_bucketed(c) for c in ("a", "b", "a")]
+ batched = encoder.forward_bucketed_batch(["a", "b", "a"])
+ for s, b in zip(singles, batched, strict=True):
+ assert torch.equal(s, b)
+ policy = make_policy()
+ encoded = []
+ original = policy.text_encoder.forward_bucketed_batch
+ object.__setattr__(
+ policy.text_encoder,
+ "forward_bucketed_batch",
+ lambda texts: encoded.append(list(texts)) or original(texts),
+ )
+ first = policy._contexts(["x", "y", "x"], torch.device("cpu"))
+ again = policy._contexts(["y", "z"], torch.device("cpu"))
+ assert encoded == [["x", "y"], ["z"]]
+ assert torch.equal(first[1][0], again[0][0])
+
+
+def test_caption_cache_rollover_keeps_the_captions_of_the_batch():
+ policy = make_policy()
+ dev = torch.device("cpu")
+ for start in range(0, 256, 32):
+ policy._contexts([str(i) for i in range(start, start + 32)], dev)
+ assert len(policy._ctx_cache) == 256
+ before = policy._contexts(["0"], dev)[0][0]
+ # "0" and "255" are cached, "new" overflows the cache: all three must come back, none may raise
+ ctxs = policy._contexts(["0", "new", "255", "0"], dev)
+ assert len(ctxs) == 4 and set(policy._ctx_cache) == {"0", "new", "255"}
+ assert torch.equal(ctxs[0][0], before)
+ assert torch.equal(ctxs[3][0], before)
+
+
+def test_batched_vae_encode_matches_per_window_encode():
+ vae = FakeVideoVAE()
+ videos = torch.rand(3, 3, 33, 64, 96) * 2 - 1
+ batched = packing.encode_videos(vae, videos, (2, 3))
+ singles = torch.cat([packing.encode_video(vae, v, (2, 3)) for v in videos])
+ assert batched.shape == (3, 96, 9, 2, 3)
+ torch.testing.assert_close(batched, singles)
+
+
+def _seeded_batch(n, seeds):
+ rng = torch.Generator().manual_seed(5)
+ return {
+ "images.top": torch.rand(n, 33, 3, 64, 96, generator=rng),
+ "state": torch.rand(n, 6, generator=rng),
+ "action": torch.rand(n, 32, 6, generator=rng),
+ "task": ["pick"] * n,
+ "window_seed": torch.tensor(seeds),
+ }
+
+
+def test_prepared_windows_give_the_same_loss_as_the_inline_path():
+ policy = make_policy(tiny_config(augment=True, vae_batch_windows=2)).train()
+ batch = _seeded_batch(3, [11, 22, 33])
+ torch.manual_seed(1)
+ inline, _ = policy(batch)
+ torch.manual_seed(1)
+ prepared = policy.prepare(batch)
+ assert prepared.idx == [0, 1, 2] and prepared.event is None
+ ahead, info = policy(batch, prepared=prepared)
+ assert torch.equal(inline, ahead) and info["n_valid_windows"] == 3
+
+
+def test_window_seeds_fix_augmentation_and_caption_dropout_independently_of_the_global_rng():
+ policy = make_policy(tiny_config(augment=True, caption_dropout=0.5)).train()
+ seeded = _seeded_batch(4, [1, 2, 3, 4])
+ torch.manual_seed(0)
+ first = policy.prepare(seeded)
+ torch.manual_seed(999)
+ second = policy.prepare(seeded)
+ assert torch.equal(first.latents, second.latents)
+ assert all(torch.equal(a, b) for a, b in zip(first.ctxs, second.ctxs, strict=True))
+ unseeded = {k: v for k, v in seeded.items() if k != "window_seed"}
+ torch.manual_seed(0)
+ third = policy.prepare(unseeded)
+ torch.manual_seed(999)
+ fourth = policy.prepare(unseeded)
+ assert not torch.equal(third.latents, fourth.latents) # augmentation from the global RNG differs
diff --git a/flux-umi/tests/test_policy.py b/flux-umi/tests/test_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..71fda2f36845ec7ded30efd492ab5b57030e1d99
--- /dev/null
+++ b/flux-umi/tests/test_policy.py
@@ -0,0 +1,506 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+import hashlib
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import torch
+from conftest import TINY_DIT, FakeVideoVAE, make_policy, tiny_config
+from safetensors.torch import load_file, save_file
+
+import flux_action
+from flux_action.config import CONTENT_STREAMS, DROID_INFERENCE_SETTINGS, PolicyConfig
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.models.transformer import JointSingleSeq, JointSingleSeqParams
+from flux_action.models.wiring import action_dit_params, restrict_content_streams, stream_of_key
+from flux_action.policy import FluxActionPolicy, _released_inference_config
+from flux_action.processing import packing
+
+
+def report_prediction_drift(actual, expected):
+ assert actual.shape == expected.shape, "prediction shape mismatch"
+ assert torch.isfinite(actual).all() and torch.isfinite(expected).all(), "nonfinite prediction"
+ print(f"prediction max_abs={(actual.float() - expected.float()).abs().max().item():.9g}")
+
+
+def test_train_export_reload_predict_and_queue(batch, tmp_path):
+ policy = make_policy().train()
+ before = policy.dit.emb_in["action"].weight.detach().clone()
+ optimizer = torch.optim.AdamW(policy.get_optim_params(), lr=1e-3)
+ loss, info = policy(batch)
+ assert torch.isfinite(loss) and info["n_valid_windows"] == 1
+ loss.backward()
+ optimizer.step()
+ assert not torch.equal(before, policy.dit.emb_in["action"].weight)
+ observation = {**batch, "images.top": batch["images.top"][:, 0]}
+ predicted = policy.predict_action_chunk(observation)
+ assert predicted.shape == (1, 32, 6) and torch.isfinite(predicted).all()
+ policy.config.trunk_weights = "/nonexistent/initialization.safetensors"
+ policy.save_pretrained(tmp_path)
+ assert json.loads((tmp_path / "config.json").read_text())["trunk_weights"] is None
+ assert all(key.startswith("dit.") for key in load_file(str(tmp_path / "model.safetensors")))
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ report_prediction_drift(restored.predict_action_chunk(observation), predicted)
+ report_prediction_drift(restored.select_action(observation), predicted[:, 0])
+ assert len(restored._action_queue) == 31
+ restored.reset()
+ assert not restored._action_queue and not restored._ctx_cache
+ with pytest.raises(FileExistsError):
+ policy.save_pretrained(tmp_path)
+
+
+def test_single_frame_encode_uses_the_frame_path_and_survives_export(batch, tmp_path):
+ observation = {**batch, "images.top": batch["images.top"][:, 0]}
+ reference = make_policy(tiny_config(single_frame_encode=False))
+ reference.predict_action_chunk(observation)
+ assert getattr(reference.video_vae, "frame_calls", 0) == 0
+ reference.prepare_inference(compile=False)
+ reference.predict_action_chunk(observation)
+ assert reference.video_vae.frame_calls == 1
+ fast = make_policy()
+ fast.load_state_dict(reference.state_dict())
+ predicted = fast.predict_action_chunk(observation)
+ assert fast.video_vae.frame_calls == 1 and predicted.shape == (1, 32, 6)
+ fast.save_pretrained(tmp_path)
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert restored.config.single_frame_encode is True
+ report_prediction_drift(restored.predict_action_chunk(observation), predicted)
+
+
+def test_full_restore_rejects_missing_head(batch, tmp_path):
+ policy = make_policy()
+ policy.save_pretrained(tmp_path)
+ file = tmp_path / "model.safetensors"
+ state = load_file(str(file))
+ del state["dit.emb_in.action.weight"]
+ save_file(state, str(file))
+ manifest = json.loads((tmp_path / "manifest.json").read_text())
+ manifest["sha256"][file.name] = hashlib.sha256(file.read_bytes()).hexdigest()
+ (tmp_path / "manifest.json").write_text(json.dumps(manifest))
+ with pytest.raises(RuntimeError, match="Missing key"):
+ FluxActionPolicy.from_pretrained(tmp_path, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+def test_delta_queue_continues_from_last_command_despite_tracking_lag(monkeypatch):
+ policy = make_policy(
+ tiny_config(
+ action_parameterization="joint_delta",
+ absolute_action_dims=(5,),
+ gripper_flip_dims=(),
+ n_action_steps=2,
+ action_normalization={"q01": [-2.0] * 6, "q99": [2.0] * 6},
+ )
+ )
+ observations = []
+
+ def predict(batch):
+ observations.append(batch["state"].clone())
+ targets = torch.full((1, 32, 6), 0.75) # denormalizes to +1.5 per arm joint
+ targets[..., -1] = 0.25 # absolute gripper command 0.5
+ return targets
+
+ monkeypatch.setattr(policy, "predict_normalized_targets", predict)
+ for tick in range(5):
+ state = torch.full((1, 6), 10.0 if tick == 0 else 100.0 + tick)
+ action = policy.select_action({"state": state})
+ torch.testing.assert_close(action[0, :5], torch.full((5,), 10.0 + (tick + 1) * 1.5))
+ assert action[0, -1] == 0.5
+ action.fill_(-999) # caller mutation must not change the retained command anchor
+ assert [value[0, 0].item() for value in observations] == [10.0, 102.0, 104.0]
+ assert len(policy._action_queue) == 1
+ policy.reset()
+ assert not policy._action_queue and policy._last_command is None
+ fresh = policy.select_action({"state": torch.full((1, 6), 20.0)})
+ torch.testing.assert_close(fresh[0, :5], torch.full((5,), 21.5))
+ assert fresh[0, -1] == 0.5
+
+
+def test_native_config_alongside_lerobot_config_is_verified(batch, tmp_path):
+ policy = make_policy()
+ policy.save_pretrained(tmp_path)
+ native = tmp_path / "config.native.json"
+ raw = json.loads((tmp_path / "config.json").read_text())
+ raw["quantization"] = None
+ native.write_text(json.dumps(raw))
+ (tmp_path / "config.json").write_text('{"type": "flux3"}')
+ manifest = json.loads((tmp_path / "manifest.json").read_text())
+ manifest["sha256"][native.name] = hashlib.sha256(native.read_bytes()).hexdigest()
+ (tmp_path / "manifest.json").write_text(json.dumps(manifest))
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ observation = {**batch, "images.top": batch["images.top"][:, 0]}
+ report_prediction_drift(
+ restored.predict_action_chunk(observation), policy.predict_action_chunk(observation)
+ )
+ native.write_text(native.read_text() + " ")
+ with pytest.raises(AssertionError, match="checkpoint checksum mismatch: config.native.json"):
+ FluxActionPolicy.from_pretrained(tmp_path)
+
+
+def test_restore_checksum(tmp_path):
+ make_policy().save_pretrained(tmp_path)
+ with (tmp_path / "config.json").open("a") as stream:
+ stream.write(" ")
+ with pytest.raises(AssertionError):
+ FluxActionPolicy.from_pretrained(tmp_path)
+
+
+@pytest.mark.parametrize("history", [False, True])
+@pytest.mark.parametrize("modality", ["action", "action_prediction_droid"])
+def test_base_remapping_and_fresh_heads(tmp_path, history, modality):
+ config = (
+ dict(inference_profile="history", n_obs_steps=8, history_snapshots=2, condition_on_past_actions=True)
+ if history
+ else {}
+ )
+ config["action_modality"] = modality
+ params = action_dit_params(
+ restrict_content_streams(JointSingleSeqParams(**TINY_DIT), CONTENT_STREAMS), "action_prediction", 16
+ )
+ base = JointSingleSeq(params)
+ path = tmp_path / "base.safetensors"
+ save_file({k: v.contiguous() for k, v in base.state_dict().items()}, str(path))
+ policy = make_policy(tiny_config(trunk_weights=str(path), **config))
+ torch.testing.assert_close(
+ policy.dit.content_mode_blocks[modality][0].q_proj.weight,
+ base.content_mode_blocks["action_prediction"][0].q_proj.weight,
+ )
+ assert policy.dit.emb_in[modality].weight.shape == (64, 6)
+ cond_width = 12 if history else 6
+ assert policy.dit.emb_in[f"{modality}_cond"].weight.shape == (64, cond_width)
+ assert policy.dit.final_layer[f"{modality}_cond"].linear.weight.shape == (cond_width, 64)
+ # fresh heads carry the reference initialization: xavier input projections, zero final layers
+ emb = policy.dit.emb_in[modality].weight
+ bound = (6 / (6 + 64)) ** 0.5
+ assert 0.5 * bound < emb.abs().max() <= bound
+ head = policy.dit.final_layer[modality]
+ assert not head.linear.weight.any() and not head.adaLN_modulation[1].weight.any()
+ assert not policy.dit.final_layer[f"{modality}_cond"].linear.weight.any()
+ # the draw depends on head_init_seed only, not on the caller's RNG state (ranks seed differently)
+ torch.manual_seed(7)
+ again = make_policy(tiny_config(trunk_weights=str(path), **config))
+ assert torch.equal(again.dit.emb_in[modality].weight, emb)
+ torch.testing.assert_close(
+ again.dit.emb_in[f"{modality}_cond"].weight,
+ policy.dit.emb_in[f"{modality}_cond"].weight,
+ rtol=0,
+ atol=0,
+ )
+ other = make_policy(tiny_config(trunk_weights=str(path), head_init_seed=3, **config))
+ assert not torch.equal(other.dit.emb_in[modality].weight, emb)
+
+
+def test_droid_inference_settings_are_valid_and_explicit():
+ assert PolicyConfig().sampler is None and PolicyConfig().caption_dropout == 0.1
+ cfg = tiny_config(**DROID_INFERENCE_SETTINGS)
+ cfg.validate_inference()
+ assert (cfg.sampler, cfg.num_inference_steps, cfg.sampler_shift) == ("cosmos_unipc", 4, 5.0)
+ assert (cfg.guidance_scale, cfg.guidance_scale_action, cfg.n_action_steps) == (4.0, 1.0, 32)
+
+
+@pytest.mark.parametrize("dit_config", [{}, {"hidden_size": 3072}, {"theta": 10000, "axes_dim": [32] * 4}])
+def test_prepared_inference_accepts_resolved_defaults(dit_config):
+ config = PolicyConfig(
+ **DROID_INFERENCE_SETTINGS,
+ action_modality="action_prediction_droid",
+ content_streams=("video", "video_cond"),
+ dit_config=dit_config,
+ )
+ assert _released_inference_config(config)
+ for overrides in (
+ {"dit_config": {"theta": 20000}},
+ {"dit_config": {"axes_dim": [16, 16, 48, 48]}},
+ {"dit_config": {"depth": 4}},
+ {"action_modality": "action"},
+ {"torch_dtype": "float32"},
+ {"sampler": "euler"},
+ {"inference_profile": "history", "gripper_flip_dims": ()},
+ {"chunk_size": 16, "n_action_steps": 16},
+ ):
+ assert not _released_inference_config(PolicyConfig(**{**config.to_dict(), **overrides}))
+
+
+def test_joint_token_loss():
+ # Unequal numbers of video/action tokens distinguish this from a modality mean.
+ pred = {"x_video": torch.full((2, 5, 3), 2.0), "x_action": torch.full((2, 2, 7), 3.0)}
+ target = {k: torch.zeros_like(v) for k, v in pred.items()}
+ result = packing.flow_loss(pred, target, "action")
+ assert result["loss"].item() == pytest.approx((10 * 4 + 50 * 4 * 9) / 14)
+
+
+def test_no_framework_dependency():
+ # Isolated mode drops PYTHONPATH, so point the child at this checkout explicitly; the check
+ # must hold whether the package is installed or only on the path (as on the cluster).
+ src = str(Path(flux_action.__file__).resolve().parents[1])
+ code = (
+ f"import sys; sys.path.insert(0, {src!r}); from flux_action.policy import FluxActionPolicy; "
+ "assert not any(k.startswith(('lerobot', 'bfl.')) for k in sys.modules)"
+ )
+ subprocess.run([sys.executable, "-I", "-c", code], check=True)
+
+
+def test_frozen_components_and_dtype(batch):
+ policy = make_policy().train()
+ assert not policy.video_vae.training and not policy.text_encoder.training
+ assert not any("video_vae" in k or "text_encoder" in k for k in policy.state_dict())
+ policy._context("test", torch.device("cpu"))
+ policy.to(dtype=torch.bfloat16)
+ assert policy.dtype_ == torch.bfloat16 and not policy._ctx_cache
+
+
+def test_strict_component_loader_rejects_partial_heads(tmp_path):
+ from flux_action.models.wiring import load_action_checkpoint
+
+ model = make_policy().dit
+ state = {k: v.contiguous() for k, v in model.state_dict().items()}
+ del state["emb_in.action_cond.weight"]
+ path = tmp_path / "partial.safetensors"
+ save_file(state, str(path))
+ with pytest.raises(ValueError, match="missing required embodiment heads"):
+ load_action_checkpoint(model, str(path), "action", strict_heads=True)
+
+
+def test_optimizer_groups_are_disjoint_and_cover_trainable_parameters():
+ policy = make_policy()
+ trunk, heads = policy.get_optim_params()
+ trunk_ids, head_ids = ({id(p) for p in group["params"]} for group in (trunk, heads))
+ assert not trunk_ids & head_ids
+ assert trunk_ids | head_ids == {id(p) for p in policy.parameters() if p.requires_grad}
+ assert trunk["lr"] == 1.92e-4 and heads["lr"] == pytest.approx(5 * 1.92e-4)
+
+
+def test_frozen_streams_leave_the_optimizer_and_untouched_streams_get_no_gradient(batch):
+ policy = make_policy(tiny_config(content_streams=CONTENT_STREAMS)).train()
+ loss, _ = policy(batch)
+ loss.backward()
+ grads = {n: p.grad for n, p in policy.named_parameters()}
+ dead = [n for n in grads if any(f".{m}." in n for m in ("image", "image_cond", "audio", "audio_cond"))]
+ assert dead and all(grads[n] is None for n in dead) # by design: these streams carry no loss
+ assert grads["dit.emb_in.action.weight"].abs().sum() > 0
+ cond_heads = [
+ n for n in grads if n.startswith(("dit.final_layer.video_cond.", "dit.final_layer.action_cond."))
+ ]
+ assert cond_heads and all(grads[n] is None for n in cond_heads) # conditioning predictions are discarded
+ policy = make_policy(tiny_config(content_streams=CONTENT_STREAMS))
+ frozen = policy.freeze_streams(("image", "image_cond", "audio", "audio_cond"))
+ assert set(frozen) == set(dead)
+ heads = policy.freeze_conditioning_heads()
+ assert set(heads) >= set(cond_heads) and set(frozen) | set(heads) == set(dead) | set(cond_heads)
+ params = dict(policy.named_parameters())
+ trainable = {id(p) for group in policy.get_optim_params() for p in group["params"]}
+ assert not any(id(params[n]) in trainable for n in frozen + heads)
+ loss, _ = policy.train()(batch)
+ loss.backward()
+ assert all(p.grad is not None for p in policy.parameters() if p.requires_grad)
+
+
+def test_uint8_frames_train_like_float_frames(batch):
+ policy = make_policy().train()
+ as_bytes = {**batch, "images.top": (batch["images.top"] * 255).round().to(torch.uint8)}
+ as_float = {**batch, "images.top": as_bytes["images.top"].float() / 255}
+ torch.manual_seed(3)
+ loss_bytes, _ = policy(as_bytes)
+ torch.manual_seed(3)
+ loss_float, _ = policy(as_float)
+ assert torch.equal(loss_bytes, loss_float)
+
+
+LEAN_STREAMS = ("video", "video_cond")
+DROPPED_STREAMS = {"image", "image_cond", "audio", "audio_cond"}
+
+
+def _tiny_trunks(tmp_path):
+ params = action_dit_params(
+ restrict_content_streams(JointSingleSeqParams(**TINY_DIT), CONTENT_STREAMS), "action_prediction", 16
+ )
+ torch.manual_seed(11)
+ full_sd = {k: v.contiguous() for k, v in JointSingleSeq(params).state_dict().items()}
+ lean_sd = {k: v for k, v in full_sd.items() if stream_of_key(k) not in DROPPED_STREAMS}
+ assert len(lean_sd) < len(full_sd)
+ full, lean = tmp_path / "full.safetensors", tmp_path / "lean.safetensors"
+ save_file(full_sd, str(full))
+ save_file(lean_sd, str(lean))
+ return full, lean
+
+
+def _same_predictions_and_loss(p_a, p_b, batch):
+ observation = {**batch, "images.top": batch["images.top"][:, 0]}
+ p_a.eval()
+ p_b.eval()
+ torch.testing.assert_close(
+ p_a.predict_action_chunk(observation), p_b.predict_action_chunk(observation), rtol=0, atol=0
+ )
+ p_a.train()
+ p_b.train()
+ torch.manual_seed(3)
+ loss_a, _ = p_a(batch)
+ torch.manual_seed(3)
+ loss_b, _ = p_b(batch)
+ assert torch.equal(loss_a, loss_b)
+
+
+def test_lean_trunk_without_image_audio_streams_predicts_identically(batch, tmp_path):
+ """The policy never feeds image / audio tokens; a trunk without those streams loads and matches exactly."""
+ full, lean = _tiny_trunks(tmp_path)
+ p_full = make_policy(tiny_config(trunk_weights=str(full), content_streams=CONTENT_STREAMS))
+ p_lean = make_policy(tiny_config(trunk_weights=str(lean)))
+ assert p_full.config.content_streams == CONTENT_STREAMS
+ assert p_lean.config.content_streams == LEAN_STREAMS
+ assert set(p_lean.dit.in_channels) == {"video", "video_cond", "action", "action_cond"}
+ assert not any(stream_of_key(k) in DROPPED_STREAMS for k in p_lean.state_dict())
+ assert sum(p.numel() for p in p_lean.parameters()) < sum(p.numel() for p in p_full.parameters())
+ full_sd = p_full.state_dict()
+ for k, v in p_lean.state_dict().items():
+ if not k.startswith(("dit.emb_in.action", "dit.final_layer.action")):
+ assert torch.equal(v, full_sd[k]), k
+ p_lean.load_state_dict({k: full_sd[k] for k in p_lean.state_dict()}) # identical fresh heads
+ _same_predictions_and_loss(p_full, p_lean, batch)
+ # the trainer's freeze list names streams a lean policy does not have: nothing to freeze, no error
+ assert p_lean.freeze_streams(("image", "image_cond", "audio", "audio_cond")) == []
+
+
+def test_lean_policy_exports_its_streams_and_full_trunks_load_into_lean_policies(batch, tmp_path):
+ full, lean = _tiny_trunks(tmp_path)
+ p_lean = make_policy(tiny_config(trunk_weights=str(lean)))
+ export = tmp_path / "export"
+ p_lean.save_pretrained(export)
+ assert json.loads((export / "config.json").read_text())["content_streams"] == list(LEAN_STREAMS)
+ restored = FluxActionPolicy.from_pretrained(
+ export, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert restored.config.content_streams == LEAN_STREAMS
+ _same_predictions_and_loss(p_lean, restored, batch)
+ explicit = make_policy(tiny_config(trunk_weights=str(full), content_streams=LEAN_STREAMS))
+ explicit.load_state_dict(p_lean.state_dict()) # fresh heads carry each build's own init
+ _same_predictions_and_loss(p_lean, explicit, batch)
+
+
+def test_bf16_noising_rounds_timesteps_and_noise_like_the_reference():
+ x0 = torch.randn(2, 4, 8, generator=torch.Generator().manual_seed(0)).to(torch.bfloat16)
+ t = torch.tensor([0.9988, 0.150390625]) # 1 - 2^-9 < t rounds to 1; (1 - t) needs 9 bits for the second
+ x_t, target = packing.add_noise(x0, t, torch.Generator().manual_seed(1))
+ eps = torch.randn(x0.shape, generator=torch.Generator().manual_seed(1), dtype=torch.float32).to(
+ torch.bfloat16
+ )
+ tb = t.to(torch.bfloat16).view(-1, 1, 1)
+ assert x_t.dtype == target.dtype == torch.bfloat16
+ assert torch.equal(x_t, tb * eps + (1 - tb) * x0) and torch.equal(target, eps - x0)
+ assert torch.equal(x_t[0], eps[0]) # t = 1 exactly: pure noise, as in the reference's bf16 packing
+ ids = torch.zeros(2, 4, 4, dtype=torch.int64)
+ video = {"x_video": x0, "x_video_ids": ids, "x_video_cond": x0[:, :1], "x_video_cond_ids": ids[:, :1]}
+ action = {
+ "x_action": x0[:, :3, :6],
+ "x_action_ids": ids[:, :3],
+ "x_action_cond": x0[:, :1, :6],
+ "x_action_cond_ids": ids[:, :1],
+ }
+ text = {
+ "ctx": torch.zeros(2, 3, 5),
+ "ctx_ids": ids[:, :3],
+ "vector": torch.zeros(2, 7),
+ "timesteps_ctx": torch.zeros(2, 3),
+ }
+ kw, targets, _ = packing.build_forward_kwargs(
+ video, action, text, t, "action", torch.Generator().manual_seed(1)
+ )
+ assert kw["x_video_timesteps"].dtype == torch.float32
+ assert kw["x_video_timesteps"][0].unique().tolist() == [1.0]
+ assert kw["x_action_timesteps"][1].unique().item() == pytest.approx(float(tb[1]))
+ assert torch.equal(kw["x_video"], x_t) and torch.equal(targets["x_video"], target)
+ # fp32 latents keep the exact timestep
+ kw32, _, _ = packing.build_forward_kwargs(
+ {k: v.float() for k, v in video.items()}, {k: v.float() for k, v in action.items()}, text, t, "action"
+ )
+ assert kw32["x_video_timesteps"][0].unique().item() == pytest.approx(0.9988)
+
+
+def test_timestep_mlp_runs_in_its_weight_precision_outside_autocast():
+ from flux_action.models.transformer import timestep_embedding
+
+ dit = make_policy().dit # fp32 parameters
+ seen = []
+ dit.time_in.register_forward_pre_hook(lambda m, args: seen.append(args[0].dtype))
+ ts = torch.tensor([0.9988, 0.0])
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ vec = dit.embed_timesteps(ts, torch.bfloat16)
+ assert seen == [torch.float32] and vec.dtype == torch.bfloat16
+ assert torch.equal(vec, dit.time_in(timestep_embedding(ts, 256)).to(torch.bfloat16))
+ dit.time_in.to(torch.bfloat16) # a bf16 inference model computes it in bf16, as before
+ assert dit.embed_timesteps(ts, torch.bfloat16).dtype == torch.bfloat16 and seen[-1] == torch.bfloat16
+
+
+@pytest.mark.parametrize("conditioning_channels", [6, 12])
+def test_fresh_heads_preserve_global_rng(conditioning_channels):
+ from flux_action.models.wiring import fresh_head_state_dict
+
+ before = torch.random.get_rng_state().clone()
+ first = fresh_head_state_dict(32, "action", 6, seed=42, conditioning_channels=conditioning_channels)
+ assert torch.equal(torch.random.get_rng_state(), before)
+ second = fresh_head_state_dict(32, "action", 6, seed=42, conditioning_channels=conditioning_channels)
+ assert all(torch.equal(first[key], second[key]) for key in first)
+ assert all(torch.count_nonzero(v) == 0 for k, v in first.items() if k.startswith("final_layer."))
+
+
+def test_conditioning_only_packing_matches_previous_target_packer():
+ policy = make_policy(tiny_config())
+ canvas = torch.linspace(-1, 1, 3 * 64 * 96).reshape(3, 1, 64, 96)
+ state = torch.arange(6).float()[None]
+ cond = policy._encode_canvas(canvas, state)
+ latent = packing.encode_single_frame(
+ policy.video_vae, canvas[:, 0], policy.config.latent_hw, single_frame=False
+ )
+ video = packing.pack_video(torch.cat([latent, torch.zeros_like(latent)], 2))
+ action = packing.pack_actions(state[None], torch.zeros(1, 32, 6), torch.zeros(1, 32), "action")
+ for key, value in cond.items():
+ torch.testing.assert_close(value, {**video, **action}[key], rtol=0, atol=0)
+
+
+def test_full_trunk_defaults_to_lean_construction_without_loading_unused_tensors(tmp_path, monkeypatch):
+ import safetensors
+
+ full, lean = _tiny_trunks(tmp_path)
+ original = safetensors.safe_open
+ loaded = []
+
+ class RecordingFile:
+ def __init__(self, *args, **kwargs):
+ self.file = original(*args, **kwargs)
+
+ def __enter__(self):
+ self.file.__enter__()
+ return self
+
+ def __exit__(self, *args):
+ return self.file.__exit__(*args)
+
+ def keys(self):
+ return self.file.keys()
+
+ def get_tensor(self, key):
+ loaded.append(key)
+ return self.file.get_tensor(key)
+
+ monkeypatch.setattr(safetensors, "safe_open", RecordingFile)
+ policy = make_policy(tiny_config(trunk_weights=str(full)))
+ assert policy.config.content_streams == LEAN_STREAMS
+ assert not any(stream_of_key(key) in DROPPED_STREAMS for key in loaded)
+ assert not any(stream_of_key(key) in DROPPED_STREAMS for key in policy.state_dict())
diff --git a/flux-umi/tests/test_policy_optional_dependencies.py b/flux-umi/tests/test_policy_optional_dependencies.py
new file mode 100644
index 0000000000000000000000000000000000000000..b46649aba12b7151b80a12668eeb32111b0270d4
--- /dev/null
+++ b/flux-umi/tests/test_policy_optional_dependencies.py
@@ -0,0 +1,89 @@
+"""The default training path and inference restores must not depend on the optional kernel stacks.
+
+Review findings (2026-10-03): (1) ``_vae_training_fused_context`` imported ``vae_fused_pointwise`` (top-level
+``import triton``) before checking whether the flag was on, so plain training / CPU fixtures failed without Triton;
+(2) ``from_pretrained`` constructed the policy with the exported training flags and installed the CUDA-only adapters
+(``dit_out_stage.install`` raises without CUDA). Now the adapter modules are imported only when their flag is on and
+the policy was built for training, exports clear the training-only flags, and restores never install adapters.
+"""
+import json
+import sys
+from dataclasses import replace
+
+import pytest
+import torch
+from conftest import FakeVideoVAE, tiny_config
+
+from flux_action.config import TRAINING_PERF_FLAGS, PolicyConfig
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy, sha256
+
+OPTIONAL = ("triton", "triton.language", "triton.language.extra", "cutlass", "cuda", "natten", "natten.functional")
+
+
+class _BlockImports:
+ """Make ``import `` raise ImportError inside the block (modules already imported are removed too)."""
+
+ def __enter__(self):
+ self.saved = {}
+ for name in list(sys.modules):
+ if name.split(".")[0] in {n.split(".")[0] for n in OPTIONAL}:
+ self.saved[name] = sys.modules.pop(name)
+ for name in OPTIONAL:
+ sys.modules[name] = None # type: ignore[assignment]
+ return self
+
+ def __exit__(self, *exc):
+ for name in OPTIONAL:
+ sys.modules.pop(name, None)
+ sys.modules.update(self.saved)
+
+
+def _policy(**flags):
+ return FluxActionPolicy(tiny_config(**flags), video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+def test_default_training_contexts_do_not_import_optional_stacks():
+ policy = _policy().train()
+ optional_modules = {"flux_action.models." + m for m in ("vae_fused_pointwise", "vae_cute_rope", "vae_cute_rmsnorm",
+ "vae_natten_no_lse", "vae_ln_exact", "vae_qk_fused")}
+ for name in optional_modules:
+ sys.modules.pop(name, None)
+ with _BlockImports():
+ with pytest.raises(ImportError):
+ import triton # noqa: F401 (the block is effective)
+ with policy._vae_training_contexts():
+ pass
+ with policy.eval()._vae_training_contexts():
+ pass
+ assert not (optional_modules & set(sys.modules)), "an adapter module was imported although every flag is off"
+ assert policy.training_adapters_installed is True # a training policy with the flags off installs nothing
+
+
+def test_export_clears_training_perf_flags_and_restore_installs_no_adapter(tmp_path):
+ policy = _policy()
+ policy.save_pretrained(tmp_path / "export")
+ exported = json.loads((tmp_path / "export" / "config.json").read_text())
+ assert all(exported[name] is False for name in TRAINING_PERF_FLAGS)
+ # an older export that still carries the v6 training flags (as the review observed) must load without CUDA
+ config = replace(PolicyConfig(**exported), vae_fused_pointwise=True, vae_ln_exact_fast=True, vae_cute_rmsnorm=True,
+ vae_cute_rope=True, vae_natten_no_lse=True, vae_na3d_triton=True, dit_swiglu_fused=True,
+ dit_qknorm_triton=True, dit_rope_triton=True, dit_qknorm_rope_fused=True,
+ dit_norm_mod_gate_fused=True, dit_time_embed_dedup=True, dit_mod_rows=True, dit_out_stage=True,
+ dit_pe_cache=True, pack_cache=True, prefetch_randomness=True, preprocess_batched=True)
+ (tmp_path / "export" / "config.json").write_text(json.dumps(config.to_dict(), indent=2) + "\n")
+ manifest_path = tmp_path / "export" / "manifest.json" # the manifest pins the config digest: update it
+ manifest = json.loads(manifest_path.read_text())
+ manifest["sha256"]["config.json"] = sha256(tmp_path / "export" / "config.json")
+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
+ with _BlockImports():
+ restored = FluxActionPolicy.from_pretrained(tmp_path / "export", video_vae=FakeVideoVAE(),
+ text_encoder=MockTextEncoder(32), device="cpu")
+ assert restored.training_adapters_installed is False and not restored.training
+ assert restored.config.dit_out_stage and restored.config.vae_fused_pointwise # the config is kept as saved
+ with _BlockImports(): # training-mode contexts of a restored policy stay eager too
+ with restored.train()._vae_training_contexts():
+ pass
+ # the restored weights equal the exported ones
+ for (n1, p1), (n2, p2) in zip(policy.state_dict().items(), restored.state_dict().items(), strict=True):
+ assert n1 == n2 and torch.equal(p1, p2.to(p1.dtype))
diff --git a/flux-umi/tests/test_precision.py b/flux-umi/tests/test_precision.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8a1fed6d6a5b79d772403aa8fd01f539263f96b
--- /dev/null
+++ b/flux-umi/tests/test_precision.py
@@ -0,0 +1,51 @@
+import sys
+
+import pytest
+from conftest import make_policy
+
+pytest.importorskip("msgpack") # flux_action.serving.robolab imports the OpenPI codec
+
+from flux_action import cli # noqa: E402
+from flux_action.serving import robolab # noqa: E402
+
+
+def test_setting_values_accept_bare_strings_and_json(monkeypatch, capsys):
+ """``--setting sampler=euler`` is the documented SO-101 evaluation flag; only JSON scalars used to parse."""
+ calls = []
+ policy = make_policy()
+ policy.serving_setup = {}
+
+ def fake_load(checkpoint, **kwargs):
+ calls.append(kwargs)
+ return policy
+
+ monkeypatch.setattr(robolab, "load_serving_policy", fake_load)
+ monkeypatch.setattr(robolab, "serve", lambda *a, **k: None)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "flux-action",
+ "serve-robolab",
+ "--checkpoint",
+ "x",
+ "--setting",
+ "sampler=euler",
+ "--setting",
+ "num_inference_steps=4",
+ "--setting",
+ "sampler_shift=6.93",
+ ],
+ )
+ cli.main()
+ assert calls[0]["settings"] == {
+ "sampler": "euler",
+ "num_inference_steps": 4,
+ "sampler_shift": 6.93,
+ }
+ capsys.readouterr()
+
+
+def test_setting_without_a_value_is_rejected():
+ with pytest.raises(ValueError, match="is not KEY=VALUE"):
+ cli._parse_settings(["sampler"])
diff --git a/flux-umi/tests/test_serving.py b/flux-umi/tests/test_serving.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fcbe4c8a5b9c4a82bcdb7f842a75656f49b7a48
--- /dev/null
+++ b/flux-umi/tests/test_serving.py
@@ -0,0 +1,275 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""OpenPI wire format, RoboLab adapter, WebSocket server and fixture replay."""
+
+import asyncio
+import contextlib
+import functools
+import json
+import socket
+import threading
+
+import numpy as np
+import pytest
+import torch
+from conftest import FakeVideoVAE, tiny_config
+
+msgpack = pytest.importorskip("msgpack") # the OpenPI wire format; flux_action.serving needs the serve extra
+
+from flux_action.models.text_encoder import MockTextEncoder # noqa: E402
+from flux_action.policy import FluxActionPolicy # noqa: E402
+from flux_action.processing import packing # noqa: E402
+from flux_action.serving import protocol # noqa: E402
+from flux_action.serving.robolab import ( # noqa: E402
+ RoboLabPolicy,
+ compose_views,
+ observation_state,
+ replay_collection,
+ serve_async,
+)
+
+
+# --- reference codec: openpi_client.msgpack_numpy 0.1.0 (Apache-2.0), copied for a byte-level check ---
+def _ref_pack_array(obj):
+ if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
+ raise ValueError(f"Unsupported dtype: {obj.dtype}")
+ if isinstance(obj, np.ndarray):
+ return {b"__ndarray__": True, b"data": obj.tobytes(), b"dtype": obj.dtype.str, b"shape": obj.shape}
+ if isinstance(obj, np.generic):
+ return {b"__npgeneric__": True, b"data": obj.item(), b"dtype": obj.dtype.str}
+ return obj
+
+
+def _ref_unpack_array(obj):
+ if b"__ndarray__" in obj:
+ return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
+ if b"__npgeneric__" in obj:
+ return np.dtype(obj[b"dtype"]).type(obj[b"data"])
+ return obj
+
+
+ref_packb = functools.partial(msgpack.packb, default=_ref_pack_array)
+ref_unpackb = functools.partial(msgpack.unpackb, object_hook=_ref_unpack_array)
+
+
+def sample_obs():
+ rng = np.random.default_rng(0)
+ return {
+ "observation/image": rng.integers(0, 256, (540, 640, 3), dtype=np.uint8),
+ "observation/joint_position": rng.standard_normal(7).astype(np.float32),
+ "observation/gripper_position": np.array([0.25], dtype=np.float32),
+ "prompt": "put the cup in the bowl",
+ }
+
+
+def test_codec_is_byte_identical_to_openpi_and_round_trips():
+ obs = sample_obs()
+ obs["nested"] = {"count": np.int64(3), "flag": True, "ratio": np.float32(0.5)}
+ ours, theirs = protocol.packb(obs), ref_packb(obs)
+ assert ours == theirs
+ back = protocol.unpackb(theirs)
+ assert back["prompt"] == obs["prompt"] and np.array_equal(
+ back["observation/image"], obs["observation/image"]
+ )
+ assert back["observation/joint_position"].dtype == np.float32 and back["nested"]["count"] == 3
+ assert ref_unpackb(ours)["observation/gripper_position"].tolist() == [0.25]
+ with pytest.raises(ValueError, match="Unsupported dtype"):
+ protocol.packb({"x": np.array([object()])})
+
+
+def droid_policy():
+ config = tiny_config(
+ camera_layout="droid",
+ camera_keys=("images.wrist", "images.left", "images.right"),
+ canvas_hw=(544, 736),
+ action_dim=8,
+ gripper_flip_dims=(-1,),
+ )
+ return FluxActionPolicy(config, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+@pytest.fixture(scope="module")
+def adapter():
+ return RoboLabPolicy(droid_policy(), seed_base=100)
+
+
+def test_adapter_returns_chunk_and_matches_the_three_camera_path(adapter):
+ obs = sample_obs()
+ out = adapter.infer(obs)
+ assert set(out) == {"action"} and out["action"].shape == (32, 8) and out["action"].dtype == np.float32
+ assert np.isfinite(out["action"]).all() and adapter.queries == 1
+ # A composite assembled from three cameras in float (the training composition) must give the
+ # actions the three-camera path gives for those cameras.
+ rng = torch.Generator().manual_seed(1)
+ cams = {
+ k: torch.rand(1, 3, 360, 640, generator=rng) for k in ("images.wrist", "images.left", "images.right")
+ }
+ stacked = torch.stack([cams[k][0] for k in ("images.wrist", "images.left", "images.right")])[:, None]
+ canvas = packing.compose_canvas(stacked, "droid", (544, 736)) # (3, 1, 544, 736) in [-1, 1]
+ composite = canvas[:, 0, :540, :640].add(1).div(2) # the un-padded content, back to [0, 1]
+ state = torch.tensor([0.1, -0.2, 0.3, 0.0, 0.5, -0.1, 0.2, 0.25])
+ policy = adapter.policy
+ direct = policy.predict_action_chunk({**cams, "state": state[None], "task": ["move"]})[0]
+ via_composite = policy.predict_from_composite(composite, state, "move", seed=policy.config.inference_seed)
+ torch.testing.assert_close(via_composite, direct, rtol=0, atol=0)
+ # uint8 composites take the same path after scaling
+ as_uint8 = (composite * 255).round().to(torch.uint8).permute(1, 2, 0)
+ assert policy.predict_from_composite(as_uint8, state, "move").shape == (32, 8)
+
+
+def test_observation_parsing_and_views(adapter):
+ obs = sample_obs()
+ obs["observation/joint_position"] = np.stack([obs["observation/joint_position"]] * 3) # history
+ obs["observation/gripper_position"] = np.array([[0.1], [0.7]], dtype=np.float32)
+ state = observation_state(obs, 8)
+ assert state.shape == (8,) and state[-1] == np.float32(0.7) # last row, gripper passed as given
+ views = {
+ "observation/wrist_image_left": obs["observation/image"][:360],
+ "observation/exterior_image_1_left": obs["observation/image"][:360],
+ "observation/exterior_image_2_left": obs["observation/image"][:360],
+ }
+ composite = compose_views(*(views[k] for k in views))
+ assert composite.shape == (540, 640, 3) and composite.dtype == np.uint8
+ out = adapter.infer(
+ {**views, "observation/joint_position": state[:7], "observation/gripper_position": 0.3}
+ )
+ assert out["action"].shape == (32, 8)
+
+
+def test_replay_collection_reports_matches_and_mismatches(adapter, tmp_path):
+ obs = sample_obs()
+ recorded = adapter.infer(obs, seed=7)["action"]
+ np.savez(tmp_path / "fixture.npz", **{k: v for k, v in obs.items() if k != "prompt"})
+ (tmp_path / "predicted_actions.json").write_text(json.dumps({"predicted_actions": recorded.tolist()}))
+ collection = {
+ "kind": "policy-fixture-collection",
+ "fixtures": [
+ {
+ "id": "a",
+ "fixture": "fixture.npz",
+ "expected_actions": "predicted_actions.json",
+ "prompt": obs["prompt"],
+ "seed": 7,
+ }
+ ],
+ }
+ (tmp_path / "collection.json").write_text(json.dumps(collection))
+ report = replay_collection(tmp_path / "collection.json", adapter, tmp_path / "out")
+ assert report["passed"] and report["cases"][0]["max_abs"] == 0.0
+ collection["fixtures"][0]["seed"] = 8 # a different seed draws different noise
+ (tmp_path / "collection.json").write_text(json.dumps(collection))
+ assert not replay_collection(tmp_path / "collection.json", adapter, tmp_path / "out2")["passed"]
+ # server query logs replay as well
+ logged = RoboLabPolicy(adapter.policy, log_dir=tmp_path / "logs")
+ logged.infer(obs)
+ metadata = json.loads((tmp_path / "logs/query_000001.json").read_text())
+ assert metadata["serving_setup"] == adapter.policy.serving_setup
+ report = replay_collection(tmp_path / "logs", logged, tmp_path / "out3")
+ assert report["passed"] and report["cases"][0]["id"] == "query_000001"
+
+
+def _free_port():
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+class _Stub:
+ chunk_size, action_dim = 32, 8
+
+ def infer(self, obs, *, seed=None):
+ if "explode" in obs:
+ raise ValueError("boom")
+ return {"action": np.full((32, 8), float(obs["observation/gripper_position"][0]), np.float32)}
+
+
+def test_server_speaks_the_openpi_protocol():
+ import websockets
+ import websockets.sync.client
+
+ port = _free_port()
+ loop = asyncio.new_event_loop()
+ ready = asyncio.Event()
+ stop = loop.create_future()
+
+ async def main():
+ task = asyncio.ensure_future(
+ serve_async(_Stub(), host="127.0.0.1", port=port, metadata={"name": "stub"}, ready=ready)
+ )
+ await stop
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ def run():
+ asyncio.set_event_loop(loop)
+ loop.run_until_complete(main())
+ loop.close()
+
+ thread = threading.Thread(target=run, daemon=True)
+ thread.start()
+ for _ in range(200):
+ if ready.is_set():
+ break
+ threading.Event().wait(0.02)
+ packer = protocol.Packer()
+ with websockets.sync.client.connect(f"ws://127.0.0.1:{port}", compression=None, max_size=None) as conn:
+ assert protocol.unpackb(conn.recv()) == {"name": "stub"}
+ conn.send(packer.pack({"observation/gripper_position": np.array([0.5], np.float32)}))
+ response = protocol.unpackb(conn.recv())
+ assert response["action"].shape == (32, 8) and float(response["action"][0, 0]) == 0.5
+ assert "infer_ms" in response["server_timing"]
+ conn.send(packer.pack({"observation/gripper_position": np.array([1.0], np.float32)}))
+ assert "prev_total_ms" in protocol.unpackb(conn.recv())["server_timing"]
+ conn.send(packer.pack({"explode": True}))
+ error = conn.recv()
+ assert isinstance(error, str) and "boom" in error
+ with pytest.raises(websockets.ConnectionClosed) as info:
+ conn.recv()
+ assert info.value.rcvd.code == 1011
+ loop.call_soon_threadsafe(stop.set_result, None)
+ thread.join(timeout=10)
+ assert not thread.is_alive()
+
+
+@pytest.mark.parametrize("views", [False, True])
+def test_msgpack_observations_are_writable_before_torch_conversion(views):
+ import warnings
+
+ adapter = RoboLabPolicy(droid_policy())
+ obs = sample_obs()
+ if views:
+ frame = obs.pop("observation/image")[:360]
+ for key in (
+ "observation/wrist_image_left",
+ "observation/exterior_image_1_left",
+ "observation/exterior_image_2_left",
+ ):
+ obs[key] = frame
+ decoded = protocol.unpackb(protocol.packb(obs))
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", UserWarning)
+ actual = adapter.infer(decoded, seed=17)["action"]
+ expected = adapter.infer(obs, seed=17)["action"]
+ np.testing.assert_array_equal(actual, expected)
+
+
+@pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf")])
+def test_nonfinite_actions_are_rejected_before_logging(tmp_path, monkeypatch, value):
+ policy = droid_policy()
+ monkeypatch.setattr(policy, "predict_from_composite", lambda *a, **k: torch.full((32, 8), value))
+ adapter = RoboLabPolicy(policy, log_dir=tmp_path / "logs")
+ with pytest.raises(RuntimeError, match="non-finite actions"):
+ adapter.infer(sample_obs())
+ assert not (tmp_path / "logs").exists()
diff --git a/flux-umi/tests/test_shared_encoder_hub.py b/flux-umi/tests/test_shared_encoder_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c9198efd387eb4a405e7bf6212930ddd3e5275c
--- /dev/null
+++ b/flux-umi/tests/test_shared_encoder_hub.py
@@ -0,0 +1,52 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Shared encoders must resolve the same pinned repo/subfolder for all components."""
+
+import sys
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+from flux_action.models.text_encoder import Qwen3VLEmbedder
+
+
+@pytest.mark.parametrize("local", [False, True])
+def test_text_model_and_processor_share_location(monkeypatch, tmp_path, local):
+ calls = []
+
+ def model(spec, **kwargs):
+ calls.append(("model", spec, kwargs))
+ return torch.nn.Identity()
+
+ def processor(spec, **kwargs):
+ calls.append(("processor", spec, kwargs))
+ return SimpleNamespace(tokenizer=SimpleNamespace(padding_side="right"))
+
+ monkeypatch.setitem(
+ sys.modules,
+ "transformers",
+ SimpleNamespace(
+ Qwen3VLForConditionalGeneration=SimpleNamespace(from_pretrained=model),
+ AutoProcessor=SimpleNamespace(from_pretrained=processor),
+ ),
+ )
+ spec = str(tmp_path) if local else "org/base:text_encoder@immutable"
+ Qwen3VLEmbedder(spec)
+ expected = {} if local else {"revision": "immutable", "subfolder": "text_encoder"}
+ repo = spec if local else "org/base"
+ assert calls == [
+ ("model", repo, {"torch_dtype": torch.bfloat16, **expected}),
+ ("processor", repo, expected),
+ ]
diff --git a/flux-umi/tests/test_so101_config.py b/flux-umi/tests/test_so101_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..992be836561d88756d4139a609fca13cbcda3a24
--- /dev/null
+++ b/flux-umi/tests/test_so101_config.py
@@ -0,0 +1,119 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Validate the runnable SO-101 training config and the separate historical corpus inventory."""
+
+import json
+import math
+from pathlib import Path
+
+from flux_action.config import PolicyConfig
+from flux_action.training.trainer import TrainConfig
+
+CONFIGS = Path(__file__).resolve().parents[1] / "configs" / "so101"
+CORPUS = json.loads((CONFIGS / "community_corpus.json").read_text())
+
+
+def test_policy_config_geometry():
+ cfg = PolicyConfig(**TrainConfig.from_file(CONFIGS / "train.json").policy)
+ assert cfg.window_frames == 50 and cfg.chunk_size == 42 and cfg.fps == 30.0
+ assert cfg.inference_profile == "history" and cfg.n_obs_steps == 8
+ assert cfg.history_snapshots == 2 and cfg.condition_on_past_actions
+ assert cfg.n_action_steps == 32 and cfg.text_fixed_length == 320 and cfg.video_position_fps == 24.0
+ assert cfg.latent_hw == (8, 16)
+ assert cfg.camera_layout == "side_by_side" and cfg.camera_keys == ("images.scene", "images.wrist")
+ assert cfg.gripper_flip_dims == () and not cfg.augment
+ assert cfg.action_parameterization == "joint_delta" and cfg.absolute_action_dims == (5,)
+ assert cfg.action_normalization is None and cfg.state_normalization is None # filled from the index
+ assert cfg.normalization_clip == 6.0 and cfg.camera_dropout == {"images.wrist": 0.2}
+ assert cfg.caption_dropout == 0.1 and cfg.train_timestep_shift == 42.0 and cfg.action_scale == 2.0
+ assert cfg.optimizer_lr == 1.3e-4 and cfg.optimizer_lr_heads_multiplier == 5.0
+ assert cfg.canvas_hw == (256, 512)
+
+
+def test_history_settings_match_current_checkpoint():
+ cfg = PolicyConfig(**TrainConfig.from_file(CONFIGS / "train.json").policy)
+ delivered = json.loads((CONFIGS.parents[1] / "tests/fixtures/so101_history/config.json").read_text())
+ for key in (
+ "n_obs_steps",
+ "history_snapshots",
+ "condition_on_past_actions",
+ "chunk_size",
+ "n_action_steps",
+ "fps",
+ "video_position_fps",
+ "text_fixed_length",
+ "separate_timesteps",
+ "video_logit_mean",
+ "video_logit_std",
+ "conditioning_noise_max",
+ "loss_reduction",
+ "action_channel_weights",
+ "action_loss_weight",
+ "video_loss_weight",
+ "train_timestep_width",
+ "train_timestep_shift",
+ ):
+ assert getattr(cfg, key) == delivered[key], key
+
+
+def test_train_config_and_global_batch():
+ cfg = TrainConfig.from_file(CONFIGS / "train.json")
+ assert cfg.global_batch(16) == 512
+ assert cfg.steps == 10000 and cfg.cooldown_start is None and cfg.checkpoint_every == 500
+ assert cfg.keep_checkpoints is None and cfg.keep_every is None # every checkpoint kept
+ assert cfg.ema_sigma_rels == (0.1, 0.05) and cfg.betas == (0.9, 0.99) and cfg.weight_decay == 0.05
+ assert cfg.frame_hw == (256, 256) and cfg.max_grad_norm == 1.0
+ assert (cfg.frozen_steps, cfg.trunk_warmup_steps, cfg.heads_warmup_steps) == (1000, 2000, 1000)
+ assert not cfg.reseed_on_resume
+
+
+def test_learning_rates_follow_batch_scaling():
+ train = TrainConfig.from_file(CONFIGS / "train.json")
+ cfg = PolicyConfig(**train.policy)
+ assert math.isclose(cfg.optimizer_lr, 2e-4 * 1.3 * math.sqrt(train.global_batch(16) / 2048))
+ assert math.isclose(cfg.optimizer_lr * cfg.optimizer_lr_heads_multiplier, 6.5e-4)
+
+
+def test_corpus_reference():
+ counts = CORPUS["counts"]
+ parts = CORPUS["parts"]
+ assert len(parts) == counts["parts_built"] == 1021
+ assert sum(p["train_windows"] for p in parts) == counts["train_windows"] == 631391
+ assert sum(p["val_windows"] for p in parts) == counts["val_windows"] == 119
+ assert sum(1 for p in parts if p["train_windows"]) == counts["parts_in_train"] == 1016
+ assert [p["part"] for p in parts if p["val_windows"]] == CORPUS["val_parts"]
+ origins = {p["origin"] for p in parts}
+ assert origins == {"molmoact", "community_dataset_v3"}
+ assert CORPUS["sources"]["molmoact"]["parts"] == sum(p["origin"] == "molmoact" for p in parts)
+ assert CORPUS["sources"]["community_dataset_v3"]["parts"] == sum(
+ p["origin"] == "community_dataset_v3" for p in parts
+ )
+ assert len(CORPUS["sources"]["community_dataset_v3"]["revision"]) == 40
+ for p in parts:
+ assert p["fps"] == 30.0 and p["scene_camera"].startswith("observation.images.")
+ assert "/" in p["dataset"] and not p["dataset"].startswith("/")
+ dim = p["action_dim"]
+ assert len(p["action_q01"]) == len(p["action_q99"]) == dim
+ assert len(p["state_q01"]) == len(p["state_q99"]) == dim
+ # names come from the source dataset; a few declare one group label ("motors") instead of six names
+ assert len(p["action_names"]) in (dim, 1) and len(p["state_names"]) in (dim, 1)
+ # q99 == q01 happens (a gripper that never moved); the builder then normalizes with span 1.0
+ assert all(hi >= lo for lo, hi in zip(p["action_q01"], p["action_q99"]))
+ assert all(hi >= lo for lo, hi in zip(p["state_q01"], p["state_q99"]))
+ if dim != 6:
+ assert "excluded" in p and p["train_windows"] == 0 and p["val_windows"] == 0
+ else:
+ assert "excluded" not in p
+ assert [p["part"] for p in parts] == sorted(p["part"] for p in parts)
+ assert "degenerate_channels" in CORPUS["builder"]
diff --git a/flux-umi/tests/test_state_dropout.py b/flux-umi/tests/test_state_dropout.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad867190ce708e9dd57e7a49890f97c34c91777c
--- /dev/null
+++ b/flux-umi/tests/test_state_dropout.py
@@ -0,0 +1,110 @@
+"""CPU tests for ``PolicyConfig.state_dropout`` (the UMI recipe sets
+``policy.state_dropout: 0.5``, a field this tree lacked). The port must blank the whole normalized conditioning state of a
+window with that probability, drawn from the window's generator right after the augmentation draws of ``_encode_windows``
+(the reference ``fluxcode_0927`` policy.py:624-629), leave the global RNG untouched when generators are provided, and
+validate the field. Every test here fails on the unfixed code (``PolicyConfig(state_dropout=...)`` raises ``TypeError``)."""
+import pytest
+import torch
+from conftest import make_policy, tiny_config
+
+from flux_action.config import PolicyConfig
+from flux_action.processing import packing
+
+
+def _batch(n, seeds=None):
+ rng = torch.Generator().manual_seed(5)
+ out = {
+ "images.top": torch.rand(n, 33, 3, 64, 96, generator=rng),
+ "state": torch.rand(n, 6, generator=rng),
+ "action": torch.rand(n, 32, 6, generator=rng),
+ "task": ["pick"] * n,
+ }
+ if seeds is not None:
+ out["window_seed"] = torch.tensor(seeds)
+ return out
+
+
+def test_config_default_and_validation():
+ cfg = PolicyConfig()
+ assert cfg.state_dropout == 0.0
+ assert tiny_config(state_dropout=0.5).state_dropout == 0.5
+ tiny_config(state_dropout=1).validate_training()
+ for bad in (-0.1, 1.5, "0.5", True, None):
+ with pytest.raises(ValueError):
+ tiny_config(state_dropout=bad)
+
+
+@pytest.mark.parametrize("seeds", [None, [1, 2, 3, 4]])
+def test_one_blanks_every_window_and_zero_leaves_the_state_untouched(seeds):
+ batch = _batch(4, seeds)
+ # policies are built before seeding: module construction consumes the global RNG
+ plain = make_policy(tiny_config(caption_dropout=0.0)).train()
+ zero = make_policy(tiny_config(caption_dropout=0.0, state_dropout=0.0)).train()
+ one = make_policy(tiny_config(caption_dropout=0.0, state_dropout=1.0)).train()
+ torch.manual_seed(0)
+ reference = plain.prepare(batch).state
+ assert reference.shape == (4, 6) and not torch.any(reference == 0)
+ torch.manual_seed(0)
+ assert torch.equal(zero.prepare(batch).state, reference)
+ torch.manual_seed(0)
+ assert torch.equal(one.prepare(batch).state, torch.zeros_like(reference))
+ # evaluation mode never blanks
+ torch.manual_seed(0)
+ assert torch.equal(one.eval().prepare(batch).state, reference)
+
+
+@pytest.mark.parametrize("augment", [False, True])
+def test_seeded_blank_decision_matches_the_reference_formula(augment):
+ """Per window: caption draw, (no camera dropout), augmentation draws, then ``rand(()) < p`` from the same generator."""
+ p = 0.5
+ seeds = list(range(100, 116))
+ policy = make_policy(tiny_config(caption_dropout=0.1, augment=augment, state_dropout=p)).train()
+ plain = make_policy(tiny_config(caption_dropout=0.1, augment=augment)).train()
+ batch = _batch(len(seeds), seeds)
+ torch.manual_seed(0)
+ reference = plain.prepare(batch).state
+ torch.manual_seed(0)
+ first = policy.prepare(batch).state
+ torch.manual_seed(999)
+ second = policy.prepare(batch).state
+ assert torch.equal(first, second) # independent of the global RNG
+ expected = []
+ for s in seeds:
+ g = torch.Generator().manual_seed(s)
+ torch.rand((), generator=g) # caption dropout draw
+ if augment:
+ packing.sample_augmentation(g, camera_hw=(64, 96))
+ expected.append(float(torch.rand((), generator=g)) < p)
+ assert any(expected) and not all(expected)
+ for i, blank in enumerate(expected):
+ assert torch.equal(first[i], torch.zeros(6) if blank else reference[i])
+
+
+def test_global_rng_tail_is_unchanged_when_generators_are_provided():
+ batch = _batch(4, [7, 8, 9, 10])
+ policy = make_policy(tiny_config(caption_dropout=0.0, state_dropout=0.5)).train()
+ plain = make_policy(tiny_config(caption_dropout=0.0)).train()
+ torch.manual_seed(0)
+ policy.prepare(batch)
+ tail = torch.rand(5)
+ torch.manual_seed(0)
+ plain.prepare(batch)
+ assert torch.equal(torch.rand(5), tail)
+
+
+def test_unseeded_windows_draw_one_scalar_each_from_the_global_rng_after_the_augmentations():
+ """Without seeds every window's blank draw is ``torch.rand((), generator=None)``, as in the reference."""
+ b, p = 3, 0.5
+ batch = _batch(b)
+ plain = make_policy(tiny_config(caption_dropout=0.0, augment=True)).train()
+ policy = make_policy(tiny_config(caption_dropout=0.0, augment=True, state_dropout=p)).train()
+ torch.manual_seed(11)
+ reference = plain.prepare(batch).state
+ expected = [float(torch.rand(())) < p for _ in range(b)]
+ assert any(expected) and not all(expected)
+ tail = torch.rand(5)
+ torch.manual_seed(11)
+ state = policy.prepare(batch).state
+ assert torch.equal(torch.rand(5), tail)
+ for i, blank in enumerate(expected):
+ assert torch.equal(state[i], torch.zeros(6) if blank else reference[i])
diff --git a/flux-umi/tests/test_umi_epoch_stream.py b/flux-umi/tests/test_umi_epoch_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..f75a7ce7928dd71deb377939265610c36b9c3645
--- /dev/null
+++ b/flux-umi/tests/test_umi_epoch_stream.py
@@ -0,0 +1,105 @@
+"""Cross-epoch loader checks without videos or a model-sized GPU run."""
+
+import gc
+import os
+from collections import Counter
+
+import pytest
+
+from flux_action.data.umi.all_windows import AllWindowDataset
+from flux_action.training.data import build_dataloader, epoch_loader_state
+
+
+def manifest():
+ return {
+ "fps": 30,
+ "chunk_size": 32,
+ "total_frames": 210,
+ "state_dim": 20,
+ "action_dim": 20,
+ "camera_order": ["left_ego", "right_ego"],
+ "episodes": [
+ {
+ "episode_id": str(i), "episode_index": i, "n_frames": 70,
+ "start_ranges": [[1, 8 + i], [15, 21 + i]],
+ "valid_ranges": [[1, 70]], "keep_ranges": [[0, 70]], "split": "train",
+ }
+ for i in range(3)
+ ],
+ }
+
+
+class IdentityWindows(AllWindowDataset):
+ def window_at(self, episode, start, *, window_seed=0):
+ return {
+ "task": "identity-only", "episode_index": episode, "start": start,
+ "window_seed": window_seed, "worker_pid": os.getpid(),
+ }
+
+
+def identities(batches):
+ return [
+ (int(episode), int(start), int(seed))
+ for batch in batches
+ for episode, start, seed in zip(
+ batch["episode_index"], batch["start"], batch["window_seed"], strict=True
+ )
+ ]
+
+
+@pytest.mark.parametrize("workers,batch,accum,rank,world,skip", [
+ (2, 2, 1, 0, 1, 0), (3, 5, 2, 1, 2, 3), (4, 3, 3, 2, 4, 0),
+])
+def test_continuous_loader_matches_rebuilt_epochs(workers, batch, accum, rank, world, skip):
+ kwargs = dict(seed=81, rank=rank, world_size=world, num_workers=workers,
+ windows_per_rank=batch, grad_accumulation=accum)
+ dataset = IdentityWindows(manifest(), ".", epoch=1, skip_batches=skip, **kwargs)
+ dataset.set_continuous_end(4 * dataset.batches_per_rank)
+ loader = build_dataloader(dataset, prefetch_factor=1, persistent_workers=True)
+ seen, pids = [], set()
+ try:
+ iterator = iter(loader)
+ for epoch in range(1, 4):
+ remaining = dataset.batches_per_rank - (skip if epoch == 1 else 0)
+ current = [next(iterator) for _ in range(remaining)]
+ reference = IdentityWindows(manifest(), ".", epoch=epoch,
+ skip_batches=skip if epoch == 1 else 0, **kwargs)
+ expected = list(build_dataloader(reference, prefetch_factor=1))
+ assert identities(current) == identities(expected)
+ seen.append(identities(current))
+ pids.update(int(pid) for row in current for pid in row["worker_pid"])
+ assert len(pids) == workers and os.getpid() not in pids
+ with pytest.raises(StopIteration):
+ next(iterator)
+ assert seen[0] != seen[1]
+ finally:
+ del loader
+ gc.collect()
+
+
+class CachedWindows(IdentityWindows):
+ def window_at(self, episode, start, *, window_seed=0):
+ self._states.setdefault(episode, self.epoch)
+ item = super().window_at(episode, start, window_seed=window_seed)
+ item["cached_epoch"] = self._states[episode]
+ return item
+
+
+def test_continuous_prefetch_clears_worker_state_at_epoch_boundaries():
+ dataset = CachedWindows(manifest(), ".", seed=9, num_workers=3,
+ windows_per_rank=2, grad_accumulation=1)
+ dataset.set_loader_state(epoch_loader_state(0, 0))
+ dataset.set_continuous_end(3 * dataset.batches_per_rank)
+ loader = build_dataloader(dataset, prefetch_factor=2, persistent_workers=True)
+ try:
+ iterator = iter(loader)
+ for epoch in range(3):
+ batches = [next(iterator) for _ in range(dataset.batches_per_rank)]
+ assert Counter(int(value) for batch in batches for value in batch["cached_epoch"]) == {
+ epoch: dataset.batches_per_rank * dataset.windows_per_rank,
+ }
+ with pytest.raises(StopIteration):
+ next(iterator)
+ finally:
+ del loader
+ gc.collect()
diff --git a/flux-umi/tests/test_vae_training_prefix.py b/flux-umi/tests/test_vae_training_prefix.py
new file mode 100644
index 0000000000000000000000000000000000000000..67e207042abc716aa73cce217f69f6cb1f5a6758
--- /dev/null
+++ b/flux-umi/tests/test_vae_training_prefix.py
@@ -0,0 +1,62 @@
+"""Contracts for the opt-in causal training prefix path; real-weight checks live in perf reports."""
+
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+from flux_action.config import PolicyConfig
+from flux_action.processing import packing
+
+
+class CausalEncoder:
+ def __init__(self, causal=True):
+ self.module = SimpleNamespace(params=SimpleNamespace(enc_causal=causal))
+ self.frames = []
+
+ @torch.inference_mode()
+ def encode(self, video):
+ self.frames.append(video.shape[2])
+ return video[:, :, ::4]
+
+ encode_task = encode
+
+
+def test_prefix_keeps_all_consumed_values_and_autograd_ownership():
+ encoder = CausalEncoder()
+ video = torch.arange(2 * 3 * 33 * 4 * 5, dtype=torch.float32).reshape(2, 3, 33, 4, 5)
+ original = video.clone()
+ rng = torch.get_rng_state().clone()
+ baseline = packing.encode_videos(encoder, video, (2, 3))
+ prefix = packing.encode_videos(encoder, video, (2, 3), trim_causal_tail=True)
+ assert encoder.frames == [45, 33]
+ assert torch.equal(prefix, baseline)
+ assert torch.equal(video, original) and torch.equal(torch.get_rng_state(), rng)
+ # Frozen encoder outputs must be usable as saved tensors by the trainable DiT.
+ parameter = torch.nn.Parameter(torch.ones_like(prefix))
+ (parameter * prefix).sum().backward()
+ assert torch.equal(parameter.grad, baseline)
+
+
+@pytest.mark.parametrize("frames,chunk,causal", [(29, 45, True), (33, 49, True), (33, 45, False)])
+def test_prefix_rejects_unvalidated_encoder_contract(frames, chunk, causal):
+ encoder = CausalEncoder(causal)
+ with pytest.raises(ValueError, match="causal VAE"):
+ packing.encode_videos(
+ encoder, torch.zeros(1, 3, frames, 2, 2), (2, 2),
+ chunk_frames=chunk, trim_causal_tail=True,
+ )
+ assert encoder.frames == []
+
+
+def test_opt_in_layout_validation_and_serialization():
+ config = PolicyConfig(vae_trim_causal_tail=True)
+ config.validate_training()
+ assert PolicyConfig(**config.to_dict()).vae_trim_causal_tail
+ config.chunk_size = 28
+ with pytest.raises(ValueError, match="33-frame"):
+ config.validate_training()
+ config.chunk_size = 32
+ config.inference_profile = "history"
+ with pytest.raises(ValueError, match="default"):
+ config.validate_training()
diff --git a/flux-umi/tests/test_video.py b/flux-umi/tests/test_video.py
new file mode 100644
index 0000000000000000000000000000000000000000..c53a2c3ea3c15b54f9e463ede0dbc4e17f9c7d81
--- /dev/null
+++ b/flux-umi/tests/test_video.py
@@ -0,0 +1,65 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Seek-decoded windows equal sequential decodes for both backends and land on the right frames."""
+
+import shutil
+
+import numpy as np
+import pytest
+from synthetic_droid import FRAME_HW, frame_image, write_av1_clip
+
+from flux_action.data.droid.cosmos import decode_frames
+from flux_action.data.droid.video import decode_window
+
+
+@pytest.fixture(scope="module")
+def clip(tmp_path_factory):
+ path = tmp_path_factory.mktemp("video") / "clip.mp4"
+ frames = np.stack([frame_image(1, i, 2) for i in range(45)])
+ write_av1_clip(path, frames)
+ return path
+
+
+def sequential_pyav(path):
+ import av
+
+ with av.open(str(path)) as container:
+ return np.stack([f.to_ndarray(format="rgb24") for f in container.decode(video=0)])
+
+
+@pytest.mark.parametrize("decoder", ["ffmpeg", "pyav"])
+def test_seek_decode_matches_sequential_decode(clip, decoder):
+ if decoder == "ffmpeg" and shutil.which("ffmpeg") is None:
+ pytest.skip("ffmpeg binary not installed")
+ if decoder == "ffmpeg":
+ reference = decode_frames(clip, 0, 45, FRAME_HW)
+ else:
+ reference = sequential_pyav(clip)
+ assert reference.shape == (45, *FRAME_HW, 3)
+ for first in (0, 1, 7, 12):
+ window = decode_window(clip, first, 33, frame_hw=FRAME_HW, decoder=decoder)
+ assert window.shape == (33, *FRAME_HW, 3)
+ assert np.array_equal(window, reference[first : first + 33]), (decoder, first)
+ # green encodes the frame index; a wrong seek shows up as a wrong ramp
+ greens = window[..., 1].reshape(33, -1).mean(1)
+ assert np.abs(greens - (6 * np.arange(first, first + 33)) % 250).max() < 4
+ with pytest.raises(ValueError):
+ decode_window(clip, 20, 33, frame_hw=FRAME_HW, decoder=decoder)
+ with pytest.raises(ValueError):
+ decode_window(clip, -1, 3, frame_hw=FRAME_HW, decoder=decoder)
+
+
+def test_unknown_decoder(clip):
+ with pytest.raises(ValueError, match="unknown decoder"):
+ decode_window(clip, 0, 1, decoder="magic")
diff --git a/flux-umi/tests/test_video_vae.py b/flux-umi/tests/test_video_vae.py
new file mode 100644
index 0000000000000000000000000000000000000000..5789d466438555c067c86849567efa7da7f53664
--- /dev/null
+++ b/flux-umi/tests/test_video_vae.py
@@ -0,0 +1,114 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""The looped video-VAE decode equals the full decode; its halo arithmetic matches NATTEN's edge clamping."""
+
+import pytest
+import torch
+
+pytest.importorskip("natten") # the VAE imports NATTEN; on CPU it runs NATTEN's flex-attention backend
+
+from flux_action.models import video_vae as vv # noqa: E402
+from flux_action.models.runtime import random_init_ # noqa: E402
+
+
+def natten_window(i: int, length: int, kernel: int, causal: bool) -> range:
+ """Frames that frame ``i`` attends to under NATTEN's neighborhood definition."""
+ if causal:
+ return range(max(0, i - kernel + 1), i + 1)
+ start = min(max(i - kernel // 2, 0), length - kernel)
+ return range(start, start + kernel)
+
+
+@pytest.mark.parametrize("causal", [False, True])
+@pytest.mark.parametrize("kernel", [3, 5])
+def test_temporal_core_halo_reproduces_full_sequence_neighborhoods(kernel, causal):
+ for length in range(kernel, 4 * kernel):
+ for max_t in range(kernel, kernel + 6):
+ for core_start in range(0, length, max_t):
+ core_end = min(core_start + max_t, length)
+ hs, he = vv._temporal_core_halo(core_start, core_end, length, kernel, causal)
+ assert 0 <= hs <= core_start and core_end <= he <= length
+ assert he - hs >= kernel
+ # Never reaches into the window before the previous one, whose output is already written.
+ assert hs >= core_start - max_t
+ for i in range(core_start, core_end):
+ inside_halo = natten_window(i - hs, he - hs, kernel, causal)
+ assert [f + hs for f in inside_halo] == list(natten_window(i, length, kernel, causal))
+
+
+def tiny_params(**overrides) -> vv.ViTNormInferenceParams:
+ # head_dim 8 at every stage; spatial kernel 3 keeps the 3x3 latent legal for NATTEN and the CPU cheap.
+ return vv.ViTNormInferenceParams(
+ z_dim=8,
+ embed_dim=8,
+ num_heads=[1, 2, 4, 8],
+ window_size=[5, 3, 3],
+ enc_depths=[1, 1, 1, 1],
+ dec_depths=[1, 1, 2, 1],
+ dtype="float32",
+ use_compile=False,
+ **overrides,
+ )
+
+
+@pytest.fixture
+def cpu_backend(monkeypatch):
+ monkeypatch.setenv(vv._NATTEN_BACKEND_ENV, "flex-fna")
+ monkeypatch.setattr(vv, "_natten_backends", {})
+
+
+def tiny_vae(decoder_max_t: int | None) -> vv.ViTNormInference:
+ model = vv.ViTNormInference(tiny_params(decoder_max_t=decoder_max_t))
+ random_init_(model, dtype=torch.float32)
+ return model.eval()
+
+
+def test_looped_decode_matches_full_decode(cpu_backend, monkeypatch):
+ model = tiny_vae(decoder_max_t=5)
+ regions = []
+ forward_region = vv.Natten3D.forward_region
+ monkeypatch.setattr(
+ vv.Natten3D,
+ "forward_region",
+ lambda self, x, **kw: regions.append(x.shape[1]) or forward_region(self, x, **kw),
+ )
+ torch.manual_seed(1)
+ # 5 latent frames -> 9 -> 17 through the decoder's two temporal expansions (NATTEN needs T >= kernel).
+ z = torch.randn(1, 8, 5, 3, 3)
+ with torch.inference_mode():
+ looped = model.decode(z)
+ for block in model.model.decoder.features.modules():
+ if isinstance(block, vv.SwinTransformerBlock):
+ block.max_t = None
+ full = model.decode(z, chunked_decode=False)
+ assert looped.shape == full.shape == (1, 3, 17, 96, 96)
+ # The 5-frame stage runs in one pass. 9 frames loop as windows [0,5) [5,9) with halos of 7 and 6 frames;
+ # 17 frames as [0,5) [5,10) [10,15) [15,17) with halos of 7, 9, 9 and 5 frames.
+ assert regions and set(regions) == {7, 6, 9, 5}
+ torch.testing.assert_close(looped, full, atol=1e-5, rtol=1e-4)
+
+
+def test_looped_decoder_handles_a_single_frame_latent(cpu_backend):
+ model = tiny_vae(decoder_max_t=5)
+ with torch.inference_mode():
+ out = model.decode(torch.randn(1, 8, 1, 3, 3))
+ assert out.shape == (1, 3, 1, 96, 96)
+
+
+def test_looped_decode_rejects_windows_below_the_kernel_and_gradients(cpu_backend):
+ with pytest.raises(ValueError, match="temporal kernel"):
+ vv.ViTNormInference(tiny_params(decoder_max_t=4))
+ model = tiny_vae(decoder_max_t=5)
+ with pytest.raises(RuntimeError, match="in place"):
+ model.model.decode(torch.randn(1, 8, 9, 3, 3))
diff --git a/flux-umi/tests/training/test_activation_offload.py b/flux-umi/tests/training/test_activation_offload.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b6d366e51adca6fb14c67650ea629268adfd125
--- /dev/null
+++ b/flux-umi/tests/training/test_activation_offload.py
@@ -0,0 +1,292 @@
+"""Tests for training/activation_offload.py: asynchronous CPU offload of checkpoint-held activations.
+
+The CUDA tests run a checkpointed stack of production ``SingleStreamBlock``s (hidden 3072, 24 heads, 2 packed windows
+of 2417 tokens) with the production selective-checkpoint policy and compare offload tiers against plain SAC:
+outputs, dx and every parameter gradient must be bitwise identical. Attention runs on the MATH SDPA backend, the
+only one with a deterministic backward (cuDNN, flash and mem-efficient use atomics for dq); under the dispatch mode
+MATH decomposes into bmm / softmax, so a test-local ``_SacPolicy`` subclass tags the ``attn @ v`` bmm as ``sdpa``.
+"""
+import dataclasses
+
+import pytest
+import torch
+from torch import nn
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
+from torch.nn.attention import SDPBackend, sdpa_kernel
+
+from flux_action.training import activation_offload as AO
+from flux_action.training.activation_offload import OffloadPlan
+from flux_action.training.trainer import TrainConfig
+
+
+def test_plan_and_train_config_validation():
+ plan = OffloadPlan.from_spec("inputs, sdpa,mlp_out", keep_last=3, prefetch=2)
+ assert plan is not None and plan.tiers == ("inputs", "sdpa", "mlp_out") and plan.sac_tiers == ("sdpa", "mlp_out")
+ assert OffloadPlan.from_spec("off") is None and OffloadPlan.from_spec("") is None
+ for bad in (dict(tiers=("bogus",)), dict(tiers=()), dict(keep_last=-1), dict(prefetch=0), dict(min_bytes=0)):
+ with pytest.raises(ValueError):
+ OffloadPlan(**bad)
+ base = dict(TrainConfig.from_file("configs/umi/umi_posttrain_16g.json").__dict__)
+ base["ac_mode"] = "full" # the cases below assume full activation checkpointing
+ cfg = dataclasses.replace(TrainConfig(**base), ac_mode="sac", ac_sac_save=("sdpa",), ac_sac_extra_save=("mlp_out",),
+ ac_sac_extra_blocks=16, ac_offload="inputs,sdpa,mlp_out", ac_offload_keep_last=2)
+ assert cfg.ac_offload == "inputs,sdpa,mlp_out"
+ dataclasses.replace(TrainConfig(**base), ac_offload="inputs") # the inputs tier needs no SAC
+ for bad in (dict(ac_offload="sdpa"), # ac_mode full
+ dict(ac_mode="sac", ac_offload="mlp_out"), # kind not saved
+ dict(ac_mode="sac", ac_offload="bogus"),
+ dict(ac_offload="inputs", activation_checkpointing=False),
+ dict(ac_offload_keep_last=-1), dict(ac_offload_prefetch=0)):
+ with pytest.raises(ValueError):
+ dataclasses.replace(TrainConfig(**base), **bad)
+
+
+# ----------------------------------------------------------------------------------------------- CUDA tests
+cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
+dev = torch.device("cuda")
+HID, HEADS, PER, W, NB = 3072, 24, 2417, 2, 3
+L = W * PER
+MIN_BYTES = 16 << 20 # hidden-width tensors are 29.7 MB here; the rotary table (4.9 MB) and modulations stay resident
+HIDDEN_BYTES = L * HID * 2
+
+
+def _item_bytes(tier):
+ return HIDDEN_BYTES * (2 if tier == "sdpa" else 1) # the MATH backend produces the attention output in fp32
+
+
+def _blocks(seed=0):
+ from flux_action.models.transformer import SingleStreamBlock
+
+ torch.manual_seed(seed)
+ blocks = nn.ModuleList([SingleStreamBlock(HID, HEADS, mlp_ratio=3.0) for _ in range(NB)]).to(dev, torch.bfloat16)
+ for block in blocks:
+ block.attn_mode = "torch"
+ return blocks
+
+
+def _inputs(seed=1):
+ from flux_action.models.transformer import rope
+
+ g = torch.Generator(device=dev).manual_seed(seed)
+ x = torch.randn(1, L, HID, device=dev, dtype=torch.bfloat16, generator=g)
+ mods = tuple(torch.randn(1, 1, HID, device=dev, dtype=torch.bfloat16, generator=g).mul_(0.1) for _ in range(3))
+ pos = (torch.arange(L, device=dev, dtype=torch.float32) % PER)[None]
+ pe = rope(pos, 128, 10000)[:, None].contiguous() # [1, 1, L, 64, 2, 2] fp32
+ return x, mods, pe
+
+
+def _policy_class():
+ from flux_action.training.distributed import _SacPolicy
+
+ class MathSacPolicy(_SacPolicy):
+ """``_SacPolicy`` for the MATH backend: the attention output is the ``bmm(attn_weights, v)`` whose last dim is
+ the head dim (``q @ k^T`` has the sequence length there)."""
+
+ def kind(self, op, args, recompute):
+ if (op is torch.ops.aten.bmm.default and len(args) == 2 and args[1].shape[-1] == 128
+ and args[0].shape[-1] == args[1].shape[-2] and args[0].shape[-1] != 128):
+ self.seen_sdpa[recompute] = True
+ return "sdpa"
+ return super().kind(op, args, recompute)
+
+ return MathSacPolicy
+
+
+def _factory(block, save):
+ from flux_action.training.distributed import _block_dims
+
+ dims, policy = _block_dims(block), _policy_class()
+ return lambda: policy(sorted(save), *dims)
+
+
+def _wrap_plain(blocks, save):
+ from torch.utils.checkpoint import create_selective_checkpoint_contexts
+
+ out = nn.ModuleList()
+ for block in blocks:
+ kwargs = {}
+ if save:
+ factory = _factory(block, save)
+ kwargs["context_fn"] = lambda factory=factory: create_selective_checkpoint_contexts(factory())
+ out.append(checkpoint_wrapper(block, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False, **kwargs))
+ return out
+
+
+def _wrap_offload(blocks, save, plan):
+ factories = [_factory(block, save) if save else None for block in blocks]
+ offloader, wrapped = AO.install(list(blocks), plan, sac_policy_factories=factories, device=dev)
+ return offloader, nn.ModuleList(wrapped)
+
+
+def _forward(blocks, x, mods, pe):
+ h = x
+ for block in blocks:
+ _, h = block(h, None, pe, mods, None, seqlens=[PER] * W)
+ return h
+
+
+def _run(blocks, x0, mods, pe, strided_rows=False):
+ if strided_rows: # the first block's input is a non-dense view (row stride 2 * HID) of a leaf
+ leaf = torch.zeros(1, L, 2, HID, device=dev, dtype=torch.bfloat16)
+ leaf[:, :, 0] = x0
+ leaf.requires_grad_(True)
+ x = leaf[:, :, 0]
+ assert not x.is_contiguous()
+ else:
+ leaf = x = x0.detach().clone().requires_grad_(True)
+ with sdpa_kernel(SDPBackend.MATH):
+ h = _forward(blocks, x, mods, pe)
+ loss = h.float().square().mean()
+ loss.backward()
+ torch.cuda.synchronize()
+ grads = [p.grad.detach().clone() for p in blocks.parameters()]
+ for p in blocks.parameters():
+ p.grad = None
+ dx = leaf.grad[:, :, 0] if strided_rows else leaf.grad
+ return h.detach().clone(), loss.detach().clone(), dx.detach().clone(), grads
+
+
+def _assert_same(a, b):
+ ha, la, dxa, ga = a
+ hb, lb, dxb, gb = b
+ assert torch.equal(ha, hb) and torch.equal(la, lb) and torch.equal(dxa, dxb)
+ assert len(ga) == len(gb) and all(torch.equal(p, q) for p, q in zip(ga, gb, strict=True))
+
+
+def _plan(tiers, **kw):
+ kw.setdefault("keep_last", 1)
+ kw.setdefault("prefetch", 1)
+ kw.setdefault("min_bytes", MIN_BYTES)
+ kw.setdefault("max_inflight_bytes", 0)
+ return OffloadPlan(tiers=tuple(tiers), **kw)
+
+
+@pytest.fixture(scope="module")
+def reference():
+ """Plain SAC (sdpa + mlp_out saved) results and the A/A proof that the stack is deterministic."""
+ x, mods, pe = _inputs()
+ save = {"sdpa", "mlp_out"}
+ blocks = _wrap_plain(_blocks(), save)
+ _run(blocks, x, mods, pe) # warm-up: cuBLAS / SDPA plans
+ first = _run(blocks, x, mods, pe)
+ _assert_same(first, _run(blocks, x, mods, pe))
+ return x, mods, pe, first
+
+
+@cuda
+@pytest.mark.parametrize("tiers,save,keep_last,prefetch", [
+ (("inputs",), {"sdpa", "mlp_out"}, 1, 1),
+ (("inputs", "sdpa"), {"sdpa", "mlp_out"}, 1, 1),
+ (("inputs", "sdpa", "mlp_out"), {"sdpa", "mlp_out"}, 1, 1),
+ (("inputs", "sdpa", "mlp_out"), {"sdpa", "mlp_out"}, 0, 1),
+ (("inputs", "sdpa", "mlp_out"), {"sdpa", "mlp_out"}, 0, 2),
+ (("sdpa", "mlp_out"), {"sdpa", "mlp_out"}, 1, 1),
+ (("inputs", "sdpa", "mlp_out", "attn_out", "qkv"), {"sdpa", "mlp_out", "attn_out", "qkv"}, 1, 1),
+])
+def test_offload_tiers_bitwise_vs_plain_sac(reference, tiers, save, keep_last, prefetch):
+ x, mods, pe, ref = reference
+ if save != {"sdpa", "mlp_out"}: # a different save set: its own plain-SAC reference (same values either way)
+ ref = _run(_wrap_plain(_blocks(), save), x, mods, pe)
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(tiers, keep_last=keep_last, prefetch=prefetch))
+ _run(blocks, x, mods, pe) # warm-up pass: pins the host slots, grows the ring
+ out = _run(blocks, x, mods, pe)
+ _assert_same(ref, out)
+ stats = offloader.summary()
+ per_block = sum(3 if t == "qkv" else 1 for t in tiers)
+ assert stats["items"] == (NB - keep_last) * per_block
+ for tier in tiers:
+ assert stats[f"items_{tier}"] == (NB - keep_last) * (3 if tier == "qkv" else 1)
+ assert stats["d2h_bytes"] == stats["h2d_bytes"] == (NB - keep_last) * sum((3 if t == "qkv" else 1) * _item_bytes(t) for t in tiers)
+ assert stats.get("late_prefetch", 0) == 0 and stats.get("never_fetched", 0) == 0
+ assert stats["ring_slots"] == min(NB - keep_last, prefetch + 1) * per_block # steady state: prefetch+1 blocks of items
+ assert stats["host_slots"] == stats["items"] and stats["host_fallback"] == 0
+ # a third pass reuses every host slot and staging slot
+ _assert_same(ref, _run(blocks, x, mods, pe))
+ again = offloader.summary()
+ assert again["host_slots"] == stats["host_slots"] and again["ring_slots"] == stats["ring_slots"]
+
+
+@cuda
+def test_gpu_memory_released_between_forward_and_backward(reference):
+ x, mods, pe, ref = reference
+ save = {"sdpa", "mlp_out"}
+ plain = _wrap_plain(_blocks(), save)
+ offloader, offl = _wrap_offload(_blocks(), save, _plan(("inputs", "sdpa", "mlp_out"), keep_last=1))
+ _run(plain, x, mods, pe)
+ _run(offl, x, mods, pe)
+
+ def held_after_forward(blocks):
+ torch.cuda.synchronize()
+ base = torch.cuda.memory_allocated(dev)
+ xx = x.detach().clone().requires_grad_(True)
+ with sdpa_kernel(SDPBackend.MATH):
+ h = _forward(blocks, xx, mods, pe)
+ torch.cuda.synchronize()
+ offloader.release_completed() # the D2H copies have completed: drop the GPU sources
+ held = torch.cuda.memory_allocated(dev) - base
+ h.float().square().mean().backward() # finish the pass
+ torch.cuda.synchronize()
+ for p in blocks.parameters():
+ p.grad = None
+ return held
+
+ held_plain = held_after_forward(plain)
+ held_offload = held_after_forward(offl)
+ offloaded = (NB - 1) * sum(_item_bytes(t) for t in ("inputs", "sdpa", "mlp_out"))
+ # with keep_last=1 nothing is staged before the backward, so the whole offloaded set must be gone
+ assert held_plain - held_offload >= 0.95 * offloaded, (held_plain, held_offload, offloaded)
+ assert offloader.summary()["inflight_bytes"] == 0
+
+
+@cuda
+def test_fallbacks_min_bytes_non_dense_and_keep_last(reference):
+ x, mods, pe, ref = reference
+ save = {"sdpa", "mlp_out"}
+ # 1. nothing is large enough: hooks installed, no copies, identical results
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(("inputs", "sdpa", "mlp_out"), min_bytes=1 << 40))
+ _assert_same(ref, _run(blocks, x, mods, pe))
+ assert offloader.summary()["items"] == 0
+ # 2. the last keep_last blocks stay resident
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(("inputs", "sdpa", "mlp_out"), keep_last=NB))
+ _assert_same(ref, _run(blocks, x, mods, pe))
+ assert offloader.summary()["items"] == 0
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(("inputs", "sdpa", "mlp_out"), keep_last=NB - 1))
+ _assert_same(ref, _run(blocks, x, mods, pe))
+ assert offloader.summary()["items"] == 3 and offloader.summary()["items_inputs"] == 1
+ # 3. a non-dense block input (a strided view) is not offloadable and stays resident; the dense outputs of the
+ # following blocks are offloaded as usual
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(("inputs",), keep_last=0))
+ plain = _wrap_plain(_blocks(), save)
+ _assert_same(_run(plain, x, mods, pe, strided_rows=True), _run(blocks, x, mods, pe, strided_rows=True))
+ stats = offloader.summary()
+ assert stats["resident_non_dense"] == 1 and stats["items"] == NB - 1
+
+
+@cuda
+def test_throttle_bounds_inflight_bytes(reference):
+ x, mods, pe, ref = reference
+ save = {"sdpa", "mlp_out"}
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(("inputs", "sdpa", "mlp_out"), keep_last=0, max_inflight_bytes=HIDDEN_BYTES))
+ _run(blocks, x, mods, pe)
+ _assert_same(ref, _run(blocks, x, mods, pe))
+ stats = offloader.summary()
+ assert stats["items"] == NB * 3 and stats["throttle_waits"] >= 1 and stats["throttle_wait_s"] > 0
+ assert stats.get("late_prefetch", 0) == 0 # the end-of-forward prefetch covers keep_last=0
+
+
+@cuda
+def test_single_memcpy_per_tensor_and_no_host_sync_in_backward(reference):
+ from torch.profiler import ProfilerActivity, profile
+
+ x, mods, pe, ref = reference
+ save = {"sdpa", "mlp_out"}
+ offloader, blocks = _wrap_offload(_blocks(), save, _plan(("inputs", "sdpa", "mlp_out"), keep_last=1))
+ _run(blocks, x, mods, pe)
+ with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
+ out = _run(blocks, x, mods, pe)
+ _assert_same(ref, out)
+ keys = {e.key: e.count for e in prof.key_averages()}
+ items = (NB - 1) * 3
+ assert keys.get("Memcpy DtoH (Device -> Pinned)", 0) == items
+ assert keys.get("Memcpy HtoD (Pinned -> Device)", 0) == items
+ assert keys.get("cudaEventSynchronize", 0) == 0 # unbounded inflight budget: no host waits at all
diff --git a/flux-umi/tests/training/test_batched_preprocess.py b/flux-umi/tests/training/test_batched_preprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..3127a7b5abfc9a508abfd313513ac67c06f92f82
--- /dev/null
+++ b/flux-umi/tests/training/test_batched_preprocess.py
@@ -0,0 +1,81 @@
+"""CUDA tests: ``materialize_videos_batched`` is ``torch.equal`` to the per-window torchvision path (``packing.materialize_video``).
+
+Covers review finding #6: the batched contrast mean over ``[n, M, 1, H, W]`` used a different fp32 reduction tree than
+torchvision's per-window ``[M, 1, H, W]`` mean whenever ``H*W >= 131072`` or ``M = n_cams*T < 16``, so canvases were
+off by 1 fp32 ulp (2-18 % of the pixels) for e.g. 3-camera 360x640 (the ``TrainConfig.frame_hw`` default), 256x512
+frames, or T=5 as soon as two windows shared a ``color_fn_order`` group. Every window below is forced into one colour
+group (contrast first) with per-window crops and factors, which is what a 28/128-window batch over 24 permutations
+produces in practice. The 256x256 / T=33 cases are the G2 (3 cameras, grid 512x512) and UMI (2 cameras,
+side_by_side 256x512) production layouts, exact before and after the fix.
+"""
+import pytest
+import torch
+
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.processing import packing
+from flux_action.processing.batched_preprocess import GRAY_LEVEL, materialize_videos_batched
+
+DEV = torch.device("cuda")
+SHARED_ORDER = [1, 0, 2, 3] # contrast, brightness, saturation, hue
+
+
+def _inputs(n_cams, hw, T, n, seed=0, shared_order=True):
+ g = torch.Generator().manual_seed(seed)
+ cams = [torch.randint(0, 256, (n, T, 3, *hw), dtype=torch.uint8, generator=g) for _ in range(n_cams)]
+ augs = [packing.sample_augmentation(torch.Generator().manual_seed(1000 + i), camera_hw=hw) for i in range(n)]
+ if shared_order:
+ for a in augs:
+ a["color_fn_order"] = list(SHARED_ORDER)
+ return cams, augs
+
+
+def _reference(cams, augs, dropped, layout, canvas_hw):
+ stacked = torch.stack(cams, dim=1) # [n, n_cams, T, 3, H, W]
+ outs = []
+ for i, a in enumerate(augs):
+ c = stacked[i].clone()
+ if dropped and dropped[i]:
+ c[dropped[i]] = GRAY_LEVEL # policy._drop_cameras on uint8 frames
+ outs.append(packing.materialize_video(c, a, DEV, layout=layout, canvas_hw=canvas_hw))
+ return torch.stack(outs)
+
+
+CASES = [
+ # n_cams, layout, canvas, frame hw, T, n M = n_cams*T
+ (3, "grid", (512, 512), (256, 256), 33, 4), # G2 production layout (M=99)
+ (2, "side_by_side", (256, 512), (256, 256), 33, 4), # UMI production layout (M=66)
+ (3, "grid", (512, 512), (256, 256), 5, 4), # M=15 < 16: failed before the fix
+ (3, "grid", (512, 512), (360, 640), 33, 3), # H*W >= 131072 (TrainConfig.frame_hw default): failed before
+ (3, "grid", (512, 512), (256, 512), 33, 3), # H*W == 131072: failed before
+]
+
+
+@pytest.mark.parametrize("n_cams,layout,canvas_hw,hw,T,n", CASES)
+def test_shared_colour_group_equals_torchvision(n_cams, layout, canvas_hw, hw, T, n):
+ cams, augs = _inputs(n_cams, hw, T, n)
+ ref = _reference(cams, augs, None, layout, canvas_hw)
+ out = materialize_videos_batched(cams, augs, None, DEV, layout=layout, canvas_hw=canvas_hw)
+ assert out.shape == ref.shape and out.dtype == torch.float32
+ assert torch.equal(out, ref), (out - ref).abs().max().item()
+
+
+def test_production_options_equal_torchvision():
+ """bf16 output (what ``_encode_windows`` requests), a dropped camera, a ``windows=`` subset and mixed colour orders
+ (two shared groups) on the G2 layout; the UMI layout with the bf16 output."""
+ n_cams, hw, T, n = 3, (256, 256), 33, 6
+ cams, augs = _inputs(n_cams, hw, T, n, seed=3, shared_order=False)
+ for i in range(n):
+ augs[i]["color_fn_order"] = list(SHARED_ORDER) if i % 2 else [0, 1, 3, 2]
+ augs[4] = None # an un-augmented window
+ dropped = [[], [1], [], [0, 2], [], []]
+ windows = [0, 1, 3, 4, 5]
+ ref = _reference(cams, augs, dropped, "grid", (512, 512))[windows]
+ out = materialize_videos_batched(cams, augs, dropped, DEV, layout="grid", canvas_hw=(512, 512),
+ out_dtype=torch.bfloat16, windows=windows)
+ assert torch.equal(out, ref.to(torch.bfloat16))
+ cams, augs = _inputs(2, hw, T, 4, seed=4)
+ ref = _reference(cams, augs, None, "side_by_side", (256, 512))
+ out = materialize_videos_batched(cams, augs, None, DEV, layout="side_by_side", canvas_hw=(256, 512), out_dtype=torch.bfloat16)
+ assert torch.equal(out, ref.to(torch.bfloat16))
diff --git a/flux-umi/tests/training/test_checkpoint.py b/flux-umi/tests/training/test_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..839efd62cbc03183c66466a99194fa0ee3b1cce1
--- /dev/null
+++ b/flux-umi/tests/training/test_checkpoint.py
@@ -0,0 +1,227 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Checkpoint round trip, exact resume, export profiles and resharded loading."""
+
+import json
+
+import pytest
+import torch
+import torch.distributed as dist
+import torch.multiprocessing as mp
+from conftest import FakeVideoVAE, make_policy, tiny_config # noqa: F401
+from safetensors.torch import load_file
+
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+from flux_action.training.checkpoint import (
+ TrainState,
+ _dcp_load,
+ _dcp_save,
+ ema_folder,
+ export_policy,
+ latest_checkpoint,
+ load_checkpoint,
+ restore_rng,
+ resume_seed,
+ rng_state,
+ save_checkpoint,
+ seed_everything,
+ set_rng_state,
+)
+from flux_action.training.ema import DROID_POWER_EMA_SIGMA_RELS, PowerEMA
+from flux_action.training.schedule import build_lr_scheduler, droid_lr_lambdas, resume_lr_scheduler
+
+
+def _setup(seed=0, **policy_overrides):
+ seed_everything(seed)
+ policy = make_policy(tiny_config(**policy_overrides) if policy_overrides else None).train()
+ policy.freeze_streams(("image", "image_cond", "audio", "audio_cond")) # no loss reaches them
+ policy.freeze_conditioning_heads()
+ optimizer = torch.optim.AdamW(policy.get_optim_params(), betas=(0.9, 0.99), eps=1e-8, weight_decay=0.05)
+ scheduler = build_lr_scheduler(optimizer, droid_lr_lambdas(cooldown_start=None))
+ emas = {ema_folder(s): PowerEMA.from_module(policy, s) for s in DROID_POWER_EMA_SIGMA_RELS}
+ return policy, optimizer, scheduler, emas
+
+
+def _train(policy, optimizer, scheduler, emas, batch, start, n):
+ losses = []
+ for step in range(start, start + n):
+ loss, _ = policy(batch)
+ loss.backward()
+ optimizer.step()
+ scheduler.step()
+ for ema in emas.values():
+ ema.update_from_module(policy, step)
+ optimizer.zero_grad(set_to_none=True)
+ losses.append(float(loss.detach()))
+ return losses
+
+
+@pytest.fixture
+def train_batch():
+ rng = torch.Generator().manual_seed(42)
+ return {
+ "images.top": torch.rand(2, 33, 3, 64, 96, generator=rng),
+ "state": torch.rand(2, 6, generator=rng),
+ "action": torch.rand(2, 32, 6, generator=rng),
+ "task": ["move the object", "move the object"],
+ }
+
+
+def test_exact_resume_and_state(tmp_path, train_batch):
+ policy, optimizer, scheduler, emas = _setup()
+ _train(policy, optimizer, scheduler, emas, train_batch, 0, 3)
+ state = TrainState(run_seed=0, data={"cursor": 17})
+ path = save_checkpoint(
+ tmp_path, step=3, model=policy, optimizer=optimizer, emas=emas, state=state, config=policy.config
+ )
+ assert path == tmp_path / "step-3" and latest_checkpoint(tmp_path) == path
+ saved_ema = {name: [t.clone() for t in ema.shadow] for name, ema in emas.items()}
+ reference = _train(policy, optimizer, scheduler, emas, train_batch, 3, 4)
+
+ policy2, optimizer2, scheduler2, emas2 = _setup(seed=123) # different init, different generator
+ loaded = load_checkpoint(path, model=policy2, optimizer=optimizer2, emas=emas2)
+ assert loaded.step == 3 and loaded.data == {"cursor": 17} and loaded.seed == 0 and loaded.world_size == 1
+ n = len(emas2[ema_folder(0.10)].names)
+ assert loaded.emas[ema_folder(0.10)] == {"sigma_rel": 0.10, "last_step": 2, "n_tensors": n}
+ for name, ema in emas2.items():
+ for a, b in zip(ema.shadow, saved_ema[name], strict=True):
+ assert torch.equal(a, b)
+ assert ema.last_step == 2
+ assert all(int(optimizer2.state[p]["step"]) == 3 for p in policy2.parameters() if p.requires_grad)
+ resume_lr_scheduler(scheduler2, loaded.step)
+ assert restore_rng(path, loaded)
+ resumed = _train(policy2, optimizer2, scheduler2, emas2, train_batch, 3, 4)
+ assert resumed == reference
+ for name, ema in emas2.items():
+ for a, b in zip(ema.shadow, emas[name].shadow, strict=True):
+ assert torch.equal(a, b)
+ # The scheduler consumed the same factors: both optimizers hold the same learning rates.
+ assert [g["lr"] for g in optimizer.param_groups] == [g["lr"] for g in optimizer2.param_groups]
+
+
+def test_rng_state_round_trip_covers_all_generators():
+ seed_everything(5)
+ state = rng_state()
+ a = (torch.rand(2).tolist(), __import__("random").random(), float(__import__("numpy").random.rand()))
+ set_rng_state(state)
+ b = (torch.rand(2).tolist(), __import__("random").random(), float(__import__("numpy").random.rand()))
+ assert a == b
+
+
+def test_world_size_mismatch_skips_rng(tmp_path):
+ state = TrainState(world_size=2)
+ assert not restore_rng(tmp_path, state)
+
+
+def test_latest_ignores_incomplete_and_foreign_dirs(tmp_path):
+ (tmp_path / "step-9").mkdir()
+ (tmp_path / "step-5").mkdir()
+ (tmp_path / "step-5" / "COMPLETE").write_text("5\n")
+ (tmp_path / "step-x").mkdir()
+ (tmp_path / "step-x" / "COMPLETE").write_text("")
+ assert latest_checkpoint(tmp_path) == tmp_path / "step-5"
+ assert latest_checkpoint(tmp_path / "missing") is None
+ with pytest.raises(FileNotFoundError):
+ load_checkpoint(tmp_path / "step-9", model=torch.nn.Linear(1, 1))
+
+
+def test_resume_seed_deterministic_and_distinct():
+ seeds = [resume_seed(42, k) for k in (1, 2, 3)]
+ assert seeds == [resume_seed(42, k) for k in (1, 2, 3)]
+ assert len({42, *seeds}) == 4 and all(0 < s < 2**31 for s in seeds)
+ with pytest.raises(ValueError):
+ resume_seed(42, 0)
+ state = TrainState(run_seed=42)
+ state.seed_history.append(resume_seed(42, 1))
+ restored = TrainState.from_json(state.to_json())
+ assert restored.seed == seeds[0] and restored.seed_history == [42, seeds[0]]
+
+
+def test_export_profiles(tmp_path, train_batch):
+ policy, optimizer, scheduler, emas = _setup()
+ _train(policy, optimizer, scheduler, emas, train_batch, 0, 2)
+ path = save_checkpoint(
+ tmp_path / "ckpt",
+ step=2,
+ model=policy,
+ optimizer=optimizer,
+ emas=emas,
+ state=TrainState(),
+ config=policy.config,
+ )
+ result = export_policy(path, tmp_path / "model_export", profile="model")
+ assert result["step"] == 2 and result["tensors"] == len(policy.state_dict())
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "model_export", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ for a, b in zip(policy.state_dict().values(), restored.state_dict().values(), strict=True):
+ assert torch.equal(a, b)
+ manifest = json.loads((tmp_path / "model_export" / "manifest.json").read_text())
+ assert manifest["weight_profile"] == "model"
+ assert json.loads((tmp_path / "model_export" / "config.json").read_text())["torch_dtype"] == "float32"
+
+ name = ema_folder(0.10)
+ export_policy(path, tmp_path / "ema_export", profile=name)
+ exported = load_file(str(tmp_path / "ema_export" / "model.safetensors"))
+ for key, value in emas[name].consolidated().items():
+ assert torch.equal(exported[key], value)
+ assert not all(torch.equal(exported[k], v) for k, v in policy.state_dict().items())
+ assert json.loads((tmp_path / "ema_export" / "manifest.json").read_text())["weight_profile"] == name
+ with pytest.raises(ValueError, match="unknown profile"):
+ export_policy(path, tmp_path / "bad", profile="ema_0p42")
+
+
+def _shard_writer(rank, world_size, init_file, ckpt_dir):
+ from torch.distributed.tensor import Shard, distribute_tensor, init_device_mesh
+
+ dist.init_process_group("gloo", init_method=f"file://{init_file}", rank=rank, world_size=world_size)
+ try:
+ mesh = init_device_mesh("cpu", (world_size,))
+ full = torch.arange(24, dtype=torch.float32).reshape(8, 3)
+ ema = PowerEMA([("w", distribute_tensor(full, mesh, [Shard(0)]))], 0.10)
+ ema.update([distribute_tensor(full * 2, mesh, [Shard(0)])], 0)
+ _dcp_save({"tensors": ema.state_dict()["tensors"]}, ckpt_dir)
+ finally:
+ dist.destroy_process_group()
+
+
+def test_sharded_save_loads_dense_in_one_process(tmp_path):
+ mp.spawn(_shard_writer, args=(2, str(tmp_path / "pg"), str(tmp_path / "ema")), nprocs=2, join=True)
+ template = {"tensors": {"w": torch.zeros(8, 3)}}
+ _dcp_load(template, tmp_path / "ema")
+ assert torch.equal(template["tensors"]["w"], torch.arange(24, dtype=torch.float32).reshape(8, 3) * 2)
+
+
+def test_export_of_a_lean_policy_rebuilds_only_its_streams(tmp_path, train_batch):
+ policy, optimizer, scheduler, emas = _setup(content_streams=("video", "video_cond"))
+ assert "image" not in policy.dit.in_channels
+ _train(policy, optimizer, scheduler, emas, train_batch, 0, 1)
+ path = save_checkpoint(
+ tmp_path / "ckpt",
+ step=1,
+ model=policy,
+ optimizer=optimizer,
+ emas=emas,
+ state=TrainState(),
+ config=policy.config,
+ )
+ result = export_policy(path, tmp_path / "lean_export", profile="model")
+ assert result["tensors"] == len(policy.state_dict())
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "lean_export", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert tuple(restored.config.content_streams) == ("video", "video_cond")
+ ema = export_policy(path, tmp_path / "lean_ema_export", profile=ema_folder(0.10))
+ assert ema["tensors"] == len(policy.state_dict())
diff --git a/flux-umi/tests/training/test_dit_fanout_linear.py b/flux-umi/tests/training/test_dit_fanout_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..7960770e85be385f0c4d5913a37938588949e7c1
--- /dev/null
+++ b/flux-umi/tests/training/test_dit_fanout_linear.py
@@ -0,0 +1,106 @@
+"""GPU test: the fan-out projection Function (dit_fanout_linear) is bitwise identical to autograd on a production
+SingleStreamBlock (rows path, MATH SDPA for determinism, checkpoint_wrapper): outputs, dx, parameter and row grads.
+``test_fanout_linear_gate_type_falls_back_bitwise`` covers review finding #12: with ``gate_type`` set the input has a
+fifth consumer (``gate_proj``) and the Function's accumulation order no longer matches autograd's, so it must fall
+back (it did not before the fix: dx max abs diff 3.1e-2, two of three modulation-row gradients differed)."""
+import pytest
+import torch
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
+from torch.nn.attention import SDPBackend, sdpa_kernel
+
+from flux_action.models import dit_mod_rows as mr
+from flux_action.models import dit_norm_mod_gate as nmg
+from flux_action.models import dit_qknorm_rope_fused as QR
+from flux_action.models import dit_qknorm_triton as QN
+from flux_action.models import dit_rope_triton as RP
+from flux_action.models import dit_swiglu_fused
+from flux_action.models.transformer import EmbedND, SingleStreamBlock
+
+DEV = torch.device("cuda")
+
+
+def _block_and_inputs(gate_type=None):
+ torch.manual_seed(0)
+ blk = SingleStreamBlock(3072, 24, mlp_ratio=3.0, gate_type=gate_type).to(device=DEV, dtype=torch.bfloat16).train()
+ blk.attn_mode = "torch"
+ dit_swiglu_fused.install(blk, require=True, inference=False)
+ QN.install(blk, require_kernel=True)
+ RP.install(require_kernel=True)
+ qr_state = QR.install(require_kernel=True)
+ nmg.install(blk)
+ mr.install(blk)
+ wrapped = checkpoint_wrapper(blk, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False)
+ counts = (80, 2048, 256, 32, 1) * 2
+ L, N = sum(counts), 3072
+ gen = torch.Generator(device=DEV).manual_seed(1)
+ x0 = torch.randn(1, L, N, device=DEV, generator=gen).to(torch.bfloat16)
+ rows = [0.5 * torch.randn(len(counts), N, device=DEV, generator=gen) for _ in range(3)]
+ plan = mr.row_plan(counts, DEV)
+ ids = torch.randint(0, 64, (1, L, 4), device=DEV, generator=gen)
+ pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(ids).to(torch.bfloat16).contiguous()
+ gout = torch.randn(1, L, N, device=DEV, generator=gen).to(torch.bfloat16)
+ seqlens = [sum((80, 2048, 256, 32, 1))] * 2
+ return blk, wrapped, x0, rows, plan, pe, gout, seqlens, qr_state
+
+
+def _run(blk, wrapped, x0, rows, plan, pe, gout, seqlens):
+ for p in blk.parameters():
+ p.grad = None
+ x = x0.clone().requires_grad_(True)
+ r = [t.clone().requires_grad_(True) for t in rows]
+ mod = mr.ModRows(r[0], r[1], r[2], plan)
+ with sdpa_kernel(SDPBackend.MATH):
+ _, out = wrapped(x, None, pe, mod, None, seqlens=seqlens)
+ out.backward(gout)
+ return dict(out=out.detach().clone(), dx=x.grad.clone(), drows=[t.grad.clone() for t in r],
+ params={n: p.grad.clone() for n, p in blk.named_parameters()})
+
+
+def test_fanout_linear_bitwise_vs_autograd():
+ blk, wrapped, x0, rows, plan, pe, gout, seqlens, qr_state = _block_and_inputs()
+ try:
+ mr.Config.fanout_linear = False
+ a = _run(blk, wrapped, x0, rows, plan, pe, gout, seqlens)
+ a2 = _run(blk, wrapped, x0, rows, plan, pe, gout, seqlens)
+ assert torch.equal(a["out"], a2["out"]) and torch.equal(a["dx"], a2["dx"]), "MATH reference not deterministic"
+ mr.Config.fanout_linear = True
+ b = _run(blk, wrapped, x0, rows, plan, pe, gout, seqlens)
+ finally:
+ mr.Config.fanout_linear = False
+ QR.uninstall(qr_state)
+ assert torch.equal(b["out"], a["out"])
+ assert torch.equal(b["dx"], a["dx"])
+ assert all(torch.equal(b["params"][n], a["params"][n]) for n in a["params"])
+ assert all(torch.equal(u, v) for u, v in zip(b["drows"], a["drows"]))
+
+
+def test_fanout_linear_gate_type_falls_back_bitwise():
+ """Finding #12: a gated block (``gate_proj(combined)`` is a 5th consumer of the shared input) must not use the fused
+ accumulation; with the flag on, every output and gradient equals the flag-off run bitwise."""
+ from flux_action.models.dit_fanout_linear import fanout_linear
+
+ blk, wrapped, x0, rows, plan, pe, gout, seqlens, qr_state = _block_and_inputs(gate_type="silu")
+ assert blk.gate_type is not None and hasattr(blk, "gate_proj")
+ try:
+ mr.Config.fanout_linear = False
+ a = _run(blk, wrapped, x0, rows, plan, pe, gout, seqlens)
+ mr.Config.fanout_linear = True
+ b = _run(blk, wrapped, x0, rows, plan, pe, gout, seqlens)
+ finally:
+ mr.Config.fanout_linear = False
+ QR.uninstall(qr_state)
+ assert torch.equal(b["out"], a["out"])
+ assert torch.equal(b["dx"], a["dx"]), (b["dx"].float() - a["dx"].float()).abs().max().item()
+ assert all(torch.equal(u, v) for u, v in zip(b["drows"], a["drows"]))
+ assert all(torch.equal(b["params"][n], a["params"][n]) for n in a["params"])
+ # the guard itself: gated=True routes through the plain modules (no _FanOutLinear node in the graph)
+ x = torch.randn(1, 8, 3072, device=DEV, dtype=torch.bfloat16, requires_grad=True)
+ q, *_ = fanout_linear(x, blk.q_proj, blk.k_proj, blk.v_proj, blk.mlp_in, gated=True)
+ assert "FanOutLinear" not in type(q.grad_fn).__name__
+ q, *_ = fanout_linear(x, blk.q_proj, blk.k_proj, blk.v_proj, blk.mlp_in, gated=False)
+ assert "FanOutLinear" in type(q.grad_fn).__name__
diff --git a/flux-umi/tests/training/test_dit_last_layer_rows.py b/flux-umi/tests/training/test_dit_last_layer_rows.py
new file mode 100644
index 0000000000000000000000000000000000000000..96110099744204a5e0ac68ccffb71faa5542e936
--- /dev/null
+++ b/flux-umi/tests/training/test_dit_last_layer_rows.py
@@ -0,0 +1,49 @@
+"""GPU test: the final layer through the fused row kernel (dit_mod_rows.last_layer_forward_rows) matches the per-token
+expansion path: output, dx and the linear weight gradient bitwise; the adaLN row/weight gradients differ only by the
+fp32 segment-sum order (same class as the rest of dit_mod_rows)."""
+import pytest
+import torch
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+import flux_action.models.dit_time_embed_dedup as D
+from flux_action.models import dit_mod_rows as mr
+from flux_action.models.transformer import LastLayer
+
+DEV = torch.device("cuda")
+
+
+def _run(layer, fn, x0, vec, counts, gout):
+ for p in layer.parameters():
+ p.grad = None
+ x = x0.clone().requires_grad_(True)
+ v = vec.clone().requires_grad_(True)
+ out = fn(layer, x, v, counts, torch.bfloat16)
+ out.backward(gout)
+ return out.detach(), x.grad, v.grad, {n: p.grad.clone() for n, p in layer.named_parameters()}
+
+
+@pytest.mark.parametrize("counts", [(2048,) * 6, (37, 64, 1, 0, 90, 5)])
+def test_last_layer_rows_matches_expansion_path(counts):
+ torch.manual_seed(0)
+ layer = LastLayer(3072, 96).to(device=DEV, dtype=torch.bfloat16)
+ L = sum(counts)
+ x0 = torch.randn(1, L, 3072, device=DEV).to(torch.bfloat16)
+ vec = torch.randn(len(counts), 3072, device=DEV)
+ gout = torch.randn(1, L, 96, device=DEV).to(torch.bfloat16)
+ a = _run(layer, D.last_layer_forward_dedup, x0, vec, counts, gout)
+ prev = mr.Config.last_layer_rows
+ mr.Config.last_layer_rows = True
+ try:
+ b = _run(layer, mr.last_layer_forward_rows, x0, vec, counts, gout)
+ finally:
+ mr.Config.last_layer_rows = prev
+ assert torch.equal(a[0], b[0]) and torch.equal(a[1], b[1])
+ assert torch.equal(a[3]["linear.weight"], b[3]["linear.weight"])
+ rel = ((a[2].float() - b[2].float()).norm() / a[2].float().norm()).item()
+ assert rel < 1e-5, rel
+ relw = ((a[3]["adaLN_modulation.1.weight"].float() - b[3]["adaLN_modulation.1.weight"].float()).norm()
+ / a[3]["adaLN_modulation.1.weight"].float().norm()).item()
+ assert relw < 1e-3, relw
diff --git a/flux-umi/tests/training/test_dit_mod_rows.py b/flux-umi/tests/training/test_dit_mod_rows.py
new file mode 100644
index 0000000000000000000000000000000000000000..b21d23b99f61e36bf3651fb6273c9c45d86ebbcb
--- /dev/null
+++ b/flux-umi/tests/training/test_dit_mod_rows.py
@@ -0,0 +1,209 @@
+"""Tests for dit_mod_rows (row-indexed AdaLN modulation kernels). CUDA + Triton required; small shapes.
+
+Run: CUDA_VISIBLE_DEVICES=1 PYTHONPATH=src python -m pytest tests/training/test_dit_mod_rows.py -q
+"""
+import pytest
+import torch
+import torch.nn.functional as F
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import dit_mod_rows as mr
+from flux_action.models import dit_norm_mod_gate as nmg
+from flux_action.models.dit_time_embed_dedup import expand_rows, segment_sum_fp32
+
+nmg.Config.bwd_variant_selected = True
+DEV = torch.device("cuda")
+N = 3072
+
+
+def test_row_plan_tables():
+ counts = (5, 0, 7, 1, 64, 3)
+ plan = mr.RowPlan(counts, DEV, T=4, gate_T=8)
+ assert plan.L == 80 and plan.R == 6
+ idx = plan.idx.cpu().tolist()
+ assert idx == sum(([r] * c for r, c in enumerate(counts)), [])
+ tab = plan.table(4)
+ start, ln, row, ptr = (tab[k].cpu().tolist() for k in ("start", "len", "row", "ptr"))
+ assert tab["C"] == len(start) == 2 + 0 + 2 + 1 + 16 + 1
+ assert ptr == [0, 2, 2, 4, 5, 21, 22]
+ pos = 0
+ for r, c in enumerate(counts): # chunks tile each run exactly, never straddle rows
+ chunks = [(s, l) for s, l, rr in zip(start, ln, row) if rr == r]
+ assert sum(l for _, l in chunks) == c and all(l <= 4 for _, l in chunks)
+ if chunks:
+ assert chunks[0][0] == pos and all(chunks[i][0] + chunks[i][1] == chunks[i + 1][0] for i in range(len(chunks) - 1))
+ pos += c
+
+
+@pytest.mark.parametrize("counts,pitch,fuse_add", [
+ ((80, 2048, 256, 32, 1) * 3, None, False), # joint window-major layout, contiguous fp32 rows
+ ((80, 2048, 256, 32, 1) * 3, None, True), # + o1/o2 fused add
+ ((1024,) * 6, 3 * N, True), # mode block: equal runs, rows are chunk views (pitch 3N)
+ ((37, 64, 1, 0, 90, 5), 3 * N, False), # unequal runs incl. an empty row and runs of 1
+])
+def test_matches_production_path(counts, pitch, fuse_add):
+ r = mr.selftest(counts=counts, N=N, device=DEV, verbose=False, fuse_add=fuse_add, pitch=pitch, seed=3)
+ assert r["exact_fwd_dx_dout"], {k: r[k] for k in ("combined", "res", "dx", "do1", "do2")}
+ for k in ("dshift", "dscale", "dgate"):
+ assert r[k + "_vs_fp64"]["rel_l2"] < 5e-7, (k, r[k + "_vs_fp64"]) # fp32 summation-order class
+ assert r[k + "_vs_current"]["rel_l2"] < 5e-7, (k, r[k + "_vs_current"])
+
+
+def test_dx_independent_of_chunk_size_and_bf16_rows():
+ counts = (80, 2048, 256, 32, 1) * 2
+ x, shift, scale, gate, o1, o2, g, G = mr.make_rows_inputs(counts, N, DEV, seed=7)
+ ref = None
+ for T in (8, 64, 128):
+ for rows_dtype in (torch.float32, torch.bfloat16):
+ plan = mr.row_plan(counts, DEV, T=T, gate_T=T)
+ rows = [r.to(rows_dtype) for r in (shift, scale, gate)]
+ cur = mr.rows_path(x, *rows, o1, o2, g, G, plan, 1e-6, True)
+ if ref is None:
+ ref = cur
+ continue
+ for k in ("combined", "res", "dx", "do1", "do2"):
+ assert torch.equal(cur[k], ref[k]), (T, rows_dtype, k)
+ for k in ("dshift", "dscale", "dgate"):
+ # fp32 rows: fp32 sums in another chunk order; bf16 rows: autograd casts the fp32 row sums to bf16
+ tol = dict(rtol=1e-5, atol=1e-4) if rows_dtype == torch.float32 else dict(rtol=1e-2, atol=1e-2)
+ assert cur[k].dtype == rows_dtype
+ assert torch.allclose(cur[k].float(), ref[k].float(), **tol), (T, rows_dtype, k)
+
+
+def test_autograd_row_grads_accumulate_across_shared_blocks():
+ """Two consumers of one row set: fp32 row gradients accumulate (like 28 single blocks sharing one modulation)."""
+ counts = (16, 32, 8) * 4
+ L = sum(counts)
+ x, shift, scale, gate, o1, o2, g, G = mr.make_rows_inputs(counts, N, DEV, seed=9)
+ plan = mr.row_plan(counts, DEV)
+ rows = [r.detach().requires_grad_(True) for r in (shift, scale, gate)]
+ mod = mr.ModRows(*rows, plan)
+ xl = x.detach().requires_grad_(True)
+ c1, xa = mr.ln_modulate_rows(xl, mod)
+ y1 = mr.gate_residual_rows(xa, mod, o1)
+ c2, ya = mr.ln_modulate_rows(y1, mod)
+ y2 = mr.gate_residual_rows(ya, mod, o2)
+ torch.autograd.backward([c1, c2, y2], [g, G, g])
+ # reference: the production path on expanded tensors, twice; separate per-token leaves per consumer so the
+ # exact (fp64) row gradient = segsum(leaf1.grad) + segsum(leaf2.grad) is available. Autograd's own
+ # accumulation of the two per-token contributions happens in bf16 in production (add_), in fp32 here.
+ tok = [expand_rows(r, counts, torch.bfloat16, (L, N)).detach() for r in (shift, scale, gate)]
+ t1 = [t.clone().requires_grad_(True) for t in tok]
+ t2 = [t.clone().requires_grad_(True) for t in tok]
+ xr = x.detach().requires_grad_(True)
+ c1r, xar = nmg.ln_modulate(xr, t1[0], t1[1], 1e-6)
+ y1r = nmg.gate_residual(xar, t1[2], o1)
+ c2r, yar = nmg.ln_modulate(y1r, t2[0], t2[1], 1e-6)
+ y2r = nmg.gate_residual(yar, t2[2], o2)
+ torch.autograd.backward([c1r, c2r, y2r], [g, G, g])
+ assert torch.equal(y2, y2r) and torch.equal(xl.grad, xr.grad)
+ for a, l1, l2 in zip(rows, t1, t2):
+ assert a.grad.dtype == torch.float32
+ exact = mr.fp64_segment_sums(l1.grad, counts) + mr.fp64_segment_sums(l2.grad, counts)
+ d_rows = ((a.grad.double() - exact).norm() / exact.norm()).item()
+ bf16_acc = (l1.grad + l2.grad) # production: bf16 add_ across blocks
+ d_prod = ((segment_sum_fp32(bf16_acc, counts).double() - exact).norm() / exact.norm()).item()
+ assert d_rows < 2e-7, d_rows # fp32 summation order only
+ assert d_prod > 10 * d_rows # the bf16 cross-block accumulation error
+
+
+def test_block_dispatch_and_fallback():
+ """SingleStreamBlock with install(): ModRows takes the row kernels and matches the production fused forward
+ bitwise (MATH SDPA); a non-fusable call (fp32 x) falls back to the previous forward via expansion."""
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ from flux_action.models.transformer import EmbedND, SingleStreamBlock
+
+ torch.manual_seed(0)
+ blk = SingleStreamBlock(1024, 8, mlp_ratio=2.0).to(DEV, torch.bfloat16).train()
+ blk.attn_mode = "torch"
+ nmg.install(blk)
+ state = mr.install(blk)
+ counts = (10, 54) * 2
+ L = sum(counts)
+ g = torch.Generator(device=DEV).manual_seed(1)
+ x = torch.randn(1, L, 1024, device=DEV, generator=g).to(torch.bfloat16)
+ rows = [(0.5 * torch.randn(len(counts), 1024, device=DEV, generator=g)) for _ in range(3)]
+ ids = torch.randint(0, 16, (1, L, 4), device=DEV, generator=g)
+ pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(ids).to(torch.bfloat16).contiguous()
+ gout = torch.randn(1, L, 1024, device=DEV, generator=g).to(torch.bfloat16)
+ seqlens = [sum(counts[:2])] * 2
+
+ def run(as_rows):
+ xl = x.clone().requires_grad_(True)
+ rr = [r.clone().requires_grad_(True) for r in rows]
+ blk.zero_grad(set_to_none=True)
+ mod = mr.ModRows(*rr, mr.row_plan(counts, DEV)) if as_rows else tuple(expand_rows(r, counts, torch.bfloat16, (1, L, 1024)) for r in rr)
+ with sdpa_kernel(SDPBackend.MATH):
+ _, out = blk(xl, None, pe, mod, None, 0.0, seqlens)
+ out.backward(gout)
+ return out.detach(), xl.grad, [r.grad for r in rr], {n: p.grad.clone() for n, p in blk.named_parameters()}
+
+ o_ref, dx_ref, dr_ref, p_ref = run(False)
+ o_new, dx_new, dr_new, p_new = run(True)
+ assert state.calls_rows == 1 and state.calls_other == 1 # run(False) passed a tuple -> previous forward
+ assert torch.equal(o_ref, o_new) and torch.equal(dx_ref, dx_new)
+ for a, b in zip(dr_new, dr_ref):
+ assert ((a - b).norm() / b.norm()) < 1e-6
+ for n in p_ref:
+ assert torch.equal(p_ref[n], p_new[n]), n # parameters see identical inputs/gradients
+ # fallback: dispatcher disabled -> ModRows expanded and routed to the previous (production fused) forward
+ state.enabled = False
+ o_fb, dx_fb, dr_fb, _ = run(True)
+ assert state.calls_other == 2 and torch.equal(o_fb, o_ref) and torch.equal(dx_fb, dx_ref)
+ mr.uninstall(state)
+
+
+def test_forward_dedup_rows_matches_forward_dedup():
+ """Small JointSingleSeq (hidden 512, 4 heads): forward_dedup_rows (row kernels) vs forward_dedup with eager
+ blocks, MATH SDPA, fwd + bwd: outputs bitwise, gradients equal up to the fp32-vs-bf16 cross-block accumulation."""
+ import copy
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ from flux_action.models import dit_time_embed_dedup as D
+ from flux_action.models.transformer import JointSingleSeq, JointSingleSeqParams
+
+ params = JointSingleSeqParams(in_channels={"video": 8, "video_cond": 8, "act": 4, "act_cond": 4},
+ sequence={"x_video": "video", "x_video_cond": "video_cond", "x_act": "act", "x_act_cond": "act_cond"},
+ vec_in_dim=12, context_in_dim=16, hidden_size=512, num_heads=4, depth=1, depth_single_blocks=2,
+ axes_dim=[32, 32, 32, 32], attn_mode="torch")
+ torch.manual_seed(0)
+ dit = JointSingleSeq(params).to(DEV, torch.bfloat16)
+ dit.time_in.float()
+ dit.train()
+ kw = D._tiny_inputs(DEV, torch.bfloat16, [5, 3, 4, 5], cond_noise=True, separate_action_t=True, vector_zero=False, lv=12, lvc=6, la=4, lac=1)
+
+ # Reference = dedup + EAGER blocks (the per-token kernels of dit_norm_mod_gate are exercised against eager in
+ # test_nmg_kernels_every_supported_n / test_dit_qknorm_rope_fused; here only the row path is under test).
+ def run(rows):
+ m = copy.deepcopy(dit)
+ assert D.install_training_time_embed_dedup(m)["installed"]
+ if rows:
+ state = mr.install_dedup_rows(m)
+ m.zero_grad(set_to_none=True)
+ with sdpa_kernel(SDPBackend.MATH):
+ pred = m(**kw)
+ loss = sum((p.float() * torch.randn(p.shape, generator=torch.Generator().manual_seed(i)).to(DEV)).sum() for i, p in enumerate(pred.values()))
+ loss.backward()
+ grads = {n: p.grad.detach().clone() for n, p in m.named_parameters() if p.grad is not None}
+ if rows:
+ assert state.calls_rows == 2 + 5 and state.calls_other == 0, (state.calls_rows, state.calls_other)
+ return {k: v.detach().clone() for k, v in pred.items()}, grads
+
+ pred_ref, g_ref = run(False)
+ pred_new, g_new = run(True)
+ assert set(g_ref) == set(g_new)
+ for k in pred_ref:
+ assert torch.equal(pred_ref[k], pred_new[k]), k # identical forward kernels -> bitwise
+ # this random bf16 toy model yields NaN prologue gradients (emb_in/txt_in/time_in/vector_in) on BOTH paths
+ # (production reference included); the NaN pattern must coincide and every finite gradient must agree.
+ nan_ref = {n for n in g_ref if torch.isnan(g_ref[n]).any()}
+ nan_new = {n for n in g_new if torch.isnan(g_new[n]).any()}
+ assert nan_ref == nan_new, nan_ref ^ nan_new
+ for n in g_ref:
+ if n in nan_ref:
+ continue
+ d = ((g_new[n].double() - g_ref[n].double()).norm() / g_ref[n].double().norm().clamp_min(1e-30)).item()
+ tol = 1e-2 if ("modulation" in n or "time_in" in n or "vector_in" in n) else 1e-6
+ assert d < tol, (n, d)
diff --git a/flux-umi/tests/training/test_dit_out_stage.py b/flux-umi/tests/training/test_dit_out_stage.py
new file mode 100644
index 0000000000000000000000000000000000000000..45b51fe120a250f0d32eb2bd5dc975bc77477a51
--- /dev/null
+++ b/flux-umi/tests/training/test_dit_out_stage.py
@@ -0,0 +1,273 @@
+"""GPU test (one GPU, ~2 min, ~130 GB): the fused output-stage op ``flux::out_stage`` (models.dit_out_stage) is bitwise
+identical to the current path on a production SingleStreamBlock under checkpoint_wrapper(NO_REENTRANT) + selective
+checkpointing (outputs, dx, all parameter grads, modulation row grads) at the real joint shape L = 309376 (cuBLASLt
+beta=1 epilogue, proven exact by the op's per-shape self-check) and at small shapes (split-K: mm + add fallback); a block
+that saves ``out_stage`` runs neither attn_out / mlp_out GEMM nor the add nor the gate kernel in its recompute; peak
+memory is not above today's. MATH SDPA (a few windows per call) gives a deterministic attention backward."""
+import pytest
+import torch
+import torch.nn.functional as F
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from torch.autograd import DeviceType
+from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
+from torch.nn.attention import SDPBackend, sdpa_kernel
+from torch.profiler import ProfilerActivity, profile
+from torch.utils.checkpoint import create_selective_checkpoint_contexts
+
+from flux_action.models import dit_mod_rows as mr
+from flux_action.models import dit_norm_mod_gate as nmg
+from flux_action.models import dit_out_stage as OS
+from flux_action.models import dit_qknorm_rope_fused as QR
+from flux_action.models import dit_qknorm_triton as QN
+from flux_action.models import dit_rope_triton as RP
+from flux_action.models import dit_swiglu_fused
+from flux_action.models.transformer import EmbedND, SingleStreamBlock
+from flux_action.training.distributed import _SacPolicy, _block_dims
+
+DEV = torch.device("cuda")
+N, HEADS, MLP_HIDDEN = 3072, 24, 9216
+WINDOW = (80, 2048, 256, 32, 1) # tokens per (window, segment) modulation row of the production joint sequence: 2417
+
+
+class ChunkedMathAttention(torch.nn.Module):
+ """``Attention.forward`` for equal-length packed windows through the MATH SDPA a few windows per call (deterministic
+ forward and backward; the fp32 attention matrix of all 128 windows at once would not fit)."""
+
+ def __init__(self, windows_per_call: int = 8):
+ super().__init__()
+ self.chunk = windows_per_call
+
+ def forward(self, q, k, v, attn_mode, seqlens):
+ lens = [int(n) for n in seqlens]
+ assert q.shape[0] == 1 and len(set(lens)) == 1
+ _, H, L, D = q.shape
+ n = len(lens)
+ per = L // n
+ qw, kw, vw = (t.reshape(H, n, per, D).transpose(0, 1) for t in (q, k, v))
+ outs = []
+ with sdpa_kernel(SDPBackend.MATH):
+ for i in range(0, n, self.chunk):
+ outs.append(F.scaled_dot_product_attention(qw[i:i + self.chunk], kw[i:i + self.chunk], vw[i:i + self.chunk]))
+ return torch.cat(outs).transpose(1, 2).reshape(1, L, H * D)
+
+
+class Inputs:
+ def __init__(self, windows: int, segments=WINDOW, seed: int = 1):
+ self.counts = tuple(segments) * windows
+ self.seqlens = [sum(segments)] * windows
+ L = sum(self.counts)
+ gen = torch.Generator(device=DEV).manual_seed(seed)
+ self.x0 = torch.randn(1, L, N, device=DEV, generator=gen).to(torch.bfloat16)
+ self.rows = [0.5 * torch.randn(len(self.counts), N, device=DEV, generator=gen) for _ in range(3)]
+ self.plan = mr.row_plan(self.counts, DEV)
+ ids = torch.randint(0, 64, (1, L, 4), device=DEV, generator=gen)
+ self.pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(ids).to(torch.bfloat16).contiguous()
+ self.gout = torch.randn(1, L, N, device=DEV, generator=gen).to(torch.bfloat16)
+ self.L = L
+
+
+def _block():
+ torch.manual_seed(0)
+ blk = SingleStreamBlock(N, HEADS, mlp_ratio=3.0).to(device=DEV, dtype=torch.bfloat16).train()
+ blk.attn_mode = "torch"
+ import flux_action.models.transformer as tr
+
+ rope_before = (tr.apply_rope, tr._CUTE_ROPE_ENABLED) # RP.install patches the module global: restore it at teardown
+ dit_swiglu_fused.install(blk, require=True, inference=False)
+ QN.install(blk, require_kernel=True)
+ RP.install(require_kernel=True)
+ qr_state = QR.install(require_kernel=True)
+ nmg.install(blk)
+ mr.install(blk)
+ blk.attention = ChunkedMathAttention()
+ return blk, (qr_state, rope_before)
+
+
+def _wrap(blk, save):
+ """checkpoint_wrapper + the production _SacPolicy (``save=None``: plain checkpoint, everything recomputed)."""
+ kwargs = {}
+ if save is not None:
+ dims = _block_dims(blk)
+ kwargs["context_fn"] = lambda: create_selective_checkpoint_contexts(_SacPolicy(save, *dims))
+ return checkpoint_wrapper(blk, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False, **kwargs)
+
+
+def _run(blk, module, inp: Inputs, out_stage: bool, profile_backward: bool = False):
+ mr.Config.out_stage = out_stage
+ for p in blk.parameters():
+ p.grad = None
+ x = inp.x0.clone().requires_grad_(True)
+ r = [t.clone().requires_grad_(True) for t in inp.rows]
+ mod = mr.ModRows(r[0], r[1], r[2], inp.plan)
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ base = torch.cuda.memory_allocated() # results of earlier runs are still alive: measure above this
+ _, out = module(x, None, inp.pe, mod, None, seqlens=inp.seqlens)
+ prof = None
+ if profile_backward:
+ with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True) as prof:
+ out.backward(inp.gout)
+ torch.cuda.synchronize()
+ else:
+ out.backward(inp.gout)
+ torch.cuda.synchronize()
+ res = dict(out=out.detach().clone(), dx=x.grad.clone(), drows=[t.grad.clone() for t in r],
+ params={n: p.grad.clone() for n, p in blk.named_parameters()},
+ peak=torch.cuda.max_memory_allocated() - base)
+ if prof is not None:
+ res["stats"] = _backward_stats(prof, inp.L)
+ del out, x, r, mod
+ return res
+
+
+def _backward_stats(prof, L):
+ """Kernel-level accounting of one block backward (recompute + backward): executed GEMMs by operand shape, hidden-width
+ adds, gate kernels. Only op records that launched a kernel count: ops popped from the SAC storage launch none, and under
+ the SAC dispatch mode every op is recorded twice (the autograd-level record has no kernel, the redispatch has it)."""
+ ev = prof.events()
+ kernels = [e.name for e in ev if e.device_type == DeviceType.CUDA]
+
+ def mm(shapes):
+ return sum(1 for e in ev if e.name in ("aten::mm", "aten::addmm_") and len(e.kernels) > 0
+ and [list(s) for s in e.input_shapes[:2]] == shapes)
+
+ return dict(
+ gate_fwd=sum("_gate_res_rows_fwd_kernel" in k for k in kernels),
+ gate_bwd=sum("_gate_res_rows_bwd_kernel" in k for k in kernels),
+ add_hidden=sum(1 for e in ev if e.name == "aten::add" and len(e.kernels) > 0
+ and [list(s) for s in e.input_shapes[:2]] in ([[1, L, N], [1, L, N]], [[L, N], [L, N]])),
+ mm_hidden=mm([[L, N], [N, N]]), # attn_out forward GEMM shape (also q/k/v recompute and the dX GEMMs)
+ mm_mlp_out=mm([[L, MLP_HIDDEN], [MLP_HIDDEN, N]]), # mlp_out forward GEMM (recompute only)
+ nvjet=sum(k.startswith("nvjet") for k in kernels),
+ )
+
+
+def _assert_same(a, b, what):
+ assert torch.equal(b["out"], a["out"]), f"{what}: output differs"
+ assert torch.equal(b["dx"], a["dx"]), f"{what}: dx differs"
+ for n in a["params"]:
+ assert torch.equal(b["params"][n], a["params"][n]), f"{what}: grad of {n} differs"
+ for u, v, name in zip(b["drows"], a["drows"], ("shift", "scale", "gate")):
+ assert torch.equal(u, v), f"{what}: {name} row grad differs"
+
+
+@pytest.fixture(scope="module")
+def block():
+ import flux_action.models.transformer as tr
+
+ blk, (qr_state, rope_before) = _block()
+ try:
+ yield blk
+ finally:
+ mr.Config.out_stage = False
+ OS.Config.epilogue = True
+ QR.uninstall(qr_state)
+ tr.apply_rope, tr._CUTE_ROPE_ENABLED = rope_before # undo RP.install (module-global patch) for later test files
+
+
+def test_out_stage_bitwise_at_production_shape_and_dead_recompute(block):
+ inp = Inputs(windows=128) # L = 309376, the joint shape
+ assert inp.L == 309376
+ cur_mlp = _wrap(block, ["sdpa", "mlp_out"]) # today's saving joint block (sdpa never matches MATH; harmless)
+ cur_none = _wrap(block, ["sdpa"]) # today's non-saving block
+ op_out = _wrap(block, ["sdpa", "out_stage"]) # out_stage in place of mlp_out
+ op_swap = _wrap(block, ["out_stage"]) # the swap: s instead of the attention output
+ op_none = _wrap(block, ["sdpa"]) # op in forward + recompute, nothing saved
+ try:
+ a = _run(block, cur_mlp, inp, out_stage=False)
+ a2 = _run(block, cur_mlp, inp, out_stage=False, profile_backward=True)
+ _assert_same(a, a2, "reference repeat") # the MATH reference is deterministic
+ b0 = _run(block, op_out, inp, out_stage=True) # first op call at this shape runs the epilogue self-check
+ _assert_same(a, b0, "op, out_stage saved (first call, self-check)")
+ key = next(k for k in OS.STATE.exact if k[0] == inp.L)
+ assert OS.STATE.exact[key] is True, f"beta=1 epilogue not bitwise at {key}"
+ b = _run(block, op_out, inp, out_stage=True, profile_backward=True)
+ _assert_same(a, b, "op, out_stage saved")
+ c = _run(block, cur_none, inp, out_stage=False, profile_backward=True)
+ _assert_same(a, c, "reference, nothing saved")
+ d = _run(block, op_none, inp, out_stage=True, profile_backward=True)
+ _assert_same(a, d, "op, nothing saved")
+ e = _run(block, op_swap, inp, out_stage=True, profile_backward=True)
+ _assert_same(a, e, "op, swap (out_stage only)")
+ f = _run(block, block, inp, out_stage=True) # no checkpoint: the op's own autograd
+ _assert_same(a, f, "op, eager")
+ finally:
+ mr.Config.out_stage = False
+ sa, sb, sc, sd, se = a2["stats"], b["stats"], c["stats"], d["stats"], e["stats"]
+ print("\nbackward stats (recompute + backward):", dict(cur_mlp=sa, op_out=sb, cur_none=sc, op_none=sd, op_swap=se))
+ # saving block: no gate forward kernel, no o1 + o2 add, one hidden-width GEMM fewer (attn_out), no mlp_out GEMM
+ assert sa["gate_fwd"] == 1 and sb["gate_fwd"] == 0
+ assert sb["add_hidden"] == sa["add_hidden"] - 1
+ assert sb["mm_hidden"] == sa["mm_hidden"] - 1 and sa["mm_mlp_out"] == 0 and sb["mm_mlp_out"] == 0
+ assert sb["nvjet"] == sa["nvjet"] - 1 and sa["gate_bwd"] == sb["gate_bwd"] == 1
+ # swap: vs today's non-saving block the recompute loses attn_out + mlp_out GEMMs, the add and the gate kernel
+ assert sc["mm_mlp_out"] == 1 and se["mm_mlp_out"] == 0 and se["mm_hidden"] == sc["mm_hidden"] - 1
+ assert se["gate_fwd"] == 0 and se["add_hidden"] == sc["add_hidden"] - 1 and se["nvjet"] == sc["nvjet"] - 2
+ # non-saving block with the op: the add is folded into the epilogue, everything else runs
+ assert sd["gate_fwd"] == 1 and sd["add_hidden"] == sc["add_hidden"] - 1 and sd["nvjet"] == sc["nvjet"]
+ # memory (peak above what was allocated before the run): not above today's -- the same tensors are kept (s in place of
+ # mlp_out's output, y aliases the block output); the op's backward holds dWo (18 MB) a little earlier than autograd did
+ slack = 32 * 2**20
+ assert b["peak"] <= a2["peak"] + slack, (b["peak"], a2["peak"])
+ assert e["peak"] <= a2["peak"] + slack, (e["peak"], a2["peak"])
+ assert d["peak"] <= c["peak"] + slack, (d["peak"], c["peak"])
+ print(f"peak GiB above the run's baseline: cur_mlp {a2['peak'] / 2**30:.3f} op_out {b['peak'] / 2**30:.3f}"
+ f" op_swap {e['peak'] / 2**30:.3f} cur_none {c['peak'] / 2**30:.3f} op_none {d['peak'] / 2**30:.3f}")
+
+
+@pytest.mark.parametrize("windows,segments", [(128, (1,)), (128, (32,)), (2, WINDOW)])
+def test_out_stage_bitwise_small_shapes_fallback(block, windows, segments):
+ inp = Inputs(windows=windows, segments=segments) # M = 128 / 4096 (split-K at K = 9216: mm + add fallback) / 4834
+ cur = _wrap(block, ["sdpa", "mlp_out"])
+ op = _wrap(block, ["sdpa", "out_stage"])
+ try:
+ a = _run(block, cur, inp, out_stage=False)
+ b = _run(block, op, inp, out_stage=True)
+ _assert_same(a, b, f"op at L={inp.L}")
+ key = next(k for k in OS.STATE.exact if k[0] == inp.L)
+ print(f"\nL={inp.L}: beta=1 epilogue bitwise = {OS.STATE.exact[key]} (False -> mm + add fallback)")
+ OS.Config.epilogue = False # the explicit mm + add path of the op
+ c = _run(block, op, inp, out_stage=True)
+ _assert_same(a, c, f"op without epilogue at L={inp.L}")
+ d = _run(block, block, inp, out_stage=True)
+ _assert_same(a, d, f"op eager at L={inp.L}")
+ OS.Config.epilogue = True
+ mr.Config.fanout_linear = True # A-0's fan-out Function upstream of the op (mlp_in stays outside)
+ e = _run(block, op, inp, out_stage=True)
+ _assert_same(a, e, f"op + fanout_linear at L={inp.L}")
+ finally:
+ OS.Config.epilogue = True
+ mr.Config.out_stage = False
+ mr.Config.fanout_linear = False
+
+
+def test_sac_policy_kind_and_validation():
+ from flux_action.training.distributed import SAC_SAVE_KINDS, apply_activation_checkpointing
+
+ assert "out_stage" in SAC_SAVE_KINDS
+ pol = _SacPolicy(["out_stage"], N, 2 * MLP_HIDDEN, MLP_HIDDEN)
+ assert pol.kind(OS.OP, (), False) == "out_stage"
+ assert pol.kind(torch.ops.aten.mm.default, (torch.empty(4, MLP_HIDDEN), torch.empty(MLP_HIDDEN, N)), False) == "mlp_out"
+
+ class Toy(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ blk = torch.nn.Module()
+ blk.mlp_in = torch.nn.Linear(N, 2 * MLP_HIDDEN, bias=False)
+ blk.mlp_out = torch.nn.Linear(MLP_HIDDEN, N, bias=False)
+ self.single_blocks = torch.nn.ModuleList([blk])
+
+ try:
+ mr.Config.out_stage = False
+ with pytest.raises(ValueError):
+ apply_activation_checkpointing(Toy(), mode="sac", sac_save=("sdpa",), sac_extra_save=("out_stage",), sac_extra_blocks=1)
+ mr.Config.out_stage = True
+ with pytest.raises(ValueError):
+ apply_activation_checkpointing(Toy(), mode="sac", sac_save=("sdpa", "mlp_out"))
+ assert apply_activation_checkpointing(Toy(), mode="sac", sac_save=("out_stage",), sac_extra_save=("sdpa",), sac_extra_blocks=1) == 1
+ finally:
+ mr.Config.out_stage = False
diff --git a/flux-umi/tests/training/test_dit_qknorm_rope_fused.py b/flux-umi/tests/training/test_dit_qknorm_rope_fused.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1c9e29c146cabd0a4be48e2f6244401a7c48fb6
--- /dev/null
+++ b/flux-umi/tests/training/test_dit_qknorm_rope_fused.py
@@ -0,0 +1,383 @@
+"""CUDA tests for the fused Q/K RMSNorm + RoPE kernel (dit_qknorm_rope_fused) and the sequential production pair.
+
+Reference semantics: eager autograd (RMSNorm.forward expression + apply_rope expression). Both the fused kernel and
+the sequential pair (dit_qknorm_triton -> dit_rope_triton) are compared *independently* against eager: oq/ok/dq/dk
+must be bitwise for fp32 and bf16 tables (both RoPE kernels emit scalar mul.rn/add.rn, no FFMA2 contraction), while
+the Q/K scale gradients dsq/dsk may differ from eager by at most 1 bf16 ulp (review finding #9: the kernels sum the
+fp32 partials in another order than ATen's column reduce; the flip happens in ~5-8 % of calls at production L, so an
+explicit large-L case is included). Fused and sequential share the partial-sum structure and must agree bitwise on
+every output including dsq/dsk. Review finding #10 (expanded stride-0 inputs) is covered by
+``test_expanded_inputs_fall_back_to_eager``.
+"""
+import copy
+import os
+import sys
+
+import pytest
+import torch
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import dit_qknorm_rope_fused as QR # noqa: E402
+from flux_action.models import dit_qknorm_triton as QN # noqa: E402
+from flux_action.models import dit_rope_triton as RP # noqa: E402
+from flux_action.models.dit_qknorm_triton import compare # noqa: E402
+from flux_action.models.transformer import rope # noqa: E402
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
+D = 128
+dev = torch.device("cuda")
+KEYS = ("oq", "ok", "dq", "dk", "dsq", "dsk")
+
+
+def make_inputs(L, H, seed, pe_dtype=torch.float32, grad_scale=1e-3):
+ g = torch.Generator(device=dev).manual_seed(seed)
+ rnd = lambda *s: torch.randn(*s, device=dev, generator=g)
+ bq = (rnd(1, L, H * D) * 1.7).to(torch.bfloat16)
+ bk = (rnd(1, L, H * D) * 1.3).to(torch.bfloat16)
+ sq = (1.0 + 0.5 * rnd(D)).to(torch.bfloat16)
+ sk = torch.linspace(-1.375, 2.625, D, device=dev).to(torch.bfloat16)
+ pos = torch.randint(0, 64, (1, L, 4), device=dev, generator=g).float()
+ pe = torch.cat([rope(pos[..., i], 32, 10000) for i in range(4)], dim=-3).unsqueeze(1).to(pe_dtype).contiguous()
+ gq = (rnd(1, L, H * D) * grad_scale).to(torch.bfloat16)
+ gk = (rnd(1, L, H * D) * grad_scale).to(torch.bfloat16)
+ return bq, bk, sq, sk, pe, gq, gk
+
+
+def run(fn, bq, bk, sq, sk, pe, gq, gk, view):
+ xq, xk = bq.clone().requires_grad_(True), bk.clone().requires_grad_(True)
+ s1, s2 = sq.clone().requires_grad_(True), sk.clone().requires_grad_(True)
+ oq, ok = fn(view(xq), view(xk), pe, s1, s2)
+ torch.autograd.backward((oq, ok), (view(gq), view(gk)))
+ return dict(oq=oq.detach(), ok=ok.detach(), dq=xq.grad, dk=xk.grad, dsq=s1.grad, dsk=s2.grad)
+
+
+FUSED = lambda *a: QR.qk_norm_rope(*a, require_kernel=True)
+SEQ = lambda *a: QR.sequential_reference(*a, require_kernel=True)
+EAGER = QR.eager_reference
+EXACT_KEYS = ("oq", "ok", "dq", "dk")
+SCALE_KEYS = ("dsq", "dsk")
+
+
+def bf16_ulp(a, b):
+ """Largest bf16 ulp distance between two bf16 tensors (0 == bitwise)."""
+ assert a.dtype == b.dtype == torch.bfloat16 and a.shape == b.shape
+ return int((a.contiguous().view(torch.int16).int() - b.contiguous().view(torch.int16).int()).abs().max())
+
+
+def assert_matches_eager(res, eager, who):
+ """oq/ok/dq/dk bitwise; dsq/dsk within 1 bf16 ulp (fp32 summation order of the scale-gradient partials)."""
+ for k in EXACT_KEYS:
+ assert compare(res[k], eager[k])["n_bits_differ"] == 0, (who, k, compare(res[k], eager[k]))
+ for k in SCALE_KEYS:
+ assert bf16_ulp(res[k], eager[k]) <= 1, (who, k, compare(res[k], eager[k]))
+
+
+@pytest.mark.parametrize("L,H,pe_dtype", [(4834, 24, torch.float32), (4833, 24, torch.float32), (1023, 7, torch.bfloat16),
+ (2417, 24, torch.bfloat16), (35420, 24, torch.float32), (35420, 24, torch.bfloat16)])
+def test_bitwise_vs_eager_and_sequential(L, H, pe_dtype):
+ """Finding #9: fused and sequential pair each vs eager (bitwise except dscale <= 1 ulp), fused vs sequential bitwise.
+ L=35420 is the UMI production joint length (28 x 1265), where the dscale flip is observed."""
+ inp = make_inputs(L, H, seed=L, pe_dtype=pe_dtype)
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3) # production token-major view
+ fused, seq, eager = (run(fn, *inp, view) for fn in (FUSED, SEQ, EAGER))
+ assert_matches_eager(fused, eager, "fused")
+ assert_matches_eager(seq, eager, "sequential") # independent of the fused result (no tautology)
+ for k in KEYS: # same partial-sum structure: bitwise incl. dsq/dsk
+ assert torch.equal(fused[k], seq[k]), (k, compare(fused[k], seq[k]))
+ assert fused["oq"].stride() == view(inp[0]).stride() # token-major outputs
+ assert fused["dq"].is_contiguous() # leaf grad of the [1, L, H*D] GEMM output: no copy
+
+
+def test_dscale_is_within_one_ulp_of_eager_at_production_L():
+ """Finding #9: dscale is NOT bit-exact (fp32 partial-sum order), but never more than 1 bf16 ulp away from eager and
+ deterministic; out/dx stay bitwise. Several seeds at the UMI joint length so a flip is actually exercised."""
+ L, H = 35420, 24
+ flips = 0
+ for seed in range(4):
+ bq, _, sq, _, _, gq, _ = make_inputs(L, H, seed=100 + seed)
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ outs = []
+ for fn in (lambda x, s: QN.rmsnorm_triton(x, s, require_kernel=True), QN.reference,
+ lambda x, s: QN.rmsnorm_triton(x, s, require_kernel=True)):
+ x = bq.clone().requires_grad_(True); s = sq.clone().requires_grad_(True)
+ fn(view(x), s).backward(view(gq))
+ outs.append((x.grad, s.grad))
+ (dx_t, ds_t), (dx_e, ds_e), (dx_t2, ds_t2) = outs
+ assert torch.equal(dx_t, dx_e)
+ assert torch.equal(ds_t, ds_t2), "dscale must be deterministic"
+ assert bf16_ulp(ds_t, ds_e) <= 1, compare(ds_t, ds_e)
+ flips += int((ds_t != ds_e).sum())
+ print(f"dscale bf16 flips vs eager over 4 x 128 entries at L={L}: {flips}")
+
+
+def test_expanded_inputs_fall_back_to_eager():
+ """Finding #10: a stride-0 dim of size > 1 (``expand``) makes ``empty_strided(x.shape, x.stride())`` outputs alias,
+ so the kernels' backward raced (dx max abs diff ~1e-2..8 vs eager). All three contracts must reject it and the
+ public entry points must return exactly the eager result (forward and backward)."""
+ B, H, L = 2, 24, 300
+ g = torch.Generator(device=dev).manual_seed(0)
+ base = (torch.randn(1, H, L, D, device=dev, generator=g) * 1.7).to(torch.bfloat16)
+ sq = (1.0 + 0.5 * torch.randn(D, device=dev, generator=g)).to(torch.bfloat16)
+ sk = torch.linspace(-1.375, 2.625, D, device=dev).to(torch.bfloat16)
+ pos = torch.randint(0, 64, (B, L, 4), device=dev, generator=g).float()
+ pe = torch.cat([rope(pos[..., i], 32, 10000) for i in range(4)], dim=-3).unsqueeze(1).contiguous() # per-batch table
+ grads = (torch.randn(B, H, L, D, device=dev, generator=g) * 1e-3).to(torch.bfloat16)
+ xe = base.expand(B, H, L, D)
+ assert QN.unsupported_reason(xe, sq) is not None
+ assert RP.unsupported_reason(xe, xe, pe) is not None
+ assert QR.unsupported_reason(xe, xe, pe, sq, sk) is not None
+ assert QN.unsupported_reason(base, sq) is None and QR.unsupported_reason(base, base, pe[:1], sq, sk) is None
+ for fn in (lambda: QN.rmsnorm_triton(xe, sq, require_kernel=True), lambda: RP.apply_rope_triton(xe, xe, pe, require_kernel=True),
+ lambda: QR.qk_norm_rope(xe, xe, pe, sq, sk, require_kernel=True)):
+ with pytest.raises(ValueError):
+ fn()
+ # QKNorm alone: distinct grads per expanded batch row
+ res = []
+ for fn in (lambda t: QN.rmsnorm_triton(t, sq), lambda t: QN.reference(t, sq)):
+ x = base.clone().requires_grad_(True)
+ y = fn(x.expand(B, H, L, D)); y.backward(grads)
+ res.append((y.detach(), x.grad))
+ assert torch.equal(res[0][0], res[1][0]) and torch.equal(res[0][1], res[1][1])
+ # RoPE alone: expanded batch with a per-batch table and expanded token dim (rows alias with different rotations)
+ xl = base[:, :, :1, :].expand(1, H, L, D)
+ for a, b, t in ((xe, xe, pe), (xl, xl, pe[:1])):
+ oq, ok = RP.apply_rope_triton(a, b, t)
+ eq, ek = RP.apply_rope_reference(a, b, t)
+ assert torch.equal(oq, eq) and torch.equal(ok, ek)
+ # fused entry point: forward and backward equal eager
+ res = []
+ for fn in (lambda q, k: QR.qk_norm_rope(q, k, pe, sq, sk), lambda q, k: QR.eager_reference(q, k, pe, sq, sk)):
+ xq, xk = base.clone().requires_grad_(True), base.clone().requires_grad_(True)
+ oq, ok = fn(xq.expand(B, H, L, D), xk.expand(B, H, L, D))
+ torch.autograd.backward((oq, ok), (grads, grads.flip(0)))
+ res.append((oq.detach(), ok.detach(), xq.grad, xk.grad))
+ assert all(torch.equal(u, v) for u, v in zip(res[0], res[1]))
+
+
+def test_general_strides_and_head_major():
+ L, H = 1030, 24
+ bq, bk, sq, sk, pe, gq, gk = make_inputs(L, H, seed=7)
+ # q/k as views of one fused [1, L, 3*H*D] projection buffer (row stride 9216: general address path, not DENSE)
+ buf = torch.cat([bq, bk, torch.zeros_like(bq)], dim=-1)
+ qv = buf[..., :H * D].view(1, L, H, D).permute(0, 2, 1, 3)
+ kv = buf[..., H * D:2 * H * D].view(1, L, H, D).permute(0, 2, 1, 3)
+ assert not QR._is_token_major_dense(qv)
+ oq, ok, rq, rk = QR._fwd(qv, kv, pe, sq, sk, 1e-6)
+ eq, ek = EAGER(qv, kv, pe, sq, sk)
+ assert torch.equal(oq, eq) and torch.equal(ok, ek)
+ assert oq.stride() == qv.stride()
+ dq, dk, dsq, dsk = QR._bwd(gq.view(1, L, H, D).permute(0, 2, 1, 3), gk.view(1, L, H, D).permute(0, 2, 1, 3), qv, kv, rq, rk, sq, sk, pe)
+ ref = run(EAGER, bq, bk, sq, sk, pe, gq, gk, lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3))
+ assert torch.equal(dq.permute(0, 2, 1, 3).reshape(1, L, H * D), ref["dq"]) and torch.equal(dk.permute(0, 2, 1, 3).reshape(1, L, H * D), ref["dk"])
+ assert bf16_ulp(dsq, ref["dsq"]) <= 1 and bf16_ulp(dsk, ref["dsk"]) <= 1 # finding #9: summation order
+ # head-major contiguous inputs and a head-major incoming gradient (any strides with stride(-1) == 1)
+ qh, kh = qv.contiguous(), kv.contiguous()
+ oq2, ok2, rq2, rk2 = QR._fwd(qh, kh, pe, sq, sk, 1e-6)
+ assert torch.equal(oq2, eq) and oq2.is_contiguous()
+ dq2, dk2, dsq2, dsk2 = QR._bwd(gq.view(1, L, H, D).permute(0, 2, 1, 3).contiguous(), gk.view(1, L, H, D).permute(0, 2, 1, 3).contiguous(),
+ qh, kh, rq2, rk2, sq, sk, pe)
+ assert torch.equal(dq2, dq) and torch.equal(dk2, dk) and torch.equal(dsq2, dsq) and torch.equal(dsk2, dsk)
+
+
+def test_row_and_token_forward_schedules_identical():
+ L, H = 4834, 24
+ bq, bk, sq, sk, pe, *_ = make_inputs(L, H, seed=3)
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ a = QR._fwd(view(bq), view(bk), pe, sq, sk, 1e-6, kernel="rows", rows=2, iters=16, warps=2)
+ for cfg in (dict(kernel="tok", tok=1, rows=2, warps=2), dict(kernel="tok", tok=2, rows=4, warps=4), dict(kernel="tok", tok=1, rows=8, warps=8),
+ dict(kernel="rows", rows=4, iters=8, warps=4)):
+ b = QR._fwd(view(bq), view(bk), pe, sq, sk, 1e-6, **cfg)
+ assert all(torch.equal(x, y) for x, y in zip(a, b)), cfg
+
+
+def test_backward_segmented_matches_unsegmented_and_sequential_partials():
+ """The segmented backward keeps _qknorm_bwd_kernel's 64-row grouping / accumulation order: partials bitwise."""
+ import triton
+ L, H = 4834, 24
+ bq, bk, sq, sk, pe, gq, gk = make_inputs(L, H, seed=5, pe_dtype=torch.bfloat16) # bf16 table: RoPE^T bitwise everywhere
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ q, k, gqv, gkv = view(bq), view(bk), view(gq), view(gk)
+ _, _, rq, rk = QR._fwd(q, k, pe, sq, sk, 1e-6)
+ a = QR._bwd(gqv, gkv, q, k, rq, rk, sq, sk, pe, segmented=True)
+ b = QR._bwd(gqv, gkv, q, k, rq, rk, sq, sk, pe, segmented=False)
+ assert all(torch.equal(x, y) for x, y in zip(a, b))
+ # sequential pair's partials (dit_qknorm_triton kernel on the Triton RoPE^T output) vs the fused kernel's partials
+ grq, grk = RP._rotate(gqv, gkv, pe, transpose=True)
+ R = H * L
+ nprog = triton.cdiv(R, QN.BWD_ROWS * QN.BWD_ITERS)
+ part_seq = torch.empty((nprog, D), dtype=torch.float32, device=dev)
+ dx = torch.empty_strided(q.shape, q.stride(), dtype=q.dtype, device=dev)
+ QN._qknorm_bwd_kernel[(nprog,)](grq, q, rq, sq, dx, part_seq, H, L, R, *QN._strides3(grq), *QN._strides3(q), *QN._strides3(dx),
+ ROWS=QN.BWD_ROWS, ITERS=QN.BWD_ITERS, TREE=1, num_warps=QN.BWD_WARPS, enable_fp_fusion=False)
+ dq = torch.empty_strided(q.shape, q.stride(), dtype=q.dtype, device=dev); dk = torch.empty_like(dq)
+ pq = torch.empty((nprog, D), dtype=torch.float32, device=dev); pk = torch.empty_like(pq)
+ sfb = 0
+ QR._fused_bwd_kernel[(nprog,)](gqv, gkv, q, k, rq, rk, sq, sk, pe, dq, dk, pq, pk, H, L, R,
+ *QR._s3(gqv), *QR._s3(gkv), *QR._s3(q), *QR._s3(k), *QR._s3(dq), *QR._s3(dk), sfb,
+ ROWS=QN.BWD_ROWS, ITERS=QN.BWD_ITERS, TREE=1, DENSE=True, SHARED_F=True, EXACT=1, SEGMENTED=1,
+ MAXSEG=(QN.BWD_ROWS * QN.BWD_ITERS + H - 1) // H + 1, num_warps=QN.BWD_WARPS, enable_fp_fusion=False)
+ assert torch.equal(pq, part_seq), "dscale partial sums must reproduce _qknorm_bwd_kernel's structure bitwise"
+ assert torch.equal(dq, dx)
+
+
+def test_fallbacks():
+ L, H = 1000, 24
+ bq, bk, sq, sk, pe, gq, gk = make_inputs(L, H, seed=9)
+ view = lambda t: t.view(1, L, H, D).permute(0, 2, 1, 3)
+ # unsupported: fp32 scale (not the FSDP-cast bf16 parameter) -> contract fails -> sequential pair (eager inside) is used
+ assert QR.unsupported_reason(view(bq), view(bk), pe, sq.float(), sk) is not None
+ with pytest.raises(ValueError):
+ QR.qk_norm_rope(view(bq), view(bk), pe, sq.float(), sk, require_kernel=True)
+ oq, ok = QR.qk_norm_rope(view(bq), view(bk), pe, sq.float(), sk)
+ eq, ek = EAGER(view(bq), view(bk), pe, sq.float(), sk)
+ assert torch.equal(oq, eq) and torch.equal(ok, ek)
+ # unsupported: non-contiguous table
+ pe_t = pe.transpose(-1, -2)
+ assert QR.unsupported_reason(view(bq), view(bk), pe_t, sq, sk) is not None
+ with pytest.raises(ValueError):
+ QR.qk_norm_rope(view(bq), view(bk), pe_t, sq, sk, require_kernel=True)
+ # supported contract: the production views
+ assert QR.unsupported_reason(view(bq), view(bk), pe, sq, sk) is None
+ # double backward falls back to the differentiable eager expression (no crash, finite)
+ xq = bq.clone().requires_grad_(True); xk = bk.clone().requires_grad_(True)
+ s1 = sq.clone().requires_grad_(True); s2 = sk.clone().requires_grad_(True)
+ oq, ok = QR.qk_norm_rope(view(xq), view(xk), pe, s1, s2, require_kernel=True)
+ (g1,) = torch.autograd.grad((oq.float() ** 2).sum() + (ok.float() ** 2).sum(), xq, create_graph=True)
+ (gg,) = torch.autograd.grad(g1.float().sum(), s1, allow_unused=True)
+ assert gg is None or torch.isfinite(gg).all()
+
+
+def _block_case(kind, pe_dtype, seed=0):
+ """Production block (v4t kernels) vs eager block vs installed block, MATH SDPA, checkpoint_wrapper(NO_REENTRANT)."""
+ from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ from flux_action.models import dit_norm_mod_gate as nmg, dit_swiglu_fused
+ from flux_action.models.transformer import EmbedND, ModeBlock, SingleStreamBlock
+
+ torch.manual_seed(seed)
+ base = SingleStreamBlock(3072, 24, mlp_ratio=3.0) if kind == "single" else ModeBlock(3072, 24, mlp_ratio=3.0)
+ with torch.no_grad():
+ for norm in (base.norm.query_norm, base.norm.key_norm):
+ norm.scale.add_(0.1 * torch.randn_like(norm.scale))
+ base = base.to(device=dev, dtype=torch.bfloat16).train()
+ base.attn_mode = "torch"
+ eager_block = copy.deepcopy(base) # plain transformer.py forward
+ prod_block = copy.deepcopy(base)
+ dit_swiglu_fused.install(prod_block, require=True, inference=False)
+ QN.install(prod_block, require_kernel=True)
+ nmg.install(prod_block)
+ RP.install(require_kernel=True)
+ fused_block = copy.deepcopy(base)
+ dit_swiglu_fused.install(fused_block, require=True, inference=False)
+ QN.install(fused_block, require_kernel=True)
+ nmg.install(fused_block)
+ blocks = dict(eager=eager_block, production=prod_block, fused=fused_block)
+ wrapped = {k: checkpoint_wrapper(b, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False) for k, b in blocks.items()}
+
+ gen = torch.Generator(device=dev).manual_seed(seed + 1)
+ counts = (80, 2048, 256, 32, 1) * 2 if kind == "single" else (2048,) * 2
+ L, N = sum(counts), 3072
+ x0 = torch.randn(1, L, N, device=dev, generator=gen).to(torch.bfloat16)
+ mods0 = [(0.5 * torch.randn(1, L, N, device=dev, generator=gen)).to(torch.bfloat16) for _ in range(3)]
+ ids = torch.randint(0, 64, (1, L, 4), device=dev, generator=gen)
+ pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(ids).to(pe_dtype).contiguous()
+ gout = torch.randn(1, L, N, device=dev, generator=gen).to(torch.bfloat16)
+ seqlens = [sum((80, 2048, 256, 32, 1))] * 2 if kind == "single" else [2048] * 2
+
+ import flux_action.models.transformer as T
+
+ def run_block(name):
+ blk, w = blocks[name], wrapped[name]
+ for p in blk.parameters():
+ p.grad = None
+ x = x0.clone().requires_grad_(True)
+ mods = [m.clone().requires_grad_(True) for m in mods0]
+ # dit_rope_triton.install patches the module global transformer.apply_rope; the eager block must run the
+ # genuine eager expression (RP.apply_rope_reference is that expression verbatim)
+ saved = T.apply_rope
+ if name == "eager":
+ T.apply_rope = RP.apply_rope_reference
+ try:
+ with sdpa_kernel(SDPBackend.MATH):
+ if kind == "single":
+ _, out = w(x, None, pe, tuple(mods), None, seqlens=seqlens)
+ else:
+ out = w(x, pe, tuple(mods), seqlens=seqlens)
+ out.backward(gout)
+ finally:
+ T.apply_rope = saved
+ return dict(out=out.detach(), dx=x.grad, dmods=[m.grad for m in mods], params={n: p.grad.clone() for n, p in blk.named_parameters()})
+ res = {k: run_block(k) for k in ("eager", "production")}
+ res["eager_repeat"] = run_block("eager")
+ st = QR.install(require_kernel=True) # module-global seam: installed only around the fused run
+ try:
+ res["fused"] = run_block("fused")
+ finally:
+ QR.uninstall(st)
+ return res, st
+
+
+def _all_equal(a, b, scale_grad_ulp=0):
+ """Differences between two block runs. ``scale_grad_ulp=1`` allows the Q/K RMSNorm scale gradients to differ by one
+ bf16 ulp (finding #9: Triton partial sums vs ATen's reduce tree) -- used only when one side is the eager block."""
+ diffs = {}
+ if not torch.equal(a["out"], b["out"]):
+ diffs["out"] = compare(a["out"], b["out"])
+ if not torch.equal(a["dx"], b["dx"]):
+ diffs["dx"] = compare(a["dx"], b["dx"])
+ for i, (x, y) in enumerate(zip(a["dmods"], b["dmods"])):
+ if not torch.equal(x, y):
+ diffs[f"dmod{i}"] = compare(x, y)
+ for n in a["params"]:
+ if torch.equal(a["params"][n], b["params"][n]):
+ continue
+ if n.endswith("norm.scale") and bf16_ulp(a["params"][n], b["params"][n]) <= scale_grad_ulp:
+ continue
+ diffs[n] = compare(a["params"][n], b["params"][n])
+ return diffs
+
+
+@pytest.mark.parametrize("kind", ["single", "mode"])
+def test_installed_block_vs_production_block_math_sdpa(kind):
+ # bf16 table: production RoPE is tie-free -> installed block must be bitwise with the production block AND eager
+ res, st = _block_case(kind, torch.bfloat16)
+ assert st.calls_fused >= 2 and st.calls_seam == 0, (st.calls_fused, st.calls_seam) # forward + recompute
+ assert _all_equal(res["eager"], res["eager_repeat"]) == {}, "MATH SDPA reference is not deterministic"
+ assert _all_equal(res["fused"], res["production"]) == {}, _all_equal(res["fused"], res["production"])
+ assert _all_equal(res["fused"], res["eager"], scale_grad_ulp=1) == {}, _all_equal(res["fused"], res["eager"])
+ assert _all_equal(res["production"], res["eager"], scale_grad_ulp=1) == {}, _all_equal(res["production"], res["eager"])
+
+
+@pytest.mark.parametrize("kind", ["single"])
+def test_installed_block_vs_eager_block_fp32_table(kind):
+ # fp32 table: the installed block and the production (sequential-pair) block are both bitwise with the eager block
+ # (both RoPE kernels use scalar mul.rn/add.rn), except the Q/K scale gradients (<= 1 bf16 ulp, finding #9)
+ res, st = _block_case(kind, torch.float32, seed=1)
+ assert _all_equal(res["fused"], res["production"]) == {}, _all_equal(res["fused"], res["production"])
+ assert _all_equal(res["fused"], res["eager"], scale_grad_ulp=1) == {}, _all_equal(res["fused"], res["eager"])
+ assert _all_equal(res["production"], res["eager"], scale_grad_ulp=1) == {}, _all_equal(res["production"], res["eager"])
+
+
+def test_install_eval_mode_uses_seam_and_uninstall_restores():
+ from flux_action.models import dit_norm_mod_gate as nmg
+ from flux_action.models.transformer import SingleStreamBlock
+ blk = SingleStreamBlock(3072, 24, mlp_ratio=3.0).to(device=dev, dtype=torch.bfloat16)
+ nmg.install(blk)
+ import flux_action.models.transformer as T
+ prev = T.qk_norm_rope
+ st = QR.install(require_kernel=True)
+ assert T.qk_norm_rope is not prev
+ blk.eval()
+ L = 64
+ x = torch.randn(1, L, 3072, device=dev, dtype=torch.bfloat16)
+ mods = tuple(torch.zeros(1, L, 3072, device=dev, dtype=torch.bfloat16) for _ in range(3))
+ from flux_action.models.transformer import EmbedND
+ pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(torch.randint(0, 64, (1, L, 4), device=dev)).contiguous()
+ with torch.no_grad():
+ blk(x, None, pe, mods, None, seqlens=[L])
+ assert st.calls_fused == 0 and st.calls_seam == 1 # eval mode -> the block's own norm + apply_rope
+ QR.uninstall(st)
+ assert T.qk_norm_rope is prev
diff --git a/flux-umi/tests/training/test_dit_rows_fixes.py b/flux-umi/tests/training/test_dit_rows_fixes.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e0f9fe6162cdd002506678d7220962d6bbaedef
--- /dev/null
+++ b/flux-umi/tests/training/test_dit_rows_fixes.py
@@ -0,0 +1,368 @@
+"""Regression tests for the dit-rows review findings (CUDA + Triton; small shapes, < 2 GB).
+
+* #3 ``dit_norm_mod_gate.ln_mod_backward`` with ``need_dx=False`` used the incoming gradient ``g`` as the dx sink and the
+ kernel wrote dx into it unconditionally, so the ``d_shift`` the autograd Function returns (``g`` itself) was wrong
+ whenever the block input did not require grad (frozen input, trainable modulations).
+* #5 the unmasked gate / residual / rows-reduce kernels launch grid ``(M, N // block)`` with ``block = min(1024, N)``;
+ ``SUPPORTED_N`` admitted N = 1536 / 2560 / 3584 whose last ``N % 1024`` columns were never written. The contract is
+ now restricted to N that tile exactly; every N it admits is checked bitwise against eager, the others fall back.
+* #4 ``dit_mod_rows._position_tables`` (``dit_pe_cache``) keyed its hit on ids shape only and verified the values with a
+ device-side assert, so a same-shape layout with different ids (e.g. caption buckets [80, 160] -> [160, 80]) killed
+ the CUDA context; it is now keyed on the host-known layout and recomputes on a key change.
+
+Run: CUDA_VISIBLE_DEVICES= PYTHONPATH=src python -m pytest -q tests/training/test_dit_rows_fixes.py
+"""
+import copy
+import types
+
+import os
+import pytest
+from pathlib import Path
+import torch
+import torch.nn.functional as F
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import dit_mod_rows as mr
+from flux_action.models import dit_norm_mod_gate as nmg
+from flux_action.models import dit_out_stage as OS
+
+nmg.Config.bwd_variant_selected = True
+DEV = torch.device("cuda")
+N = 3072
+UNSUPPORTED = (1536, 2560, 3584) # multiples of 512 (LN kernels fine) that do not tile the 1024-wide gate block
+
+
+def _rel(a, b):
+ return ((a.double() - b.double()).norm() / b.double().norm().clamp_min(1e-30)).item()
+
+
+# ============================================================================================== #3 frozen input
+def test_ln_mod_backward_frozen_x_keeps_dshift_and_does_not_mutate_g():
+ """Finding #3 (kernel level): x frozen, shift/scale trainable -> d_shift must be g itself (eager: alias of the
+ incoming gradient) and g must not be modified; d_scale as eager."""
+ M = 777
+ x, shift, scale, gate, out, g, G, = nmg.make_inputs(M, N, DEV, seed=3)
+ g_copy = g.clone()
+ sh = shift.detach().requires_grad_(True)
+ sc = scale.detach().requires_grad_(True)
+ combined, _ = nmg.ln_modulate(x, sh, sc, 1e-6) # x does not require grad -> need_dx False in backward
+ combined.backward(g)
+ assert torch.equal(g, g_copy), "the incoming gradient was mutated by the backward kernel"
+ assert torch.equal(sh.grad, g_copy), f"d_shift rel L2 {_rel(sh.grad, g_copy):.3f} (expected the alias of g)"
+ # eager reference for d_scale
+ sh_e = shift.detach().requires_grad_(True)
+ sc_e = scale.detach().requires_grad_(True)
+ ref = (1 + sc_e) * F.layer_norm(x, (N,), None, None, 1e-6) + sh_e
+ ref.backward(g_copy)
+ assert torch.equal(sc.grad, sc_e.grad) and torch.equal(sh.grad, sh_e.grad)
+ # explicit wrapper call: need_dx=False and need_dscale=False must leave g intact as well
+ _, mean, rstd = nmg.ln_mod_forward(x, shift, scale, 1e-6)
+ dx, dsc = nmg.ln_mod_backward(g, x, scale, mean, rstd, None, need_dscale=False, need_dx=False)
+ assert dx is None and dsc is None and torch.equal(g, g_copy)
+
+
+def _nmg_block(kind, seed=0):
+ """Production-width block (3072, 24 heads) with ONLY dit_norm_mod_gate installed (eager everything else) so that any
+ difference to the eager block is the fused LN/modulation/gate path; MATH SDPA; checkpoint_wrapper(NO_REENTRANT)."""
+ from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
+ from flux_action.models.transformer import EmbedND, ModeBlock, SingleStreamBlock
+
+ torch.manual_seed(seed)
+ base = SingleStreamBlock(N, 24, mlp_ratio=3.0) if kind == "single" else ModeBlock(N, 24, mlp_ratio=3.0)
+ base = base.to(device=DEV, dtype=torch.bfloat16).train()
+ base.attn_mode = "torch"
+ eager_block = copy.deepcopy(base)
+ fused_block = copy.deepcopy(base)
+ nmg.install(fused_block)
+ counts = (80, 512, 64, 32, 1) * 2 if kind == "single" else (256,) * 2
+ L = sum(counts)
+ gen = torch.Generator(device=DEV).manual_seed(seed + 1)
+ x0 = torch.randn(1, L, N, device=DEV, generator=gen).to(torch.bfloat16)
+ mods0 = [(0.5 * torch.randn(1, L, N, device=DEV, generator=gen)).to(torch.bfloat16) for _ in range(3)]
+ ids = torch.randint(0, 64, (1, L, 4), device=DEV, generator=gen)
+ pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(ids).to(torch.bfloat16).contiguous()
+ gout = torch.randn(1, L, N, device=DEV, generator=gen).to(torch.bfloat16)
+ seqlens = [L // 2] * 2
+ wrapped = {k: checkpoint_wrapper(b, checkpoint_impl=CheckpointImpl.NO_REENTRANT, preserve_rng_state=False)
+ for k, b in dict(eager=eager_block, fused=fused_block).items()}
+ blocks = dict(eager=eager_block, fused=fused_block)
+
+ def run(name, x_requires_grad):
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ blk, w = blocks[name], wrapped[name]
+ for p in blk.parameters():
+ p.grad = None
+ x = x0.clone().requires_grad_(x_requires_grad)
+ mods = [m.clone().requires_grad_(True) for m in mods0]
+ with sdpa_kernel(SDPBackend.MATH):
+ if kind == "single":
+ _, out = w(x, None, pe, tuple(mods), None, seqlens=seqlens)
+ else:
+ out = w(x, pe, tuple(mods), seqlens=seqlens)
+ out.backward(gout)
+ return dict(out=out.detach(), dx=x.grad, dmods=[m.grad for m in mods],
+ params={n: p.grad.clone() for n, p in blk.named_parameters()})
+
+ return run
+
+
+@pytest.mark.parametrize("kind", ["single", "mode"])
+def test_block_frozen_input_trainable_modulations_bitwise_with_eager(kind):
+ """Finding #3 (block level, the failing case of the review: dshift rel L2 ~0.45 before the fix): the block input does
+ not require grad, the three per-token modulation tensors do (e.g. the first block of a frozen ``emb_in`` stream with
+ a trainable time embedder). Modulation and parameter gradients must be bitwise those of the eager block; the
+ trainable-input case is re-asserted alongside (unchanged by the fix)."""
+ run = _nmg_block(kind)
+ for x_requires_grad in (False, True):
+ ref = run("eager", x_requires_grad)
+ cur = run("fused", x_requires_grad)
+ assert torch.equal(cur["out"], ref["out"])
+ assert (cur["dx"] is None) == (ref["dx"] is None) == (not x_requires_grad)
+ if x_requires_grad:
+ assert torch.equal(cur["dx"], ref["dx"])
+ for i, name in enumerate(("shift", "scale", "gate")):
+ assert torch.equal(cur["dmods"][i], ref["dmods"][i]), \
+ f"x.requires_grad={x_requires_grad}: d_{name} rel L2 {_rel(cur['dmods'][i], ref['dmods'][i]):.3f}"
+ for n in ref["params"]:
+ assert torch.equal(cur["params"][n], ref["params"][n]), (x_requires_grad, n)
+
+
+# ============================================================================================== #5 supported N
+@pytest.mark.parametrize("N_", nmg.SUPPORTED_N)
+def test_nmg_kernels_every_supported_n(N_):
+ """Finding #5: every hidden size ``dit_norm_mod_gate.SUPPORTED_N`` admits is bitwise with eager on every output and
+ gradient (LN + modulation forward/backward, gate + residual forward/backward, incl. the o1 + o2 variant). Before the
+ fix N = 1536 was admitted and its last 512 columns of ``res`` / ``d_gate`` / ``d_out`` were uninitialised memory."""
+ M = 16
+ x, shift, scale, gate, out, g, G = nmg.make_inputs(M, N_, DEV, seed=N_)
+ ref = nmg._eager_reference(x, shift, scale, gate, out, g, G, 1e-6)
+ cur = nmg._fused_reference(x, shift, scale, gate, out, g, G, 1e-6)
+ for k in ref:
+ assert torch.equal(cur[k], ref[k]), (N_, k, nmg._compare(cur[k], ref[k]))
+ # the o1 + o2 gate variant
+ o1, o2 = out, g
+ xl, gl, o1l, o2l = (t.detach().requires_grad_(True) for t in (x, gate, o1, o2))
+ res2 = nmg.gate_residual2(xl, gl, o1l, o2l)
+ res2.backward(G)
+ xe, ge, o1e, o2e = (t.detach().requires_grad_(True) for t in (x, gate, o1, o2))
+ ref2 = xe + ge * (o1e + o2e)
+ ref2.backward(G)
+ for a, b in ((res2, ref2), (xl.grad, xe.grad), (gl.grad, ge.grad), (o1l.grad, o1e.grad), (o2l.grad, o2e.grad)):
+ assert torch.equal(a, b), N_
+ assert nmg.fusable(torch.nn.LayerNorm(N_, elementwise_affine=False, eps=1e-6).to(DEV), x, shift, scale)
+ assert nmg._gate_fusable(x, gate, out)
+
+
+@pytest.mark.parametrize("N_", mr.SUPPORTED_N)
+def test_rows_kernels_every_supported_n(N_):
+ """Finding #5: every hidden size ``dit_mod_rows.SUPPORTED_N`` admits: forward / dx / d_out bitwise with the per-token
+ fused path, row gradients fp32-sum-order close to fp64 segment sums (rows_reduce covered). Before the fix N = 1536,
+ 2560 and 3584 were admitted with their last ``N % 1024`` columns uninitialised."""
+ counts = (7, 9, 0, 3, 16, 1)
+ for fuse_add in (False, True):
+ r = mr.selftest(counts=counts, N=N_, device=DEV, verbose=False, fuse_add=fuse_add, seed=N_)
+ assert r["exact_fwd_dx_dout"], (N_, fuse_add, {k: r[k] for k in ("combined", "res", "dx", "do1", "do2")})
+ for k in ("dshift", "dscale", "dgate"):
+ assert r[k + "_vs_fp64"]["rel_l2"] < 5e-7, (N_, k, r[k + "_vs_fp64"])
+ x = torch.randn(sum(counts), N_, device=DEV).to(torch.bfloat16)
+ rows = [torch.randn(len(counts), N_, device=DEV) for _ in range(3)]
+ mod = mr.ModRows(*rows, mr.row_plan(counts, DEV))
+ assert mr.rows_fusable(torch.nn.LayerNorm(N_, elementwise_affine=False, eps=1e-6).to(DEV), x, mod)
+
+
+@pytest.mark.parametrize("N_", UNSUPPORTED)
+def test_unsupported_n_is_rejected_everywhere(N_):
+ """Finding #5: N that do not tile the 1024-wide gate block are not admitted by any fusable check (the eager / previous
+ forward handles them) and the launch helpers refuse them loudly instead of writing a partial output."""
+ M = 8
+ x, shift, scale, gate, out, g, G = nmg.make_inputs(M, N_, DEV, seed=1)
+ ln = torch.nn.LayerNorm(N_, elementwise_affine=False, eps=1e-6).to(DEV)
+ assert N_ not in nmg.SUPPORTED_N and N_ not in mr.SUPPORTED_N
+ assert not nmg.fusable(ln, x, shift, scale)
+ assert not nmg._gate_fusable(x, gate, out)
+ with pytest.raises(ValueError):
+ nmg.gate_grid(M, N_)
+ with pytest.raises(ValueError):
+ nmg.gate_res_forward(x, gate, out)
+ counts = (3, 5)
+ rows = [torch.randn(2, N_, device=DEV) for _ in range(3)]
+ mod = mr.ModRows(*rows, mr.row_plan(counts, DEV))
+ assert not mr.rows_fusable(ln, x, mod)
+ with pytest.raises(ValueError):
+ mr._check_x(x)
+ with pytest.raises(ValueError):
+ mr.rows_reduce(torch.zeros(1, 2, N_, device=DEV), torch.tensor([0, 1, 2], dtype=torch.int32, device=DEV), 2)
+ # the out_stage op glue
+ blk = types.SimpleNamespace(attn_out=torch.nn.Linear(N_, N_, bias=False).to(DEV, torch.bfloat16),
+ mlp_out=torch.nn.Linear(2 * N_, N_, bias=False).to(DEV, torch.bfloat16))
+ attn = torch.randn(1, M, N_, device=DEV).to(torch.bfloat16)
+ sw = torch.randn(1, M, 2 * N_, device=DEV).to(torch.bfloat16)
+ assert not OS.applies(blk, attn, sw, x.unsqueeze(0), mod)
+ # the dispatcher: a 1536-wide block falls back to the previous forward instead of running the row kernels
+ from flux_action.models.transformer import EmbedND, SingleStreamBlock
+ torch.manual_seed(0)
+ sblk = SingleStreamBlock(N_, N_ // 128, mlp_ratio=2.0).to(DEV, torch.bfloat16).train()
+ sblk.attn_mode = "torch"
+ nmg_state = nmg.install(sblk)
+ state = mr.install(sblk)
+ xx = torch.randn(1, M, N_, device=DEV).to(torch.bfloat16)
+ pe = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])(torch.randint(0, 16, (1, M, 4), device=DEV)).to(torch.bfloat16).contiguous()
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ with sdpa_kernel(SDPBackend.MATH):
+ _, y = sblk(xx, None, pe, mr.ModRows(*rows, mr.row_plan(counts, DEV)), None, 0.0, [M])
+ # eager reference on the expanded per-token modulation
+ from flux_action.models.dit_time_embed_dedup import expand_rows
+ mr.uninstall(state)
+ nmg.uninstall(nmg_state)
+ tok = tuple(expand_rows(r, counts, torch.bfloat16, (1, M, N_)) for r in rows)
+ _, y_ref = sblk(xx, None, pe, tok, None, 0.0, [M])
+ assert state.calls_rows == 0 and state.calls_other == 1 and nmg_state.calls_fused == 0
+ assert torch.equal(y, y_ref)
+
+
+# ============================================================================================== #4 pe cache
+class _FakeDit:
+ """Minimal stand-in for ``_position_tables``' ``self``: a ``pe_embedder`` and an instance ``__dict__``."""
+
+ def __init__(self):
+ from flux_action.models.transformer import EmbedND
+ self.pe_embedder = EmbedND(dim=128, theta=10000, axes_dim=[32, 32, 32, 32])
+ self.calls = 0
+ emb = self.pe_embedder
+
+ def counted(ids):
+ self.calls += 1
+ return emb(ids)
+
+ self.pe_embedder = counted
+
+
+def _ids(lens, seed):
+ g = torch.Generator().manual_seed(seed)
+ return torch.cat([torch.randint(0, 20, (1, n, 4), generator=g) for n in lens], 1).to(DEV)
+
+
+def test_position_tables_hit_shape_change_and_same_shape_different_ids():
+ """Finding #4 (function level): hit on an identical layout; a changed window count recomputes; a same-shape layout
+ with different ids (caption buckets [5, 3] -> [3, 5]) recomputes through the host key (no device assert for a
+ legitimate layout change); the no-cache tables are returned bitwise in every case; the CUDA context stays alive."""
+ dit = _FakeDit()
+ mods = ["act", "video"]
+
+ def call(ctx_lens, mod_lens, ids_seed, cast=torch.bfloat16, check="async"):
+ ids_by_mod = {k: _ids(mod_lens[k], ids_seed + i) for i, k in enumerate(mods)}
+ ctx_ids = _ids(ctx_lens, ids_seed + 10)
+ layout = (tuple(ctx_lens), tuple((k, tuple(mod_lens[k])) for k in mods))
+ pe_by_mod, pe_ctx = mr._position_tables(dit, ids_by_mod, ctx_ids, mods, cast, layout, check)
+ ref = {k: dit.pe_embedder(ids_by_mod[k]).to(cast) for k in mods}, dit.pe_embedder(ctx_ids).to(cast)
+ return (pe_by_mod, pe_ctx), ref
+
+ def same(a, b):
+ return all(torch.equal(a[0][k], b[0][k]) for k in mods) and torch.equal(a[1], b[1])
+
+ lay = {"act": [4, 4], "video": [12, 12]}
+ out, ref = call([5, 3], lay, ids_seed=0)
+ assert same(out, ref) and mr.pe_cache_stats(dit) == {"builds": 1, "hits": 0}
+ out, ref = call([5, 3], lay, ids_seed=0) # identical layout and ids -> hit
+ assert same(out, ref) and mr.pe_cache_stats(dit) == {"builds": 1, "hits": 1}
+ out, ref = call([5, 3, 2], {"act": [4, 4, 4], "video": [12, 12, 12]}, ids_seed=1) # window count change
+ assert same(out, ref) and mr.pe_cache_stats(dit) == {"builds": 2, "hits": 1}
+ out, ref = call([3, 5, 2], {"act": [4, 4, 4], "video": [12, 12, 12]}, ids_seed=2) # same shapes, other buckets
+ assert same(out, ref) and mr.pe_cache_stats(dit) == {"builds": 3, "hits": 1}
+ out, ref = call([3, 5, 2], {"act": [4, 4, 4], "video": [12, 12, 12]}, ids_seed=2, cast=torch.float32) # dtype change
+ assert same(out, ref) and out[1].dtype == torch.float32 and mr.pe_cache_stats(dit) == {"builds": 4, "hits": 1}
+ torch.cuda.synchronize() # no device-side assert pending
+ assert mr.pe_cache_verified(dit)
+ assert torch.equal(torch.arange(4, device=DEV) + 1, torch.tensor([1, 2, 3, 4], device=DEV)) # context alive
+ # a key collision (same layout key, different ids: only possible when the fixed layout parameters of the packing
+ # change under one module): "sync" mode compares on the host and recomputes; "async" mode asserts on the device
+ # (tested in a subprocess below, the assert is sticky)
+ out, ref = call([3, 5, 2], {"act": [4, 4, 4], "video": [12, 12, 12]}, ids_seed=8, cast=torch.float32, check="sync")
+ assert same(out, ref) and mr.pe_cache_stats(dit) == {"builds": 5, "hits": 1} and mr.pe_cache_verified(dit)
+ out, ref = call([3, 5, 2], {"act": [4, 4, 4], "video": [12, 12, 12]}, ids_seed=8, cast=torch.float32, check="sync")
+ assert same(out, ref) and mr.pe_cache_stats(dit) == {"builds": 5, "hits": 2}
+
+
+def test_position_tables_async_check_asserts_on_stale_hit():
+ """MR !1 review: an ``"async"``-mode hit whose ids differ from the cached ones must stop the run (device assert), not
+ serve the stale tables. Run in a subprocess because the assert kills the CUDA context."""
+ import subprocess, sys, textwrap
+ code = textwrap.dedent("""
+ import torch, sys
+ sys.path.insert(0, %r)
+ from test_dit_rows_fixes import _FakeDit, _ids
+ from flux_action.models import dit_mod_rows as mr
+ dit = _FakeDit(); mods = ["act", "video"]
+ def call(seed):
+ ids_by_mod = {k: _ids([4, 4], seed + i) for i, k in enumerate(mods)}
+ ctx_ids = _ids([5, 3], seed + 10)
+ layout = ((5, 3), tuple((k, (4, 4)) for k in mods))
+ return mr._position_tables(dit, ids_by_mod, ctx_ids, mods, torch.bfloat16, layout, "async")
+ call(0); call(0) # build, hit
+ torch.cuda.synchronize(); print("hit-ok", mr.pe_cache_stats(dit))
+ call(7) # same key, different ids -> device assert
+ torch.cuda.synchronize(); print("UNEXPECTED: stale hit served")
+ """) % str(Path(__file__).resolve().parent)
+ proc = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=600,
+ env={**os.environ, "PYTHONPATH": os.environ.get("PYTHONPATH", "")})
+ assert "hit-ok" in proc.stdout, proc.stdout + proc.stderr
+ assert proc.returncode != 0 and "UNEXPECTED" not in proc.stdout, proc.stdout + proc.stderr
+ assert "device-side assert" in (proc.stderr + proc.stdout) or "Assertion" in (proc.stderr + proc.stdout), proc.stderr[-800:]
+
+
+def test_forward_dedup_rows_pe_cache_same_shape_different_caption_buckets():
+ """Finding #4 (DiT level): ``forward_dedup_rows`` with ``dit_pe_cache`` on a tiny JointSingleSeq -- a hit, then the
+ same total context length split differently across the windows ([5, 3, 4, 5] -> [3, 5, 5, 4]): outputs and
+ gradients bitwise with the cache off, no device-side assert (the unfixed cache killed the CUDA context here)."""
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+ from flux_action.models import dit_time_embed_dedup as D
+ from flux_action.models.transformer import JointSingleSeq, JointSingleSeqParams
+
+ params = JointSingleSeqParams(in_channels={"video": 8, "video_cond": 8, "act": 4, "act_cond": 4},
+ sequence={"x_video": "video", "x_video_cond": "video_cond", "x_act": "act", "x_act_cond": "act_cond"},
+ vec_in_dim=12, context_in_dim=16, hidden_size=1024, num_heads=8, depth=1, depth_single_blocks=2,
+ axes_dim=[32, 32, 32, 32], attn_mode="torch")
+ torch.manual_seed(0)
+ dit = JointSingleSeq(params).to(DEV, torch.bfloat16)
+ dit.time_in.float()
+ dit.train()
+ assert D.install_training_time_embed_dedup(dit)["installed"]
+ nmg.install(dit)
+ mr.install_dedup_rows(dit)
+ dit.__dict__.pop(mr.PE_CAST_ATTR, None) # no FSDP here: fp32 tables on both paths (the cast is covered above)
+ kws = [D._tiny_inputs(DEV, torch.bfloat16, [5, 3, 4, 5], seed=1, lv=12, lvc=6, la=4, lac=1),
+ D._tiny_inputs(DEV, torch.bfloat16, [5, 3, 4, 5], seed=1, lv=12, lvc=6, la=4, lac=1),
+ D._tiny_inputs(DEV, torch.bfloat16, [3, 5, 5, 4], seed=2, lv=12, lvc=6, la=4, lac=1)]
+ assert kws[2]["ctx_ids"].shape == kws[0]["ctx_ids"].shape and not torch.equal(kws[2]["ctx_ids"], kws[0]["ctx_ids"])
+
+ def run(kw, cache):
+ prev = mr.Config.pe_cache
+ mr.Config.pe_cache = cache
+ try:
+ dit.zero_grad(set_to_none=True)
+ with sdpa_kernel(SDPBackend.MATH):
+ pred = dit(**kw)
+ loss = sum((p.float() * torch.randn(p.shape, generator=torch.Generator().manual_seed(i)).to(DEV)).sum()
+ for i, p in enumerate(pred.values()))
+ loss.backward()
+ torch.cuda.synchronize()
+ return {k: v.detach().clone() for k, v in pred.items()}, {n: p.grad.clone() for n, p in dit.named_parameters() if p.grad is not None}
+ finally:
+ mr.Config.pe_cache = prev
+
+ try:
+ for i, kw in enumerate(kws):
+ ref_pred, ref_grad = run(kw, cache=False)
+ pred, grad = run(kw, cache=True)
+ assert set(pred) == set(ref_pred) and set(grad) == set(ref_grad)
+ for k in pred:
+ assert torch.equal(pred[k], ref_pred[k]), (i, k)
+ for n in grad:
+ assert torch.equal(grad[n], ref_grad[n]), (i, n)
+ assert mr.pe_cache_stats(dit) == {"builds": 2, "hits": 1}
+ assert mr.pe_cache_verified(dit)
+ finally:
+ dit.__dict__.pop(mr._PE_CACHE_ATTR, None)
diff --git a/flux-umi/tests/training/test_ema.py b/flux-umi/tests/training/test_ema.py
new file mode 100644
index 0000000000000000000000000000000000000000..50c008be1222890125be51e8e08267c83dcb5c25
--- /dev/null
+++ b/flux-umi/tests/training/test_ema.py
@@ -0,0 +1,171 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Power EMA against a direct transcription of the reference callback, plus sharded equality."""
+
+import math
+
+import numpy as np
+import pytest
+import torch
+import torch.distributed as dist
+import torch.multiprocessing as mp
+
+from flux_action.training.ema import (
+ DROID_POWER_EMA_SIGMA_RELS,
+ PowerEMA,
+ power_ema_beta,
+ sigma_rel_to_gamma,
+)
+
+
+def reference_gamma(sigma_rel):
+ """bfl.modules.callbacks.ema.power_ema_sigma_rel_to_gamma, transcribed."""
+ t = sigma_rel**-2
+ return float(np.roots([1, 7, 16 - t, 12 - t]).real.max())
+
+
+def reference_decay(gamma, n_averaged):
+ """bfl.modules.callbacks.ema.power_ema_decay, transcribed."""
+ if n_averaged == 0:
+ return 0.0
+ return (1 - 1 / (n_averaged + 1)) ** (gamma + 1)
+
+
+def reference_update(ema_params, model_params, n_averaged, gamma):
+ """AveragedModel.update_parameters with power_ema_sigma_rel set, transcribed."""
+ if n_averaged == 0:
+ for p_ema, p_model in zip(ema_params, model_params, strict=True):
+ p_ema.copy_(p_model)
+ return
+ decay = reference_decay(gamma, n_averaged)
+ torch._foreach_lerp_(ema_params, model_params, 1 - decay) # get_ema_multi_avg_fn(decay)
+
+
+@pytest.mark.parametrize("sigma_rel", DROID_POWER_EMA_SIGMA_RELS)
+def test_gamma_matches_reference_and_edm2_profile(sigma_rel):
+ gamma = sigma_rel_to_gamma(sigma_rel)
+ assert gamma == reference_gamma(sigma_rel)
+ assert math.sqrt((gamma + 1) / ((gamma + 2) ** 2 * (gamma + 3))) == pytest.approx(sigma_rel, abs=1e-12)
+
+
+def test_recipe_gammas():
+ assert sigma_rel_to_gamma(0.10) == pytest.approx(6.937203937601809, abs=1e-9)
+ assert sigma_rel_to_gamma(0.05) == pytest.approx(16.972198602303443, abs=1e-9)
+ for bad in (0.0, -0.1, 12**-0.5, 0.5):
+ with pytest.raises(ValueError):
+ sigma_rel_to_gamma(bad)
+
+
+def test_beta_schedule():
+ gamma = sigma_rel_to_gamma(0.10)
+ assert power_ema_beta(gamma, 0) == 0.0
+ assert power_ema_beta(gamma, 1) == pytest.approx(0.5 ** (gamma + 1))
+ betas = [power_ema_beta(gamma, s) for s in range(1, 30001)]
+ assert all(b1 < b2 for b1, b2 in zip(betas, betas[1:], strict=False)) and betas[-1] < 1.0
+ assert betas[25999] == pytest.approx(reference_decay(gamma, 26000))
+ with pytest.raises(ValueError):
+ power_ema_beta(gamma, -1)
+
+
+@pytest.mark.parametrize("sigma_rel", DROID_POWER_EMA_SIGMA_RELS)
+def test_trace_matches_reference_update(sigma_rel):
+ rng = torch.Generator().manual_seed(7)
+ model = torch.nn.Linear(5, 3)
+ ema = PowerEMA.from_module(model, sigma_rel)
+ ref = [p.detach().clone() for p in model.parameters()]
+ gamma = reference_gamma(sigma_rel)
+ for step in range(40):
+ with torch.no_grad():
+ for p in model.parameters():
+ p.add_(torch.randn(p.shape, generator=rng) * 0.1)
+ beta = ema.update_from_module(model, step)
+ assert beta == reference_decay(gamma, step)
+ reference_update(ref, [p.detach() for p in model.parameters()], step, gamma)
+ for ours, theirs in zip(ema.shadow, ref, strict=True):
+ torch.testing.assert_close(ours, theirs, rtol=0, atol=0)
+ assert ema.last_step == 39
+ # The first update was a copy of the post-update weights, not the initialization.
+ assert not any(torch.equal(s, torch.zeros_like(s)) for s in ema.shadow)
+
+
+def test_state_dict_round_trip_copy_to_and_consolidated():
+ model = torch.nn.Linear(4, 2)
+ ema = PowerEMA.from_module(model, 0.10)
+ for step in range(3):
+ with torch.no_grad():
+ model.weight.add_(1.0)
+ ema.update_from_module(model, step)
+ state = ema.state_dict()
+ assert state["sigma_rel"] == 0.10 and state["last_step"] == 2
+ other = PowerEMA.from_module(torch.nn.Linear(4, 2), 0.10)
+ other.load_state_dict(state)
+ for a, b in zip(ema.shadow, other.shadow, strict=True):
+ assert torch.equal(a, b)
+ with pytest.raises(ValueError, match="sigma_rel"):
+ PowerEMA.from_module(torch.nn.Linear(4, 2), 0.05).load_state_dict(state)
+ target = torch.nn.Linear(4, 2)
+ ema.copy_to(list(target.parameters()))
+ assert torch.equal(target.weight.detach(), ema.shadow[0])
+ full = ema.consolidated()
+ assert set(full) == {"weight", "bias"} and torch.equal(full["weight"], ema.shadow[0])
+ with pytest.raises(TypeError):
+ PowerEMA([("ids", torch.zeros(2, dtype=torch.int64))], 0.10)
+ with pytest.raises(ValueError):
+ PowerEMA([], 0.10)
+
+
+def _sharded_worker(rank, world_size, init_file):
+ from torch.distributed.tensor import Shard, distribute_tensor, init_device_mesh
+
+ dist.init_process_group("gloo", init_method=f"file://{init_file}", rank=rank, world_size=world_size)
+ try:
+ mesh = init_device_mesh("cpu", (world_size,))
+ rng = torch.Generator().manual_seed(11)
+ full = torch.randn(8, 3, generator=rng)
+ dense = PowerEMA([("w", full.clone())], 0.10)
+ sharded = PowerEMA([("w", distribute_tensor(full.clone(), mesh, [Shard(0)]))], 0.10)
+ for step in range(6):
+ full = full + torch.randn(8, 3, generator=rng) # identical on every rank
+ dense.update([full], step)
+ sharded.update([distribute_tensor(full, mesh, [Shard(0)])], step)
+ gathered = sharded.consolidated()["w"]
+ torch.testing.assert_close(gathered, dense.shadow[0], rtol=0, atol=0)
+ local = sharded.state_dict()["tensors"]["w"].to_local()
+ assert local.shape == (8 // world_size, 3)
+ finally:
+ dist.destroy_process_group()
+
+
+def test_sharded_update_matches_unsharded(tmp_path):
+ mp.spawn(_sharded_worker, args=(2, str(tmp_path / "pg")), nprocs=2, join=True)
+
+
+@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
+def test_low_precision_model_ema_accumulates_small_updates_and_resumes(dtype):
+ source = torch.ones(4, dtype=dtype)
+ ema = PowerEMA([("w", source)], 0.1)
+ state = {"sigma_rel": 0.1, "last_step": 29999, "tensors": {"w": source.clone()}}
+ ema.load_state_dict(state)
+ assert ema.shadow[0].dtype == torch.float32
+ source.fill_(2)
+ beta = ema.update([source], 30000)
+ expected = torch.ones(4).lerp(source.float(), 1 - beta)
+ torch.testing.assert_close(ema.shadow[0], expected, rtol=0, atol=0)
+ assert (ema.shadow[0] > 1).all()
+ assert source.dtype == dtype and (source == 2).all()
+ resumed = PowerEMA([("w", source)], 0.1)
+ resumed.load_state_dict(ema.state_dict())
+ ema.update([source], 30001)
+ resumed.update([source], 30001)
+ torch.testing.assert_close(resumed.shadow[0], ema.shadow[0], rtol=0, atol=0)
diff --git a/flux-umi/tests/training/test_embodiment_plug.py b/flux-umi/tests/training/test_embodiment_plug.py
new file mode 100644
index 0000000000000000000000000000000000000000..96b267e692327723fbba6178c5aa4e34a7bcc6b9
--- /dev/null
+++ b/flux-umi/tests/training/test_embodiment_plug.py
@@ -0,0 +1,362 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""The trainer's embodiment settings: the dataset plug (``TrainConfig.dataset``), configurable LR phases, a
+per-window action mask through ``prepare`` -> ``flow_loss``, the export dtype and the pre-rename export key.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+
+import pytest
+import torch
+from conftest import TINY_DIT, FakeVideoVAE
+from torch.utils.data import IterableDataset, get_worker_info
+
+from flux_action.data.umi.all_windows import AllWindowDataset
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+from flux_action.processing import packing
+from flux_action.training.checkpoint import export_policy, latest_checkpoint
+from flux_action.training.data import get_epoch_loader_state, set_epoch_loader_state
+from flux_action.training.trainer import TrainConfig, Trainer, _import_dataset_builder
+
+FRAMES, H, W, D, CHUNK = 33, 32, 48, 4, 32 # window = 1 conditioning frame + 32 future
+TINY_POLICY = dict(
+ camera_layout="single", camera_keys=["images.game"], canvas_hw=[64, 96], action_dim=D, dit_config=TINY_DIT
+)
+
+
+class TwoEmbodimentWindows(IterableDataset):
+ """Synthetic windows of two 'games' sharing one 4-dim head: game A uses all 4 dims, game B the first 2
+ (its last two are zero-padded and masked). Deterministic from (seed, epoch, rank, position)."""
+
+ def __init__(
+ self,
+ seed,
+ epoch,
+ rank,
+ world_size,
+ num_workers,
+ windows_per_rank,
+ skip_batches,
+ grad_accumulation,
+ **_,
+ ):
+ self.seed, self.epoch, self.rank, self.num_workers = seed, epoch, rank, num_workers
+ self.windows_per_rank, self.skip_batches = windows_per_rank, skip_batches
+ self.batches_per_rank = 4 * grad_accumulation
+
+ def __iter__(self):
+ info = get_worker_info()
+ worker_id = info.id if info is not None else 0
+ first = self.skip_batches + (worker_id - self.skip_batches) % self.num_workers
+ for b in range(first, self.batches_per_rank, self.num_workers):
+ for w in range(self.windows_per_rank):
+ g = torch.Generator().manual_seed(hash((self.seed, self.epoch, self.rank, b, w)) % (2**31))
+ game_b = (b + w) % 2 == 1
+ mask = torch.tensor([1.0, 1.0, 0.0, 0.0]) if game_b else torch.ones(D)
+ actions = torch.rand(CHUNK, D, generator=g) * mask
+ yield {
+ "images.game": torch.randint(0, 255, (FRAMES, 3, H, W), dtype=torch.uint8, generator=g),
+ "state": torch.rand(D, generator=g) * mask,
+ "action": actions,
+ "action_mask": mask,
+ "task": "drive the racer" if game_b else "play the shooter",
+ "window_seed": int(torch.randint(0, 2**62, (), generator=g)),
+ }
+
+
+def build(config, **kwargs):
+ return TwoEmbodimentWindows(**kwargs)
+
+
+def tiny_policy(config):
+ return FluxActionPolicy(config, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+def make_config(output, **overrides):
+ values = dict(
+ dataset=f"{__name__}:build",
+ source_root="unused",
+ index_dir="unused",
+ output_dir=str(output),
+ policy=TINY_POLICY,
+ steps=6,
+ cooldown_start=4,
+ cooldown_steps=2,
+ frozen_steps=1,
+ trunk_warmup_steps=2,
+ heads_warmup_steps=1,
+ windows_per_rank=2,
+ num_workers=1,
+ in_process_loader=True,
+ param_dtype="float32",
+ compute_dtype="float32",
+ checkpoint_every=3,
+ log_every=1,
+ ema_sigma_rels=(0.10,),
+ )
+ values.update(overrides)
+ return TrainConfig(**values)
+
+
+def records(output):
+ lines = [json.loads(line) for line in (output / "metrics.jsonl").read_text().splitlines()]
+ return [r for r in lines if "loss" in r]
+
+
+def test_dataset_plug_spec_parsing():
+ assert _import_dataset_builder(f"{__name__}:build") is build
+ with pytest.raises(ValueError, match="pkg.module:callable"):
+ _import_dataset_builder("no_colon_here")
+
+
+def test_plugged_dataset_trains_without_an_index_and_uses_the_lr_phases(tmp_path):
+ output = tmp_path / "run"
+ result = Trainer(make_config(output), policy_factory=tiny_policy).run()
+ assert result["step"] == 6 and latest_checkpoint(output) == output / "step-6"
+ rows = records(output)
+ assert [r["step"] for r in rows] == [1, 2, 3, 4, 5, 6]
+ assert all(torch.isfinite(torch.tensor(r["loss"])) for r in rows)
+ # frozen_steps=1, trunk_warmup_steps=2, reference semantics (boundary step still zero): update g uses
+ # factor(g): g=0,1 -> 0; g=2 -> 1/2; g=3 -> 1 (then the cooldown overlay from g=4)
+ assert rows[0]["lr_trunk"] == 0.0 and rows[1]["lr_trunk"] == 0.0
+ assert rows[2]["lr_trunk"] == pytest.approx(0.5 * rows[3]["lr_trunk"]) and rows[3]["lr_trunk"] > 0
+ # heads_warmup_steps=1: heads at full LR from the second update
+ assert rows[1]["lr_heads"] == rows[2]["lr_heads"] == rows[3]["lr_heads"]
+
+
+def test_resume_is_exact_with_a_plugged_dataset(tmp_path):
+ full = tmp_path / "full"
+ Trainer(make_config(full, checkpoint_every=100), policy_factory=tiny_policy).run()
+ resumed = tmp_path / "resumed"
+ Trainer(make_config(resumed, steps=3, reseed_on_resume=False), policy_factory=tiny_policy).run()
+ Trainer(make_config(resumed, steps=6, reseed_on_resume=False), policy_factory=tiny_policy).run()
+ a = [(r["step"], r["loss"]) for r in records(full)]
+ b = [(r["step"], r["loss"]) for r in records(resumed)]
+ assert a == b
+
+
+def test_action_mask_removes_padded_dims_from_the_loss():
+ pred = {"x_video": torch.zeros(1, 3, 2), "x_action": torch.ones(1, 4, D)} # 2 windows x 2 action tokens
+ target = {k: torch.zeros_like(v) for k, v in pred.items()}
+ mask = torch.tensor([[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0]])
+ plain = packing.flow_loss(pred, target, "action")
+ masked = packing.flow_loss(pred, target, "action", action_mask=mask)
+ # every action dim errs by 1: unmasked token MSE is 1 everywhere; masked, the 2 padded dims of window 2
+ # leave its tokens at mean over 2 dims = 1 as well -> same MSE, but with errors only on padded dims the
+ # masked loss must vanish for that window
+ assert masked["action_mse"].item() == pytest.approx(plain["action_mse"].item())
+ pred2 = {
+ "x_video": torch.zeros(1, 3, 2),
+ "x_action": torch.tensor([[0.0, 0.0, 0.0, 0.0]] * 2 + [[0.0, 0.0, 1.0, 1.0]] * 2)[None],
+ }
+ only_padded = packing.flow_loss(pred2, target, "action", action_mask=mask)
+ assert only_padded["action_mse"].item() == 0.0
+ assert packing.flow_loss(pred2, target, "action")["action_mse"].item() > 0.0
+
+
+def test_masked_windows_train_and_the_mask_reaches_the_loss(tmp_path):
+ seen = {}
+ original = packing.flow_loss
+
+ def spy(*args, **kwargs):
+ seen["mask"] = kwargs.get("action_mask")
+ return original(*args, **kwargs)
+
+ packing.flow_loss = spy
+ try:
+ Trainer(make_config(tmp_path / "run", steps=1, cooldown_start=None), policy_factory=tiny_policy).run()
+ finally:
+ packing.flow_loss = original
+ assert seen["mask"] is not None and seen["mask"].shape == (2, D)
+ assert seen["mask"].sum().item() == 6.0 # one full window (4) + one game-B window (2)
+
+
+def test_epoch_boundary_checkpoint_and_versioned_resume(tmp_path):
+ output = tmp_path / "epochs"
+ first = make_config(output, steps=4, cooldown_start=None, checkpoint_every=4, max_epochs=1,
+ sampling_contract="test-all-windows-v1", reseed_on_resume=False)
+ result = Trainer(first, policy_factory=tiny_policy).run()
+ assert result["epoch"] == 1
+ state = json.loads((output / "step-4/state.json").read_text())
+ assert state["data"]["position"]["epoch"] == 1
+ assert state["data"]["position"]["batches_consumed"] == 0
+ next_config = make_config(output, steps=8, cooldown_start=None, checkpoint_every=4, max_epochs=2,
+ sampling_contract="test-all-windows-v1", reseed_on_resume=False)
+ resumed = Trainer(next_config, policy_factory=tiny_policy)
+ assert resumed.run()["epoch"] == 2
+ assert resumed.state.extra["resumes"][-1]["mode"] == "exact"
+ wrong = make_config(output, steps=8, cooldown_start=None, grad_accumulation=2,
+ sampling_contract="test-all-windows-v1", reseed_on_resume=False)
+ with pytest.raises(ValueError, match="grad_accumulation"):
+ Trainer(wrong, policy_factory=tiny_policy).build()
+
+ reseeded = tmp_path / "reseeded"
+ Trainer(make_config(reseeded, steps=4, cooldown_start=None, checkpoint_every=4,
+ max_epochs=1, sampling_contract="test-all-windows-v1"), policy_factory=tiny_policy).run()
+ result = Trainer(make_config(reseeded, steps=8, cooldown_start=None, checkpoint_every=4,
+ max_epochs=2, sampling_contract="test-all-windows-v1"), policy_factory=tiny_policy).run()
+ assert (result["step"], result["epoch"]) == (8, 2)
+
+
+def test_reuse_epoch_loader_rejects_other_datasets():
+ with pytest.raises(ValueError, match="multi-process all-windows"):
+ make_config("unused", reuse_epoch_loader=True)
+ with pytest.raises(ValueError, match="multi-process all-windows"):
+ make_config("unused", dataset="flux_action.data.umi.all_windows:build",
+ reuse_epoch_loader=True, in_process_loader=True)
+ with pytest.raises(ValueError, match="requires reuse_epoch_loader"):
+ make_config("unused", prefetch_next_epoch=True)
+ with pytest.raises(ValueError, match="finite positive max_epochs"):
+ make_config("unused", dataset="flux_action.data.umi.all_windows:build", num_workers=2,
+ in_process_loader=False, reuse_epoch_loader=True, prefetch_next_epoch=True)
+
+
+class ReusedTrainingWindows(TwoEmbodimentWindows):
+ def set_loader_state(self, state):
+ self._loader_state = state
+
+ def start_epoch(self, epoch, skip_batches):
+ set_epoch_loader_state(self._loader_state, epoch, skip_batches)
+ self.epoch, self.skip_batches = epoch, skip_batches
+
+ def __iter__(self):
+ if getattr(self, "_loader_state", None) is not None:
+ self.epoch, self.skip_batches = get_epoch_loader_state(self._loader_state)
+ for row in super().__iter__():
+ row["worker_pid"] = os.getpid()
+ yield row
+
+
+def test_reused_loader_keeps_training_and_checkpoint_contract(tmp_path, monkeypatch):
+ import flux_action.training.trainer as module
+
+ monkeypatch.setattr(module, "_import_dataset_builder", lambda spec: lambda cfg, **kw: ReusedTrainingWindows(**kw))
+ full, reused, resumed = (tmp_path / name for name in ("full", "reused", "resumed"))
+
+ def cfg(output, **kw):
+ return make_config(output, dataset="flux_action.data.umi.all_windows:build", num_workers=2,
+ in_process_loader=False, steps=8, cooldown_start=None, checkpoint_every=4,
+ max_epochs=2, sampling_contract="test-all-windows-v1", reseed_on_resume=False, **kw)
+
+ Trainer(cfg(full), policy_factory=tiny_policy).run()
+ Trainer(cfg(reused, reuse_epoch_loader=True), policy_factory=tiny_policy).run()
+ for step in (4, 8):
+ left = json.loads((full / f"step-{step}/state.json").read_text())
+ right = json.loads((reused / f"step-{step}/state.json").read_text())
+ assert left["data"]["position"] == right["data"]["position"]
+ assert [(r["step"], r["epoch"], r["loss"]) for r in records(full)] == [
+ (r["step"], r["epoch"], r["loss"]) for r in records(reused)
+ ]
+ for line in (reused / "metrics.jsonl").read_text().splitlines():
+ event = json.loads(line)
+ if event.get("event") == "epoch_loader":
+ assert event["reused"] == (event["epoch"] != 0)
+ first = cfg(resumed, reuse_epoch_loader=True)
+ first.steps = 4
+ first.max_epochs = 1
+ Trainer(first, policy_factory=tiny_policy).run()
+ trainer = Trainer(cfg(resumed, reuse_epoch_loader=True), policy_factory=tiny_policy)
+ assert trainer.run()["epoch"] == 2
+ assert trainer.state.extra["resumes"][-1]["mode"] == "exact"
+ assert [(r["step"], r["epoch"], r["loss"]) for r in records(resumed)] == [
+ (r["step"], r["epoch"], r["loss"]) for r in records(full)
+ ]
+
+ middle = tmp_path / "middle"
+ partial = cfg(middle, reuse_epoch_loader=True)
+ partial.steps = 2
+ Trainer(partial, policy_factory=tiny_policy).run()
+ position = json.loads((middle / "step-2/state.json").read_text())["data"]["position"]
+ assert (position["epoch"], position["batches_consumed"]) == (0, 2)
+ trainer = Trainer(cfg(middle, reuse_epoch_loader=True), policy_factory=tiny_policy)
+ assert trainer.run()["epoch"] == 2
+ assert trainer.state.extra["resumes"][-1]["mode"] == "exact"
+ assert [(r["step"], r["epoch"], r["loss"]) for r in records(middle)] == [
+ (r["step"], r["epoch"], r["loss"]) for r in records(full)
+ ]
+
+
+class PrefetchedTrainingWindows(AllWindowDataset):
+ def window_at(self, episode, start, *, window_seed=0):
+ g = torch.Generator().manual_seed(window_seed)
+ mask = torch.ones(D)
+ return {
+ "images.game": torch.randint(0, 255, (FRAMES, 3, H, W), dtype=torch.uint8, generator=g),
+ "state": torch.rand(D, generator=g),
+ "action": torch.rand(CHUNK, D, generator=g),
+ "action_mask": mask,
+ "task": "drive the racer",
+ "window_seed": window_seed,
+ "episode_index": episode,
+ "start": start,
+ }
+
+
+def test_prefetched_next_epoch_keeps_training_and_resume_contract(tmp_path, monkeypatch):
+ import flux_action.training.trainer as module
+
+ manifest = {
+ "fps": 30, "chunk_size": CHUNK, "total_frames": 60, "state_dim": D, "action_dim": D,
+ "camera_order": ["game"],
+ "episodes": [{"episode_index": i, "episode_id": str(i), "n_frames": 60,
+ "start_ranges": [[1, 8]], "valid_ranges": [[1, 60]],
+ "keep_ranges": [[0, 60]], "split": "train"} for i in range(2)],
+ }
+ monkeypatch.setattr(module, "_import_dataset_builder", lambda spec: lambda cfg, **kw: PrefetchedTrainingWindows(
+ manifest, ".", **kw
+ ))
+ full, ahead, resumed = (tmp_path / name for name in ("full", "ahead", "resumed"))
+
+ def cfg(output, **kw):
+ return make_config(output, dataset="flux_action.data.umi.all_windows:build", num_workers=2,
+ in_process_loader=False, steps=8, cooldown_start=None,
+ checkpoint_every=4, max_epochs=2, sampling_contract="test-all-windows-v1",
+ reseed_on_resume=False, reuse_epoch_loader=True, **kw)
+
+ Trainer(cfg(full), policy_factory=tiny_policy).run()
+ Trainer(cfg(ahead, prefetch_next_epoch=True), policy_factory=tiny_policy).run()
+ assert [(r["step"], r["epoch"], r["loss"]) for r in records(full)] == [
+ (r["step"], r["epoch"], r["loss"]) for r in records(ahead)
+ ]
+ for step in (4, 8):
+ a = json.loads((full / f"step-{step}/state.json").read_text())
+ b = json.loads((ahead / f"step-{step}/state.json").read_text())
+ assert a["data"]["position"] == b["data"]["position"]
+ assert [json.loads(s)["epoch"] for s in (ahead / "metrics.jsonl").read_text().splitlines()
+ if json.loads(s).get("event") == "epoch_first_batch"] == [0, 1]
+
+ first = cfg(resumed, prefetch_next_epoch=True)
+ first.steps = 3
+ Trainer(first, policy_factory=tiny_policy).run()
+ trainer = Trainer(cfg(resumed, prefetch_next_epoch=True), policy_factory=tiny_policy)
+ assert trainer.run()["step"] == 8
+ assert [(r["step"], r["epoch"], r["loss"]) for r in records(resumed)] == [
+ (r["step"], r["epoch"], r["loss"]) for r in records(full)
+ ]
+
+
+def test_export_dtype(tmp_path):
+ output = tmp_path / "run"
+ Trainer(make_config(output), policy_factory=tiny_policy).run()
+ export_policy(output / "step-6", tmp_path / "bf16", profile="model", dtype="bfloat16")
+ cfg = json.loads((tmp_path / "bf16" / "config.json").read_text())
+ assert cfg["torch_dtype"] == "bfloat16"
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "bf16", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert next(restored.dit.parameters()).dtype == torch.bfloat16
diff --git a/flux-umi/tests/training/test_pack_cache.py b/flux-umi/tests/training/test_pack_cache.py
new file mode 100644
index 0000000000000000000000000000000000000000..1460f67c0f6dd86e4a02dcbe22b387b8a20be06b
--- /dev/null
+++ b/flux-umi/tests/training/test_pack_cache.py
@@ -0,0 +1,168 @@
+"""CPU (and, when available, CUDA) tests for ``PolicyConfig.pack_cache``: the cached packing path must produce exactly the
+eager path's DiT inputs -- int64 ids, bf16 tokens, fp32 timesteps, seqlens, flow targets -- for the G2 layout, for unequal
+context lengths, across cache hits with new batches, with separate timesteps / conditioning noise, and end to end through
+``FluxActionPolicy.forward`` (bit-identical loss)."""
+import pytest
+import torch
+from conftest import make_policy, tiny_config
+
+from flux_action.config import PolicyConfig
+from flux_action.processing import packing
+
+DEVICES = ["cpu"] + (["cuda"] if torch.cuda.is_available() else [])
+
+
+def _cfg(**kw):
+ return PolicyConfig(action_dim=21, action_modality="action_prediction_g2_joints", camera_layout="grid",
+ camera_keys=("images.a", "images.b", "images.c"), canvas_hw=(512, 512), gripper_flip_dims=(),
+ action_scale=1.0, video_vae_id="x", text_encoder_id="y", **kw)
+
+
+def test_flag_validation():
+ assert _cfg(pack_cache=True).pack_cache is True
+ with pytest.raises(ValueError):
+ _cfg(pack_cache="yes")
+
+
+def _batch(device, *, b, n_latent, hw, chunk, action_dim, ctx_lens, ctx_dim, seed):
+ gen = torch.Generator().manual_seed(seed)
+ latents = torch.randn(b, 96, n_latent, *hw, generator=gen).to(torch.bfloat16).to(device)
+ state = torch.randn(b, 1, action_dim, generator=gen).to(device)
+ actions = torch.randn(b, chunk, action_dim, generator=gen).to(device)
+ ctxs = [torch.randn(1, n, ctx_dim, generator=gen).to(torch.bfloat16).to(device) for n in ctx_lens]
+ return latents, state, actions, ctxs
+
+
+def _drawn(b, *, n_latent, hw, chunk, action_dim, separate, cond, device, seed):
+ torch.manual_seed(seed)
+ drawn = packing.draw_training_randomness(
+ b, n_video_tokens=(n_latent - 1) * hw[0] * hw[1], n_cond_tokens=hw[0] * hw[1], chunk=chunk, action_dim=action_dim,
+ width=0.75, shift=42.0, separate_timesteps=separate, video_logit_mean=1.08, video_logit_std=1.0,
+ conditioning_noise=cond > 0,
+ )
+ # the trainer's prepare moves the noise to the device ahead of the step; the timesteps stay on the host
+ for key in ("video", "action", "cond"):
+ if key in drawn:
+ drawn[key] = drawn[key].to(device)
+ return drawn
+
+
+def _eager(latents, state, actions, ctxs, drawn, modality, *, fps, chunk, scale, separate, cond):
+ video = packing.pack_video(latents, fps=fps)
+ action = packing.pack_actions(state, actions, packing.default_action_times(len(ctxs), chunk, fps), modality,
+ scale=scale)
+ t = drawn["t"]
+ kw, targets, _ = packing.build_forward_kwargs(video, action, {}, drawn["t_video"] if separate else t, modality,
+ action_timesteps=t, conditioning_noise_max=cond, drawn=drawn)
+ packed, seqlens = packing.pack_windows(kw, ctxs, packing.VEC_DIM)
+ return packed, seqlens, targets
+
+
+def _assert_same(cached, eager):
+ packed_c, seqlens_c, targets_c = cached
+ packed_e, seqlens_e, targets_e = eager
+ assert set(packed_c) == set(packed_e)
+ for key in packed_e:
+ a, b = packed_c[key], packed_e[key]
+ assert a.dtype == b.dtype and a.shape == b.shape and a.device == b.device, key
+ assert torch.equal(a, b), key
+ assert seqlens_c == seqlens_e
+ assert set(targets_c) == set(targets_e)
+ for key in targets_e:
+ assert targets_c[key].dtype == targets_e[key].dtype and torch.equal(targets_c[key], targets_e[key]), key
+ ids = [k for k in packed_e if k.endswith("_ids")]
+ assert ids and all(packed_e[k].dtype == torch.int64 for k in ids)
+ assert all(packed_e[k].dtype == torch.float32 for k in packed_e if k.endswith("_timesteps") or k == "timesteps_ctx")
+
+
+@pytest.mark.parametrize("device", DEVICES)
+def test_g2_layout_matches_eager(device):
+ """128 windows x (9 latent frames x 16 x 16, chunk 32, 21 joints, fps 30, 80-token captions): the production layout."""
+ b, n_latent, hw, chunk, d, fps = 128, 9, (16, 16), 32, 21, 30.0
+ modality = "action_prediction_g2_joints"
+ cache = packing.PackCache()
+ for seed in (0, 1): # second call: cache hit with a new batch and a new caption-dropout pattern
+ lens = [80] * b if seed == 0 else [80 if i % 7 else 160 for i in range(b)]
+ latents, state, actions, ctxs = _batch(device, b=b, n_latent=n_latent, hw=hw, chunk=chunk, action_dim=d,
+ ctx_lens=lens, ctx_dim=32, seed=seed)
+ drawn = _drawn(b, n_latent=n_latent, hw=hw, chunk=chunk, action_dim=d, separate=False, cond=0.0, device=device,
+ seed=seed)
+ cached = cache.pack_training_windows(latents, state, actions, ctxs, drawn, modality, fps=fps, chunk=chunk,
+ scale=1.0)
+ eager = _eager(latents, state, actions, ctxs, drawn, modality, fps=fps, chunk=chunk, scale=1.0, separate=False,
+ cond=0.0)
+ _assert_same(cached, eager)
+ assert cached[0]["x_video"].shape == (1, b * 8 * 256, 96) and cached[0]["x_video_ids"].shape == (1, b * 2048, 4)
+ assert cache.layout_builds == 1
+
+
+@pytest.mark.parametrize("device", DEVICES)
+@pytest.mark.parametrize("separate,cond", [(False, 0.0), (True, 0.0), (False, 0.3), (True, 0.3)])
+def test_unequal_contexts_and_randomness_variants(device, separate, cond):
+ b, n_latent, hw, chunk, d, fps = 4, 3, (2, 3), 8, 6, 15.0
+ cache = packing.PackCache()
+ for seed, lens in ((10, [4, 8, 4, 12]), (11, [12, 4, 8, 4]), (12, [8, 8, 8, 8])):
+ latents, state, actions, ctxs = _batch(device, b=b, n_latent=n_latent, hw=hw, chunk=chunk, action_dim=d,
+ ctx_lens=lens, ctx_dim=16, seed=seed)
+ drawn = _drawn(b, n_latent=n_latent, hw=hw, chunk=chunk, action_dim=d, separate=separate, cond=cond,
+ device=device, seed=seed)
+ cached = cache.pack_training_windows(latents, state, actions, ctxs, drawn, "action", fps=fps, chunk=chunk,
+ scale=2.0, separate_timesteps=separate, conditioning_noise_max=cond)
+ eager = _eager(latents, state, actions, ctxs, drawn, "action", fps=fps, chunk=chunk, scale=2.0,
+ separate=separate, cond=cond)
+ _assert_same(cached, eager)
+ assert cached[1]["ctx"] == lens
+ assert cache.layout_builds == 1
+
+
+def test_batch_size_one_and_layout_change():
+ cache = packing.PackCache()
+ for b, n_latent in ((1, 3), (2, 3), (1, 2)):
+ latents, state, actions, ctxs = _batch("cpu", b=b, n_latent=n_latent, hw=(2, 2), chunk=4, action_dim=3,
+ ctx_lens=[4] * b, ctx_dim=8, seed=b)
+ drawn = _drawn(b, n_latent=n_latent, hw=(2, 2), chunk=4, action_dim=3, separate=False, cond=0.0, device="cpu",
+ seed=b)
+ cached = cache.pack_training_windows(latents, state, actions, ctxs, drawn, "action", fps=15.0, chunk=4, scale=2.0)
+ eager = _eager(latents, state, actions, ctxs, drawn, "action", fps=15.0, chunk=4, scale=2.0, separate=False,
+ cond=0.0)
+ _assert_same(cached, eager)
+ assert cache.layout_builds == 3 # three distinct layouts
+
+
+def test_timesteps_round_on_the_host_like_the_eager_path():
+ """``t`` values just below 1 collapse to exactly 1 on the bf16 grid in both paths (the reference's rounding)."""
+ b = 4
+ latents, state, actions, ctxs = _batch("cpu", b=b, n_latent=2, hw=(2, 2), chunk=4, action_dim=3, ctx_lens=[4] * b,
+ ctx_dim=8, seed=5)
+ drawn = _drawn(b, n_latent=2, hw=(2, 2), chunk=4, action_dim=3, separate=False, cond=0.0, device="cpu", seed=5)
+ drawn["t"] = torch.tensor([1 - 2 ** -10, 0.5 + 2 ** -9, 2 ** -9, 0.99999994])
+ cached = packing.PackCache().pack_training_windows(latents, state, actions, ctxs, drawn, "action", fps=15.0, chunk=4)
+ eager = _eager(latents, state, actions, ctxs, drawn, "action", fps=15.0, chunk=4, scale=2.0, separate=False, cond=0.0)
+ _assert_same(cached, eager)
+ assert cached[0]["x_video_timesteps"].reshape(b, -1)[0, 0] == 1.0 # collapsed, as in the reference
+
+
+@pytest.mark.parametrize("state_dropout", [0.0, 0.5])
+@pytest.mark.parametrize("prefetch", [False, True])
+def test_policy_forward_loss_is_bit_identical(batch, prefetch, state_dropout):
+ """End to end on the CPU fixture policy: the same global RNG draws, the same loss, either way the randomness arrives.
+ With ``state_dropout`` (synthesis B.1) the unseeded blank draws come from the global RNG between the augmentation
+ and the forward's draws, so both paths must still agree bit for bit and leave the same RNG tail."""
+ torch.manual_seed(0)
+ eager = make_policy(tiny_config(prefetch_randomness=prefetch, state_dropout=state_dropout)).train()
+ torch.manual_seed(0)
+ cached = make_policy(tiny_config(prefetch_randomness=prefetch, pack_cache=True, state_dropout=state_dropout)).train()
+ assert all(torch.equal(a, b) for a, b in zip(eager.state_dict().values(), cached.state_dict().values(), strict=True))
+ two = {**batch, "images.top": batch["images.top"].repeat(2, 1, 1, 1, 1), "state": batch["state"].repeat(2, 1),
+ "action": batch["action"].repeat(2, 1, 1), "task": ["move the object", ""]}
+ for step in range(2):
+ torch.manual_seed(3 + step)
+ loss_e, info_e = eager(two)
+ tail_e = torch.rand(3) # the global RNG must have advanced identically in both paths
+ torch.manual_seed(3 + step)
+ loss_c, info_c = cached(two)
+ tail_c = torch.rand(3)
+ assert torch.equal(loss_e, loss_c)
+ assert torch.equal(info_e["video_mse"], info_c["video_mse"]) and torch.equal(info_e["action_mse"], info_c["action_mse"])
+ assert torch.equal(tail_e, tail_c)
+ assert cached._pack_cache.layout_builds == 1
diff --git a/flux-umi/tests/training/test_perf2_options.py b/flux-umi/tests/training/test_perf2_options.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc8673916481619ec0667b7b30c1c896eb2ace70
--- /dev/null
+++ b/flux-umi/tests/training/test_perf2_options.py
@@ -0,0 +1,54 @@
+"""CPU tests for the campaign-2 (2026-10-01) training options: config validation and RNG-order invariance."""
+import pytest
+import torch
+
+from flux_action.config import PolicyConfig
+from flux_action.processing import packing
+
+
+def _cfg(**kw):
+ return PolicyConfig(action_dim=21, action_modality="action_prediction_g2_joints", camera_layout="grid",
+ camera_keys=("images.a", "images.b", "images.c"), canvas_hw=(512, 512), gripper_flip_dims=(),
+ action_scale=1.0, video_vae_id="x", text_encoder_id="y", **kw)
+
+
+def test_flag_validation():
+ _cfg(vae_natten_no_lse=True, vae_natten_triton_tokperm=True, vae_na3d_triton=True)
+ with pytest.raises(ValueError):
+ _cfg(vae_natten_triton_tokperm=True) # needs no-LSE
+ with pytest.raises(ValueError):
+ _cfg(vae_na3d_triton=True)
+ with pytest.raises(ValueError):
+ _cfg(dit_swiglu_fused=True, dit_swiglu_native_out=True)
+ with pytest.raises(ValueError):
+ _cfg(dit_qknorm_triton=True, dit_cute_qknorm=True)
+ with pytest.raises(ValueError):
+ _cfg(vae_fused_pointwise=True, compile_model=True)
+ with pytest.raises(ValueError):
+ _cfg(prefetch_randomness="yes")
+
+
+def test_prefetch_randomness_preserves_rng_order():
+ n, nv, nc, chunk, D = 3, 64, 16, 8, 21
+ video = {"x_video": torch.zeros(n, nv, 96, dtype=torch.bfloat16), "x_video_ids": torch.zeros(n, nv, 4, dtype=torch.int64),
+ "x_video_cond": torch.zeros(n, nc, 96, dtype=torch.bfloat16), "x_video_cond_ids": torch.zeros(n, nc, 4, dtype=torch.int64)}
+ action = {"x_a": torch.zeros(n, chunk, D, dtype=torch.bfloat16), "x_a_ids": torch.zeros(n, chunk, 4, dtype=torch.int64),
+ "x_a_cond": torch.zeros(n, 1, D), "x_a_cond_ids": torch.zeros(n, 1, 4, dtype=torch.int64)}
+ for cond, sep in ((0.0, False), (0.3, True)):
+ torch.manual_seed(11)
+ t = packing.sample_timesteps(n, None, 0.75, 42.0)
+ tv = torch.sigmoid(torch.randn(n) * 1.0 + 1.08) if sep else t
+ kw1, tg1, _ = packing.build_forward_kwargs(video, action, {}, tv, "a", action_timesteps=t, conditioning_noise_max=cond)
+ tail1 = torch.rand(4)
+ torch.manual_seed(11)
+ drawn = packing.draw_training_randomness(n, n_video_tokens=nv, n_cond_tokens=nc, chunk=chunk, action_dim=D, width=0.75,
+ shift=42.0, separate_timesteps=sep, video_logit_mean=1.08,
+ video_logit_std=1.0, conditioning_noise=cond > 0)
+ kw2, tg2, _ = packing.build_forward_kwargs(video, action, {}, drawn["t_video"] if sep else drawn["t"], "a",
+ action_timesteps=drawn["t"], conditioning_noise_max=cond, drawn=drawn)
+ tail2 = torch.rand(4)
+ for k in kw1:
+ assert torch.equal(kw1[k], kw2[k]), k
+ for k in tg1:
+ assert torch.equal(tg1[k], tg2[k]), k
+ assert torch.equal(tail1, tail2)
diff --git a/flux-umi/tests/training/test_perf3_options.py b/flux-umi/tests/training/test_perf3_options.py
new file mode 100644
index 0000000000000000000000000000000000000000..d228aea09340437adb2b0499f203d71951c6967c
--- /dev/null
+++ b/flux-umi/tests/training/test_perf3_options.py
@@ -0,0 +1,128 @@
+"""CPU tests for the campaign-3 (2026-10-02) training options: config validation, selective-checkpoint policy."""
+import dataclasses
+
+import pytest
+import torch
+from torch import nn
+from torch.utils.checkpoint import CheckpointPolicy, checkpoint, create_selective_checkpoint_contexts
+
+from flux_action.config import PolicyConfig
+from flux_action.training.distributed import SAC_SAVE_KINDS, _SacPolicy, apply_activation_checkpointing
+from flux_action.training.trainer import TrainConfig
+
+
+def _cfg(**kw):
+ return PolicyConfig(action_dim=21, action_modality="action_prediction_g2_joints", camera_layout="grid",
+ camera_keys=("images.a", "images.b", "images.c"), canvas_hw=(512, 512), gripper_flip_dims=(),
+ action_scale=1.0, video_vae_id="x", text_encoder_id="y", **kw)
+
+
+def test_policy_flag_validation():
+ _cfg(vae_fused_pointwise=True, vae_ln_exact_fast=True, vae_qk_fused=True, vae_mlp_residual_fused=True)
+ _cfg(dit_norm_mod_gate_fused=True, dit_time_embed_dedup=True, dit_mod_rows=True)
+ for bad in (dict(vae_ln_exact_fast=True), dict(vae_qk_fused=True), dict(vae_mlp_residual_fused=True)):
+ with pytest.raises(ValueError):
+ _cfg(**bad) # need vae_fused_pointwise
+ with pytest.raises(ValueError):
+ _cfg(dit_mod_rows=True, dit_norm_mod_gate_fused=True) # needs dit_time_embed_dedup too
+ with pytest.raises(ValueError):
+ _cfg(dit_mod_rows="yes", dit_norm_mod_gate_fused=True, dit_time_embed_dedup=True)
+ _cfg(dit_norm_mod_gate_fused=True, dit_time_embed_dedup=True, dit_mod_rows=True, dit_fanout_linear=True)
+ with pytest.raises(ValueError):
+ _cfg(dit_fanout_linear=True) # needs dit_mod_rows
+ _cfg(dit_norm_mod_gate_fused=True, dit_time_embed_dedup=True, dit_mod_rows=True, dit_pe_cache=True, dit_last_layer_rows=True)
+ with pytest.raises(ValueError):
+ _cfg(dit_pe_cache=True)
+
+
+def test_train_config_sac_validation():
+ base = dict(TrainConfig.from_file("configs/umi/umi_posttrain_16g.json").__dict__)
+ cfg = dataclasses.replace(TrainConfig(**base), ac_mode="sac", ac_sac_save=("sdpa", "mlp_out"),
+ ac_sac_extra_save=("attn_out",), ac_sac_extra_blocks=4, manual_gc_every=5)
+ assert cfg.ac_mode == "sac"
+ for bad in (dict(ac_mode="sac_mlp"), dict(ac_sac_save=("bogus",)), dict(ac_sac_extra_blocks=-1), dict(manual_gc_every=-1)):
+ with pytest.raises(ValueError):
+ dataclasses.replace(TrainConfig(**base), **bad)
+
+
+HIDDEN, MLP_IN, MLP_HIDDEN = 64, 384, 192
+
+
+class _Block(nn.Module):
+ """A SingleStreamBlock-shaped graph: q/k/v + mlp_in GEMMs on the same input, attention, attn_out + mlp_out."""
+
+ def __init__(self):
+ super().__init__()
+ self.q_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.k_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.v_proj = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.mlp_in = nn.Linear(HIDDEN, MLP_IN, bias=False)
+ self.attn_out = nn.Linear(HIDDEN, HIDDEN, bias=False)
+ self.mlp_out = nn.Linear(MLP_HIDDEN, HIDDEN, bias=False)
+
+ def forward(self, x):
+ B, L, _ = x.shape
+ q, k, v = (p(x).view(B, L, 4, 16).transpose(1, 2) for p in (self.q_proj, self.k_proj, self.v_proj))
+ a = nn.functional.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(B, L, HIDDEN)
+ g, u = self.mlp_in(x).chunk(2, -1)
+ return x + self.attn_out(a) + self.mlp_out(nn.functional.silu(g) * u)
+
+
+class _Spy(_SacPolicy):
+ def __init__(self, save):
+ super().__init__(save, HIDDEN, MLP_IN, MLP_HIDDEN)
+ self.kinds = {False: [], True: []}
+
+ def __call__(self, ctx, op, *args, **kwargs):
+ kind = self.kind(op, args, bool(ctx.is_recompute))
+ if kind is not None:
+ self.kinds[bool(ctx.is_recompute)].append(kind)
+ return CheckpointPolicy.MUST_SAVE if kind in self.save else CheckpointPolicy.PREFER_RECOMPUTE
+
+
+def test_sac_policy_classifies_block_gemms_and_matches_plain_autograd():
+ torch.manual_seed(0)
+ block = _Block()
+ x = torch.randn(1, 32, HIDDEN, requires_grad=True)
+ spy = _Spy(["mlp_out"])
+ out = checkpoint(block, x, use_reentrant=False, context_fn=lambda: create_selective_checkpoint_contexts(spy))
+ out.sum().backward()
+ # the CPU SDPA decomposes into math ops, so no "sdpa" kind here; the GEMMs classify by weight shape and order
+ assert spy.kinds[False] == ["qkv", "qkv", "qkv", "mlp_in", "qkv", "mlp_out"]
+ assert "mlp_out" not in spy.kinds[True] # saved: not recomputed
+ x2 = x.detach().clone().requires_grad_(True)
+ block(x2).sum().backward()
+ assert torch.equal(out.detach(), block(x.detach())) and torch.equal(x.grad, x2.grad)
+ assert set(SAC_SAVE_KINDS) >= {"sdpa", "mlp_out", "attn_out", "qkv", "mlp_in"}
+
+
+def test_apply_activation_checkpointing_orders_extra_blocks_from_single_blocks():
+ class Toy(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.content_mode_blocks = nn.ModuleDict({"video": nn.ModuleList([_Block() for _ in range(2)])})
+ self.single_blocks = nn.ModuleList([_Block() for _ in range(3)])
+
+ dit = Toy()
+ singles = [id(b) for b in dit.single_blocks]
+ n = apply_activation_checkpointing(dit, mode="sac", sac_save=("sdpa",), sac_extra_save=("mlp_out",), sac_extra_blocks=2)
+ assert n == 5
+ wrapped_singles = [id(b._checkpoint_wrapped_module) for b in dit.single_blocks]
+ assert wrapped_singles == singles # instances retained inside the wrappers
+ with pytest.raises(ValueError):
+ apply_activation_checkpointing(Toy(), mode="sac", sac_save=("bogus",))
+ with pytest.raises(ValueError):
+ apply_activation_checkpointing(Toy(), mode="nope")
+ # extra save kinds reach the policy of the first two single blocks only
+ for module, expect_extra in zip([*dit.single_blocks, *dit.content_mode_blocks["video"]], [True, True, False, False, False]):
+ ctx_fn = module.checkpoint_fn.keywords["context_fn"]
+ policy = ctx_fn()[0].policy_fn
+ assert ("mlp_out" in policy.save) is expect_extra
+
+
+def test_vae_graph_capture_defaults_to_thread_local_mode():
+ import inspect
+
+ from flux_action.models.vae_graphed import GraphedVAEEncoder
+
+ assert inspect.signature(GraphedVAEEncoder.__init__).parameters["capture_error_mode"].default == "thread_local"
diff --git a/flux-umi/tests/training/test_resume_prefetch_rng.py b/flux-umi/tests/training/test_resume_prefetch_rng.py
new file mode 100644
index 0000000000000000000000000000000000000000..62ce690876604864d698c412a955ca78aaf84a7e
--- /dev/null
+++ b/flux-umi/tests/training/test_resume_prefetch_rng.py
@@ -0,0 +1,112 @@
+"""Exact resume from a periodic checkpoint written while the next micro-batch was already prepared.
+
+Review finding 3 (2026-10-03): ``prepare`` runs ahead of the update that consumes the batch and draws from the global
+CPU RNG (timesteps/noise with ``prefetch_randomness``; caption/camera dropout, augmentation and state dropout when the
+loader provides no ``window_seed``). A periodic checkpoint used to store the already-advanced generators, so the resumed
+run drew different values for the batch it prepared again while logging ``mode=exact``. The checkpoint now stores the
+generator states captured when that prepare started (``PreparedWindows.rng_before``). These tests use the plugged
+tiny dataset of ``test_embodiment_plug`` (CPU, 4 updates per epoch) and resume from steps 2 and 4 of a 6-step run.
+"""
+import json
+import shutil
+
+import pytest
+import torch
+from test_embodiment_plug import TINY_POLICY, TwoEmbodimentWindows, make_config, records, tiny_policy
+
+import flux_action.training.trainer as trainer_module
+from flux_action.training.checkpoint import cpu_rng_state
+from flux_action.training.trainer import Trainer
+
+
+class NoSeedWindows(TwoEmbodimentWindows):
+ """The same windows without ``window_seed``: dropout / augmentation then draw from the global RNG in ``prepare``."""
+
+ def __iter__(self):
+ for row in super().__iter__():
+ row.pop("window_seed")
+ yield row
+
+
+def _loss_tuples(output):
+ return [(r["step"], r["epoch"], r["loss"], r["grad_norm"]) for r in records(output)]
+
+
+def _run(cfg):
+ return Trainer(cfg, policy_factory=tiny_policy).run()
+
+
+def _resume_from(full_dir, step, new_dir, cfg):
+ new_dir.mkdir(parents=True, exist_ok=True)
+ shutil.copytree(full_dir / f"step-{step}", new_dir / f"step-{step}")
+ _run(cfg)
+ state = json.loads((new_dir / f"step-{cfg.steps}" / "state.json").read_text())
+ return state["extra"]["resumes"][-1]["mode"]
+
+
+@pytest.fixture
+def checkpoint_log(monkeypatch):
+ """Per checkpoint: (step, prefetched batch pending?, saved torch RNG == rng_before, saved != live)."""
+ log = []
+ original = Trainer._checkpoint
+
+ def _checkpoint(self):
+ live = cpu_rng_state()
+ before = getattr(self._prepared, "rng_before", None) if self._prepared is not None else None
+ original(self)
+ saved = torch.load(self.output_dir / f"step-{self.step}" / "rng" / "rank-0000.pt", weights_only=True)
+ assert set(saved) == {"torch", "cuda", "python", "numpy"}
+ if before is not None:
+ log.append((self.step, True, torch.equal(saved["torch"], before["torch"]),
+ not torch.equal(saved["torch"], live["torch"])))
+ else:
+ log.append((self.step, False, torch.equal(saved["torch"], live["torch"]), None))
+
+ monkeypatch.setattr(Trainer, "_checkpoint", _checkpoint)
+ return log
+
+
+@pytest.mark.parametrize("prefetch", [True, False])
+def test_resume_from_periodic_checkpoint_with_window_seeds(tmp_path, monkeypatch, checkpoint_log, prefetch):
+ monkeypatch.setattr(trainer_module, "_import_dataset_builder", lambda spec: lambda cfg, **kw: TwoEmbodimentWindows(**kw))
+ policy = {**TINY_POLICY, "prefetch_randomness": prefetch, "caption_dropout": 0.5}
+
+ def cfg(out, **kw):
+ return make_config(out, steps=6, cooldown_start=None, checkpoint_every=2, reseed_on_resume=False, policy=policy, **kw)
+
+ full = tmp_path / "full"
+ _run(cfg(full))
+ ref = _loss_tuples(full)
+ assert len(ref) == 6
+ for k in (2, 4):
+ new = tmp_path / f"r{k}"
+ assert _resume_from(full, k, new, cfg(new)) == "exact"
+ assert _loss_tuples(new) == ref[k:], (k, _loss_tuples(new), ref[k:])
+ # 4 updates per epoch: step 2 has a prefetched batch pending, step 4 (epoch end) and step 6 (final) have none
+ assert [(s, p) for s, p, *_ in checkpoint_log[:3]] == [(2, True), (4, False), (6, False)], checkpoint_log
+ step2 = checkpoint_log[0]
+ assert step2[2] is True # saved == the generators before the pending prepare
+ assert step2[3] is prefetch # with prefetch that prepare drew from the global RNG, so saved != live
+ assert checkpoint_log[1][2] is True and checkpoint_log[2][2] is True # nothing pending: saved == live
+
+
+@pytest.mark.parametrize("prefetch", [True, False])
+def test_resume_without_window_seeds_dropout_and_grad_accumulation(tmp_path, monkeypatch, checkpoint_log, prefetch):
+ monkeypatch.setattr(trainer_module, "_import_dataset_builder", lambda spec: lambda cfg, **kw: NoSeedWindows(**kw))
+ policy = {**TINY_POLICY, "prefetch_randomness": prefetch, "caption_dropout": 0.5, "state_dropout": 0.3, "augment": True}
+
+ def cfg(out, **kw):
+ return make_config(out, steps=6, cooldown_start=None, checkpoint_every=2, reseed_on_resume=False,
+ grad_accumulation=2, policy=policy, **kw)
+
+ full = tmp_path / "full"
+ _run(cfg(full))
+ ref = _loss_tuples(full)
+ assert len(ref) == 6
+ for k in (2, 4):
+ new = tmp_path / f"r{k}"
+ assert _resume_from(full, k, new, cfg(new)) == "exact"
+ assert _loss_tuples(new) == ref[k:], (k, _loss_tuples(new), ref[k:])
+ assert [(s, p) for s, p, *_ in checkpoint_log[:3]] == [(2, True), (4, False), (6, False)], checkpoint_log
+ # without window seeds the pending prepare drew dropout/augmentation from the global RNG even without prefetch
+ assert checkpoint_log[0][2] is True and checkpoint_log[0][3] is True
diff --git a/flux-umi/tests/training/test_schedule.py b/flux-umi/tests/training/test_schedule.py
new file mode 100644
index 0000000000000000000000000000000000000000..27abb034bfffb8d38f184c09c5f291559a1e523f
--- /dev/null
+++ b/flux-umi/tests/training/test_schedule.py
@@ -0,0 +1,152 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Schedule factors against the reference formulas and the pinned call order."""
+
+import pytest
+import torch
+
+from flux_action.training.schedule import (
+ CooldownFrom,
+ FrozenThenLinearWarmup,
+ LinearWarmupLinearDecay,
+ build_lr_scheduler,
+ droid_lr_lambdas,
+ resume_lr_scheduler,
+)
+
+# Values computed by hand from the reference classes with LR_SCALE folded out (scale one).
+# Trunk: FrozenThenLinearWarmup(1000, 2000); heads: LinearWarmupLinearDecay(1000, None);
+# both replaced from step 25000 by LinearWarmupLinearDecay(None, 5000, start_step=25000).
+TABLE = {
+ 0: (0.0, 1 / 1001),
+ 999: (0.0, 1000 / 1001),
+ 1000: (0.0, 1.0),
+ 1001: (1 / 2000, 1.0),
+ 2999: (1999 / 2000, 1.0),
+ 3000: (1.0, 1.0),
+ 24999: (1.0, 1.0),
+ 25000: (1.0, 1.0),
+ 27500: (0.5, 0.5),
+ 29999: (1 / 5000, 1 / 5000),
+ 30000: (0.0, 0.0),
+}
+
+
+def test_droid_factor_table():
+ trunk, heads = droid_lr_lambdas()
+ for step, (t, h) in TABLE.items():
+ assert trunk(step) == pytest.approx(t, abs=1e-15), step
+ assert heads(step) == pytest.approx(h, abs=1e-15), step
+ for f in (trunk, heads):
+ with pytest.raises(RuntimeError, match="past the scheduled end"):
+ f(30001)
+
+
+def test_open_ended_base_launch_is_constant_after_warmup():
+ trunk, heads = droid_lr_lambdas(cooldown_start=None)
+ assert trunk(25000) == heads(25000) == trunk(49999) == heads(49999) == 1.0
+
+
+def test_lr_scale_folding_matches_reference_peaks():
+ # Reference: base LR 2e-4 / 1e-3 with LR_SCALE 0.96 in the factor. Ours: 1.92e-4 / 9.6e-4 at scale one.
+ ref_trunk, ref_heads = droid_lr_lambdas(lr_scale=0.96)
+ trunk, heads = droid_lr_lambdas()
+ for step in TABLE:
+ assert 2e-4 * ref_trunk(step) == pytest.approx(1.92e-4 * trunk(step), rel=1e-12)
+ assert 1e-3 * ref_heads(step) == pytest.approx(9.6e-4 * heads(step), rel=1e-12)
+
+
+def test_cooldown_from_any_step_matches_reference_overlay():
+ base = LinearWarmupLinearDecay(1000, None)
+ overlay = LinearWarmupLinearDecay(None, 5000, start_step=12345, lr_scale=0.96)
+ combined = CooldownFrom(base, 12345, 5000, lr_scale=0.96)
+ for step in (0, 12344, 12345, 12346, 15000, 17345):
+ expected = base(step) if step < 12345 else overlay(step)
+ assert combined(step) == expected
+ with pytest.raises(RuntimeError):
+ combined(17346)
+
+
+def test_reference_class_edge_cases():
+ with pytest.raises(ValueError):
+ FrozenThenLinearWarmup(-1, 10)
+ with pytest.raises(ValueError):
+ FrozenThenLinearWarmup(0, 0)
+ with pytest.raises(ValueError):
+ LinearWarmupLinearDecay(-1, None)
+ with pytest.raises(ValueError):
+ CooldownFrom(lambda s: 1.0, 10, 0)
+ # warmup + constant + decay, the full torchtitan shape, at scale 0.5
+ f = LinearWarmupLinearDecay(4, 10, constant_steps=6, lr_scale=0.5)
+ assert [f(s) for s in (0, 3, 4, 9, 10, 15, 20)] == pytest.approx(
+ [0.5 / 5, 0.5 * 4 / 5, 0.5, 0.5, 0.5, 0.25, 0.0]
+ )
+ with pytest.raises(RuntimeError):
+ f(21)
+
+
+def _two_group_optimizer():
+ trunk = torch.nn.Parameter(torch.ones(3))
+ heads = torch.nn.Parameter(torch.ones(2))
+ return torch.optim.AdamW([{"params": [trunk], "lr": 1.92e-4}, {"params": [heads], "lr": 9.6e-4}])
+
+
+def _run(optimizer, scheduler, steps, start=0):
+ """Reference loop: the LR consumed by update g must equal base * factor(g)."""
+ trunk, heads = droid_lr_lambdas()
+ consumed = []
+ for g in range(start, start + steps):
+ for p in (pg["params"][0] for pg in optimizer.param_groups):
+ p.grad = torch.ones_like(p)
+ consumed.append(tuple(pg["lr"] for pg in optimizer.param_groups))
+ assert consumed[-1] == pytest.approx((1.92e-4 * trunk(g), 9.6e-4 * heads(g)), rel=1e-12), g
+ optimizer.step()
+ scheduler.step()
+ return consumed
+
+
+def test_lambda_lr_call_order_and_resume():
+ optimizer = _two_group_optimizer()
+ scheduler = build_lr_scheduler(optimizer, droid_lr_lambdas())
+ assert scheduler.get_last_lr() == pytest.approx([0.0, 9.6e-4 / 1001])
+ uninterrupted = _run(optimizer, scheduler, 6)
+ assert scheduler.state_dict()["lr_lambdas"] == [None, None] # config, not checkpoint, owns the schedule
+
+ # Interrupt after three updates: a fresh optimizer loads the stale state, then the reference resume.
+ optimizer2 = _two_group_optimizer()
+ scheduler2 = build_lr_scheduler(optimizer2, droid_lr_lambdas())
+ _run(optimizer2, scheduler2, 3)
+ state = optimizer2.state_dict()
+ optimizer3 = _two_group_optimizer()
+ scheduler3 = build_lr_scheduler(optimizer3, droid_lr_lambdas())
+ optimizer3.load_state_dict(state)
+ resume_lr_scheduler(scheduler3, 3)
+ resumed = _run(optimizer3, scheduler3, 3, start=3)
+ assert resumed == uninterrupted[3:]
+ with pytest.raises(ValueError):
+ build_lr_scheduler(_two_group_optimizer(), [lambda s: 1.0])
+
+
+def test_frozen_trunk_still_accumulates_adam_state():
+ # The reference keeps the trunk in AdamW at LR zero: weights hold, moments and step advance.
+ param = torch.nn.Parameter(torch.ones(4))
+ optimizer = torch.optim.AdamW([{"params": [param], "lr": 1.92e-4}], weight_decay=0.05)
+ scheduler = build_lr_scheduler(optimizer, [FrozenThenLinearWarmup(1000, 2000)])
+ for _ in range(3):
+ param.grad = torch.full_like(param, 0.5)
+ optimizer.step()
+ scheduler.step()
+ assert torch.equal(param.detach(), torch.ones(4))
+ state = optimizer.state[param]
+ assert int(state["step"]) == 3 and state["exp_avg"].abs().sum() > 0
diff --git a/flux-umi/tests/training/test_trainer.py b/flux-umi/tests/training/test_trainer.py
new file mode 100644
index 0000000000000000000000000000000000000000..305e94544523a2e07e0e966abaf24d3372e26aa4
--- /dev/null
+++ b/flux-umi/tests/training/test_trainer.py
@@ -0,0 +1,396 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Trainer smoke and resume tests on the synthetic compact dataset with the tiny policy."""
+
+import json
+import os
+
+import pytest
+import torch
+import torch.distributed as dist
+import torch.multiprocessing as mp
+from conftest import TINY_DIT, FakeVideoVAE
+from synthetic_droid import FRAME_HW, build_compact_dataset
+
+from flux_action.data.droid.index import ROWS_FILENAME, build_manifest, build_rows, write_manifest
+from flux_action.models.text_encoder import MockTextEncoder
+from flux_action.policy import FluxActionPolicy
+from flux_action.training.checkpoint import export_policy, latest_checkpoint
+from flux_action.training.trainer import TrainConfig, Trainer
+
+EPISODES = [
+ {"n_frames": 40, "caption": "pick up the cup | grab the cup", "keep": [[0, 40]]},
+ {"n_frames": 38, "caption": "close the drawer", "keep": [[2, 38]]},
+ {"n_frames": 44, "caption": "open the box", "keep": [[0, 44]]},
+ {"n_frames": 39, "caption": "push the plate", "keep": [[0, 39]]},
+]
+TINY_POLICY = dict(
+ camera_layout="single",
+ camera_keys=["images.wrist"],
+ canvas_hw=[64, 96],
+ action_dim=8,
+ dit_config=TINY_DIT,
+ augment=True,
+)
+
+
+def tiny_policy(config):
+ return FluxActionPolicy(config, video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32))
+
+
+@pytest.fixture(scope="module")
+def indexed(tmp_path_factory):
+ root = tmp_path_factory.mktemp("trainer")
+ filter_path = build_compact_dataset(root / "source", EPISODES)
+ manifest = build_manifest(root / "source", filter_path)
+ (root / "index").mkdir()
+ build_rows(root / "source", manifest, root / "index" / ROWS_FILENAME)
+ write_manifest(manifest, root / "index" / "manifest.json")
+ return root
+
+
+def make_config(root, output, **overrides):
+ values = dict(
+ source_root=str(root / "source"),
+ index_dir=str(root / "index"),
+ output_dir=str(output),
+ policy=TINY_POLICY,
+ steps=6,
+ cooldown_start=4,
+ cooldown_steps=2,
+ windows_per_rank=2,
+ num_workers=1,
+ in_process_loader=True,
+ decoder="pyav",
+ frame_hw=FRAME_HW,
+ param_dtype="float32",
+ compute_dtype="float32",
+ activation_checkpointing=True,
+ checkpoint_every=3,
+ log_every=1,
+ ema_sigma_rels=(0.10,),
+ )
+ values.update(overrides)
+ return TrainConfig(**values)
+
+
+READ_BATCHES: list[int] = []
+
+
+class CountingDataset(torch.utils.data.IterableDataset):
+ batches_per_rank = 24
+
+ def __init__(self, *, seed, epoch, rank, num_workers, windows_per_rank, skip_batches, **kwargs):
+ self.seed, self.epoch, self.rank = seed, epoch, rank
+ self.num_workers, self.windows_per_rank = num_workers, windows_per_rank
+ self.skip_batches = skip_batches
+
+ def __iter__(self):
+ for index in range(self.skip_batches, self.batches_per_rank):
+ READ_BATCHES.append(index)
+ yield {
+ "images.wrist": torch.full((33, 3, *FRAME_HW), index % 255, dtype=torch.uint8),
+ "state": torch.zeros(8),
+ "action": torch.zeros(32, 8),
+ "task": "move",
+ "window_seed": index + 1,
+ }
+
+
+def build_counting_dataset(config, **kwargs):
+ return CountingDataset(**kwargs)
+
+
+def counting_config(output, **overrides):
+ values = dict(
+ source_root="unused",
+ index_dir="unused",
+ output_dir=str(output),
+ dataset=f"{__name__}:build_counting_dataset",
+ policy=TINY_POLICY,
+ steps=30,
+ cooldown_start=25,
+ cooldown_steps=5,
+ windows_per_rank=1,
+ grad_accumulation=2,
+ num_workers=1,
+ in_process_loader=True,
+ param_dtype="float32",
+ compute_dtype="float32",
+ activation_checkpointing=False,
+ checkpoint_every=30,
+ log_every=30,
+ ema_sigma_rels=(),
+ )
+ values.update(overrides)
+ return TrainConfig(**values)
+
+
+def losses(output):
+ lines = [json.loads(line) for line in (output / "metrics.jsonl").read_text().splitlines()]
+ return [(r["step"], r["loss"], r["lr_trunk"], r["lr_heads"]) for r in lines if "loss" in r]
+
+
+def test_single_process_run_checkpoints_and_exports(indexed, tmp_path):
+ output = tmp_path / "run"
+ result = Trainer(make_config(indexed, output), policy_factory=tiny_policy).run()
+ assert result["step"] == 6 and latest_checkpoint(output) == output / "step-6"
+ assert (output / "step-3" / "COMPLETE").exists()
+ records = losses(output)
+ assert [r[0] for r in records] == [1, 2, 3, 4, 5, 6] and all(
+ torch.isfinite(torch.tensor(r[1])) for r in records
+ )
+ # update g consumes factor(g): trunk frozen through g=3, the cooldown overlay from g=4 (1.0, then 0.5)
+ assert records[3][2] == 0.0 and records[3][3] == pytest.approx(9.6e-4 * 4 / 1001)
+ assert records[4][2] == pytest.approx(1.92e-4) and records[4][3] == pytest.approx(9.6e-4)
+ assert records[5][2] == pytest.approx(0.96e-4) and records[5][3] == pytest.approx(4.8e-4)
+ state = json.loads((output / "step-6" / "state.json").read_text())
+ assert state["data"]["position"]["batches_consumed"] in (0, 1, 2) and state["seed_history"] == [42]
+ export = export_policy(output / "step-6", tmp_path / "export", profile="ema_0p10")
+ assert export["profile"] == "ema_0p10"
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "export", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert restored.config.action_dim == 8 and restored.config.torch_dtype == "float32"
+
+
+def test_runtime_step_limit_and_cpu_timing_keep_recipe(tmp_path):
+ READ_BATCHES.clear()
+ output = tmp_path / "timed-stop"
+ config = counting_config(output)
+ result = Trainer(config, policy_factory=tiny_policy, stop_after_steps=2, timing_breakdown=True).run()
+ assert result["step"] == 2 and config.steps == 30
+ assert (output / "step-2" / "COMPLETE").exists()
+ state = json.loads((output / "step-2" / "state.json").read_text())
+ assert state["extra"]["train_config"]["steps"] == 30
+ records = [json.loads(line) for line in (output / "metrics.jsonl").read_text().splitlines()]
+ steps = [record for record in records if "loss" in record]
+ assert [record["step"] for record in steps] == [1, 2]
+ for record in steps:
+ timing = record["timing_breakdown_s"]
+ assert timing["scope"] == "rank_max"
+ assert timing["dit_forward"] > 0
+ assert timing["data_wait"] >= 0 and timing["step_time"] >= 0
+ assert steps[0]["timing_breakdown_s"]["prepare_total"] > 0
+ assert steps[0]["timing_breakdown_s"]["prepare_total_host"] > 0
+ assert any(record.get("event") == "build_timing" for record in records)
+ assert any(record.get("event") == "timing_info" for record in records)
+ assert next(record for record in records if record.get("event") == "checkpoint")["step"] == 2
+
+
+def test_runtime_step_limit_does_not_read_next_batch(tmp_path):
+ READ_BATCHES.clear()
+ output = tmp_path / "no-extra-read"
+ config = counting_config(output)
+ result = Trainer(config, policy_factory=tiny_policy, stop_after_steps=10).run()
+ assert result["step"] == 10 and READ_BATCHES == list(range(20))
+ assert (output / "step-10" / "COMPLETE").exists()
+ state = json.loads((output / "step-10" / "state.json").read_text())
+ assert state["data"]["position"]["batches_consumed"] == 20
+ assert state["extra"]["train_config"]["steps"] == 30
+
+
+@pytest.mark.parametrize("prefetch", [False, True])
+def test_exact_resume_matches_uninterrupted(indexed, tmp_path, prefetch):
+ """Resume from a *periodic* checkpoint (step 3 of a 6-step run that keeps going) must reproduce the uninterrupted
+ losses bitwise. With ``prefetch_randomness`` the next micro-batch's timesteps/noise are drawn before the checkpoint
+ is written; the checkpoint therefore stores the generator states from before that prepare (review finding 3)."""
+ policy = {**TINY_POLICY, "prefetch_randomness": prefetch}
+ full = Trainer(
+ make_config(indexed, tmp_path / "full", checkpoint_every=100, policy=policy), policy_factory=tiny_policy
+ ).run()
+ assert full["step"] == 6
+ part = make_config(indexed, tmp_path / "part", steps=3, checkpoint_every=3, reseed_on_resume=False, policy=policy)
+ Trainer(part, policy_factory=tiny_policy).run()
+ rest = make_config(indexed, tmp_path / "part", steps=6, checkpoint_every=3, reseed_on_resume=False, policy=policy)
+ Trainer(rest, policy_factory=tiny_policy).run()
+ assert losses(tmp_path / "part") == losses(tmp_path / "full")
+ state = json.loads((tmp_path / "part" / "step-6" / "state.json").read_text())
+ assert state["extra"]["resumes"][0]["mode"] == "exact" and state["seed_history"] == [42]
+ # the same from a checkpoint written while the run continued (the next batch was already prepared)
+ cont = make_config(indexed, tmp_path / "cont", steps=6, checkpoint_every=3, reseed_on_resume=False, policy=policy)
+ Trainer(cont, policy_factory=tiny_policy, stop_after_steps=4).run() # writes step-3, trains step 4, stops
+ resumed = make_config(indexed, tmp_path / "cont2", steps=6, checkpoint_every=3, reseed_on_resume=False, policy=policy)
+ import shutil
+ shutil.copytree(tmp_path / "cont" / "step-3", tmp_path / "cont2" / "step-3")
+ Trainer(resumed, policy_factory=tiny_policy).run()
+ assert losses(tmp_path / "cont2") == losses(tmp_path / "full")[3:]
+
+
+def test_reseeded_resume_records_new_seed(indexed, tmp_path):
+ Trainer(
+ make_config(indexed, tmp_path / "r", steps=3, checkpoint_every=3), policy_factory=tiny_policy
+ ).run()
+ Trainer(
+ make_config(indexed, tmp_path / "r", steps=5, checkpoint_every=5), policy_factory=tiny_policy
+ ).run()
+ state = json.loads((tmp_path / "r" / "step-5" / "state.json").read_text())
+ assert state["extra"]["resumes"][0]["mode"] == "reseeded"
+ assert len(state["seed_history"]) == 2 and state["seed_history"][1] != 42
+
+
+def test_config_overrides_and_validation(tmp_path):
+ path = tmp_path / "train.json"
+ path.write_text(
+ json.dumps(
+ {"source_root": "s", "index_dir": "i", "output_dir": "o", "steps": 10, "cooldown_start": None}
+ )
+ )
+ cfg = TrainConfig.from_file(
+ path, ["steps=20", "policy.attn_mode=flash", "frame_hw=[36, 64]", "decoder=pyav"]
+ )
+ assert cfg.steps == 20 and cfg.policy == {"attn_mode": "flash"} and cfg.frame_hw == (36, 64)
+ assert cfg.global_batch(64) == 64 * 32
+ with pytest.raises(ValueError, match="cooldown_start"):
+ TrainConfig(source_root="s", index_dir="i", output_dir="o", steps=40000)
+ with pytest.raises(ValueError, match="key=value"):
+ TrainConfig.from_file(path, ["steps"])
+
+
+def _sharded_worker(rank, world_size, init_file, root, output, steps, reseed):
+ os.environ.update(RANK=str(rank), WORLD_SIZE=str(world_size), LOCAL_RANK=str(rank))
+ dist.init_process_group("gloo", init_method=f"file://{init_file}", rank=rank, world_size=world_size)
+ try:
+ from pathlib import Path
+
+ config = make_config(
+ Path(root),
+ Path(output),
+ steps=steps,
+ windows_per_rank=1,
+ checkpoint_every=2,
+ reseed_on_resume=reseed,
+ )
+ Trainer(config, policy_factory=tiny_policy).run()
+ finally:
+ dist.destroy_process_group()
+
+
+def test_two_rank_fsdp_run_resumes_exactly_and_exports(indexed, tmp_path):
+ output = tmp_path / "fsdp"
+ mp.spawn(
+ _sharded_worker,
+ args=(2, str(tmp_path / "pg1"), str(indexed), str(output), 2, False),
+ nprocs=2,
+ join=True,
+ )
+ assert latest_checkpoint(output) == output / "step-2"
+ first = losses(output)
+ mp.spawn(
+ _sharded_worker,
+ args=(2, str(tmp_path / "pg2"), str(indexed), str(output), 4, False),
+ nprocs=2,
+ join=True,
+ )
+ resumed = losses(output)
+ assert [r[0] for r in resumed] == [1, 2, 3, 4] and resumed[:2] == first
+ reference = tmp_path / "fsdp_full"
+ mp.spawn(
+ _sharded_worker,
+ args=(2, str(tmp_path / "pg3"), str(indexed), str(reference), 4, False),
+ nprocs=2,
+ join=True,
+ )
+ assert losses(reference) == resumed
+ export = export_policy(output / "step-4", tmp_path / "fsdp_export", profile="model")
+ assert export["step"] == 4
+ restored = FluxActionPolicy.from_pretrained(
+ tmp_path / "fsdp_export", video_vae=FakeVideoVAE(), text_encoder=MockTextEncoder(32)
+ )
+ assert sum(p.numel() for p in restored.parameters()) > 0
+
+
+def test_resume_rejects_a_changed_global_batch(indexed, tmp_path):
+ output = tmp_path / "run"
+ Trainer(make_config(indexed, output, steps=3), policy_factory=tiny_policy).run()
+ with pytest.raises(ValueError, match="windows per update"):
+ Trainer(make_config(indexed, output, steps=6, windows_per_rank=1), policy_factory=tiny_policy).run()
+ # checkpoints written before the field existed are checked from their saved configuration
+ state_path = output / "step-3" / "state.json"
+ state = json.loads(state_path.read_text())
+ del state["extra"]["global_batch"]
+ state_path.write_text(json.dumps(state))
+ with pytest.raises(ValueError, match="windows per update"):
+ Trainer(make_config(indexed, output, steps=6, windows_per_rank=1), policy_factory=tiny_policy).run()
+ Trainer(
+ make_config(indexed, output, steps=6, windows_per_rank=1, allow_global_batch_change=True),
+ policy_factory=tiny_policy,
+ ).run()
+
+
+def test_checkpoint_retention_keeps_recent_and_milestones(indexed, tmp_path):
+ output = tmp_path / "keep"
+ config = make_config(indexed, output, checkpoint_every=1, keep_checkpoints=2, keep_every=3)
+ Trainer(config, policy_factory=tiny_policy).run()
+ kept = sorted(int(p.name.removeprefix("step-")) for p in output.glob("step-*"))
+ assert kept == [3, 5, 6]
+ events = [json.loads(line) for line in (output / "metrics.jsonl").read_text().splitlines()]
+ assert [e["removed_steps"] for e in events if e.get("event") == "prune"] == [[1], [2], [4]]
+ with pytest.raises(ValueError, match="keep_checkpoints"):
+ make_config(indexed, output, keep_checkpoints=0)
+
+
+def test_non_finite_update_aborts_before_any_state_changes(indexed, tmp_path, monkeypatch):
+ from flux_action.policy import FluxActionPolicy
+
+ calls = {"n": 0}
+ original = FluxActionPolicy.forward
+
+ def poisoned(self, batch, **kwargs):
+ loss, info = original(self, batch, **kwargs)
+ calls["n"] += 1
+ return (loss * float("nan") if calls["n"] == 2 else loss), info
+
+ monkeypatch.setattr(FluxActionPolicy, "forward", poisoned)
+ output = tmp_path / "nan"
+ with pytest.raises(RuntimeError, match="non-finite update at step 2"):
+ Trainer(make_config(indexed, output, checkpoint_every=2), policy_factory=tiny_policy).run()
+ steps = losses(output)
+ assert [s for s, *_ in steps] == [1] and latest_checkpoint(output) is None
+ first = next(
+ r for r in map(json.loads, (output / "metrics.jsonl").read_text().splitlines()) if "step" in r
+ )
+ assert first["step"] == 1 and first["grad_norm"] > 0 and first["data_wait"] >= 0
+
+
+def test_resume_rejects_a_different_run_seed(indexed, tmp_path):
+ output = tmp_path / "seed"
+ Trainer(make_config(indexed, output, steps=3, checkpoint_every=3), policy_factory=tiny_policy).run()
+ with pytest.raises(ValueError, match="run seed 42"):
+ Trainer(make_config(indexed, output, steps=6, seed=43), policy_factory=tiny_policy).run()
+ result = Trainer(
+ make_config(indexed, output, steps=6, seed=43, allow_seed_change=True), policy_factory=tiny_policy
+ ).run()
+ assert result["step"] == 6
+
+
+def test_resume_preserves_explicit_full_stream_architecture(indexed, tmp_path):
+ from flux_action.config import CONTENT_STREAMS
+
+ output = tmp_path / "full_streams"
+ full = {**TINY_POLICY, "content_streams": CONTENT_STREAMS}
+ Trainer(
+ make_config(indexed, output, policy=full, steps=3, reseed_on_resume=False), policy_factory=tiny_policy
+ ).run()
+ # The new default is lean, but an existing checkpoint owns its architecture.
+ resumed = Trainer(
+ make_config(indexed, output, reseed_on_resume=False), policy_factory=tiny_policy
+ ).build()
+ assert resumed.policy.config.content_streams == CONTENT_STREAMS
+ assert resumed.step == 3
+ with pytest.raises(ValueError, match="content_streams"):
+ Trainer(
+ make_config(indexed, output, policy={**TINY_POLICY, "content_streams": ("video", "video_cond")}),
+ policy_factory=tiny_policy,
+ ).build()
diff --git a/flux-umi/tests/training/test_vae_fused_gemm.py b/flux-umi/tests/training/test_vae_fused_gemm.py
new file mode 100644
index 0000000000000000000000000000000000000000..35690c41c4ede37977c66b3fa4464aee8e5d9b6c
--- /dev/null
+++ b/flux-umi/tests/training/test_vae_fused_gemm.py
@@ -0,0 +1,348 @@
+"""GPU tests for src/flux_action/models/vae_fused_gemm.py (fused fc1 + GLU GEMM of the frozen VAE; bitwise vs the eager GLU_MLP)."""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import vae_fused_gemm as G # noqa: E402
+SHAPES = G.STAGE_SHAPES
+
+
+def _data(M, C, seed=0):
+ g = torch.Generator(device="cuda").manual_seed(seed)
+ H = G.glu_hidden(C)
+ a = (torch.randn(M, C, generator=g, device="cuda") * 1.5).bfloat16()
+ w1 = (torch.randn(2 * H, C, generator=g, device="cuda") / C ** 0.5).bfloat16()
+ return a, w1, H
+
+
+def test_silu_division_exhaustive():
+ r = G.check_silu_division_exhaustive()
+ assert r["n_mismatch"] == 0 and r["nan_inputs_both_nan"], r
+
+
+@pytest.mark.parametrize("M,C", SHAPES)
+def test_fc1_glu_bit_exact(M, C):
+ from flux_action.models.vae_fused_pointwise import glu_bf16
+ a, w1, H = _data(M, C)
+ ref = glu_bf16(F.linear(a, w1))
+ out = G.fc1_glu(a, w1)
+ assert out.shape == (M, H)
+ assert G.compare(out, ref)["bitwise"] == 1.0
+ assert G.compare(G.glu_bf16_fast(F.linear(a, w1)), ref)["bitwise"] == 1.0
+
+
+@pytest.mark.parametrize("M,C", [SHAPES[0], SHAPES[-1]])
+def test_fc1_glu_extreme_gates(M, C):
+ from flux_action.models.vae_fused_pointwise import glu_bf16
+ a, w1, H = _data(M, C, seed=3)
+ big = (a.float() * 40).bfloat16() # gates far outside +-88: expf overflow / d = inf paths
+ assert G.compare(G.fc1_glu(big, w1), glu_bf16(F.linear(big, w1)))["bitwise"] == 1.0
+
+
+@pytest.mark.parametrize("M,C", [SHAPES[0], SHAPES[2], SHAPES[-1]])
+def test_plain_linear_matches_cublas(M, C):
+ a, _, _ = _data(M, C)
+ wq = (torch.randn(3 * C, C, device="cuda") / C ** 0.5).bfloat16()
+ bq = (torch.randn(3 * C, device="cuda") * 0.1).bfloat16()
+ assert G.compare(G.linear(a, wq, bq), F.linear(a, wq, bq))["bitwise"] == 1.0
+ assert G.compare(G.linear(a, wq), F.linear(a, wq))["bitwise"] == 1.0
+
+
+@pytest.mark.parametrize("M,C", [SHAPES[1], SHAPES[-1]])
+def test_fc2_residual(M, C):
+ a, _, H = _data(M, C)
+ g = torch.randn(M, H, device="cuda").bfloat16()
+ w2 = (torch.randn(C, H, device="cuda") / H ** 0.5).bfloat16()
+ assert G.compare(G.linear_residual(g, w2, a), a + F.linear(g, w2))["bitwise"] == 1.0
+
+
+@pytest.mark.parametrize("M,C", SHAPES)
+def test_ln_stats_prologue(M, C):
+ from flux_action.models.vae_ln_exact import layer_norm_bf16, residual_layer_norm_bf16
+ ln = torch.nn.LayerNorm(C).cuda().bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ x = (torch.randn(M, C, device="cuda") * 2 + 0.5).bfloat16()
+ d = (torch.randn(M, C, device="cuda") * 0.5).bfloat16()
+ h = layer_norm_bf16(x, ln.weight, ln.bias, ln.eps)
+ mean, rstd, _ = G.ln_stats(x, ln.eps)
+ assert G.compare(G.ln_apply(x, mean, rstd, ln.weight, ln.bias), h)["bitwise"] == 1.0
+ wq = (torch.randn(3 * C, C, device="cuda") / C ** 0.5).bfloat16()
+ assert G.compare(G.ln_linear(x, mean, rstd, ln.weight, ln.bias, wq), F.linear(h, wq))["bitwise"] == 1.0
+ xo_ref, h2 = residual_layer_norm_bf16(x, d, ln.weight, ln.bias, ln.eps)
+ mean, rstd, xo = G.ln_stats(x, ln.eps, residual2=d)
+ assert torch.equal(xo, xo_ref)
+ assert G.compare(G.ln_apply(xo, mean, rstd, ln.weight, ln.bias), h2)["bitwise"] == 1.0
+
+
+def test_cuda_graph_capture_replay():
+ from flux_action.models.vae_fused_pointwise import glu_bf16
+ M, C = SHAPES[1]
+ a, w1, H = _data(M, C, seed=7)
+ prepped = G.prep_glu_weight(w1, G.DEFAULT_CFG[1] // 2)
+ static_a = a.clone()
+ s = torch.cuda.Stream()
+ s.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s):
+ for _ in range(3):
+ out = G.fc1_glu(static_a, w1, prepped=prepped)
+ torch.cuda.current_stream().wait_stream(s)
+ torch.cuda.synchronize()
+ graph = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(graph, stream=s):
+ static_out = G.fc1_glu(static_a, w1, prepped=prepped)
+ graph.replay()
+ torch.cuda.synchronize()
+ r1 = static_out.clone()
+ graph.replay()
+ torch.cuda.synchronize()
+ assert torch.equal(r1, static_out)
+ assert torch.equal(r1, glu_bf16(F.linear(a, w1)))
+ a2 = (torch.randn(M, C, device="cuda") * 1.5).bfloat16()
+ static_a.copy_(a2)
+ graph.replay()
+ torch.cuda.synchronize()
+ assert torch.equal(static_out, glu_bf16(F.linear(a2, w1)))
+
+
+def test_install_random_vae_bit_exact():
+ """Random-init VAE, production fused stack + install(): latents bitwise equal, uninstall restores."""
+ import contextlib
+ from flux_action.models.vae_fused_pointwise import install_training_fused, training_fused_context
+ from flux_action.models.video_vae import ViTNormInference, VideoVAE
+ torch.manual_seed(0)
+ model = ViTNormInference().cuda().bfloat16().eval()
+ for p in model.parameters():
+ p.requires_grad_(False)
+ vae = VideoVAE(model)
+ state, _ = install_training_fused(vae)
+
+ def encode(video):
+ with contextlib.ExitStack() as st:
+ st.enter_context(training_fused_context(state))
+ st.enter_context(torch.autocast("cuda", dtype=torch.bfloat16))
+ st.enter_context(torch.inference_mode())
+ return vae.encode(video)
+
+ video = (torch.rand(1, 3, 33, 256, 256, device="cuda") * 2 - 1).bfloat16()
+ ref = encode(video).clone()
+ inst = G.install(vae, state, glu_dims=(256, 512, 1024, 2048))
+ try:
+ out = encode(video).clone()
+ assert sum(inst.calls.values()) > 0
+ finally:
+ G.uninstall(inst)
+ assert torch.equal(out, ref)
+ assert torch.equal(encode(video), ref)
+
+
+# ----------------------------------------------------------------------------------------------- review fixes
+def _glu_ref_rows(gu_rows):
+ gate, up = gu_rows.chunk(2, dim=-1)
+ return F.silu(gate) * up
+
+
+@pytest.mark.parametrize("fn_name", ["glu_bf16", "glu_bf16_fast"])
+def test_glu_store_mask_above_2_31_elements(fn_name):
+ """Review finding #1: ``mask = idx < M * H`` multiplied the runtime i32 ``M`` by the constexpr ``H`` in i32
+ before the i64 extension, so for M*H >= 2**31 the mask wrapped negative and the torch.empty output was returned
+ untouched. M=3050403, H=704 (M*H = 2**31 + 64) must match eager; ~22 GB of device memory."""
+ from flux_action.models import vae_fused_pointwise as vfp
+ if torch.cuda.get_device_properties(0).total_memory < 30 * 2 ** 30:
+ pytest.skip("needs >= 30 GB of device memory")
+ fn = vfp.glu_bf16 if fn_name == "glu_bf16" else G.glu_bf16_fast
+ M, H = 2 ** 31 // 704 + 1, 704
+ assert M * H >= 2 ** 31
+ g = torch.Generator(device="cuda").manual_seed(1)
+ gu = torch.empty(M, 2 * H, device="cuda", dtype=torch.bfloat16)
+ step = 1 << 19
+ for i in range(0, M, step):
+ gu[i:i + step].normal_(generator=g).mul_(3)
+ out = fn(gu)
+ assert out.shape == (M, H)
+ try:
+ for i in range(0, M, step): # chunked eager reference (bounded peak memory)
+ assert torch.equal(out[i:i + step], _glu_ref_rows(gu[i:i + step])), f"rows {i}.. differ"
+ finally:
+ del out, gu
+ torch.cuda.empty_cache()
+
+
+@pytest.mark.parametrize("fn_name", ["glu_bf16", "glu_bf16_fast"])
+@pytest.mark.parametrize("M", [1, 2, 3])
+def test_glu_tiny_row_counts_match_eager(fn_name, M):
+ """M == 1 is specialized by Triton as a Python int (so ``M.to(tl.int64)`` would not compile): the store mask must be
+ formed on the i64 row index. Tiny M must equal eager for both GLU entry points."""
+ from flux_action.models import vae_fused_pointwise as vfp
+ fn = vfp.glu_bf16 if fn_name == "glu_bf16" else G.glu_bf16_fast
+ for H in (16, 32, 704):
+ gu = (torch.randn(M, 2 * H, device="cuda", generator=torch.Generator(device="cuda").manual_seed(M * 7 + H)) * 3).to(torch.bfloat16)
+ assert torch.equal(fn(gu), _glu_ref_rows(gu)), (fn_name, M, H)
+
+
+def _single_mlp_install(dim):
+ """A minimal 'VAE' (``.model.encoder`` holding one GLU_MLP) for vae_fused_gemm.install."""
+ from types import SimpleNamespace
+ from flux_action.models import video_vae as vv
+ mlp = vv.GLU_MLP(dim)
+ mlp.to(device="cuda", dtype=torch.bfloat16)
+ for p in mlp.parameters():
+ p.requires_grad_(False)
+ enc = torch.nn.ModuleDict({"blk": mlp})
+ return mlp, SimpleNamespace(model=SimpleNamespace(encoder=enc))
+
+
+def test_prepped_fc1_weight_not_served_to_recycled_address():
+ """Review finding #2: the pair-interleaved fc1 weight was cached in a module-global dict keyed on
+ ``weight.data_ptr()`` with no reference to the weight and never cleared by ``uninstall``; a new same-shape weight
+ landing on the recycled address silently used the previous model's interleaved copy. Install A -> encode ->
+ uninstall -> free A; a fresh weight at A's address must give the eager GLU of its own values."""
+ from flux_action.models.vae_fused_pointwise import FusedState, training_fused_context, glu_bf16
+ dim = 1024
+ state = FusedState()
+ x = (torch.randn(64, dim, device="cuda") * 1.5).bfloat16()
+
+ mlp_a, fake_a = _single_mlp_install(dim)
+ inst_a = G.install(fake_a, state, glu_dims=(dim,), require_kernel=True)
+ with torch.inference_mode(), training_fused_context(state):
+ out_a = mlp_a(x)
+ assert torch.equal(out_a, mlp_a.down_proj(glu_bf16(mlp_a.gate_up_proj(x))))
+ G.uninstall(inst_a)
+ shape = tuple(mlp_a.gate_up_proj.weight.shape)
+ ptr_a = mlp_a.gate_up_proj.weight.data_ptr()
+ del mlp_a, fake_a, inst_a, out_a
+
+ reused = None
+ for _ in range(8): # the caching allocator hands back A's block (same size)
+ w = torch.empty(shape, device="cuda", dtype=torch.bfloat16)
+ if w.data_ptr() == ptr_a:
+ reused = w
+ break
+ del w
+ if reused is None:
+ pytest.skip("allocator did not recycle the freed weight address")
+ mlp_b, fake_b = _single_mlp_install(dim)
+ with torch.no_grad():
+ reused.normal_(0.0, dim ** -0.5)
+ mlp_b.gate_up_proj.weight = torch.nn.Parameter(reused, requires_grad=False)
+ assert mlp_b.gate_up_proj.weight.data_ptr() == ptr_a
+ inst_b = G.install(fake_b, state, glu_dims=(dim,), require_kernel=True)
+ try:
+ with torch.inference_mode(), training_fused_context(state):
+ out_b = mlp_b(x)
+ assert torch.equal(out_b, mlp_b.down_proj(glu_bf16(mlp_b.gate_up_proj(x))))
+ finally:
+ G.uninstall(inst_b)
+ assert not inst_b.prepped
+
+
+def _random_vae(seed):
+ from flux_action.models.video_vae import ViTNormInference, VideoVAE
+ torch.manual_seed(seed)
+ model = ViTNormInference().cuda().bfloat16().eval()
+ for p in model.parameters():
+ p.requires_grad_(False)
+ return VideoVAE(model)
+
+
+def test_two_sequential_vaes_fc1_glu_bit_exact():
+ """Review finding #2 at the model level: VAE A (fused fc1+GLU installed, encoded, uninstalled), then VAE B whose
+ fc1 weights are moved one by one onto the addresses A's fc1 weights are freed from (the caching allocator returns
+ the exact-size block just released) must reproduce B's own latents with the fused fc1+GLU installed."""
+ import contextlib
+ from flux_action.models.video_vae import GLU_MLP
+ from flux_action.models.vae_fused_pointwise import install_training_fused, training_fused_context
+
+ def encode(vae, state, video):
+ with contextlib.ExitStack() as st:
+ st.enter_context(training_fused_context(state))
+ st.enter_context(torch.autocast("cuda", dtype=torch.bfloat16))
+ st.enter_context(torch.inference_mode())
+ return vae.encode(video)
+
+ def fc1_mlps(vae):
+ return [m for _, m in vae.module.model.encoder.named_modules() if type(m) is GLU_MLP]
+
+ video = (torch.rand(1, 3, 33, 256, 256, device="cuda") * 2 - 1).bfloat16()
+ vae_a = _random_vae(11)
+ vae_b = _random_vae(12)
+ state_a, _ = install_training_fused(vae_a)
+ inst_a = G.install(vae_a, state_a, glu_dims=(256, 512, 1024, 2048), require_kernel=True)
+ encode(vae_a, state_a, video)
+ G.uninstall(inst_a)
+ reused = 0
+ for mlp_a, mlp_b in zip(fc1_mlps(vae_a), fc1_mlps(vae_b)):
+ shape, ptr = tuple(mlp_a.gate_up_proj.weight.shape), mlp_a.gate_up_proj.weight.data_ptr()
+ mlp_a.gate_up_proj.weight = torch.nn.Parameter(torch.empty(0, device="cuda", dtype=torch.bfloat16),
+ requires_grad=False) # frees A's fc1 weight
+ w = torch.empty(shape, device="cuda", dtype=torch.bfloat16) # best fit: the block just freed
+ w.copy_(mlp_b.gate_up_proj.weight)
+ mlp_b.gate_up_proj.weight = torch.nn.Parameter(w, requires_grad=False)
+ reused += int(w.data_ptr() == ptr)
+ if reused == 0:
+ pytest.skip("allocator did not recycle any of the freed fc1 weight addresses")
+ state_b, _ = install_training_fused(vae_b)
+ ref = encode(vae_b, state_b, video).clone()
+ inst_b = G.install(vae_b, state_b, glu_dims=(256, 512, 1024, 2048), require_kernel=True)
+ try:
+ out = encode(vae_b, state_b, video)
+ finally:
+ G.uninstall(inst_b)
+ assert torch.equal(out, ref), f"{reused} fc1 weights on recycled addresses"
+
+
+def _install_v6_vae_stack(vae):
+ """The frozen-VAE fused family of the v6 config, all with require_kernel=True (policy.py order)."""
+ from flux_action.models import vae_ln_exact, vae_merge_glue, vae_qk_fused
+ from flux_action.models.vae_fused_pointwise import install_training_fused
+ state, _ = install_training_fused(vae)
+ un_ln = vae_ln_exact.install()
+ inst_qk = vae_qk_fused.install(vae, state, qk_fused=True, mlp_residual=True, require_kernel=True)
+ inst_mg = vae_merge_glue.install(vae, state, require_kernel=True)
+ inst_gm = G.install(vae, state, glu_dims=(256, 512, 1024), require_kernel=True)
+
+ def uninstall():
+ G.uninstall(inst_gm)
+ vae_merge_glue.uninstall(inst_mg)
+ vae_qk_fused.uninstall(inst_qk)
+ un_ln()
+ return state, inst_gm, uninstall
+
+
+def test_fc1_glu_falls_back_to_eager_outside_training_context():
+ """Review finding #7: with ``require_kernel=True`` (policy.py) the patched GLU_MLP raised 'fused fc1+GLU contract
+ not satisfied' on every encode outside ``training_fused_context`` (policy.eval(), select_action, from_pretrained
+ of a v6 export). It must run the stock GLU_MLP.forward there, like vae_qk_fused / vae_merge_glue, and keep
+ raising only when the context is active and the contract fails."""
+ from flux_action.models.vae_fused_pointwise import training_fused_context
+ vae = _random_vae(21)
+ video = (torch.rand(1, 3, 33, 256, 256, device="cuda") * 2 - 1).bfloat16()
+ frame = video[:, :, 0]
+ with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
+ ref_frame = vae.encode_frame(frame).clone()
+ ref_video = vae.encode(video).clone()
+ state, inst_gm, uninstall = _install_v6_vae_stack(vae)
+ try:
+ with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
+ assert torch.equal(vae.encode_frame(frame), ref_frame) # outside the context: eager fallback
+ assert torch.equal(vae.encode(video), ref_video)
+ assert sum(inst_gm.calls.values()) == 0
+ with training_fused_context(state):
+ assert torch.equal(vae.encode_frame(frame), ref_frame) # inside: fused, bit-exact
+ assert sum(inst_gm.calls.values()) > 0
+ mlp = next(m for n, m in vae.module.model.encoder.named_modules() if type(m).__name__ == "GLU_MLP")
+ x32 = torch.randn(4, mlp.gate_up_proj.in_features, device="cuda")
+ with torch.inference_mode(), training_fused_context(state), pytest.raises(RuntimeError, match="contract"):
+ mlp(x32) # context active, fp32 input: fail closed
+ finally:
+ uninstall()
diff --git a/flux-umi/tests/training/test_vae_ln_exact.py b/flux-umi/tests/training/test_vae_ln_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..72cb9306c88d34e211920d50bf9983c6a3dabe31
--- /dev/null
+++ b/flux-umi/tests/training/test_vae_ln_exact.py
@@ -0,0 +1,77 @@
+"""GPU tests: the fast bit-exact LayerNorm kernels of ``flux_action.models.vae_ln_exact`` equal the eager autocast
+LayerNorm for every N in ``TILE`` (plain, fused residual, fused broadcast conv bias; even and masked row counts), and
+``install()`` probes that exactness before swapping the kernels in (review finding #11)."""
+import pytest
+import torch
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import vae_fused_pointwise as vfp
+from flux_action.models import vae_ln_exact as L
+
+
+def _eager(x, ln):
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ return ln(x).to(torch.bfloat16)
+
+
+@pytest.mark.parametrize("N", sorted(L.TILE))
+@pytest.mark.parametrize("M", [256, 1001, 3])
+def test_exact_kernels_match_eager_every_tile_n(N, M):
+ """Finding #11 (test gap): vae_ln_exact vs eager nn.LayerNorm for every N in TILE (incl. the N=256 ksplit
+ kernel), the residual and broadcast-bias variants, even (M=256) and masked (M=1001, 3) row tiles."""
+ torch.manual_seed(N * 7 + M)
+ ln = torch.nn.LayerNorm(N, eps=1e-5).cuda().bfloat16()
+ with torch.no_grad():
+ ln.weight.normal_(1.0, 0.3)
+ ln.bias.normal_(0.0, 0.3)
+ x = (torch.randn(M, N, device="cuda") * 2 + 0.5).bfloat16()
+ d = (torch.randn(M, N, device="cuda") * 0.5).bfloat16()
+ cb = (torch.randn(N, device="cuda") * 0.1).bfloat16()
+ assert torch.equal(L.layer_norm_bf16(x, ln.weight, ln.bias, ln.eps), _eager(x, ln))
+ assert torch.equal(L.eager_layer_norm_bf16(x, ln.weight, ln.bias, ln.eps), _eager(x, ln))
+ with torch.autocast("cuda", dtype=torch.bfloat16):
+ xr = x + d
+ xrb = x.clone()
+ xrb.add_(cb)
+ xo, y = L.residual_layer_norm_bf16(x, d, ln.weight, ln.bias, ln.eps)
+ assert torch.equal(xo, xr) and torch.equal(y, _eager(xr, ln))
+ xob, yb = L.residual_layer_norm_bf16(x, cb, ln.weight, ln.bias, ln.eps)
+ assert torch.equal(xob, xrb) and torch.equal(yb, _eager(xrb, ln))
+
+
+def test_selftest_production_and_odd_shapes_bitwise():
+ res = L.selftest(verbose=False)
+ assert res["all_bit_exact"] is True, {k: v for k, v in res.items() if v is not True}
+
+
+def test_probe_exact_passes_on_pinned_build():
+ report = L.probe_exact()
+ assert set(int(k.split("/")[0]) for k in report) == set(L.TILE)
+ assert all(v == 0 for v in report.values()), report
+
+
+def test_install_probes_kernels_and_refuses_inexact_ones(monkeypatch):
+ """Review finding #11: ``install()`` swapped the kernels in without any check although their bit-exactness
+ rests on Triton layout/reduction-order details. A kernel that is off by one bf16 ulp must make install() raise
+ and leave vae_fused_pointwise untouched; the genuine kernels install and uninstall cleanly."""
+ prev = (vfp.layer_norm_bf16, vfp.residual_layer_norm_bf16)
+ good = L.layer_norm_bf16
+
+ def one_ulp_off(x, w, b, eps=1e-5):
+ y = good(x, w, b, eps)
+ return (y.view(torch.int16) + 1).view(torch.bfloat16)
+
+ monkeypatch.setattr(L, "layer_norm_bf16", one_ulp_off)
+ with pytest.raises(RuntimeError, match="probe"):
+ L.install()
+ assert (vfp.layer_norm_bf16, vfp.residual_layer_norm_bf16) == prev
+ monkeypatch.setattr(L, "layer_norm_bf16", good)
+ un = L.install()
+ try:
+ assert vfp.layer_norm_bf16 is good and vfp.residual_layer_norm_bf16 is L.residual_layer_norm_bf16
+ finally:
+ un()
+ assert (vfp.layer_norm_bf16, vfp.residual_layer_norm_bf16) == prev
diff --git a/flux-umi/tests/training/test_vae_merge_glue.py b/flux-umi/tests/training/test_vae_merge_glue.py
new file mode 100644
index 0000000000000000000000000000000000000000..26c3db562ded35f90450c48857228778b317522c
--- /dev/null
+++ b/flux-umi/tests/training/test_vae_merge_glue.py
@@ -0,0 +1,15 @@
+"""GPU test: the gather-LayerNorm merge kernels (vae_merge_glue) are bitwise identical to the eager PatchMerging /
+TemporalMerging chains (with the deferred MLP residual) at the production merge shapes and odd shapes."""
+import pytest
+import torch
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import vae_merge_glue
+
+
+def test_merge_glue_selftest_bitwise():
+ res = vae_merge_glue.selftest(verbose=False)
+ assert res["all_bit_exact"] is True, {k: v for k, v in res.items() if v not in (True, 1.0)}
diff --git a/flux-umi/tests/training/test_vae_na3d_v2.py b/flux-umi/tests/training/test_vae_na3d_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a1b5c3cdf84f4ba93f4b3db5ea3ef7df2424189
--- /dev/null
+++ b/flux-umi/tests/training/test_vae_na3d_v2.py
@@ -0,0 +1,57 @@
+"""GPU test: the TMA NA3D kernel (vae_na3d_v2) is bit-identical to the production Triton NA3D kernel (vae_na3d_triton) at
+the five production VAE shapes and under CUDA-graph replay, and install()/install("v1") swap the module entry point."""
+import pytest
+import torch
+
+pytest.importorskip("triton")
+if not torch.cuda.is_available(): # pragma: no cover
+ pytest.skip("CUDA required", allow_module_level=True)
+
+from flux_action.models import vae_na3d_triton as v1
+from flux_action.models import vae_na3d_v2 as v2
+
+DEV = torch.device("cuda")
+SHAPES = [(33, 128, 128, 4), (33, 64, 64, 8), (33, 32, 32, 16), (33, 16, 16, 32), (17, 16, 16, 32)]
+
+
+def _qkv(T, H, W, heads, seed=0):
+ g = torch.Generator(device=DEV).manual_seed(seed)
+ qkv = torch.randn(1, T, H, W, 3, heads, 64, device=DEV, generator=g).to(torch.bfloat16)
+ q, k, v = qkv.unbind(4)
+ return q.contiguous(), k.contiguous(), v # v stays the strided QKV-unbind view, as in production
+
+
+@pytest.mark.parametrize("shape", SHAPES)
+def test_tma_kernel_bitwise_vs_v1(shape):
+ q, k, v = _qkv(*shape)
+ a = v1.na3d_triton(q, k, v, (5, 5, 5), (True, False, False), 0.125)
+ b = v2._v2_entry(q, k, v, (5, 5, 5), (True, False, False), 0.125)
+ assert a.shape == b.shape and a.dtype == b.dtype
+ assert torch.equal(a, b)
+
+
+def test_install_swaps_entry_point_and_graph_replay_is_stable():
+ q, k, v = _qkv(33, 32, 32, 16, seed=3)
+ ref = v1.na3d_triton(q, k, v, (5, 5, 5), (True, False, False), 0.125)
+ orig = v1.na3d_triton
+ try:
+ v2.install("v2")
+ assert v1.na3d_triton is not orig
+ out = v1.na3d_triton(q, k, v, (5, 5, 5), (True, False, False), 0.125)
+ assert torch.equal(out, ref)
+ s = torch.cuda.Stream()
+ with torch.cuda.stream(s):
+ v1.na3d_triton(q, k, v, (5, 5, 5), (True, False, False), 0.125)
+ torch.cuda.synchronize()
+ g = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(g, stream=s, capture_error_mode="thread_local"):
+ cap = v1.na3d_triton(q, k, v, (5, 5, 5), (True, False, False), 0.125)
+ g.replay()
+ torch.cuda.synchronize()
+ first = cap.clone()
+ g.replay()
+ torch.cuda.synchronize()
+ assert torch.equal(first, ref) and torch.equal(cap, ref)
+ finally:
+ v2.install("v1")
+ assert v1.na3d_triton is orig
diff --git a/flux-umi/tests/training/test_window_loader.py b/flux-umi/tests/training/test_window_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..561cbd33c8ec6819a1cb339dc626e7f2a8fd6cd0
--- /dev/null
+++ b/flux-umi/tests/training/test_window_loader.py
@@ -0,0 +1,197 @@
+# Copyright 2026 Black Forest Labs. All rights reserved.
+#
+# 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.
+"""Manifest, rows array and the streaming window dataset on a synthetic compact layout."""
+
+import json
+
+import numpy as np
+import pytest
+import torch
+from synthetic_droid import FRAME_HW, build_compact_dataset
+
+from flux_action.data.droid.index import (
+ ROWS_FILENAME,
+ build_manifest,
+ build_rows,
+ load_manifest,
+ open_rows,
+ write_manifest,
+)
+from flux_action.data.droid.video import decode_window
+from flux_action.training.data import DataPosition, DroidWindowDataset, build_dataloader, epoch_order
+
+pq = pytest.importorskip("pyarrow.parquet") # the data extra; skip these tests without it
+
+EPISODES = [
+ {"n_frames": 40, "caption": "pick up the cup | grab the cup", "keep": [[0, 40]]}, # 8 starts
+ {"n_frames": 38, "caption": "close the drawer", "keep": [[2, 38]]}, # starts 2..5
+ {"n_frames": 36, "caption": "no filter entry", "keep": None}, # excluded
+ {"n_frames": 20, "caption": "too short", "keep": [[0, 20]]}, # excluded
+]
+
+
+@pytest.fixture(scope="module")
+def indexed(tmp_path_factory):
+ root = tmp_path_factory.mktemp("compact")
+ filter_path = build_compact_dataset(root / "source", EPISODES)
+ manifest = build_manifest(root / "source", filter_path, revision="f" * 40)
+ out = root / "index"
+ out.mkdir()
+ rows_result = build_rows(root / "source", manifest, out / ROWS_FILENAME)
+ write_manifest(manifest, out / "manifest.json")
+ return root / "source", out, rows_result
+
+
+def test_manifest_counts_and_rows(indexed):
+ source, out, rows_result = indexed
+ manifest = load_manifest(out / "manifest.json")
+ counts = manifest["counts"]
+ assert counts["listed"] == 4 and counts["eligible"] == 2 and counts["no_valid_window"] == 2
+ assert counts["valid_starts_total"] == 8 + 4 and rows_result == {"kept": 2, "rejected": {}}
+ first, second = manifest["episodes"]
+ assert first["videos"]["left"]["first_frame"] == 0 and second["videos"]["wrist"]["first_frame"] == 40
+ assert second["from_index"] == 40 and manifest["dataset_revision"] == "f" * 40
+ assert set(manifest["files"]) == {first["data_file"], *(v["file"] for v in first["videos"].values())}
+ rows = open_rows(out / ROWS_FILENAME, manifest["total_frames"])
+ table = pq.read_table(source / first["data_file"]).to_pylist()
+ assert rows[41, :7].tolist() == pytest.approx([1 + 1 / 1000] * 7, rel=1e-6)
+ assert (
+ rows[41, 7] == 0.25
+ and rows[41, 15] == 0.75
+ and rows[41, 8] == pytest.approx(table[41]["action.joint_position"][0])
+ )
+ assert np.isnan(rows[80:]).all() # frames of excluded episodes are never read
+
+
+def test_windows_are_topology_invariant_and_exact(indexed):
+ source, out, _ = indexed
+ manifest = load_manifest(out / "manifest.json")
+ rows_path = out / ROWS_FILENAME
+ common = dict(seed=7, epoch=0, frame_hw=FRAME_HW, decoder="pyav")
+ single = DroidWindowDataset(manifest, source, rows_path, **common)
+ windows = list(single)
+ assert [w["episode_index"] for w in windows] == epoch_order(2, 7, 0)
+ split = [
+ w
+ for rank in range(2)
+ for w in DroidWindowDataset(manifest, source, rows_path, rank=rank, world_size=2, **common)
+ ]
+ key = lambda w: (w["episode_index"], w["start"], w["task"]) # noqa: E731
+ assert sorted(map(key, windows)) == sorted(map(key, split))
+ for w in windows:
+ episode = next(e for e in manifest["episodes"] if e["episode_index"] == w["episode_index"])
+ start = w["start"]
+ assert start in range(*episode["valid_ranges"][0][:1], episode["n_frames"] - 32)
+ assert w["task"] in episode["caption"].split(" | ")
+ assert w["images.wrist"].dtype == torch.uint8 and w["images.wrist"].shape == (33, 3, *FRAME_HW)
+ for camera in ("wrist", "left", "right"):
+ video = episode["videos"][camera]
+ expected = decode_window(
+ source / video["file"], video["first_frame"] + start, 33, frame_hw=FRAME_HW, decoder="pyav"
+ )
+ assert torch.equal(w[f"images.{camera}"], torch.from_numpy(expected).permute(0, 3, 1, 2))
+ assert w["state"].tolist() == pytest.approx(
+ [w["episode_index"] + start / 1000] * 7 + [0.25], rel=1e-6
+ )
+ assert w["action"].shape == (32, 8) and w["action"][0, 0] == pytest.approx(
+ 100 + w["episode_index"] + start / 1000
+ )
+ different_epoch = list(DroidWindowDataset(manifest, source, rows_path, **{**common, "epoch": 1}))
+ assert sorted(map(key, different_epoch)) != sorted(map(key, windows))
+
+
+def test_loader_batches_and_exact_resume(indexed):
+ source, out, _ = indexed
+ manifest = load_manifest(out / "manifest.json")
+ rows_path = out / ROWS_FILENAME
+ common = dict(seed=3, frame_hw=FRAME_HW, decoder="pyav", windows_per_rank=1)
+ full = list(build_dataloader(DroidWindowDataset(manifest, source, rows_path, **common), in_process=True))
+ assert (
+ len(full) == 2 and full[0]["images.left"].shape == (1, 33, 3, *FRAME_HW) and len(full[0]["task"]) == 1
+ )
+ resumed = list(
+ build_dataloader(
+ DroidWindowDataset(manifest, source, rows_path, skip_batches=1, **common), in_process=True
+ )
+ )
+ assert len(resumed) == 1 and resumed[0]["episode_index"].tolist() == full[1]["episode_index"].tolist()
+ assert torch.equal(resumed[0]["images.right"], full[1]["images.right"])
+ position = DataPosition(epoch=0, batches_consumed=1, world_size=1, num_workers=1, windows_per_rank=1)
+ assert DataPosition.from_dict(json.loads(json.dumps(position.to_dict()))) == position
+ assert position.matches(world_size=1, num_workers=1, windows_per_rank=1)
+ assert not position.matches(world_size=2, num_workers=1, windows_per_rank=1)
+ with pytest.raises(ValueError):
+ build_dataloader(
+ DroidWindowDataset(manifest, source, rows_path, num_workers=2, **common), in_process=True
+ )
+
+
+def test_two_worker_loader_and_skip(indexed):
+ source, out, _ = indexed
+ manifest = load_manifest(out / "manifest.json")
+ rows_path = out / ROWS_FILENAME
+ common = dict(seed=5, frame_hw=FRAME_HW, decoder="pyav", windows_per_rank=1, num_workers=2)
+ batches = list(
+ build_dataloader(DroidWindowDataset(manifest, source, rows_path, **common), prefetch_factor=1)
+ )
+ order = epoch_order(2, 5, 0)
+ assert [b["episode_index"].item() for b in batches] == order # worker 0 then worker 1
+ resumed = list(
+ build_dataloader(
+ DroidWindowDataset(manifest, source, rows_path, skip_batches=1, **common), prefetch_factor=1
+ )
+ )
+ assert [b["episode_index"].item() for b in resumed] == order[1:]
+
+
+def _round_robin(per_worker: list[list[int]]) -> list[int]:
+ """The DataLoader's in-order service of workers 0..n-1 until each is exhausted."""
+ out, i = [], 0
+ while any(per_worker):
+ w = i % len(per_worker)
+ if per_worker[w]:
+ out.append(per_worker[w].pop(0))
+ i += 1
+ return out
+
+
+def test_epochs_have_equal_batches_per_rank_and_resume_rotates_workers():
+ manifest = {
+ "episodes": [{"episode_index": i} for i in range(600)],
+ "fps": 15,
+ "chunk_size": 32,
+ "total_frames": 0,
+ }
+
+ def make(**kw):
+ return DroidWindowDataset(manifest, "/nowhere", "/nowhere", seed=1, **kw)
+
+ tops = dict(world_size=8, num_workers=4, windows_per_rank=4)
+ counts = [sum(len(make(rank=r, **tops).worker_positions(w)) for w in range(4)) for r in range(8)]
+ assert len(set(counts)) == 1 and counts[0] == 16 * 4 # 600 // (8*4*4) = 4 batches per worker
+ acc = make(rank=0, grad_accumulation=3, **tops)
+ assert acc.batches_per_rank == 15 and sum(len(acc.worker_positions(w)) for w in range(4)) == 60
+ with pytest.raises(ValueError):
+ make(rank=0, world_size=64, num_workers=8, windows_per_rank=4)
+ # two workers, one window per batch, seven episodes: six batches, three per worker
+ small = {**manifest, "episodes": manifest["episodes"][:7]}
+ full = DroidWindowDataset(small, "/nowhere", "/nowhere", seed=1, num_workers=2, windows_per_rank=1)
+ order = _round_robin([full.worker_positions(w) for w in range(2)])
+ assert len(order) == 6
+ for skip in range(1, 6):
+ resumed = DroidWindowDataset(
+ small, "/nowhere", "/nowhere", seed=1, num_workers=2, windows_per_rank=1, skip_batches=skip
+ )
+ served = _round_robin([resumed.worker_positions(resumed.logical_worker(p)) for p in range(2)])
+ assert served == order[skip:], skip
diff --git a/flux-umi/tools/prepare_umi_lerobot_v3.py b/flux-umi/tools/prepare_umi_lerobot_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bb36dbea890e090bd51e6f64fe0100e5dd7ef96
--- /dev/null
+++ b/flux-umi/tools/prepare_umi_lerobot_v3.py
@@ -0,0 +1,181 @@
+"""Index bimanual UMI LeRobot v3.0 episodes for ``flux_action.data.umi.all_windows:build``.
+
+Input: one or more roots, each holding one single-episode LeRobot v3.0 dataset per directory with
+``observation.state`` = float32[16], per arm ``[x, y, z, qw, qx, qy, qz, gripper]`` (left arm first),
+videos ``observation.images.left_ego`` / ``observation.images.right_ego`` at 30 fps, one mp4 per camera.
+
+Output (``--out``): per-episode ``states.npy``, ``training_manifest.json`` and ``statistics.json``
+(q01/q99 of the 20-D state/action windows). Source videos are referenced in place, never copied.
+
+Optional ``--cuts`` JSON files restrict each episode to keep ranges (e.g. with static spans removed):
+``{"episodes": {"": {"n_frames": int, "keep_ranges": [[start, end), ...]}}}``.
+
+ python tools/prepare_umi_lerobot_v3.py --roots /data/umi_v3 --out /data/umi_v3_flux [--cuts cuts.json]
+
+It prints the ``sampling_*`` values the training config needs. With ``--config-template`` and ``--world-size`` it
+also writes ``train_config.json`` with data paths, normalization and an epoch-based schedule filled in (warmup 1 epoch,
+linear cooldown over the last 20%, one checkpoint per epoch).
+"""
+
+import argparse
+import hashlib
+import json
+import math
+import os
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+import numpy as np
+import pyarrow.parquet as pq
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+from flux_action.data.umi.all_windows import SAMPLER_VERSION # noqa: E402
+from flux_action.data.umi.dataset import MANIFEST_KIND # noqa: E402
+from flux_action.data.umi.representation import REPRESENTATION, make_window # noqa: E402
+from flux_action.data.windows import valid_window_spans # noqa: E402
+
+CAMERAS = ("left_ego", "right_ego")
+CHUNK, FPS = 32, 30
+
+
+def single_file(directory):
+ files = sorted(f for f in os.listdir(directory) if f.endswith((".parquet", ".mp4")))
+ if len(files) != 1:
+ raise ValueError(f"expected exactly one file in {directory}, found {files}")
+ return os.path.join(directory, files[0])
+
+
+def read_episode(path, prompt):
+ info = json.loads(Path(path, "meta", "info.json").read_text())
+ if float(info.get("fps", 0)) != FPS:
+ raise ValueError(f"fps {info.get('fps')} != {FPS}")
+ states = np.asarray(
+ pq.read_table(single_file(os.path.join(path, "data", "chunk-000")), columns=["observation.state"])
+ ["observation.state"].to_pylist(),
+ dtype=np.float32,
+ )
+ if states.ndim != 2 or states.shape[1] != 16 or not np.isfinite(states).all():
+ raise ValueError(f"observation.state shape {states.shape} (need finite (n, 16))")
+ task = prompt
+ if task is None:
+ tasks = pq.read_table(os.path.join(path, "meta", "tasks.parquet")).to_pandas()
+ task = str(tasks.index[0]) if "task_index" in tasks.columns else str(tasks.iloc[0, 0])
+ videos = {
+ camera: single_file(os.path.join(path, "videos", f"observation.images.{camera}", "chunk-000"))
+ for camera in CAMERAS
+ }
+ return states, task, videos
+
+
+def start_ranges(n_frames, keep_ranges):
+ """A start t reads the state at t-1 and frames t..t+32; the whole window must stay inside one keep range."""
+ ranges = [[lo + 1, hi] for lo, hi in keep_ranges if hi - lo >= CHUNK + 2]
+ return [[first, first + count] for first, count in valid_window_spans(n_frames, ranges, CHUNK)]
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--roots", nargs="+", required=True)
+ ap.add_argument("--out", type=Path, required=True)
+ ap.add_argument("--cuts", type=Path, nargs="*", default=())
+ ap.add_argument("--prompt", default=None, help="override every episode's task string")
+ ap.add_argument("--stats-windows", type=int, default=200_000, help="windows sampled for q01/q99")
+ ap.add_argument("--workers", type=int, default=32)
+ ap.add_argument("--seed", type=int, default=0)
+ ap.add_argument("--config-template", type=Path, help="e.g. configs/umi/umi_posttrain_16g.json")
+ ap.add_argument("--world-size", type=int, help="number of GPUs the run will use (with --config-template)")
+ a = ap.parse_args()
+ if (a.out / "training_manifest.json").exists():
+ raise FileExistsError(a.out / "training_manifest.json")
+ cuts = {}
+ for path in a.cuts:
+ for session, cut in json.loads(path.read_text())["episodes"].items():
+ if session in cuts:
+ raise ValueError("session in two cut files: " + session)
+ cuts[session] = cut
+ dirs = sorted(str(p) for root in a.roots for p in Path(root).iterdir() if (p / "meta" / "info.json").is_file())
+ sessions = [os.path.basename(d) for d in dirs]
+ if len(set(sessions)) != len(sessions):
+ raise ValueError("duplicate session names across roots")
+
+ def load(d):
+ try:
+ return read_episode(d, a.prompt)
+ except Exception as exc: # noqa: BLE001 - report and skip one broken episode
+ print(f"skip {d}: {exc}", file=sys.stderr)
+ return None
+
+ with ThreadPoolExecutor(a.workers) as pool:
+ loaded = list(pool.map(load, dirs))
+ episodes, all_states, skipped = [], [], 0
+ for session, item in zip(sessions, loaded):
+ if item is None or (cuts and session not in cuts):
+ skipped += 1
+ continue
+ states, task, videos = item
+ n = len(states)
+ keep = [[0, n]]
+ if session in cuts:
+ if cuts[session]["n_frames"] != n:
+ raise ValueError(f"{session}: {n} frames vs cut {cuts[session]['n_frames']}")
+ keep = cuts[session]["keep_ranges"]
+ starts = start_ranges(n, keep)
+ if not starts:
+ skipped += 1
+ continue
+ (a.out / session).mkdir(parents=True, exist_ok=True)
+ np.save(a.out / session / "states.npy", states)
+ episodes.append({
+ "episode_index": len(episodes), "episode_id": session, "session": session, "split": "train",
+ "n_frames": n, "caption": task, "states": f"{session}/states.npy",
+ "videos": {camera: {"file": str(Path(videos[camera]).resolve()), "first_frame": 0} for camera in CAMERAS},
+ "keep_ranges": keep, "start_ranges": starts,
+ })
+ all_states.append(states)
+ if not episodes:
+ raise ValueError("no usable episodes")
+ index = [(i, t) for i, e in enumerate(episodes) for lo, hi in e["start_ranges"] for t in range(lo, hi)]
+ rng = np.random.default_rng(a.seed)
+ picks = rng.choice(len(index), size=min(a.stats_windows, len(index)), replace=False)
+ obs, act = zip(*(make_window(all_states[index[p][0]], index[p][1], CHUNK) for p in picks))
+ obs, act = np.stack(obs), np.concatenate(act)
+ statistics = {
+ "representation": REPRESENTATION, "episodes": len(episodes), "legal_starts": len(index),
+ "sampled_windows": len(picks),
+ "state": {"q01": np.quantile(obs, 0.01, axis=0).tolist(), "q99": np.quantile(obs, 0.99, axis=0).tolist()},
+ "action": {"q01": np.quantile(act, 0.01, axis=0).tolist(), "q99": np.quantile(act, 0.99, axis=0).tolist()},
+ }
+ (a.out / "statistics.json").write_text(json.dumps(statistics, indent=1) + "\n")
+ manifest = {
+ "kind": MANIFEST_KIND, "representation": REPRESENTATION, "fps": FPS, "chunk_size": CHUNK,
+ "state_dim": 20, "action_dim": 20, "camera_order": list(CAMERAS), "legal_starts": len(index),
+ "total_frames": sum(e["n_frames"] for e in episodes),
+ "statistics_sha256": hashlib.sha256((a.out / "statistics.json").read_bytes()).hexdigest(),
+ "episodes": episodes,
+ }
+ (a.out / "training_manifest.json").write_text(json.dumps(manifest) + "\n")
+ fields = {
+ "source_root": str(a.out.resolve()), "index_dir": str(a.out.resolve()),
+ "sampling_contract": SAMPLER_VERSION,
+ "sampling_manifest_sha256": hashlib.sha256((a.out / "training_manifest.json").read_bytes()).hexdigest(),
+ "sampling_legal_starts": len(index),
+ }
+ norm = {"state_normalization": statistics["state"], "action_normalization": statistics["action"]}
+ print(json.dumps({"episodes": len(episodes), "skipped": skipped, **fields}, indent=1))
+ if a.config_template:
+ if not a.world_size:
+ raise ValueError("--config-template needs --world-size")
+ config = json.loads(a.config_template.read_text())
+ per_epoch = math.ceil(len(index) / (a.world_size * config["windows_per_rank"] * config["grad_accumulation"]))
+ steps = config["max_epochs"] * per_epoch
+ cooldown_start = round(0.8 * steps)
+ config.update(fields, steps=steps, trunk_warmup_steps=per_epoch, heads_warmup_steps=per_epoch,
+ cooldown_start=cooldown_start, cooldown_steps=steps - cooldown_start, checkpoint_every=per_epoch)
+ config["policy"].update(norm)
+ (a.out / "train_config.json").write_text(json.dumps(config, indent=1) + "\n")
+ print(f"wrote {a.out / 'train_config.json'}: {per_epoch} updates/epoch, {steps} steps")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/flux-umi/tools/train_umi.sh b/flux-umi/tools/train_umi.sh
new file mode 100644
index 0000000000000000000000000000000000000000..fadd97cce218586bc21d6759c78be252a13f04f1
--- /dev/null
+++ b/flux-umi/tools/train_umi.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# UMI post-training with the optimized (v6) kernels. FLUX_CONFIG is the train_config.json written by
+# tools/prepare_umi_lerobot_v3.py --config-template configs/umi/umi_posttrain_16g.json.
+#
+# FLUX_CONFIG=/data/umi_flux/train_config.json bash tools/train_umi.sh --override 'output_dir="/path/to/run"'
+#
+# See docs/training-environment.md for the validated stack. The REQUIRE_KERNEL guards make the CuTe/NATTEN adapters fail
+# loudly on another stack. For several nodes set FLUX_NNODES / FLUX_NODE_RANK / FLUX_MASTER_ADDR on every node.
+set -euo pipefail
+repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
+cd -- "$repo"
+: "${FLUX_CONFIG:?set FLUX_CONFIG to a train_config.json}"
+export CUDA_VISIBLE_DEVICES=${CUDA_VISIBLE_DEVICES:-0,1,2,3,4,5,6,7}
+python=${FLUX_PYTHON:-python}
+export PYTHONPATH="$repo/src"
+export PYTHONDONTWRITEBYTECODE=1
+export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
+export NCCL_DEBUG=${NCCL_DEBUG:-WARN}
+# Selective activation checkpointing keeps more activations alive; expandable segments avoid allocator thrash near the limit.
+export PYTORCH_CUDA_ALLOC_CONF=${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}
+# Optional: a CUDA 13 ptxas / host compiler for Triton (see docs/training-environment.md).
+[[ -n "${TRITON_PTXAS_PATH:-}" ]] && export TRITON_PTXAS_BLACKWELL_PATH=${TRITON_PTXAS_BLACKWELL_PATH:-$TRITON_PTXAS_PATH}
+export FLUX_ACTION_CUTE_RMSNORM_REQUIRE_KERNEL=1
+export FLUX_ACTION_CUTE_VAE_ROPE_REQUIRE_KERNEL=1
+export FLUX_ACTION_NATTEN_NO_LSE_REQUIRE_KERNEL=1
+export NATTEN_TOKPERM_DEFAULT_IMPL=cutlass
+nproc_per_node=$(awk -F, '{print NF}' <<<"$CUDA_VISIBLE_DEVICES")
+if [[ "${FLUX_NNODES:-1}" -gt 1 ]]; then
+ rdzv=(--nnodes="$FLUX_NNODES" --node_rank="${FLUX_NODE_RANK:?set FLUX_NODE_RANK}" --rdzv_backend=c10d
+ --rdzv_endpoint="${FLUX_MASTER_ADDR:?set FLUX_MASTER_ADDR}:${FLUX_MASTER_PORT:-29500}")
+else
+ rdzv=(--standalone --nnodes=1)
+fi
+exec "$python" -m torch.distributed.run "${rdzv[@]}" --nproc_per_node="$nproc_per_node" --max-restarts=0 \
+ --module flux_action.cli train --config "$FLUX_CONFIG" "$@"
diff --git a/flux-umi/uv.lock b/flux-umi/uv.lock
new file mode 100644
index 0000000000000000000000000000000000000000..6fde9bb9d7df05d4cecc75f4a0b1f249711c65fd
--- /dev/null
+++ b/flux-umi/uv.lock
@@ -0,0 +1,977 @@
+version = 1
+revision = 3
+requires-python = "==3.12.*"
+resolution-markers = [
+ "sys_platform == 'darwin'",
+ "sys_platform == 'linux'",
+ "sys_platform != 'darwin' and sys_platform != 'linux'",
+]
+
+[[package]]
+name = "annotated-doc"
+version = "0.0.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/5a/8e/38aa427ed5402449e226975b649c5dc73ccadfefeb95e6aecb8f8ea4b6b6/annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb", size = 10758, upload-time = "2026-07-28T13:50:58.129Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3e/30/e900b21425a860e195f32e37657aa1f7c7f2b1bfb26f03ca209b90933c06/annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101", size = 5302, upload-time = "2026-07-28T13:50:57.239Z" },
+]
+
+[[package]]
+name = "anyio"
+version = "4.15.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "idna" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" },
+]
+
+[[package]]
+name = "av"
+version = "15.1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e9/c3/83e6e73d1592bc54436eae0bc61704ae0cff0c3cfbde7b58af9ed67ebb49/av-15.1.0.tar.gz", hash = "sha256:39cda2dc810e11c1938f8cb5759c41d6b630550236b3365790e67a313660ec85", size = 3774192, upload-time = "2025-08-30T04:41:56.076Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/58/de78b276d20db6ffcd4371283df771721a833ba525a3d57e753d00a9fe79/av-15.1.0-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:40c5df37f4c354ab8190c6fd68dab7881d112f527906f64ca73da4c252a58cee", size = 21760991, upload-time = "2025-08-30T04:40:00.801Z" },
+ { url = "https://files.pythonhosted.org/packages/56/cc/45f85775304ae60b66976360d82ba5b152ad3fd91f9267d5020a51e9a828/av-15.1.0-cp312-cp312-macosx_13_0_x86_64.whl", hash = "sha256:af455ce65ada3d361f80c90c810d9bced4db5655ab9aa513024d6c71c5c476d5", size = 26953097, upload-time = "2025-08-30T04:40:03.998Z" },
+ { url = "https://files.pythonhosted.org/packages/f3/f8/2d781e5e71d02fc829487e775ccb1185e72f95340d05f2e84eb57a11e093/av-15.1.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:86226d2474c80c3393fa07a9c366106029ae500716098b72b3ec3f67205524c3", size = 38319710, upload-time = "2025-08-30T04:40:07.701Z" },
+ { url = "https://files.pythonhosted.org/packages/ac/13/37737ef2193e83862ccacff23580c39de251da456a1bf0459e762cca273c/av-15.1.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:11326f197e7001c4ca53a83b2dbc67fd39ddff8cdf62ce6be3b22d9f3f9338bd", size = 39915519, upload-time = "2025-08-30T04:40:11.066Z" },
+ { url = "https://files.pythonhosted.org/packages/26/e9/e8032c7b8f2a4129a03f63f896544f8b7cf068e2db2950326fa2400d5c47/av-15.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a631ea879cc553080ee62874f4284765c42ba08ee0279851a98a85e2ceb3cc8d", size = 40286166, upload-time = "2025-08-30T04:40:14.561Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/23/612c0fd809444d04b8387a2dfd942ccc77829507bd78a387ff65a9d98c24/av-15.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8f383949b010c3e731c245f80351d19dc0c08f345e194fc46becb1cb279be3ff", size = 41150592, upload-time = "2025-08-30T04:40:17.951Z" },
+ { url = "https://files.pythonhosted.org/packages/15/74/6f8e38a3b0aea5f28e72813672ff45b64615f2c69e6a4a558718c95edb9f/av-15.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:d5921aa45f4c1f8c1a8d8185eb347e02aa4c3071278a2e2dd56368d54433d643", size = 31336093, upload-time = "2025-08-30T04:40:21.393Z" },
+]
+
+[[package]]
+name = "certifi"
+version = "2026.7.22"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
+]
+
+[[package]]
+name = "click"
+version = "8.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
+]
+
+[[package]]
+name = "cuda-bindings"
+version = "12.9.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cuda-pathfinder", marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0c/c2/65bfd79292b8ff18be4dd7f7442cea37bcbc1a228c1886f1dea515c45b67/cuda_bindings-12.9.4-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:694ba35023846625ef471257e6b5a4bc8af690f961d197d77d34b1d1db393f56", size = 11760260, upload-time = "2025-10-21T14:51:40.79Z" },
+ { url = "https://files.pythonhosted.org/packages/a9/c1/dabe88f52c3e3760d861401bb994df08f672ec893b8f7592dc91626adcf3/cuda_bindings-12.9.4-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fda147a344e8eaeca0c6ff113d2851ffca8f7dfc0a6c932374ee5c47caa649c8", size = 12151019, upload-time = "2025-10-21T14:51:43.167Z" },
+]
+
+[[package]]
+name = "cuda-pathfinder"
+version = "1.8.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9d/e6/22df83f82f9bc26cb1c42265cf14d34d4908dba2a0f261bd7b28244acb00/cuda_pathfinder-1.8.1-py3-none-any.whl", hash = "sha256:ae0137ff9e56ea97499bcbf54f5f2778ec25f3266715ac86da192a795af982a8", size = 62552, upload-time = "2026-09-02T16:55:28.64Z" },
+]
+
+[[package]]
+name = "einops"
+version = "0.8.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805, upload-time = "2025-02-09T03:17:00.434Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359, upload-time = "2025-02-09T03:17:01.998Z" },
+]
+
+[[package]]
+name = "filelock"
+version = "3.32.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0a/a0/50c2c0ce5e74d7721bbb1b19a26ebd339aac5878553a6e35308c2f31f935/filelock-3.32.5.tar.gz", hash = "sha256:f6a6a28f743f9b95ce19db5abe0f376f75eb56517dff21e1a4751e2657d3e83d", size = 222838, upload-time = "2026-08-31T18:56:34.729Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/36/d2/b70a31e13d04456d28493f31d2aa087e99eeb2767ef0293b2625727ccb8c/filelock-3.32.5-py3-none-any.whl", hash = "sha256:142cd9fa77a872c5e78c62329a0d15278fadc686eb89e760017968961a4fd6b2", size = 100003, upload-time = "2026-08-31T18:56:33.078Z" },
+]
+
+[[package]]
+name = "flux-action"
+version = "0.1.0.dev0"
+source = { editable = "." }
+dependencies = [
+ { name = "einops" },
+ { name = "numpy" },
+ { name = "safetensors" },
+ { name = "torch", version = "2.10.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux'" },
+ { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" },
+ { name = "torchvision", version = "0.25.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "torchvision", version = "0.25.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux'" },
+ { name = "torchvision", version = "0.26.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" },
+]
+
+[package.optional-dependencies]
+data = [
+ { name = "av" },
+ { name = "pyarrow" },
+]
+encoders = [
+ { name = "huggingface-hub" },
+ { name = "transformers" },
+]
+serve = [
+ { name = "msgpack" },
+ { name = "websockets" },
+]
+
+[package.dev-dependencies]
+dev = [
+ { name = "pytest" },
+ { name = "ruff" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "av", marker = "extra == 'data'", specifier = ">=14,<16" },
+ { name = "einops", specifier = "==0.8.1" },
+ { name = "huggingface-hub", marker = "extra == 'encoders'", specifier = ">=0.34,<2" },
+ { name = "msgpack", marker = "extra == 'serve'", specifier = ">=1.0,<2" },
+ { name = "numpy", specifier = ">=2.0,<2.3" },
+ { name = "pyarrow", marker = "extra == 'data'", specifier = ">=19,<22" },
+ { name = "safetensors", specifier = ">=0.4.3,<1" },
+ { name = "torch", marker = "sys_platform != 'darwin' and sys_platform != 'linux'", specifier = ">=2.10.0" },
+ { name = "torch", marker = "sys_platform == 'darwin'", specifier = ">=2.11.0" },
+ { name = "torch", marker = "sys_platform == 'linux'", specifier = ">=2.10.0", index = "https://download.pytorch.org/whl/cu128" },
+ { name = "torchvision", marker = "sys_platform != 'darwin' and sys_platform != 'linux'", specifier = ">=0.25.0" },
+ { name = "torchvision", marker = "sys_platform == 'darwin'", specifier = ">=0.26.0" },
+ { name = "torchvision", marker = "sys_platform == 'linux'", specifier = ">=0.25.0", index = "https://download.pytorch.org/whl/cu128" },
+ { name = "transformers", marker = "extra == 'encoders'", specifier = "==5.16.1" },
+ { name = "websockets", marker = "extra == 'serve'", specifier = ">=13,<16" },
+]
+provides-extras = ["encoders", "data", "serve"]
+
+[package.metadata.requires-dev]
+dev = [
+ { name = "pytest", specifier = ">=8,<10" },
+ { name = "ruff", specifier = "==0.14.3" },
+]
+
+[[package]]
+name = "fsspec"
+version = "2026.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/00/78/f34251dadb8f3921264a1d9b8946f5e542014ee2614b285261b4e40e6775/fsspec-2026.7.0.tar.gz", hash = "sha256:c803c40f4cf860b49dea58ee3e1c33cb9c790520e233537e1340049f89b82a88", size = 317040, upload-time = "2026-07-28T16:34:51.052Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/3c/6a2bf344106328fd04963664a60b9bb6496fc25df8e962fcdc1367285fb9/fsspec-2026.7.0-py3-none-any.whl", hash = "sha256:b57ddbafedfaef7018c1ecab32aa200a9d7ca26b77965f64e48b70061249d279", size = 206583, upload-time = "2026-07-28T16:34:49.538Z" },
+]
+
+[[package]]
+name = "h11"
+version = "0.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
+]
+
+[[package]]
+name = "hf-xet"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1b/ab/522a2ab67f27971a9d48ca666d4fca85ef7d5282d142e31fd087e27b1bbe/hf_xet-1.6.0.tar.gz", hash = "sha256:2e58454a340b3556dfa4972d5451aff4fba8dd42a236600ba1a1d2b1514f0fef", size = 920527, upload-time = "2026-08-03T22:33:13.243Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/50/7afa2c9c787405864fc47a0d1bbc02c62e9101947ed43c1f43899fc7d91d/hf_xet-1.6.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:633dc0cd71d32da58ab8c03ad38e2fac452c15c2b0a2866ebf6ededfe0a5061d", size = 4071729, upload-time = "2026-08-03T22:33:00.721Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/69/55b8dcf636142ae660fec1869fcac14c4da2e8412e14d6eee1523be77e9f/hf_xet-1.6.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:f0906082d9932ae0c0057fa194041c22b4e2cdb46b2592ef3b91f020d62a081a", size = 3876287, upload-time = "2026-08-03T22:33:02.251Z" },
+ { url = "https://files.pythonhosted.org/packages/67/4e/a28359bf1c1ecf11eba22123168c138698f7cb576ac678f5a2e16cd5da08/hf_xet-1.6.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d62671bb130879cef0ee4c9ebe47a14af6c66ec53e6d84dc15936e5ffdfac82f", size = 4464663, upload-time = "2026-08-03T22:33:03.802Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/69/1f0cbc2fb22ae6082d094f743d1b8945a3f36f6089cb95f42b7ee348cda7/hf_xet-1.6.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0e6e21fa3cdfcdcd76748564bf593870a5e013f47d97cf10aed63aa222cff5b7", size = 4262538, upload-time = "2026-08-03T22:33:05.287Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/3a/4f4f2301ade26e404462d3336fa11f7958d914cabbabdd6e03c3c5d5658c/hf_xet-1.6.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:4fc74352a17015bd0ee90038bc9efe38db894cde45f268b6712b04fce8cd0acb", size = 4460520, upload-time = "2026-08-03T22:33:06.81Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/5f/311725e2a905534dfee2dcb5b08414f249147f1f12252bfc2bd24caa075c/hf_xet-1.6.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8fb4f71cba6129110c3374a33f919001ff130488fc23553698e34cc1c2a1198c", size = 4675937, upload-time = "2026-08-03T22:33:08.616Z" },
+ { url = "https://files.pythonhosted.org/packages/98/b7/8c59a66d15205024662f1d66968136f13893f96df1ddc5087e2e281fc95f/hf_xet-1.6.0-cp38-abi3-win_amd64.whl", hash = "sha256:fb4fadde1b2b70bf4c0c14a6dccbe7194b1c28947fefd5bbe3fed9d940676c3b", size = 4033128, upload-time = "2026-08-03T22:33:10.171Z" },
+ { url = "https://files.pythonhosted.org/packages/73/63/ca511b6f802f28cf3489b280fe77475bcca8de85e81a6299d7916b5b5555/hf_xet-1.6.0-cp38-abi3-win_arm64.whl", hash = "sha256:3dc3e35441ba395006af5aaacc40ef2e603c51ef46c3530b9156185f00935ea3", size = 3859359, upload-time = "2026-08-03T22:33:11.725Z" },
+]
+
+[[package]]
+name = "httpcore"
+version = "1.0.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "h11" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
+]
+
+[[package]]
+name = "httpx"
+version = "0.28.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "certifi" },
+ { name = "httpcore" },
+ { name = "idna" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
+]
+
+[[package]]
+name = "huggingface-hub"
+version = "1.30.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click" },
+ { name = "filelock" },
+ { name = "fsspec" },
+ { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
+ { name = "httpx" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "tqdm" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/35/97/2eb4abaa5b969ed385066a0496a3823b3ff467fc1082e2202955f1867d60/huggingface_hub-1.30.0.tar.gz", hash = "sha256:e6a6120bc8c8e2723d03648434ee247088cceb55ba7067e7d34d692cad5fdb57", size = 964291, upload-time = "2026-09-03T10:05:14.053Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c3/0e/3e45bbe0dd48f4e56b1d46649d342de853cd1c7e815323472ab62687f153/huggingface_hub-1.30.0-py3-none-any.whl", hash = "sha256:96ae0a8e99a234374a6fe43e989ebd21c04640b91ab2927e7e5773ba1131ca59", size = 796795, upload-time = "2026-09-03T10:05:12.21Z" },
+]
+
+[[package]]
+name = "idna"
+version = "3.19"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/5f/f7/abb373e5757eaec4b922b92f97ec8d6d7e057cf06778247604fbc4e7c3f3/idna-3.19.tar.gz", hash = "sha256:5e0811a4383b21dc5838069f801c4fb62113b7447663d2530d2bd6e77b49bf15", size = 215237, upload-time = "2026-08-18T05:14:24.27Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/57/b0/0e52c878c53f245edd3a11020f20979b3f490f245af532c7cae3027754b5/idna-3.19-py3-none-any.whl", hash = "sha256:815e7be7a7806d54abb586dc943addc79e8b2ee16915059658cbeff4b1b43bf4", size = 68550, upload-time = "2026-08-18T05:14:22.343Z" },
+]
+
+[[package]]
+name = "iniconfig"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
+]
+
+[[package]]
+name = "jinja2"
+version = "3.1.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markupsafe" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" },
+]
+
+[[package]]
+name = "markdown-it-py"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" },
+]
+
+[[package]]
+name = "markupsafe"
+version = "3.0.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5a/72/147da192e38635ada20e0a2e1a51cf8823d2119ce8883f7053879c2199b5/markupsafe-3.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e", size = 11615, upload-time = "2025-09-27T18:36:30.854Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/81/7e4e08678a1f98521201c3079f77db69fb552acd56067661f8c2f534a718/markupsafe-3.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce", size = 12020, upload-time = "2025-09-27T18:36:31.971Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/2c/799f4742efc39633a1b54a92eec4082e4f815314869865d876824c257c1e/markupsafe-3.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d", size = 24332, upload-time = "2025-09-27T18:36:32.813Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/2e/8d0c2ab90a8c1d9a24f0399058ab8519a3279d1bd4289511d74e909f060e/markupsafe-3.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d", size = 22947, upload-time = "2025-09-27T18:36:33.86Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/54/887f3092a85238093a0b2154bd629c89444f395618842e8b0c41783898ea/markupsafe-3.0.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a", size = 21962, upload-time = "2025-09-27T18:36:35.099Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/2f/336b8c7b6f4a4d95e91119dc8521402461b74a485558d8f238a68312f11c/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b", size = 23760, upload-time = "2025-09-27T18:36:36.001Z" },
+ { url = "https://files.pythonhosted.org/packages/32/43/67935f2b7e4982ffb50a4d169b724d74b62a3964bc1a9a527f5ac4f1ee2b/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f", size = 21529, upload-time = "2025-09-27T18:36:36.906Z" },
+ { url = "https://files.pythonhosted.org/packages/89/e0/4486f11e51bbba8b0c041098859e869e304d1c261e59244baa3d295d47b7/markupsafe-3.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b", size = 23015, upload-time = "2025-09-27T18:36:37.868Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/e1/78ee7a023dac597a5825441ebd17170785a9dab23de95d2c7508ade94e0e/markupsafe-3.0.3-cp312-cp312-win32.whl", hash = "sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d", size = 14540, upload-time = "2025-09-27T18:36:38.761Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/5b/bec5aa9bbbb2c946ca2733ef9c4ca91c91b6a24580193e891b5f7dbe8e1e/markupsafe-3.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c", size = 15105, upload-time = "2025-09-27T18:36:39.701Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/f1/216fc1bbfd74011693a4fd837e7026152e89c4bcf3e77b6692fba9923123/markupsafe-3.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f", size = 13906, upload-time = "2025-09-27T18:36:40.689Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
+[[package]]
+name = "mpmath"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" },
+]
+
+[[package]]
+name = "msgpack"
+version = "1.2.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6d/44/ea2100ec54d30c46ee9dba10a3bfb79b655e96c6df237238a3234c75869b/msgpack-1.2.2.tar.gz", hash = "sha256:9eb0b0e602064527a045ea28c4f174ed69383587e29cebe28947e3b84106eb2a", size = 187025, upload-time = "2026-08-27T10:03:47.793Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/31/78/90c15bebb1a72667349ca62d4507e9d9369e7f8f76b95f490b823d3622e5/msgpack-1.2.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a4348705be86e029d04e741cf9ed0dfe03e942d7d3b92e838fa80d3aa2c3ebc", size = 84275, upload-time = "2026-08-27T10:02:07.106Z" },
+ { url = "https://files.pythonhosted.org/packages/88/88/c2b6d8e81571da87aa232c0e34a3f3a0e618e6235892065ec82d1d81fc7a/msgpack-1.2.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0a652ceeededf71d3fa40c303a02a149d42338d310162367b91c539d4bd6e0a3", size = 83970, upload-time = "2026-08-27T10:02:08.488Z" },
+ { url = "https://files.pythonhosted.org/packages/da/c0/d3ede9f5d16acb4c05a9281859f1e99ef9f877a928eb78454c37f70db001/msgpack-1.2.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90986cc9aab9d7d1d8f38bcbf65d3f7ac83bdd90c35765db7d691b4829698cba", size = 409401, upload-time = "2026-08-27T10:02:09.877Z" },
+ { url = "https://files.pythonhosted.org/packages/41/f0/29f591bea185616cf417645ac03bd3ad9b317483ad8572160e325f7fe777/msgpack-1.2.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:77c2e018417dc1d66f235e383877ee885b60ade9d29e494dd581e08af2cb1923", size = 420619, upload-time = "2026-08-27T10:02:11.526Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/8e/c70c8c9180c5ddf4440eb8658ebead98e22e7686fbf84f6b165031430750/msgpack-1.2.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0e91332144f69bc3018c91232fac26da580ef748fb8eaddd7914d4458001cc4f", size = 379747, upload-time = "2026-08-27T10:02:13.345Z" },
+ { url = "https://files.pythonhosted.org/packages/50/9a/f10ce11fa62700c9ab87a22e65b9ca272f7f673ddd31aeb2de6ae272ad35/msgpack-1.2.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3e915d390d7068b257ca8b62f3fc59fad135c8631d1017ab03b0b924b07c5367", size = 398944, upload-time = "2026-08-27T10:02:15.006Z" },
+ { url = "https://files.pythonhosted.org/packages/82/fe/d7be978456ff8552e69a8e270d882e7530e01513c096b293d83df03753ea/msgpack-1.2.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:c522420d78db2431887d45b518e304d86e27b9ad0b30f24e3806a6ad5d8bdbfc", size = 373979, upload-time = "2026-08-27T10:02:16.618Z" },
+ { url = "https://files.pythonhosted.org/packages/be/af/91b0d8d3fb3063e259daee3ea8515cea6282f68f4b0e5f0b6fea25762c6e/msgpack-1.2.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4b554d8164ebb526892194f71dcd96ef1fefe0c250087498785d3ffc04a80be3", size = 417781, upload-time = "2026-08-27T10:02:18.293Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/3c/ce8e9efe1fd9e95c78b3705e4300ba7feba3dc6c00fb76259895db155518/msgpack-1.2.2-cp312-cp312-win32.whl", hash = "sha256:0e3315de5a4b2920ccef48d96b4448025e064a10d0f5a250f6584477d839c8d4", size = 65267, upload-time = "2026-08-27T10:02:19.869Z" },
+ { url = "https://files.pythonhosted.org/packages/85/98/a33b8b4af14e3476bb0da1b8c36ef7a0f28dcf95db1c5e68ff88cb89d591/msgpack-1.2.2-cp312-cp312-win_amd64.whl", hash = "sha256:b68614fba0570349833b7dd999ff0aed4e5cc8d9eb6e3a7d4527be33c65e33d3", size = 72275, upload-time = "2026-08-27T10:02:21.141Z" },
+ { url = "https://files.pythonhosted.org/packages/df/5e/2f323a33a6aba5bd4b2d8b430e4fab21d92cd91c093b49ee287bc166ee54/msgpack-1.2.2-cp312-cp312-win_arm64.whl", hash = "sha256:59d5b93efa45fd09f620d0c9ba81cde339a2c9937af3eea42ee9653094ce6640", size = 65488, upload-time = "2026-08-27T10:02:22.575Z" },
+]
+
+[[package]]
+name = "networkx"
+version = "3.6.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" },
+]
+
+[[package]]
+name = "numpy"
+version = "2.2.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/82/5d/c00588b6cf18e1da539b45d3598d3557084990dcc4331960c15ee776ee41/numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff", size = 20875348, upload-time = "2025-05-17T21:34:39.648Z" },
+ { url = "https://files.pythonhosted.org/packages/66/ee/560deadcdde6c2f90200450d5938f63a34b37e27ebff162810f716f6a230/numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c", size = 14119362, upload-time = "2025-05-17T21:35:01.241Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/65/4baa99f1c53b30adf0acd9a5519078871ddde8d2339dc5a7fde80d9d87da/numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3", size = 5084103, upload-time = "2025-05-17T21:35:10.622Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/89/e5a34c071a0570cc40c9a54eb472d113eea6d002e9ae12bb3a8407fb912e/numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282", size = 6625382, upload-time = "2025-05-17T21:35:21.414Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/35/8c80729f1ff76b3921d5c9487c7ac3de9b2a103b1cd05e905b3090513510/numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87", size = 14018462, upload-time = "2025-05-17T21:35:42.174Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/3d/1e1db36cfd41f895d266b103df00ca5b3cbe965184df824dec5c08c6b803/numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249", size = 16527618, upload-time = "2025-05-17T21:36:06.711Z" },
+ { url = "https://files.pythonhosted.org/packages/61/c6/03ed30992602c85aa3cd95b9070a514f8b3c33e31124694438d88809ae36/numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49", size = 15505511, upload-time = "2025-05-17T21:36:29.965Z" },
+ { url = "https://files.pythonhosted.org/packages/b7/25/5761d832a81df431e260719ec45de696414266613c9ee268394dd5ad8236/numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de", size = 18313783, upload-time = "2025-05-17T21:36:56.883Z" },
+ { url = "https://files.pythonhosted.org/packages/57/0a/72d5a3527c5ebffcd47bde9162c39fae1f90138c961e5296491ce778e682/numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4", size = 6246506, upload-time = "2025-05-17T21:37:07.368Z" },
+ { url = "https://files.pythonhosted.org/packages/36/fa/8c9210162ca1b88529ab76b41ba02d433fd54fecaf6feb70ef9f124683f1/numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2", size = 12614190, upload-time = "2025-05-17T21:37:26.213Z" },
+]
+
+[[package]]
+name = "nvidia-cublas-cu12"
+version = "12.8.4.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/29/99/db44d685f0e257ff0e213ade1964fc459b4a690a73293220e98feb3307cf/nvidia_cublas_cu12-12.8.4.1-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b86f6dd8935884615a0683b663891d43781b819ac4f2ba2b0c9604676af346d0", size = 590537124, upload-time = "2025-03-07T01:43:53.556Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/61/e24b560ab2e2eaeb3c839129175fb330dfcfc29e5203196e5541a4c44682/nvidia_cublas_cu12-12.8.4.1-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:8ac4e771d5a348c551b2a426eda6193c19aa630236b418086020df5ba9667142", size = 594346921, upload-time = "2025-03-07T01:44:31.254Z" },
+]
+
+[[package]]
+name = "nvidia-cuda-cupti-cu12"
+version = "12.8.90"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d5/1f/b3bd73445e5cb342727fd24fe1f7b748f690b460acadc27ea22f904502c8/nvidia_cuda_cupti_cu12-12.8.90-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:4412396548808ddfed3f17a467b104ba7751e6b58678a4b840675c56d21cf7ed", size = 9533318, upload-time = "2025-03-07T01:40:10.421Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/02/2adcaa145158bf1a8295d83591d22e4103dbfd821bcaf6f3f53151ca4ffa/nvidia_cuda_cupti_cu12-12.8.90-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ea0cb07ebda26bb9b29ba82cda34849e73c166c18162d3913575b0c9db9a6182", size = 10248621, upload-time = "2025-03-07T01:40:21.213Z" },
+]
+
+[[package]]
+name = "nvidia-cuda-nvrtc-cu12"
+version = "12.8.93"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/05/6b/32f747947df2da6994e999492ab306a903659555dddc0fbdeb9d71f75e52/nvidia_cuda_nvrtc_cu12-12.8.93-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:a7756528852ef889772a84c6cd89d41dfa74667e24cca16bb31f8f061e3e9994", size = 88040029, upload-time = "2025-03-07T01:42:13.562Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/d1/e50d0acaab360482034b84b6e27ee83c6738f7d32182b987f9c7a4e32962/nvidia_cuda_nvrtc_cu12-12.8.93-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fc1fec1e1637854b4c0a65fb9a8346b51dd9ee69e61ebaccc82058441f15bce8", size = 43106076, upload-time = "2025-03-07T01:41:59.817Z" },
+]
+
+[[package]]
+name = "nvidia-cuda-runtime-cu12"
+version = "12.8.90"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/75/f865a3b236e4647605ea34cc450900854ba123834a5f1598e160b9530c3a/nvidia_cuda_runtime_cu12-12.8.90-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:52bf7bbee900262ffefe5e9d5a2a69a30d97e2bc5bb6cc866688caa976966e3d", size = 965265, upload-time = "2025-03-07T01:39:43.533Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/9b/a997b638fcd068ad6e4d53b8551a7d30fe8b404d6f1804abf1df69838932/nvidia_cuda_runtime_cu12-12.8.90-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:adade8dcbd0edf427b7204d480d6066d33902cab2a4707dcfc48a2d0fd44ab90", size = 954765, upload-time = "2025-03-07T01:40:01.615Z" },
+]
+
+[[package]]
+name = "nvidia-cudnn-cu12"
+version = "9.10.2.21"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cublas-cu12", marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fa/41/e79269ce215c857c935fd86bcfe91a451a584dfc27f1e068f568b9ad1ab7/nvidia_cudnn_cu12-9.10.2.21-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:c9132cc3f8958447b4910a1720036d9eff5928cc3179b0a51fb6d167c6cc87d8", size = 705026878, upload-time = "2025-06-06T21:52:51.348Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/51/e123d997aa098c61d029f76663dedbfb9bc8dcf8c60cbd6adbe42f76d049/nvidia_cudnn_cu12-9.10.2.21-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:949452be657fa16687d0930933f032835951ef0892b37d2d53824d1a84dc97a8", size = 706758467, upload-time = "2025-06-06T21:54:08.597Z" },
+]
+
+[[package]]
+name = "nvidia-cufft-cu12"
+version = "11.3.3.83"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/60/bc/7771846d3a0272026c416fbb7e5f4c1f146d6d80704534d0b187dd6f4800/nvidia_cufft_cu12-11.3.3.83-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:848ef7224d6305cdb2a4df928759dca7b1201874787083b6e7550dd6765ce69a", size = 193109211, upload-time = "2025-03-07T01:44:56.873Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/13/ee4e00f30e676b66ae65b4f08cb5bcbb8392c03f54f2d5413ea99a5d1c80/nvidia_cufft_cu12-11.3.3.83-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4d2dd21ec0b88cf61b62e6b43564355e5222e4a3fb394cac0db101f2dd0d4f74", size = 193118695, upload-time = "2025-03-07T01:45:27.821Z" },
+]
+
+[[package]]
+name = "nvidia-cufile-cu12"
+version = "1.13.1.3"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bb/fe/1bcba1dfbfb8d01be8d93f07bfc502c93fa23afa6fd5ab3fc7c1df71038a/nvidia_cufile_cu12-1.13.1.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1d069003be650e131b21c932ec3d8969c1715379251f8d23a1860554b1cb24fc", size = 1197834, upload-time = "2025-03-07T01:45:50.723Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/f5/5607710447a6fe9fd9b3283956fceeee8a06cda1d2f56ce31371f595db2a/nvidia_cufile_cu12-1.13.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:4beb6d4cce47c1a0f1013d72e02b0994730359e17801d395bdcbf20cfb3bb00a", size = 1120705, upload-time = "2025-03-07T01:45:41.434Z" },
+]
+
+[[package]]
+name = "nvidia-curand-cu12"
+version = "10.3.9.90"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/45/5e/92aa15eca622a388b80fbf8375d4760738df6285b1e92c43d37390a33a9a/nvidia_curand_cu12-10.3.9.90-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:dfab99248034673b779bc6decafdc3404a8a6f502462201f2f31f11354204acd", size = 63625754, upload-time = "2025-03-07T01:46:10.735Z" },
+ { url = "https://files.pythonhosted.org/packages/fb/aa/6584b56dc84ebe9cf93226a5cde4d99080c8e90ab40f0c27bda7a0f29aa1/nvidia_curand_cu12-10.3.9.90-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:b32331d4f4df5d6eefa0554c565b626c7216f87a06a4f56fab27c3b68a830ec9", size = 63619976, upload-time = "2025-03-07T01:46:23.323Z" },
+]
+
+[[package]]
+name = "nvidia-cusolver-cu12"
+version = "11.7.3.90"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-cublas-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cusparse-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c8/32/f7cd6ce8a7690544d084ea21c26e910a97e077c9b7f07bf5de623ee19981/nvidia_cusolver_cu12-11.7.3.90-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:db9ed69dbef9715071232caa9b69c52ac7de3a95773c2db65bdba85916e4e5c0", size = 267229841, upload-time = "2025-03-07T01:46:54.356Z" },
+ { url = "https://files.pythonhosted.org/packages/85/48/9a13d2975803e8cf2777d5ed57b87a0b6ca2cc795f9a4f59796a910bfb80/nvidia_cusolver_cu12-11.7.3.90-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:4376c11ad263152bd50ea295c05370360776f8c3427b30991df774f9fb26c450", size = 267506905, upload-time = "2025-03-07T01:47:16.273Z" },
+]
+
+[[package]]
+name = "nvidia-cusparse-cu12"
+version = "12.5.8.93"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bc/f7/cd777c4109681367721b00a106f491e0d0d15cfa1fd59672ce580ce42a97/nvidia_cusparse_cu12-12.5.8.93-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9b6c161cb130be1a07a27ea6923df8141f3c295852f4b260c65f18f3e0a091dc", size = 288117129, upload-time = "2025-03-07T01:47:40.407Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/f5/e1854cb2f2bcd4280c44736c93550cc300ff4b8c95ebe370d0aa7d2b473d/nvidia_cusparse_cu12-12.5.8.93-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1ec05d76bbbd8b61b06a80e1eaf8cf4959c3d4ce8e711b65ebd0443bb0ebb13b", size = 288216466, upload-time = "2025-03-07T01:48:13.779Z" },
+]
+
+[[package]]
+name = "nvidia-cusparselt-cu12"
+version = "0.7.1"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/73/b9/598f6ff36faaece4b3c50d26f50e38661499ff34346f00e057760b35cc9d/nvidia_cusparselt_cu12-0.7.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:8878dce784d0fac90131b6817b607e803c36e629ba34dc5b433471382196b6a5", size = 283835557, upload-time = "2025-02-26T00:16:54.265Z" },
+ { url = "https://files.pythonhosted.org/packages/56/79/12978b96bd44274fe38b5dde5cfb660b1d114f70a65ef962bcbbed99b549/nvidia_cusparselt_cu12-0.7.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:f1bb701d6b930d5a7cea44c19ceb973311500847f81b634d802b7b539dc55623", size = 287193691, upload-time = "2025-02-26T00:15:44.104Z" },
+]
+
+[[package]]
+name = "nvidia-nccl-cu12"
+version = "2.27.5"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bb/1c/857979db0ef194ca5e21478a0612bcdbbe59458d7694361882279947b349/nvidia_nccl_cu12-2.27.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:31432ad4d1fb1004eb0c56203dc9bc2178a1ba69d1d9e02d64a6938ab5e40e7a", size = 322400625, upload-time = "2025-06-26T04:11:04.496Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/89/f7a07dc961b60645dbbf42e80f2bc85ade7feb9a491b11a1e973aa00071f/nvidia_nccl_cu12-2.27.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ad730cf15cb5d25fe849c6e6ca9eb5b76db16a80f13f425ac68d8e2e55624457", size = 322348229, upload-time = "2025-06-26T04:11:28.385Z" },
+]
+
+[[package]]
+name = "nvidia-nvjitlink-cu12"
+version = "12.8.93"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f6/74/86a07f1d0f42998ca31312f998bd3b9a7eff7f52378f4f270c8679c77fb9/nvidia_nvjitlink_cu12-12.8.93-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:81ff63371a7ebd6e6451970684f916be2eab07321b73c9d244dc2b4da7f73b88", size = 39254836, upload-time = "2025-03-07T01:49:55.661Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/a2/8cee5da30d13430e87bf99bb33455d2724d0a4a9cb5d7926d80ccb96d008/nvidia_nvjitlink_cu12-12.8.93-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:adccd7161ace7261e01bb91e44e88da350895c270d23f744f0820c818b7229e7", size = 38386204, upload-time = "2025-03-07T01:49:43.612Z" },
+]
+
+[[package]]
+name = "nvidia-nvshmem-cu12"
+version = "3.4.5"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1d/6a/03aa43cc9bd3ad91553a88b5f6fb25ed6a3752ae86ce2180221962bc2aa5/nvidia_nvshmem_cu12-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0b48363fc6964dede448029434c6abed6c5e37f823cb43c3bcde7ecfc0457e15", size = 138936938, upload-time = "2025-09-06T00:32:05.589Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/09/6ea3ea725f82e1e76684f0708bbedd871fc96da89945adeba65c3835a64c/nvidia_nvshmem_cu12-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:042f2500f24c021db8a06c5eec2539027d57460e1c1a762055a6554f72c369bd", size = 139103095, upload-time = "2025-09-06T00:32:31.266Z" },
+]
+
+[[package]]
+name = "nvidia-nvtx-cu12"
+version = "12.8.90"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/10/c0/1b303feea90d296f6176f32a2a70b5ef230f9bdeb3a72bddb0dc922dc137/nvidia_nvtx_cu12-12.8.90-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d7ad891da111ebafbf7e015d34879f7112832fc239ff0d7d776b6cb685274615", size = 91161, upload-time = "2025-03-07T01:42:23.922Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/eb/86626c1bbc2edb86323022371c39aa48df6fd8b0a1647bc274577f72e90b/nvidia_nvtx_cu12-12.8.90-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5b17e2001cc0d751a5bc2c6ec6d26ad95913324a4adb86788c944f8ce9ba441f", size = 89954, upload-time = "2025-03-07T01:42:44.131Z" },
+]
+
+[[package]]
+name = "packaging"
+version = "26.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
+]
+
+[[package]]
+name = "pillow"
+version = "12.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },
+ { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },
+ { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },
+ { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },
+ { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },
+ { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },
+]
+
+[[package]]
+name = "pluggy"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
+]
+
+[[package]]
+name = "pyarrow"
+version = "21.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ef/c2/ea068b8f00905c06329a3dfcd40d0fcc2b7d0f2e355bdb25b65e0a0e4cd4/pyarrow-21.0.0.tar.gz", hash = "sha256:5051f2dccf0e283ff56335760cbc8622cf52264d67e359d5569541ac11b6d5bc", size = 1133487, upload-time = "2025-07-18T00:57:31.761Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ca/d4/d4f817b21aacc30195cf6a46ba041dd1be827efa4a623cc8bf39a1c2a0c0/pyarrow-21.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:3a302f0e0963db37e0a24a70c56cf91a4faa0bca51c23812279ca2e23481fccd", size = 31160305, upload-time = "2025-07-18T00:55:35.373Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/9c/dcd38ce6e4b4d9a19e1d36914cb8e2b1da4e6003dd075474c4cfcdfe0601/pyarrow-21.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:b6b27cf01e243871390474a211a7922bfbe3bda21e39bc9160daf0da3fe48876", size = 32684264, upload-time = "2025-07-18T00:55:39.303Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/74/2a2d9f8d7a59b639523454bec12dba35ae3d0a07d8ab529dc0809f74b23c/pyarrow-21.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e72a8ec6b868e258a2cd2672d91f2860ad532d590ce94cdf7d5e7ec674ccf03d", size = 41108099, upload-time = "2025-07-18T00:55:42.889Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/90/2660332eeb31303c13b653ea566a9918484b6e4d6b9d2d46879a33ab0622/pyarrow-21.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:b7ae0bbdc8c6674259b25bef5d2a1d6af5d39d7200c819cf99e07f7dfef1c51e", size = 42829529, upload-time = "2025-07-18T00:55:47.069Z" },
+ { url = "https://files.pythonhosted.org/packages/33/27/1a93a25c92717f6aa0fca06eb4700860577d016cd3ae51aad0e0488ac899/pyarrow-21.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:58c30a1729f82d201627c173d91bd431db88ea74dcaa3885855bc6203e433b82", size = 43367883, upload-time = "2025-07-18T00:55:53.069Z" },
+ { url = "https://files.pythonhosted.org/packages/05/d9/4d09d919f35d599bc05c6950095e358c3e15148ead26292dfca1fb659b0c/pyarrow-21.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:072116f65604b822a7f22945a7a6e581cfa28e3454fdcc6939d4ff6090126623", size = 45133802, upload-time = "2025-07-18T00:55:57.714Z" },
+ { url = "https://files.pythonhosted.org/packages/71/30/f3795b6e192c3ab881325ffe172e526499eb3780e306a15103a2764916a2/pyarrow-21.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:cf56ec8b0a5c8c9d7021d6fd754e688104f9ebebf1bf4449613c9531f5346a18", size = 26203175, upload-time = "2025-07-18T00:56:01.364Z" },
+]
+
+[[package]]
+name = "pygments"
+version = "2.21.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
+]
+
+[[package]]
+name = "pytest"
+version = "9.1.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "iniconfig" },
+ { name = "packaging" },
+ { name = "pluggy" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" },
+]
+
+[[package]]
+name = "pyyaml"
+version = "6.0.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" },
+ { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" },
+ { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" },
+ { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" },
+ { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" },
+ { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" },
+ { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" },
+]
+
+[[package]]
+name = "regex"
+version = "2026.9.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/19/c1/6b30b775c7bcc6cf6506a4d4741c2123e8d99cd50f3fe8cbd731f5fef526/regex-2026.9.3.tar.gz", hash = "sha256:aabd43208e335f4c3f0b56de3464b066dd425983a58f6eeb5738bcd7465403db", size = 416720, upload-time = "2026-09-01T00:53:43.821Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/da/cb/cba530bc3b068fc337f8f455c63ef5ee91a4eb4c76ecf5998e5cef5aaa6b/regex-2026.9.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:5db80d0b1c8238940b5957dd66b5c818ea40a221f6652fb717c027a562d09c77", size = 496699, upload-time = "2026-09-01T00:50:27.98Z" },
+ { url = "https://files.pythonhosted.org/packages/81/39/f2e9fb6bbbc80f8bf67ad79d7e2e8866f7837d7c24c692f7faf8f1272e7e/regex-2026.9.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:35d48ce3dee087b63b15cd0a7a3110d0a76c29edbe1f2ad0520b8c4adb7cb596", size = 297018, upload-time = "2026-09-01T00:50:29.487Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/b6/c16ee58840baf7659def27ef6f62f3d9a9909670d3c1b4b98bb8b8ee47e2/regex-2026.9.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1f22e0d21ae7016c77175c139a7fca465b988efc1280df4816c79752068d9e2e", size = 292008, upload-time = "2026-09-01T00:50:30.929Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/b4/4987bf0f17604669b4ea5aef219886d0a73188c4716ff3a7d275d4d15c15/regex-2026.9.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:233662cf8cfdfe3c0e58aa8f7bbefc579b5be0ac34546f123c159804179e8687", size = 796101, upload-time = "2026-09-01T00:50:32.486Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/95/2a9ab02a68c8a61dc0b4882ed643b1a95740d9dc291dc26c77d19af79691/regex-2026.9.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7d2eed2e4d231278a2ccab3f4bfa2c1e39855f336475f7756a281d767d2b1753", size = 865435, upload-time = "2026-09-01T00:50:34.171Z" },
+ { url = "https://files.pythonhosted.org/packages/04/92/0570d41559b446c97c1148cb9ebc1df09f2949b03c7c9bfee09976b3465f/regex-2026.9.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e674cecb61cb160be392da07fd8a71509ef927f437fbf3215432692ed385151", size = 911828, upload-time = "2026-09-01T00:50:35.72Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/8b/9cc6d4123033f7cb82df6cd8ce19eb0fc18a964afe060a03c9b26757c9f3/regex-2026.9.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:665207e41bacd435db001099eeab44103197c2c1a729d73ade74688a905ed4ce", size = 801965, upload-time = "2026-09-01T00:50:37.701Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/98/39262e91aa87a67c82cbe90a0df4c3d382c7a44811fe80067904085211b4/regex-2026.9.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7a7ddc9a8ca1795166a1ca80364b8ce74187fc210e112d3fb048b711b934f36c", size = 776192, upload-time = "2026-09-01T00:50:39.57Z" },
+ { url = "https://files.pythonhosted.org/packages/24/e9/3bb93fe4ee4b6f8ce7ba69b527c4a63cfa3393fc425ab26486041fe441c8/regex-2026.9.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e3037d02425863ce9501afbaa04ba967162810004bacde39a53ea9a5b740eb32", size = 785053, upload-time = "2026-09-01T00:50:41.156Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/05/31d5bc2553a700c0dfc6b5b6a13c61cdcd1210fde1e304cfa18a33f138b2/regex-2026.9.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:3de4eab8c763393b75bbb26f81934ab2cc8794f48f79e90622e3ab7ea57f3d14", size = 860546, upload-time = "2026-09-01T00:50:42.746Z" },
+ { url = "https://files.pythonhosted.org/packages/65/a3/2e1e854d80becda0f061093805bbfc037a5849448f46d0a2b71a070d45e2/regex-2026.9.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:98620c9c4c22568ad70f57b80527c780b6f8fd26e36507bf8e2273262a228275", size = 765841, upload-time = "2026-09-01T00:50:44.5Z" },
+ { url = "https://files.pythonhosted.org/packages/6a/d6/43d02948cedde2e8476ac893ea02755ee5ee1b21c531fda92d80e114f0bc/regex-2026.9.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:0b1ba3aaaf5776de473ee16625ac60ac195abb0343afb273575a8201d99be089", size = 852147, upload-time = "2026-09-01T00:50:46.474Z" },
+ { url = "https://files.pythonhosted.org/packages/21/ff/adb4e2d08afe8f4c6df004d94604257e1f72af7ba328af7715601585aba4/regex-2026.9.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56d8659c65166641d8f1b5efccc391c62c8a899eff4d528b981cc62b7b402a4b", size = 789761, upload-time = "2026-09-01T00:50:48.749Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/e1/1490d1351758e87f6e702cf2025036bdc7bc59182e2ff5c7bec004b19aed/regex-2026.9.3-cp312-cp312-win32.whl", hash = "sha256:837c1859913798d8bebcd98d4a037e113f8d79e81733009bf590e449769eecb3", size = 267150, upload-time = "2026-09-01T00:50:50.414Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/49/4c40cf722d84d60e807a08ef4c3f579216bf97df60c4a1b10be49655d302/regex-2026.9.3-cp312-cp312-win_amd64.whl", hash = "sha256:1ba1dbbb93c5c5629c1861763aec5bfa9f05ad24ef450694130e25029ce7bc36", size = 277773, upload-time = "2026-09-01T00:50:51.963Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/af/c48b3b2b4244b4b090554c78d3387e9ae7b859f3dbf7148a27d427e9e5b8/regex-2026.9.3-cp312-cp312-win_arm64.whl", hash = "sha256:d7b3a8a4bbd83ad8b29758f5d24bab10a3f2de87970db36f1e3651c733353136", size = 277122, upload-time = "2026-09-01T00:50:53.778Z" },
+]
+
+[[package]]
+name = "rich"
+version = "15.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },
+]
+
+[[package]]
+name = "ruff"
+version = "0.14.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/75/62/50b7727004dfe361104dfbf898c45a9a2fdfad8c72c04ae62900224d6ecf/ruff-0.14.3.tar.gz", hash = "sha256:4ff876d2ab2b161b6de0aa1f5bd714e8e9b4033dc122ee006925fbacc4f62153", size = 5558687, upload-time = "2025-10-31T00:26:26.878Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ce/8e/0c10ff1ea5d4360ab8bfca4cb2c9d979101a391f3e79d2616c9bf348cd26/ruff-0.14.3-py3-none-linux_armv6l.whl", hash = "sha256:876b21e6c824f519446715c1342b8e60f97f93264012de9d8d10314f8a79c371", size = 12535613, upload-time = "2025-10-31T00:25:44.302Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/c8/6724f4634c1daf52409fbf13fefda64aa9c8f81e44727a378b7b73dc590b/ruff-0.14.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b6fd8c79b457bedd2abf2702b9b472147cd860ed7855c73a5247fa55c9117654", size = 12855812, upload-time = "2025-10-31T00:25:47.793Z" },
+ { url = "https://files.pythonhosted.org/packages/de/03/db1bce591d55fd5f8a08bb02517fa0b5097b2ccabd4ea1ee29aa72b67d96/ruff-0.14.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:71ff6edca490c308f083156938c0c1a66907151263c4abdcb588602c6e696a14", size = 11944026, upload-time = "2025-10-31T00:25:49.657Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/75/4f8dbd48e03272715d12c87dc4fcaaf21b913f0affa5f12a4e9c6f8a0582/ruff-0.14.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:786ee3ce6139772ff9272aaf43296d975c0217ee1b97538a98171bf0d21f87ed", size = 12356818, upload-time = "2025-10-31T00:25:51.949Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/9b/506ec5b140c11d44a9a4f284ea7c14ebf6f8b01e6e8917734a3325bff787/ruff-0.14.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cd6291d0061811c52b8e392f946889916757610d45d004e41140d81fb6cd5ddc", size = 12336745, upload-time = "2025-10-31T00:25:54.248Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/e1/c560d254048c147f35e7f8131d30bc1f63a008ac61595cf3078a3e93533d/ruff-0.14.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a497ec0c3d2c88561b6d90f9c29f5ae68221ac00d471f306fa21fa4264ce5fcd", size = 13101684, upload-time = "2025-10-31T00:25:56.253Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/32/e310133f8af5cd11f8cc30f52522a3ebccc5ea5bff4b492f94faceaca7a8/ruff-0.14.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:e231e1be58fc568950a04fbe6887c8e4b85310e7889727e2b81db205c45059eb", size = 14535000, upload-time = "2025-10-31T00:25:58.397Z" },
+ { url = "https://files.pythonhosted.org/packages/a2/a1/7b0470a22158c6d8501eabc5e9b6043c99bede40fa1994cadf6b5c2a61c7/ruff-0.14.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:469e35872a09c0e45fecf48dd960bfbce056b5db2d5e6b50eca329b4f853ae20", size = 14156450, upload-time = "2025-10-31T00:26:00.889Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/96/24bfd9d1a7f532b560dcee1a87096332e461354d3882124219bcaff65c09/ruff-0.14.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3d6bc90307c469cb9d28b7cfad90aaa600b10d67c6e22026869f585e1e8a2db0", size = 13568414, upload-time = "2025-10-31T00:26:03.291Z" },
+ { url = "https://files.pythonhosted.org/packages/a7/e7/138b883f0dfe4ad5b76b58bf4ae675f4d2176ac2b24bdd81b4d966b28c61/ruff-0.14.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2f8a0bbcffcfd895df39c9a4ecd59bb80dca03dc43f7fb63e647ed176b741e", size = 13315293, upload-time = "2025-10-31T00:26:05.708Z" },
+ { url = "https://files.pythonhosted.org/packages/33/f4/c09bb898be97b2eb18476b7c950df8815ef14cf956074177e9fbd40b7719/ruff-0.14.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:678fdd7c7d2d94851597c23ee6336d25f9930b460b55f8598e011b57c74fd8c5", size = 13539444, upload-time = "2025-10-31T00:26:08.09Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/aa/b30a1db25fc6128b1dd6ff0741fa4abf969ded161599d07ca7edd0739cc0/ruff-0.14.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:1ec1ac071e7e37e0221d2f2dbaf90897a988c531a8592a6a5959f0603a1ecf5e", size = 12252581, upload-time = "2025-10-31T00:26:10.297Z" },
+ { url = "https://files.pythonhosted.org/packages/da/13/21096308f384d796ffe3f2960b17054110a9c3828d223ca540c2b7cc670b/ruff-0.14.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:afcdc4b5335ef440d19e7df9e8ae2ad9f749352190e96d481dc501b753f0733e", size = 12307503, upload-time = "2025-10-31T00:26:12.646Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/cc/a350bac23f03b7dbcde3c81b154706e80c6f16b06ff1ce28ed07dc7b07b0/ruff-0.14.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7bfc42f81862749a7136267a343990f865e71fe2f99cf8d2958f684d23ce3dfa", size = 12675457, upload-time = "2025-10-31T00:26:15.044Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/76/46346029fa2f2078826bc88ef7167e8c198e58fe3126636e52f77488cbba/ruff-0.14.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a65e448cfd7e9c59fae8cf37f9221585d3354febaad9a07f29158af1528e165f", size = 13403980, upload-time = "2025-10-31T00:26:17.81Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/a4/35f1ef68c4e7b236d4a5204e3669efdeefaef21f0ff6a456792b3d8be438/ruff-0.14.3-py3-none-win32.whl", hash = "sha256:f3d91857d023ba93e14ed2d462ab62c3428f9bbf2b4fbac50a03ca66d31991f7", size = 12500045, upload-time = "2025-10-31T00:26:20.503Z" },
+ { url = "https://files.pythonhosted.org/packages/03/15/51960ae340823c9859fb60c63301d977308735403e2134e17d1d2858c7fb/ruff-0.14.3-py3-none-win_amd64.whl", hash = "sha256:d7b7006ac0756306db212fd37116cce2bd307e1e109375e1c6c106002df0ae5f", size = 13594005, upload-time = "2025-10-31T00:26:22.533Z" },
+ { url = "https://files.pythonhosted.org/packages/b7/73/4de6579bac8e979fca0a77e54dec1f1e011a0d268165eb8a9bc0982a6564/ruff-0.14.3-py3-none-win_arm64.whl", hash = "sha256:26eb477ede6d399d898791d01961e16b86f02bc2486d0d1a7a9bb2379d055dc1", size = 12590017, upload-time = "2025-10-31T00:26:24.52Z" },
+]
+
+[[package]]
+name = "safetensors"
+version = "0.8.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" },
+ { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" },
+ { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" },
+ { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" },
+ { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" },
+ { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" },
+ { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" },
+ { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" },
+ { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" },
+ { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" },
+ { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" },
+]
+
+[[package]]
+name = "setuptools"
+version = "81.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0d/1c/73e719955c59b8e424d015ab450f51c0af856ae46ea2da83eba51cc88de1/setuptools-81.0.0.tar.gz", hash = "sha256:487b53915f52501f0a79ccfd0c02c165ffe06631443a886740b91af4b7a5845a", size = 1198299, upload-time = "2026-02-06T21:10:39.601Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/e3/c164c88b2e5ce7b24d667b9bd83589cf4f3520d97cad01534cd3c4f55fdb/setuptools-81.0.0-py3-none-any.whl", hash = "sha256:fdd925d5c5d9f62e4b74b30d6dd7828ce236fd6ed998a08d81de62ce5a6310d6", size = 1062021, upload-time = "2026-02-06T21:10:37.175Z" },
+]
+
+[[package]]
+name = "shellingham"
+version = "1.5.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310, upload-time = "2023-10-24T04:13:40.426Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
+]
+
+[[package]]
+name = "sympy"
+version = "1.14.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mpmath" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" },
+]
+
+[[package]]
+name = "tokenizers"
+version = "0.23.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "huggingface-hub" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/18/1e/bc6587c5ab643b2e17776cace9070a2ae73549c86bffac9934a600bf3c31/tokenizers-0.23.2.tar.gz", hash = "sha256:7f0f085686b9de0d0079e6f874ae053600db64c5d13049e0bbc0119926d25aac", size = 385745, upload-time = "2026-09-03T08:55:42.89Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4d/ed/8a443528baa6fac8dfe8c3b75b038c63ac92bb539bcabe311e227c718173/tokenizers-0.23.2-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:85a9a357a3764aecc904ee76bdaf8cf1ad8e5a67a1b929a487c4a39b49ed0e90", size = 3148852, upload-time = "2026-09-03T08:55:30.874Z" },
+ { url = "https://files.pythonhosted.org/packages/67/49/22da045a91732384d3a3771816bf188dc5a1f702c32e635afa7c679c0bef/tokenizers-0.23.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:986670e43691469dcee610ea0f846f91a8f84e91fc6f7a48d4c064414c0ec2bf", size = 3101593, upload-time = "2026-09-03T08:55:28.587Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/4d/8f569ed49372a3ed8e57099bd515055fd48d7c95912c4307cda6973c2168/tokenizers-0.23.2-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a37039b5dfc4af84eb3ef0a92f4307e28936c8f9adccba2629d36f652e9bf7a2", size = 3516830, upload-time = "2026-09-03T08:55:14.741Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/de/e2f14c8919d5bf51874051d00d6c7b7e0e8bde6c6a2dbeddda7f642896ff/tokenizers-0.23.2-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7b7e37ba198f24150f523e1242e83c4970de4a525480586be5dcc24d9add32c5", size = 3407975, upload-time = "2026-09-03T08:55:16.842Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/bd/93c69152d02ef06ce47aed8b2bf4952dcf733c935a62791873932b2934d9/tokenizers-0.23.2-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:43e4f2071e3cc8d5d86421c874aebc82659bb51a68bcdef5a0da75ee89511ccb", size = 3748165, upload-time = "2026-09-03T08:55:24.769Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/b7/56b84b80bc96942bba8eb23751a9e8a1fce4faaf4390425e7083f721c98c/tokenizers-0.23.2-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:325fee2e0418a9dc6c9ecf736a5f5f0db7875183ace9549ae339da76f7a1fbb7", size = 4024165, upload-time = "2026-09-03T08:55:18.806Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/8a/0175e216f005c2fe08238292663aa41e4c802b216e71047a69a0e9fc6fa3/tokenizers-0.23.2-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:950d7c9426fa72406a0ffeacdbc0bb9985f5db20eb8b263f29c79aaf83105703", size = 3591899, upload-time = "2026-09-03T08:55:22.752Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/ca/ca6b93c7820df123b2662a9469e8facc826ccc94e98fdd0d615f6431e73a/tokenizers-0.23.2-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:41c2f84d172449b4dadb9cdc508e3e364076613c35b16e76ecfe47a60d1e3305", size = 3386843, upload-time = "2026-09-03T08:55:26.584Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/a4/4f9106d317b14a80aefea9f0e3a8d07ef25f856a7607eb7f5ab894281fcb/tokenizers-0.23.2-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:12f0835dc2ee694746a76adf7b1567d4346a4a502ebe93fb1f5f80ea49799b78", size = 3577314, upload-time = "2026-09-03T08:55:20.825Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/6a/1552b70fb0d9ab074fd3fc961435d01364e79c9058481822c3af6e8d402c/tokenizers-0.23.2-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:eb2f9c8a24da020ea8c11a01a19c1c2547912d92121ae4a01cfbca46125dee40", size = 9967367, upload-time = "2026-09-03T08:55:33.188Z" },
+ { url = "https://files.pythonhosted.org/packages/06/01/3ccb3a956c7528b2507b8a9714155c4baf86af593039db6ea375dd0c96c3/tokenizers-0.23.2-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:f486f402f6f9abee5bb032553736813af0c710a86b2e0ca592634c55cea1f835", size = 9811886, upload-time = "2026-09-03T08:55:35.642Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/73/7038e612d48bda1599457f712f6bd3854eae1a9dc9c13aa47f835349db48/tokenizers-0.23.2-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:bef235815a067b2648caf6dcc7a71091b0b0fff9ee8057f6451eb9335fae52ef", size = 10146224, upload-time = "2026-09-03T08:55:38.391Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/d8/8e9e4e0b287a338d8f88976729628c9d22e8a54cfaf9777018a7f7cb58a0/tokenizers-0.23.2-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5c56bda1511921587789163e524d196ed8284174ac23abd7685d5ea8da6c4718", size = 10256304, upload-time = "2026-09-03T08:55:40.977Z" },
+ { url = "https://files.pythonhosted.org/packages/f3/1f/c79a01f671a49728ebb0b61f7ff9ea45663b66cab40bc0858e9859b25c16/tokenizers-0.23.2-cp310-abi3-win32.whl", hash = "sha256:debf978920d93ba9c219bd67cc4bbfaf912c9039e41e7a28b91ec15e3728c95a", size = 2592809, upload-time = "2026-09-03T08:55:48.02Z" },
+ { url = "https://files.pythonhosted.org/packages/db/f7/0a69ac6b82dbccf3f71add938a161c497952749294b8dd6dfe03a819dc40/tokenizers-0.23.2-cp310-abi3-win_amd64.whl", hash = "sha256:2e96f5699d5249c9c64aa8412e044f727aae3a4098cf830f9901ec1afc361cde", size = 2863236, upload-time = "2026-09-03T08:55:46.193Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/b0/dee84cb44175be1b4c35bd2f770727494e78f0bb38e571a623ade94dbebb/tokenizers-0.23.2-cp310-abi3-win_arm64.whl", hash = "sha256:e49c394456dd9985787fec76132438ba3fb8911f857b1bf3d40119f9292d41aa", size = 2729352, upload-time = "2026-09-03T08:55:44.345Z" },
+]
+
+[[package]]
+name = "torch"
+version = "2.10.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "sys_platform != 'darwin' and sys_platform != 'linux'",
+]
+dependencies = [
+ { name = "filelock", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "fsspec", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "jinja2", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "networkx", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "setuptools", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "sympy", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "typing-extensions", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6e/01/624c4324ca01f66ae4c7cd1b74eb16fb52596dce66dbe51eff95ef9e7a4c/torch-2.10.0-cp312-cp312-win_amd64.whl", hash = "sha256:2c66c61f44c5f903046cc696d088e21062644cbe541c7f1c4eaae88b2ad23547", size = 113757972, upload-time = "2026-01-21T16:24:39.516Z" },
+]
+
+[[package]]
+name = "torch"
+version = "2.10.0+cu128"
+source = { registry = "https://download.pytorch.org/whl/cu128" }
+resolution-markers = [
+ "sys_platform == 'linux'",
+]
+dependencies = [
+ { name = "cuda-bindings", marker = "sys_platform == 'linux'" },
+ { name = "filelock", marker = "sys_platform == 'linux'" },
+ { name = "fsspec", marker = "sys_platform == 'linux'" },
+ { name = "jinja2", marker = "sys_platform == 'linux'" },
+ { name = "networkx", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cublas-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cuda-cupti-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cuda-nvrtc-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cuda-runtime-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cudnn-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cufft-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cufile-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-curand-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cusolver-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cusparse-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-cusparselt-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nccl-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nvjitlink-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nvshmem-cu12", marker = "sys_platform == 'linux'" },
+ { name = "nvidia-nvtx-cu12", marker = "sys_platform == 'linux'" },
+ { name = "setuptools", marker = "sys_platform == 'linux'" },
+ { name = "sympy", marker = "sys_platform == 'linux'" },
+ { name = "triton", marker = "sys_platform == 'linux'" },
+ { name = "typing-extensions", marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://download-r2.pytorch.org/whl/cu128/torch-2.10.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:6f09cdf2415516be028ae82e6b985bcfc3eac37bc52ab401142689f6224516ca", upload-time = "2026-01-21T15:22:03Z" },
+ { url = "https://download-r2.pytorch.org/whl/cu128/torch-2.10.0%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:628e89bd5110ced7debee2a57c69959725b7fbc64eab81a39dd70e46c7e28ba5", upload-time = "2026-01-21T15:22:11Z" },
+]
+
+[[package]]
+name = "torch"
+version = "2.11.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "sys_platform == 'darwin'",
+]
+dependencies = [
+ { name = "filelock", marker = "sys_platform == 'darwin'" },
+ { name = "fsspec", marker = "sys_platform == 'darwin'" },
+ { name = "jinja2", marker = "sys_platform == 'darwin'" },
+ { name = "networkx", marker = "sys_platform == 'darwin'" },
+ { name = "setuptools", marker = "sys_platform == 'darwin'" },
+ { name = "sympy", marker = "sys_platform == 'darwin'" },
+ { name = "typing-extensions", marker = "sys_platform == 'darwin'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6f/8b/69e3008d78e5cee2b30183340cc425081b78afc5eff3d080daab0adda9aa/torch-2.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b5866312ee6e52ea625cd211dcb97d6a2cdc1131a5f15cc0d87eec948f6dd34", size = 80606338, upload-time = "2026-03-23T18:11:34.781Z" },
+]
+
+[[package]]
+name = "torchvision"
+version = "0.25.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "sys_platform != 'darwin' and sys_platform != 'linux'",
+]
+dependencies = [
+ { name = "numpy", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "pillow", marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+ { name = "torch", version = "2.10.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ad/16/8f650c2e288977cf0f8f85184b90ee56ed170a4919347fc74ee99286ed6f/torchvision-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:f9c55ae8d673ab493325d1267cbd285bb94d56f99626c00ac4644de32a59ede3", size = 4303059, upload-time = "2026-01-21T16:27:11.08Z" },
+]
+
+[[package]]
+name = "torchvision"
+version = "0.25.0+cu128"
+source = { registry = "https://download.pytorch.org/whl/cu128" }
+resolution-markers = [
+ "sys_platform == 'linux'",
+]
+dependencies = [
+ { name = "numpy", marker = "sys_platform == 'linux'" },
+ { name = "pillow", marker = "sys_platform == 'linux'" },
+ { name = "torch", version = "2.10.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux'" },
+]
+wheels = [
+ { url = "https://download-r2.pytorch.org/whl/cu128/torchvision-0.25.0%2Bcu128-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:8623e534ef6a815bd6407d4b52dd70c7154e2eda626ad4b9cb895d36c5a3305b", upload-time = "2026-01-21T22:32:23Z" },
+ { url = "https://download-r2.pytorch.org/whl/cu128/torchvision-0.25.0%2Bcu128-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:1255a0ca2bf987acf9f103b96c5c4cfe3415fc4a1eef17fa08af527a04a4f573", upload-time = "2026-01-21T22:32:24Z" },
+]
+
+[[package]]
+name = "torchvision"
+version = "0.26.0"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "sys_platform == 'darwin'",
+]
+dependencies = [
+ { name = "numpy", marker = "sys_platform == 'darwin'" },
+ { name = "pillow", marker = "sys_platform == 'darwin'" },
+ { name = "torch", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ae/e7/56b47cc3b132aea90ccce22bcb8975dec688b002150012acc842846039d0/torchvision-0.26.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c409e1c3fdebec7a3834465086dbda8bf7680eff79abf7fd2f10c6b59520a7a4", size = 1863502, upload-time = "2026-03-23T18:12:57.326Z" },
+]
+
+[[package]]
+name = "tqdm"
+version = "4.70.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/21/3b/6c24bec5be5e743ffd99576daa5cc077722fc7d5bbc00bd133fa0c698dc6/tqdm-4.70.0.tar.gz", hash = "sha256:55b0b0dbd97462d06ebee91e4dac24ed4d4702be82b24f07e6c1d27e08cea220", size = 795438, upload-time = "2026-07-27T11:33:15.271Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f9/1c/01bfd571a64e7f270e6bab5e33777debe0edc56759233ce84f27dec92d14/tqdm-4.70.0-py3-none-any.whl", hash = "sha256:7f585706bfddbdebf89daac705b2dfcc16890130727d3197ca62c732b4310953", size = 80184, upload-time = "2026-07-27T11:33:13.167Z" },
+]
+
+[[package]]
+name = "transformers"
+version = "5.16.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "huggingface-hub" },
+ { name = "numpy" },
+ { name = "packaging" },
+ { name = "pyyaml" },
+ { name = "regex" },
+ { name = "safetensors" },
+ { name = "tokenizers" },
+ { name = "tqdm" },
+ { name = "typer" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ad/2e/ba418680ab901dae269360bb8642485eae04f1af91ee2ebb8bd6f3607305/transformers-5.16.1.tar.gz", hash = "sha256:17b0eac726ddc55e84ac58946063e0c6d37fd000c456b581f050ea0f4e822869", size = 9650542, upload-time = "2026-08-26T14:48:58.789Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0d/4d/ee3728674c0bbc637bb4af88ccf0be697f92e4e90b55f5dc110c44d61b61/transformers-5.16.1-py3-none-any.whl", hash = "sha256:2f2d5b98a5ad3718713653734298fa620754ed683702a635ebb587df3ed29c7e", size = 12080592, upload-time = "2026-08-26T14:48:55.083Z" },
+]
+
+[[package]]
+name = "triton"
+version = "3.6.0"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/17/5d/08201db32823bdf77a0e2b9039540080b2e5c23a20706ddba942924ebcd6/triton-3.6.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:374f52c11a711fd062b4bfbb201fd9ac0a5febd28a96fb41b4a0f51dde3157f4", size = 176128243, upload-time = "2026-01-20T16:16:07.857Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/a8/cdf8b3e4c98132f965f88c2313a4b493266832ad47fb52f23d14d4f86bb5/triton-3.6.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74caf5e34b66d9f3a429af689c1c7128daba1d8208df60e81106b115c00d6fca", size = 188266850, upload-time = "2026-01-20T16:00:43.041Z" },
+]
+
+[[package]]
+name = "typer"
+version = "0.27.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "annotated-doc" },
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "rich" },
+ { name = "shellingham" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/16/f7/57713ba479fd405eb76de31404b2c744c289e336b2d999511ebf51e496f7/typer-0.27.2.tar.gz", hash = "sha256:269b7eb9d3c202ca84b4bc9618cb04ebb43d3d4d1e567e4c768607232c05f945", size = 204045, upload-time = "2026-08-28T10:26:55.046Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/dc/bf/205d0004930ede8f542fb58f601526fccf4ae7626075ca1e6c4de5d3d652/typer-0.27.2-py3-none-any.whl", hash = "sha256:b3a5fc4342d5fc8fda8fc3010b1cf117e9249aab7fae800c2eff62fd3842d97d", size = 123130, upload-time = "2026-08-28T10:26:53.752Z" },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
+]
+
+[[package]]
+name = "websockets"
+version = "15.0.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/21/e6/26d09fab466b7ca9c7737474c52be4f76a40301b08362eb2dbc19dcc16c1/websockets-15.0.1.tar.gz", hash = "sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee", size = 177016, upload-time = "2025-03-05T20:03:41.606Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/6b/4545a0d843594f5d0771e86463606a3988b5a09ca5123136f8a76580dd63/websockets-15.0.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3", size = 175437, upload-time = "2025-03-05T20:02:16.706Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/71/809a0f5f6a06522af902e0f2ea2757f71ead94610010cf570ab5c98e99ed/websockets-15.0.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665", size = 173096, upload-time = "2025-03-05T20:02:18.832Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/69/1a681dd6f02180916f116894181eab8b2e25b31e484c5d0eae637ec01f7c/websockets-15.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2", size = 173332, upload-time = "2025-03-05T20:02:20.187Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/02/0073b3952f5bce97eafbb35757f8d0d54812b6174ed8dd952aa08429bcc3/websockets-15.0.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215", size = 183152, upload-time = "2025-03-05T20:02:22.286Z" },
+ { url = "https://files.pythonhosted.org/packages/74/45/c205c8480eafd114b428284840da0b1be9ffd0e4f87338dc95dc6ff961a1/websockets-15.0.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0af68c55afbd5f07986df82831c7bff04846928ea8d1fd7f30052638788bc9b5", size = 182096, upload-time = "2025-03-05T20:02:24.368Z" },
+ { url = "https://files.pythonhosted.org/packages/14/8f/aa61f528fba38578ec553c145857a181384c72b98156f858ca5c8e82d9d3/websockets-15.0.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65", size = 182523, upload-time = "2025-03-05T20:02:25.669Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/6d/0267396610add5bc0d0d3e77f546d4cd287200804fe02323797de77dbce9/websockets-15.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe", size = 182790, upload-time = "2025-03-05T20:02:26.99Z" },
+ { url = "https://files.pythonhosted.org/packages/02/05/c68c5adbf679cf610ae2f74a9b871ae84564462955d991178f95a1ddb7dd/websockets-15.0.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:5d54b09eba2bada6011aea5375542a157637b91029687eb4fdb2dab11059c1b4", size = 182165, upload-time = "2025-03-05T20:02:30.291Z" },
+ { url = "https://files.pythonhosted.org/packages/29/93/bb672df7b2f5faac89761cb5fa34f5cec45a4026c383a4b5761c6cea5c16/websockets-15.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597", size = 182160, upload-time = "2025-03-05T20:02:31.634Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/83/de1f7709376dc3ca9b7eeb4b9a07b4526b14876b6d372a4dc62312bebee0/websockets-15.0.1-cp312-cp312-win32.whl", hash = "sha256:c338ffa0520bdb12fbc527265235639fb76e7bc7faafbb93f6ba80d9c06578a9", size = 176395, upload-time = "2025-03-05T20:02:33.017Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/71/abf2ebc3bbfa40f391ce1428c7168fb20582d0ff57019b69ea20fa698043/websockets-15.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcd5cf9e305d7b8338754470cf69cf81f420459dbae8a3b40cee57417f4614a7", size = 176841, upload-time = "2025-03-05T20:02:34.498Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743, upload-time = "2025-03-05T20:03:39.41Z" },
+]
diff --git a/openpi-umi/.github/workflows/pre-commit.yml b/openpi-umi/.github/workflows/pre-commit.yml
new file mode 100644
index 0000000000000000000000000000000000000000..157755c29c97eb062acc5561c0db257b92caf801
--- /dev/null
+++ b/openpi-umi/.github/workflows/pre-commit.yml
@@ -0,0 +1,17 @@
+name: pre-commit
+on:
+ push:
+ branches:
+ - main
+ pull_request:
+ branches:
+ - "*"
+jobs:
+ pre-commit:
+ runs-on: ubuntu-latest
+ env:
+ GIT_LFS_SKIP_SMUDGE: true
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v3
+ - uses: pre-commit/action@v3.0.1
diff --git a/openpi-umi/.github/workflows/test.yml b/openpi-umi/.github/workflows/test.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f24cac2756217ae3031e5dc15ebd8df2aec2d419
--- /dev/null
+++ b/openpi-umi/.github/workflows/test.yml
@@ -0,0 +1,31 @@
+name: Test
+on:
+ pull_request:
+ branches:
+ - "*"
+
+jobs:
+ run_tests:
+ name: Run Tests
+ runs-on: openpi-verylarge
+ env:
+ GIT_LFS_SKIP_SMUDGE: true
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install FFmpeg dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y ffmpeg libavcodec-dev libavformat-dev libavutil-dev
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v5
+
+ - name: Set up Python
+ run: uv python install
+
+ - name: Install the project
+ run: uv sync --all-extras --dev
+
+ - name: Run tests
+ run: uv run pytest --strict-markers -m "not manual"
diff --git a/openpi-umi/.gitignore b/openpi-umi/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..94598336e22a8e7915afb3d9675ac7785132b766
--- /dev/null
+++ b/openpi-umi/.gitignore
@@ -0,0 +1,173 @@
+# Data directories.
+assets/
+checkpoints/
+data/
+wandb/
+.vscode
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+# in version control.
+# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
+.pdm.toml
+.pdm-python
+.pdm-build/
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+#.idea/
+
+/model
+
+# Eval outputs (plots / .npz trajectory dumps — generated, not code)
+eval/outputs/
diff --git a/openpi-umi/.pre-commit-config.yaml b/openpi-umi/.pre-commit-config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..f98be5a132f617e321aa5dd3ac42b2b878eff089
--- /dev/null
+++ b/openpi-umi/.pre-commit-config.yaml
@@ -0,0 +1,16 @@
+exclude: third_party/
+
+repos:
+ - repo: https://github.com/astral-sh/uv-pre-commit
+ # uv version.
+ rev: 0.5.14
+ hooks:
+ - id: uv-lock
+ - repo: https://github.com/astral-sh/ruff-pre-commit
+ # Ruff version.
+ rev: v0.8.6
+ hooks:
+ # Run the linter.
+ - id: ruff
+ args: [--fix]
+ - id: ruff-format
\ No newline at end of file
diff --git a/openpi-umi/.python-version b/openpi-umi/.python-version
new file mode 100644
index 0000000000000000000000000000000000000000..e4fba2183587225f216eeada4c78dfab6b2e65f5
--- /dev/null
+++ b/openpi-umi/.python-version
@@ -0,0 +1 @@
+3.12
diff --git a/openpi-umi/CONTRIBUTING.md b/openpi-umi/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..a8f3e80bab3c6a5fc45ed251173f3eebd829a959
--- /dev/null
+++ b/openpi-umi/CONTRIBUTING.md
@@ -0,0 +1,33 @@
+# Contributing to openpi
+
+We welcome contributions, improvements, and modifications. Everyone is welcome to use openpi in accordance to the [license](LICENSE). Contributors are also welcome to submit bug reports, feature requests, and pull requests. We can't promise to approve every pull request, and we are a small team with limited bandwidth to review all requests, but we'll give it our best effort. Specifics are described below.
+
+## Issues and feature requests
+
+You are welcome to use the Github [discussion](https://github.com/Physical-Intelligence/openpi/discussions) feature if you would like to discuss something that is not directly reporting an issue or making a feature request. This is suitable for questions about how to use some aspect of openpi, or other topics.
+
+If you found a bug or other issue, please first check that the issue was not already reported (use the search bar on Github under Issues). If the issue has not yet been reported, please include this information when filing a Github issue:
+
+- Your OS type and version and the version of Python you are using
+- Code that allows us to reproduce your bug, including all dependencies
+- Traceback of any exception
+- Any other information that would help us, such as a screenshot
+
+In order for us to address any issue, we must be able to reproduce it, so if you encountered the issue after making modifications to openpi, please reproduce the issue without any other modifications and provide a code snippet that allows us to quickly reproduce the problem on `main`.
+
+If you would like to submit a feature request, please check that the feature request does not already exist, and please provide the following information:
+
+- The motivation for the feature
+- A description of the problem you are trying to solve or your use case
+- Enough information for us to understand the nature of the request
+- Some information for how you intend to use it (this might help us in understanding the motivation!)
+
+We can't promise to support every feature request, but it is helpful to us to know the use cases that you are interested in!
+
+## Submitting a pull request
+
+If you implemented support for a new robot or environment, or some other new feature, we welcome pull requests (PRs) to openpi. We encourage you to create a [feature request](https://github.com/Physical-Intelligence/openpi/issues) or make a post on the [discussion](https://github.com/Physical-Intelligence/openpi/discussions) board before starting to work on your PR, if you would like to get a sense for whether we are likely to approve your PR if it is submitted. Since we are a small team with limited ability to provide maintenance and support, we may not accept all PRs (e.g., if we believe it would make the code harder to maintain, or if reviewing the PR is out of scope for us), so contacting us in advance is a good way to get a sense for whether your PR is likely to get approved for merging into openpi directly. But even if it isn't, you are of course more than welcome to maintain your own fork with whatever modifications you would like. When creating PRs, we recommend every contribution to consider the following:
+
+- Make sure that your PR has a clear title and description
+- Run `pre-commit` (install using `pre-commit install` first), and run `ruff check .` and `ruff format .`
+- Make sure your PR passes all tests
diff --git a/openpi-umi/LICENSE b/openpi-umi/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f49a4e16e68b128803cc2dcea614603632b04eac
--- /dev/null
+++ b/openpi-umi/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.
\ No newline at end of file
diff --git a/openpi-umi/LICENSE_GEMMA.txt b/openpi-umi/LICENSE_GEMMA.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e0f8930d83fe9eef924c0eed50ee0e572eb471fa
--- /dev/null
+++ b/openpi-umi/LICENSE_GEMMA.txt
@@ -0,0 +1,77 @@
+Gemma Terms of Use
+
+Last modified: February 21, 2024
+
+By using, reproducing, modifying, distributing, performing or displaying any portion or element of Gemma, Model Derivatives including via any Hosted Service, (each as defined below) (collectively, the "Gemma Services") or otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement.
+
+Section 1: DEFINITIONS
+1.1 Definitions
+(a) "Agreement" or "Gemma Terms of Use" means these terms and conditions that govern the use, reproduction, Distribution or modification of the Gemma Services and any terms and conditions incorporated by reference.
+
+(b) "Distribution" or "Distribute" means any transmission, publication, or other sharing of Gemma or Model Derivatives to a third party, including by providing or making Gemma or its functionality available as a hosted service via API, web access, or any other electronic or remote means ("Hosted Service").
+
+(c) "Gemma" means the set of machine learning language models, trained model weights and parameters identified at ai.google.dev/gemma, regardless of the source that you obtained it from.
+
+(d) "Google" means Google LLC.
+
+(e) "Model Derivatives" means all (i) modifications to Gemma, (ii) works based on Gemma, or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Gemma, to that model in order to cause that model to perform similarly to Gemma, including distillation methods that use intermediate data representations or methods based on the generation of synthetic data Outputs by Gemma for training that model. For clarity, Outputs are not deemed Model Derivatives.
+
+(f) "Output" means the information content output of Gemma or a Model Derivative that results from operating or otherwise using Gemma or the Model Derivative, including via a Hosted Service.
+
+1.2
+As used in this Agreement, "including" means "including without limitation".
+
+Section 2: ELIGIBILITY AND USAGE
+2.1 Eligibility
+You represent and warrant that you have the legal capacity to enter into this Agreement (including being of sufficient age of consent). If you are accessing or using any of the Gemma Services for or on behalf of a legal entity, (a) you are entering into this Agreement on behalf of yourself and that legal entity, (b) you represent and warrant that you have the authority to act on behalf of and bind that entity to this Agreement and (c) references to "you" or "your" in the remainder of this Agreement refers to both you (as an individual) and that entity.
+
+2.2 Use
+You may use, reproduce, modify, Distribute, perform or display any of the Gemma Services only in accordance with the terms of this Agreement, and must not violate (or encourage or permit anyone else to violate) any term of this Agreement.
+
+Section 3: DISTRIBUTION AND RESTRICTIONS
+3.1 Distribution and Redistribution
+You may reproduce or Distribute copies of Gemma or Model Derivatives if you meet all of the following conditions:
+
+You must include the use restrictions referenced in Section 3.2 as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Gemma or Model Derivatives and you must provide notice to subsequent users you Distribute to that Gemma or Model Derivatives are subject to the use restrictions in Section 3.2.
+You must provide all third party recipients of Gemma or Model Derivatives a copy of this Agreement.
+You must cause any modified files to carry prominent notices stating that you modified the files.
+All Distributions (other than through a Hosted Service) must be accompanied by a "Notice" text file that contains the following notice: "Gemma is provided under and subject to the Gemma Terms of Use found at ai.google.dev/gemma/terms".
+You may add your own intellectual property statement to your modifications and, except as set forth in this Section, may provide additional or different terms and conditions for use, reproduction, or Distribution of your modifications, or for any such Model Derivatives as a whole, provided your use, reproduction, modification, Distribution, performance, and display of Gemma otherwise complies with the terms and conditions of this Agreement. Any additional or different terms and conditions you impose must not conflict with the terms of this Agreement.
+
+3.2 Use Restrictions
+You must not use any of the Gemma Services:
+
+for the restricted uses set forth in the Gemma Prohibited Use Policy at ai.google.dev/gemma/prohibited_use_policy ("Prohibited Use Policy"), which is hereby incorporated by reference into this Agreement; or
+in violation of applicable laws and regulations.
+To the maximum extent permitted by law, Google reserves the right to restrict (remotely or otherwise) usage of any of the Gemma Services that Google reasonably believes are in violation of this Agreement.
+
+3.3 Generated Output
+Google claims no rights in Outputs you generate using Gemma. You and your users are solely responsible for Outputs and their subsequent uses.
+
+Section 4: ADDITIONAL PROVISIONS
+4.1 Updates
+Google may update Gemma from time to time, and you must make reasonable efforts to use the latest version of Gemma.
+
+4.2 Trademarks
+Nothing in this Agreement grants you any rights to use Google's trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between you and Google. Google reserves any rights not expressly granted herein.
+
+4.3 DISCLAIMER OF WARRANTY
+UNLESS REQUIRED BY APPLICABLE LAW, THE GEMMA SERVICES, AND OUTPUTS, ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING 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, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR OR DISTRIBUTING ANY OF THE GEMMA SERVICES OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR USE OR DISTRIBUTION OF ANY OF THE GEMMA SERVICES OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
+
+4.4 LIMITATION OF LIABILITY
+TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY, CONTRACT, OR OTHERWISE, UNLESS REQUIRED BY APPLICABLE LAW, SHALL GOOGLE OR ITS AFFILIATES BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO, ANY OF THE GEMMA SERVICES OR OUTPUTS EVEN IF GOOGLE OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+4.5 Term, Termination, and Survival
+The term of this Agreement will commence upon your acceptance of this Agreement (including acceptance by your use, modification, or Distribution, reproduction, performance or display of any portion or element of the Gemma Services) and will continue in full force and effect until terminated in accordance with the terms of this Agreement. Google may terminate this Agreement if you are in breach of any term of this Agreement. Upon termination of this Agreement, you must delete and cease use and Distribution of all copies of Gemma and Model Derivatives in your possession or control. Sections 1, 2.1, 3.3, 4.2 to 4.9 shall survive the termination of this Agreement.
+
+4.6 Governing Law and Jurisdiction
+This Agreement will be governed by the laws of the State of California without regard to choice of law principles. The UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The state and federal courts of Santa Clara County, California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
+
+4.7 Severability
+If any provision of this Agreement is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
+
+4.8 Entire Agreement
+This Agreement states all the terms agreed between the parties and supersedes all other agreements between the parties as of the date of acceptance relating to its subject matter.
+
+4.9 No Waiver
+Google will not be treated as having waived any rights by not exercising (or delaying the exercise of) any rights under this Agreement.
\ No newline at end of file
diff --git a/openpi-umi/README.md b/openpi-umi/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..d85946add808c19a105e86c9e09d2b904971ae5c
--- /dev/null
+++ b/openpi-umi/README.md
@@ -0,0 +1,193 @@
+# 中文 / English
+
+[中文](#zh) · [English](#en)
+
+
+
+# OpenPI / π0.5 · 双臂UMI衣物操作
+
+基于[OpenPI](https://github.com/Physical-Intelligence/openpi)的双臂UMI适配,支持PyTorch π0.5训练、策略加载与推理。机器人部署使用相邻的[flexiv-umi-infer](../flexiv-umi-infer/README.md)。
+
+## 环境安装
+
+使用Linux(glibc ≥2.31)、NVIDIA GPU及Python **3.12**。项目的`.python-version`固定为3.12,依赖版本由`uv.lock`管理。在本目录运行:
+
+```bash
+uv python install 3.12
+uv sync --frozen --python 3.12
+source .venv/bin/activate
+```
+
+已有Python3.12时可跳过第一条命令。安装需要访问依赖源,并准备与环境匹配的CUDA驱动。FLUX与OpenPI使用独立虚拟环境。
+
+## 数据格式
+
+`DATA_ROOT`指向包含独立LeRobot v3 episode目录的根目录,例如`/path/to/sample_data/demonstrations`,多根目录可用冒号分隔。
+
+| 项目 | 约定 |
+| --- | --- |
+| 视频 | observation.images.left_ego、observation.images.right_ego |
+| 原始state/action | float32[16],左手8维在前,每手[x,y,z,qw,qx,qy,qz,gripper_deg] |
+| 单位 | 位置为米,四元数wxyz,夹爪为度 |
+| 模型输入/目标 | 双臂20维相对表示,每手3维平移、6维旋转、1维夹爪 |
+| 模型动作头 | 内部填充到32维,UMI输出取前20维 |
+| 动作时间窗 | 50步,30Hz目标时间网格 |
+
+每只手以当前位姿为独立anchor;状态包含前帧相对当前帧的位姿及当前夹爪,动作包含未来相对位姿及夹爪。rot6d拼接旋转矩阵前两列。
+
+## 训练
+
+准备兼容的PyTorch π0.5基础权重与tokenizer,在已激活的环境中运行:
+
+```bash
+DATA_ROOT=/path/to/sample_data/demonstrations \
+PYTORCH_WEIGHT_PATH=/path/to/pi05_base_pytorch \
+TOKENIZER_DIR=/path/to/tokenizer_root \
+NUM_GPUS=1 \
+BATCH_SIZE=16 \
+bash scripts/train_umi_v3.sh
+```
+
+默认执行30步smoke run。脚本建立episode manifest、计算归一化统计,再通过torchrun启动训练;数据根目录变化时自动重算统计,`FORCE_NORM=1`可强制重算。checkpoint输出到`checkpoints/pi05_umi_v3//`。
+
+单机多GPU微调示例:
+
+```bash
+DATA_ROOT=/path/to/fold_clothes_training_data \
+PYTORCH_WEIGHT_PATH=/path/to/compatible_pi05_checkpoint \
+TOKENIZER_DIR=/path/to/tokenizer_root \
+NUM_GPUS=8 \
+NUM_EPOCHS=2 \
+BATCH_SIZE=1280 \
+EXP_NAME=fold_clothes \
+bash scripts/train_umi_v3.sh \
+--save-interval 1 \
+--lr-schedule.warmup-steps 0 \
+--lr-schedule.hold-steps 1.5 \
+--lr-schedule.decay-steps 2 \
+--lr-schedule.peak-lr 7.5e-5 \
+--lr-schedule.decay-lr 7.5e-6 \
+--lr-schedule.decay-shape linear \
+--no-gradient-checkpointing
+```
+
+`BATCH_SIZE`为全局批量;按显存和进程数调整。设置`NUM_EPOCHS`时,调度按epoch解释。可用`OPENPI_UMI_V3_MANIFEST`指定manifest、`OPENPI_UMI_V3_TARGET_FPS`指定目标频率,`OPENPI_UMI_V3_SKIP_VIDEOS=1`用于归一化统计计算。
+
+## 推理与机器人部署
+
+模型权重、tokenizer和归一化统计需单独配置。tokenizer目录应包含`paligemma-3b-pt-224/tokenizer.model`,推理统计使用checkpoint配套的`assets/umi_v3/`内容。
+
+从本目录安装部署接口,再回到`inference_code/`启动服务:
+
+```bash
+uv pip install --python .venv/bin/python -e '../flexiv-umi-infer[pi05]'
+cd ..
+set -a; source /path/to/private_inference.env; set +a
+PI05_PYTHON="$PWD/openpi-umi/.venv/bin/python" bash scripts/run_pi05_server.sh
+```
+
+私有配置可参考`configs/inference.env.example`,填写模型资源路径、tokenizer和设备标定。启动脚本应用与模型匹配的transformers替换;离线环境应提前准备tokenizer。
+
+客户端需提供前帧/当前帧位姿和两路腕图像。`create_trained_policy`的flat-buffer repack需显式配置;`UmiOutputs`选取前20维后,由部署接口根据当前anchor还原相对动作,并执行相机/末端/机器人坐标与夹爪单位转换。接口约定见[INFERENCE_CONTRACT.md](../docs/INFERENCE_CONTRACT.md)。
+
+JAX权重转PyTorch可使用`examples/convert_jax_model_to_pytorch.py`,参数为`--checkpoint-dir`、`--config-name`和`--output-path`。
+
+## 许可证
+
+见[LICENSE](LICENSE)与[LICENSE_GEMMA.txt](LICENSE_GEMMA.txt)。模型资源与第三方依赖遵循各自许可。
+
+---
+
+
+
+# OpenPI / π0.5 for Bimanual UMI Garment Manipulation
+
+A bimanual UMI adaptation of [OpenPI](https://github.com/Physical-Intelligence/openpi), supporting PyTorch π0.5 training, policy loading and inference. Robot deployment uses the adjacent [flexiv-umi-infer](../flexiv-umi-infer/README.md) package.
+
+## Installation
+
+Use Linux (glibc ≥2.31), an NVIDIA GPU and Python **3.12**. The project pins Python 3.12 in `.python-version` and manages dependency versions with `uv.lock`. Run from this directory:
+
+```bash
+uv python install 3.12
+uv sync --frozen --python 3.12
+source .venv/bin/activate
+```
+
+Skip the first command if Python 3.12 is already available. Installation requires access to dependency sources and a compatible CUDA driver. Use separate virtual environments for FLUX and OpenPI.
+
+## Data format
+
+Set `DATA_ROOT` to a root of independent LeRobot v3 episode directories, such as `/path/to/sample_data/demonstrations`. Separate multiple roots with colons.
+
+| Item | Convention |
+| --- | --- |
+| Video | observation.images.left_ego, observation.images.right_ego |
+| Raw state/action | float32[16], left hand first; each hand is [x,y,z,qw,qx,qy,qz,gripper_deg] |
+| Units | Position in metres, wxyz quaternions, gripper in degrees |
+| Model input/targets | 20 relative dimensions: translation3, rotation6 and gripper1 per hand |
+| Model action head | Padded internally to 32 dimensions; UMI returns the first 20 |
+| Action window | 50 steps on a 30 Hz target time grid |
+
+Each hand has its own current-pose anchor. State includes the previous pose relative to the current pose and the current gripper value; actions include future relative poses and gripper values. Rot6d concatenates the first two rotation-matrix columns.
+
+## Training
+
+Prepare compatible PyTorch π0.5 base weights and a tokenizer, then run in the activated environment:
+
+```bash
+DATA_ROOT=/path/to/sample_data/demonstrations \
+PYTORCH_WEIGHT_PATH=/path/to/pi05_base_pytorch \
+TOKENIZER_DIR=/path/to/tokenizer_root \
+NUM_GPUS=1 \
+BATCH_SIZE=16 \
+bash scripts/train_umi_v3.sh
+```
+
+The default is a 30-step smoke run. The script builds an episode manifest, computes normalization statistics and starts training with torchrun. Statistics are recomputed when the data root changes; use `FORCE_NORM=1` to force recomputation. Checkpoints are written to `checkpoints/pi05_umi_v3//`.
+
+Single-node multi-GPU fine-tuning example:
+
+```bash
+DATA_ROOT=/path/to/fold_clothes_training_data \
+PYTORCH_WEIGHT_PATH=/path/to/compatible_pi05_checkpoint \
+TOKENIZER_DIR=/path/to/tokenizer_root \
+NUM_GPUS=8 \
+NUM_EPOCHS=2 \
+BATCH_SIZE=1280 \
+EXP_NAME=fold_clothes \
+bash scripts/train_umi_v3.sh \
+--save-interval 1 \
+--lr-schedule.warmup-steps 0 \
+--lr-schedule.hold-steps 1.5 \
+--lr-schedule.decay-steps 2 \
+--lr-schedule.peak-lr 7.5e-5 \
+--lr-schedule.decay-lr 7.5e-6 \
+--lr-schedule.decay-shape linear \
+--no-gradient-checkpointing
+```
+
+`BATCH_SIZE` is global; adjust it for memory and worker count. With `NUM_EPOCHS`, scheduling is interpreted in epochs. `OPENPI_UMI_V3_MANIFEST` selects a manifest, `OPENPI_UMI_V3_TARGET_FPS` sets the target frequency and `OPENPI_UMI_V3_SKIP_VIDEOS=1` supports normalization-statistics computation.
+
+## Inference and robot deployment
+
+Configure model weights, tokenizer and normalization statistics separately. The tokenizer directory must contain `paligemma-3b-pt-224/tokenizer.model`. Use the checkpoint's corresponding `assets/umi_v3/` statistics.
+
+Install the deployment interface from this directory, then return to `inference_code/` to start the service:
+
+```bash
+uv pip install --python .venv/bin/python -e '../flexiv-umi-infer[pi05]'
+cd ..
+set -a; source /path/to/private_inference.env; set +a
+PI05_PYTHON="$PWD/openpi-umi/.venv/bin/python" bash scripts/run_pi05_server.sh
+```
+
+Use `configs/inference.env.example` as a private configuration template for model resources, tokenizer and cell calibration. The launcher applies the model-compatible transformers replacements. Prepare the tokenizer before use in offline environments.
+
+Clients provide previous/current poses and both wrist images. Configure the flat-buffer repack explicitly for `create_trained_policy`. After `UmiOutputs` selects 20 dimensions, the deployment interface restores relative actions using the current anchor and applies camera/EEF/robot-frame and gripper-unit transforms. See [INFERENCE_CONTRACT.md](../docs/INFERENCE_CONTRACT.md).
+
+For JAX-to-PyTorch conversion, use `examples/convert_jax_model_to_pytorch.py` with `--checkpoint-dir`, `--config-name` and `--output-path`.
+
+## License
+
+See [LICENSE](LICENSE) and [LICENSE_GEMMA.txt](LICENSE_GEMMA.txt). Model resources and third-party dependencies retain their respective licenses.
diff --git a/openpi-umi/docs/folding-checkpoint.md b/openpi-umi/docs/folding-checkpoint.md
new file mode 100644
index 0000000000000000000000000000000000000000..4ae7c1ea611886bb0bd77cc0ecd1decf731a40ad
--- /dev/null
+++ b/openpi-umi/docs/folding-checkpoint.md
@@ -0,0 +1,48 @@
+# π0.5 cloth-folding inference checkpoint
+
+This inventory was supplied by the model owner. Remote model bytes and metadata have not been downloaded or executed during this documentation update. Public paths below are neutral examples; internal job IDs, experiment names and storage addresses are omitted.
+
+## Provided checkpoint
+
+```text
+checkpoints/pi05_fold_clothes/epoch_2/
+ model.safetensors
+ metadata.pt
+ assets/umi_v3/norm_stats.json
+```
+
+- Model/config family: π0.5, `pi05_umi_v3`.
+- Selected checkpoint: epoch 2; epoch 1 was also reported in training storage, but only epoch 2 was reported in the supplied remote location.
+- Reported model-file size: 7,473,091,464 bytes.
+- `optimizer.pt` is not in the reported copy. Its absence does **not** prevent inference; it does prevent an exact optimizer-state training resume from that copy alone.
+- Use `assets/umi_v3/norm_stats.json` from this checkpoint. Do not replace it with statistics recomputed from the one-hour sample.
+- `metadata.pt` is supplied for checkpoint metadata; the generic `create_trained_policy` PyTorch path is driven by the training/model config, safetensors weights and normalization statistics. It does not require loading optimizer state for inference.
+
+## Training information and provenance
+
+The supplied experiment label indicates 16 workers, global batch 1280 (80 per worker), 2 epochs, action horizon 50, peak LR 7.5e-5, zero warmup, a 1.5-epoch hold and linear cooldown. These are label-derived details, not a replacement for the saved run configuration. Confirm them against the run configuration before presenting them as a fully reproduced experiment.
+
+The existing shell launcher is single-node. The README's 8-worker command is a portable example, not the reported 16-worker run. Do not present it as the exact multi-node launch used for the video.
+
+## Policy construction
+
+Prepare the patched transformers environment described in the main README. With a compatible runtime, the generic loading interface is:
+
+```python
+from pathlib import Path
+from openpi.policies import policy_config
+from openpi.training import config as training_config
+
+checkpoint = Path("/path/to/checkpoints/pi05_fold_clothes/epoch_2")
+config = training_config.get_config("pi05_umi_v3")
+data_config = config.data.create(config.assets_dirs, config.model)
+policy = policy_config.create_trained_policy(
+ config,
+ checkpoint,
+ repack_transforms=data_config.repack_transforms,
+ norm_stats_path=checkpoint / "assets/umi_v3/norm_stats.json",
+ pytorch_device="cuda",
+)
+```
+
+This illustrates the existing API and explicit UMI repack/statistics wiring. It has not been run against the remote weights. `policy.infer` still needs both wrist images, previous/current 16-D pose states, and the prompt in the agreed observation schema. It returns a model-space action chunk, not directly executable Flexiv commands. A robot adapter must preserve the per-chunk anchors and restore absolute target poses with the correct calibration and gripper units.
diff --git a/openpi-umi/docs/norm_stats.md b/openpi-umi/docs/norm_stats.md
new file mode 100644
index 0000000000000000000000000000000000000000..77163f8cfa915923d463c0b3e8920721f87b0c65
--- /dev/null
+++ b/openpi-umi/docs/norm_stats.md
@@ -0,0 +1,69 @@
+# Normalization statistics
+
+Following common practice, our models normalize the proprioceptive state inputs and action targets during policy training and inference. The statistics used for normalization are computed over the training data and stored alongside the model checkpoint.
+
+## Reloading normalization statistics
+
+When you fine-tune one of our models on a new dataset, you need to decide whether to (A) reuse existing normalization statistics or (B) compute new statistics over your new training data. Which option is better for you depends on the similarity of your robot and task to the robot and task distribution in the pre-training dataset. Below, we list all the available pre-training normalization statistics for each model.
+
+**If your target robot matches one of these pre-training statistics, consider reloading the same normalization statistics.** By reloading the normalization statistics, the actions in your dataset will be more "familiar" to the model, which can lead to better performance. You can reload the normalization statistics by adding an `AssetsConfig` to your training config that points to the corresponding checkpoint directory and normalization statistics ID, like below for the `Trossen` (aka ALOHA) robot statistics of the `pi0_base` checkpoint:
+
+```python
+TrainConfig(
+ ...
+ data=LeRobotAlohaDataConfig(
+ ...
+ assets=AssetsConfig(
+ assets_dir="gs://openpi-assets/checkpoints/pi0_base/assets",
+ asset_id="trossen",
+ ),
+ ),
+)
+```
+
+For an example of a full training config that reloads normalization statistics, see the `pi0_aloha_pen_uncap` config in the [training config file](https://github.com/physical-intelligence/openpi/blob/main/src/openpi/training/config.py).
+
+**Note:** To successfully reload normalization statistics, it's important that your robot + dataset are following the action space definitions used in pre-training. We provide a detailed description of our action space definitions below.
+
+**Note #2:** Whether reloading normalization statistics is beneficial depends on the similarity of your robot and task to the robot and task distribution in the pre-training dataset. We recommend to always try both, reloading and training with a fresh set of statistics computed on your new dataset (see [main README](../README.md) for instructions on how to compute new statistics), and pick the one that works better for your task.
+
+
+## Provided Pre-training Normalization Statistics
+
+Below is a list of all the pre-training normalization statistics we provide. We provide them for both, the `pi0_base` and `pi0_fast_base` models. For `pi0_base`, set the `assets_dir` to `gs://openpi-assets/checkpoints/pi0_base/assets` and for `pi0_fast_base`, set the `assets_dir` to `gs://openpi-assets/checkpoints/pi0_fast_base/assets`.
+| Robot | Description | Asset ID |
+|-------|-------------|----------|
+| ALOHA | 6-DoF dual arm robot with parallel grippers | trossen |
+| Mobile ALOHA | Mobile version of ALOHA mounted on a Slate base | trossen_mobile |
+| Franka Emika (DROID) | 7-DoF arm with parallel gripper based on the DROID setup | droid |
+| Franka Emika (non-DROID) | Franka FR3 arm with Robotiq 2F-85 gripper | franka |
+| UR5e | 6-DoF UR5e arm with Robotiq 2F-85 gripper | ur5e |
+| UR5e bi-manual | Bi-manual UR5e setup with Robotiq 2F-85 grippers | ur5e_dual |
+| ARX | Bi-manual ARX-5 robot arm setup with parallel gripper | arx |
+| ARX mobile | Mobile version of bi-manual ARX-5 robot arm setup mounted on a Slate base | arx_mobile |
+| Fibocom mobile | Fibocom mobile robot with 2x ARX-5 arms | fibocom_mobile |
+
+
+## Pi0 Model Action Space Definitions
+
+Out of the box, both the `pi0_base` and `pi0_fast_base` use the following action space definitions (left and right are defined looking from behind the robot towards the workspace):
+```
+ "dim_0:dim_5": "left arm joint angles",
+ "dim_6": "left arm gripper position",
+ "dim_7:dim_12": "right arm joint angles (for bi-manual only)",
+ "dim_13": "right arm gripper position (for bi-manual only)",
+
+ # For mobile robots:
+ "dim_14:dim_15": "x-y base velocity (for mobile robots only)",
+```
+
+The proprioceptive state uses the same definitions as the action space, except for the base x-y position (the last two dimensions) for mobile robots, which we don't include in the proprioceptive state.
+
+For 7-DoF robots (e.g. Franka), we use the first 7 dimensions of the action space for the joint actions, and the 8th dimension for the gripper action.
+
+General info for Pi robots:
+- Joint angles are expressed in radians, with position zero corresponding to the zero position reported by each robot's interface library, except for ALOHA, where the standard ALOHA code uses a slightly different convention (see the [ALOHA example code](https://github.com/Physical-Intelligence/openpi/tree/main/examples/aloha_real) for details).
+- Gripper positions are in [0.0, 1.0], with 0.0 corresponding to fully open and 1.0 corresponding to fully closed.
+- Control frequencies are either 20 Hz for UR5e and Franka, and 50 Hz for ARX and Trossen (ALOHA) arms.
+
+For DROID, we use the original DROID action configuration, with joint velocity actions in the first 7 dimensions and gripper actions in the 8th dimension + a control frequency of 15 Hz.
diff --git a/openpi-umi/examples/convert_jax_model_to_pytorch.py b/openpi-umi/examples/convert_jax_model_to_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..edc8a2094dc1819587df34e85cc5058f2cea9059
--- /dev/null
+++ b/openpi-umi/examples/convert_jax_model_to_pytorch.py
@@ -0,0 +1,587 @@
+#!/usr/bin/env python3
+"""
+Load a JAX model and print all parameter keys, with optional conversion to PyTorch.
+
+This script loads a JAX model checkpoint using orbax and can either:
+1. Print out all the parameter keys in a hierarchical structure for inspection
+2. Convert the JAX model to PyTorch format using our PI0Pytorch model
+
+Usage:
+ # Just inspect keys:
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir /path/to/checkpoint --inspect_only
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir /path/to/checkpoint --inspect_only
+
+ # Convert to PyTorch:
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir /path/to/checkpoint --output_path /path/to/output
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir /path/to/checkpoint --output_path /path/to/output
+
+Example:
+ # pi0_droid
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir ${HOME}/.cache/openpi/openpi-assets/checkpoints/pi0_droid --output_path ${HOME}/.cache/openpi/openpi-assets/checkpoints/pi0_droid_pytorch
+
+ # pi0_aloha_sim
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir ${HOME}/.cache/openpi/openpi-assets/checkpoints/pi0_aloha_sim --output_path ${HOME}/.cache/openpi/openpi-assets/checkpoints/pi0_aloha_sim_pytorch
+
+ # pi05_droid
+ python examples/convert_jax_model_to_pytorch.py --checkpoint_dir ${HOME}/.cache/openpi/openpi-assets/checkpoints/pi05_droid --output_path ${HOME}/.cache/openpi/openpi-assets/checkpoints/pi05_droid_pytorch
+"""
+
+import json
+import os
+import pathlib
+import shutil
+from typing import Literal
+
+from flax.nnx import traversals
+import numpy as np
+import orbax.checkpoint as ocp
+import safetensors
+import torch
+import tyro
+
+import openpi.models.gemma
+import openpi.models.model
+import openpi.models.pi0_config
+import openpi.models_pytorch.pi0_pytorch
+from openpi.training import utils
+import openpi.training.config as _config
+
+
+def slice_paligemma_state_dict(state_dict, config):
+ """Convert PaliGemma JAX parameters to PyTorch format."""
+ suffix = "/value" if "img/embedding/kernel/value" in state_dict else ""
+
+ # patch embeddings
+ jax_key = f"img/embedding/kernel{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.vision_tower.vision_model.embeddings.patch_embedding.weight"
+ state_dict[pytorch_key] = state_dict.pop(jax_key).transpose(3, 2, 0, 1)
+
+ jax_key = f"img/embedding/bias{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.vision_tower.vision_model.embeddings.patch_embedding.bias"
+ state_dict[pytorch_key] = state_dict.pop(jax_key)
+
+ # positional embeddings
+ jax_key = f"img/pos_embedding{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.vision_tower.vision_model.embeddings.position_embedding.weight"
+ state_dict[pytorch_key] = state_dict.pop(jax_key).reshape(-1, config.vision_config.hidden_size)
+
+ # extract vision layers to be sliced at index 0. There are 27 layers in the base model.
+ encoderblock_layernorm0_scale = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_0/scale{suffix}")
+ encoderblock_layernorm0_bias = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_0/bias{suffix}")
+ encoderblock_layernorm1_scale = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_1/scale{suffix}")
+ encoderblock_layernorm1_bias = state_dict.pop(f"img/Transformer/encoderblock/LayerNorm_1/bias{suffix}")
+
+ encoderblock_mlp_dense0_kernel = state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_0/kernel{suffix}")
+ encoderblock_mlp_dense0_bias = state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_0/bias{suffix}")
+ encoderblock_mlp_dense1_kernel = state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_1/kernel{suffix}")
+ encoderblock_mlp_dense1_bias = state_dict.pop(f"img/Transformer/encoderblock/MlpBlock_0/Dense_1/bias{suffix}")
+
+ encoderblock_attention_0_key_kernel = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/key/kernel{suffix}"
+ )
+ encoderblock_attention_0_key_bias = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/key/bias{suffix}"
+ )
+ encoderblock_attention_0_value_kernel = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/value/kernel{suffix}"
+ )
+ encoderblock_attention_0_value_bias = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/value/bias{suffix}"
+ )
+ encoderblock_attention_0_query_kernel = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/query/kernel{suffix}"
+ )
+ encoderblock_attention_0_query_bias = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/query/bias{suffix}"
+ )
+ encoderblock_attention_0_out_kernel = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/out/kernel{suffix}"
+ )
+ encoderblock_attention_0_out_bias = state_dict.pop(
+ f"img/Transformer/encoderblock/MultiHeadDotProductAttention_0/out/bias{suffix}"
+ )
+
+ for i in range(config.vision_config.num_hidden_layers):
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.layer_norm1.weight"
+ ] = encoderblock_layernorm0_scale[i].transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.layer_norm1.bias"
+ ] = encoderblock_layernorm0_bias[i]
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.layer_norm2.weight"
+ ] = encoderblock_layernorm1_scale[i].transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.layer_norm2.bias"
+ ] = encoderblock_layernorm1_bias[i]
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.mlp.fc1.weight"
+ ] = encoderblock_mlp_dense0_kernel[i].transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.mlp.fc1.bias"
+ ] = encoderblock_mlp_dense0_bias[i]
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.mlp.fc2.weight"
+ ] = encoderblock_mlp_dense1_kernel[i].transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.mlp.fc2.bias"
+ ] = encoderblock_mlp_dense1_bias[i]
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.k_proj.weight"
+ ] = encoderblock_attention_0_key_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.k_proj.bias"
+ ] = encoderblock_attention_0_key_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.v_proj.weight"
+ ] = encoderblock_attention_0_value_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.v_proj.bias"
+ ] = encoderblock_attention_0_value_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.q_proj.weight"
+ ] = encoderblock_attention_0_query_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.q_proj.bias"
+ ] = encoderblock_attention_0_query_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.out_proj.weight"
+ ] = encoderblock_attention_0_out_kernel[i].reshape(-1, config.vision_config.hidden_size).transpose()
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.vision_tower.vision_model.encoder.layers.{i}.self_attn.out_proj.bias"
+ ] = encoderblock_attention_0_out_bias[i].reshape(-1, config.vision_config.hidden_size).reshape(-1)
+
+ jax_key = f"img/Transformer/encoder_norm/scale{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.vision_tower.vision_model.post_layernorm.weight"
+ state_dict[pytorch_key] = state_dict.pop(jax_key).transpose()
+
+ jax_key = f"img/Transformer/encoder_norm/bias{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.vision_tower.vision_model.post_layernorm.bias"
+ state_dict[pytorch_key] = state_dict.pop(jax_key)
+
+ # multimodal projector
+ jax_key = f"img/head/kernel{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.multi_modal_projector.linear.weight"
+ state_dict[pytorch_key] = state_dict.pop(jax_key).transpose()
+
+ jax_key = f"img/head/bias{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.multi_modal_projector.linear.bias"
+ state_dict[pytorch_key] = state_dict.pop(jax_key)
+
+ # text decoder (gemma)
+ jax_key = f"llm/embedder/input_embedding{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.language_model.embed_tokens.weight"
+ state_dict[pytorch_key] = state_dict.pop(jax_key)
+
+ # pop the einsum attention + mlp representations
+ llm_attention_attn_vec_einsum = state_dict.pop(f"llm/layers/attn/attn_vec_einsum/w{suffix}")
+ llm_attention_kv_einsum = state_dict.pop(f"llm/layers/attn/kv_einsum/w{suffix}")
+ llm_attention_q_einsum = state_dict.pop(f"llm/layers/attn/q_einsum/w{suffix}")
+
+ llm_mlp_gating_einsum = state_dict.pop(f"llm/layers/mlp/gating_einsum{suffix}")
+ llm_mlp_linear = state_dict.pop(f"llm/layers/mlp/linear{suffix}")
+
+ llm_input_layernorm = state_dict.pop(f"llm/layers/pre_attention_norm/scale{suffix}")
+ llm_post_attention_layernorm = state_dict.pop(f"llm/layers/pre_ffw_norm/scale{suffix}")
+
+ for i in range(config.text_config.num_hidden_layers):
+ q_proj_weight_reshaped = (
+ llm_attention_q_einsum[i]
+ .transpose(0, 2, 1)
+ .reshape(
+ config.text_config.num_attention_heads * config.text_config.head_dim, config.text_config.hidden_size
+ )
+ )
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.self_attn.q_proj.weight"] = (
+ q_proj_weight_reshaped
+ )
+
+ k_proj_weight_reshaped = llm_attention_kv_einsum[i, 0, 0].transpose()
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.self_attn.k_proj.weight"] = (
+ k_proj_weight_reshaped
+ )
+ v_proj_weight_reshaped = llm_attention_kv_einsum[i, 1, 0].transpose()
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.self_attn.v_proj.weight"] = (
+ v_proj_weight_reshaped
+ )
+
+ o_proj_weight_reshaped = (
+ llm_attention_attn_vec_einsum[i]
+ .transpose(2, 0, 1)
+ .reshape(
+ config.text_config.num_attention_heads * config.text_config.head_dim, config.text_config.hidden_size
+ )
+ )
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.self_attn.o_proj.weight"] = (
+ o_proj_weight_reshaped
+ )
+
+ gate_proj_weight = llm_mlp_gating_einsum[i, 0]
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.mlp.gate_proj.weight"] = (
+ gate_proj_weight.transpose()
+ )
+ up_proj_weight = llm_mlp_gating_einsum[i, 1]
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.mlp.up_proj.weight"] = (
+ up_proj_weight.transpose()
+ )
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.mlp.down_proj.weight"] = (
+ llm_mlp_linear[i].transpose()
+ )
+ state_dict[f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.input_layernorm.weight"] = (
+ llm_input_layernorm[i]
+ )
+ state_dict[
+ f"paligemma_with_expert.paligemma.model.language_model.layers.{i}.post_attention_layernorm.weight"
+ ] = llm_post_attention_layernorm[i]
+
+ jax_key = f"llm/final_norm/scale{suffix}"
+ pytorch_key = "paligemma_with_expert.paligemma.model.language_model.norm.weight"
+ state_dict[pytorch_key] = state_dict.pop(jax_key)
+
+ expert_dict = {}
+ final_state_dict = {}
+
+ # Expert-related keys to extract (including pi05 Dense layer parameters)
+ expert_keys = [
+ f"llm/final_norm_1/scale{suffix}",
+ f"llm/final_norm_1/Dense_0/bias{suffix}",
+ f"llm/final_norm_1/Dense_0/kernel{suffix}",
+ f"llm/layers/attn/attn_vec_einsum_1/w{suffix}",
+ f"llm/layers/attn/kv_einsum_1/w{suffix}",
+ f"llm/layers/attn/q_einsum_1/w{suffix}",
+ f"llm/layers/mlp_1/gating_einsum{suffix}",
+ f"llm/layers/mlp_1/linear{suffix}",
+ f"llm/layers/pre_attention_norm_1/scale{suffix}",
+ f"llm/layers/pre_attention_norm_1/Dense_0/bias{suffix}",
+ f"llm/layers/pre_attention_norm_1/Dense_0/kernel{suffix}",
+ f"llm/layers/pre_ffw_norm_1/scale{suffix}",
+ f"llm/layers/pre_ffw_norm_1/Dense_0/bias{suffix}",
+ f"llm/layers/pre_ffw_norm_1/Dense_0/kernel{suffix}",
+ ]
+
+ for key, value in state_dict.items():
+ if key not in expert_keys:
+ final_state_dict[key] = torch.from_numpy(value)
+ else:
+ expert_dict[key] = value
+
+ return final_state_dict, expert_dict
+
+
+def slice_gemma_state_dict(state_dict, config, *, num_expert, checkpoint_dir, pi05):
+ """Convert Gemma JAX parameters to PyTorch format."""
+ # Add missing attributes to config if they don't exist
+ if not hasattr(config, "vocab_size"):
+ config.vocab_size = 257152 # PALIGEMMA_VOCAB_SIZE
+ if not hasattr(config, "hidden_size"):
+ config.hidden_size = config.width
+ if not hasattr(config, "num_hidden_layers"):
+ config.num_hidden_layers = config.depth
+ if not hasattr(config, "num_attention_heads"):
+ config.num_attention_heads = config.num_heads
+
+ suffix = "/value" if f"llm/layers/attn/attn_vec_einsum_{num_expert}/w/value" in state_dict else ""
+
+ llm_attention_attn_vec_einsum = state_dict.pop(f"llm/layers/attn/attn_vec_einsum_{num_expert}/w{suffix}")
+ llm_attention_kv_einsum = state_dict.pop(f"llm/layers/attn/kv_einsum_{num_expert}/w{suffix}")
+ llm_attention_q_einsum = state_dict.pop(f"llm/layers/attn/q_einsum_{num_expert}/w{suffix}")
+
+ llm_mlp_gating_einsum = state_dict.pop(f"llm/layers/mlp_{num_expert}/gating_einsum{suffix}")
+ llm_mlp_linear = state_dict.pop(f"llm/layers/mlp_{num_expert}/linear{suffix}")
+
+ # Check if we have Dense layers (for pi05/adaptive normalization) or scale layers (for regular pi0)
+ if "pi05" in checkpoint_dir:
+ # Pi05 with adaptive normalization
+ llm_input_layernorm_bias = state_dict.pop(f"llm/layers/pre_attention_norm_{num_expert}/Dense_0/bias{suffix}")
+ llm_post_attention_layernorm_bias = state_dict.pop(f"llm/layers/pre_ffw_norm_{num_expert}/Dense_0/bias{suffix}")
+ llm_input_layernorm_kernel = state_dict.pop(
+ f"llm/layers/pre_attention_norm_{num_expert}/Dense_0/kernel{suffix}"
+ )
+ llm_post_attention_layernorm_kernel = state_dict.pop(
+ f"llm/layers/pre_ffw_norm_{num_expert}/Dense_0/kernel{suffix}"
+ )
+ else:
+ # Regular pi0 with standard RMSNorm
+ llm_input_layernorm = state_dict.pop(f"llm/layers/pre_attention_norm_{num_expert}/scale{suffix}")
+ llm_post_attention_layernorm = state_dict.pop(f"llm/layers/pre_ffw_norm_{num_expert}/scale{suffix}")
+
+ for i in range(config.num_hidden_layers):
+ q_proj_weight_reshaped = (
+ llm_attention_q_einsum[i]
+ .transpose(0, 2, 1)
+ .reshape(config.num_attention_heads * config.head_dim, config.hidden_size)
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.self_attn.q_proj.weight"] = (
+ q_proj_weight_reshaped
+ )
+
+ k_proj_weight_reshaped = llm_attention_kv_einsum[i, 0, 0].transpose()
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.self_attn.k_proj.weight"] = (
+ k_proj_weight_reshaped
+ )
+ v_proj_weight_reshaped = llm_attention_kv_einsum[i, 1, 0].transpose()
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.self_attn.v_proj.weight"] = (
+ v_proj_weight_reshaped
+ )
+
+ o_proj_weight_reshaped = (
+ llm_attention_attn_vec_einsum[i]
+ .reshape(config.num_attention_heads * config.head_dim, config.hidden_size)
+ .transpose(1, 0)
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.self_attn.o_proj.weight"] = (
+ o_proj_weight_reshaped
+ )
+
+ gate_proj_weight = llm_mlp_gating_einsum[i, 0]
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.mlp.gate_proj.weight"] = (
+ gate_proj_weight.transpose()
+ )
+ up_proj_weight = llm_mlp_gating_einsum[i, 1]
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.mlp.up_proj.weight"] = (
+ up_proj_weight.transpose()
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.mlp.down_proj.weight"] = llm_mlp_linear[
+ i
+ ].transpose()
+
+ if "pi05" in checkpoint_dir:
+ # Pi05 with adaptive normalization - use Dense layer parameters directly
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.input_layernorm.dense.bias"] = (
+ llm_input_layernorm_bias[i]
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.post_attention_layernorm.dense.bias"] = (
+ llm_post_attention_layernorm_bias[i]
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.input_layernorm.dense.weight"] = (
+ llm_input_layernorm_kernel[i].transpose()
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.post_attention_layernorm.dense.weight"] = (
+ llm_post_attention_layernorm_kernel[i].transpose()
+ )
+ else:
+ # Regular pi0 with standard RMSNorm
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.input_layernorm.weight"] = (
+ llm_input_layernorm[i]
+ )
+ state_dict[f"paligemma_with_expert.gemma_expert.model.layers.{i}.post_attention_layernorm.weight"] = (
+ llm_post_attention_layernorm[i]
+ )
+
+ # Handle final norm layer
+ if "pi05" in checkpoint_dir:
+ # Pi05 with adaptive normalization - use Dense layer parameters directly
+ final_norm_bias = state_dict.pop(f"llm/final_norm_{num_expert}/Dense_0/bias{suffix}")
+ final_norm_kernel = state_dict.pop(f"llm/final_norm_{num_expert}/Dense_0/kernel{suffix}")
+ state_dict["paligemma_with_expert.gemma_expert.model.norm.dense.bias"] = final_norm_bias
+ state_dict["paligemma_with_expert.gemma_expert.model.norm.dense.weight"] = final_norm_kernel.transpose()
+ else:
+ # Regular pi0 with standard RMSNorm
+ state_dict["paligemma_with_expert.gemma_expert.model.norm.weight"] = state_dict.pop(
+ f"llm/final_norm_{num_expert}/scale{suffix}"
+ )
+
+ # state_dict["paligemma_with_expert.gemma_expert.lm_head.weight"] = embedding_vector # weights are tied.
+
+ final_state_dict = {}
+ for key, value in state_dict.items():
+ if not isinstance(value, torch.Tensor):
+ final_state_dict[key] = torch.from_numpy(value)
+ else:
+ final_state_dict[key] = value
+
+ return final_state_dict
+
+
+def slice_initial_orbax_checkpoint(checkpoint_dir: str, restore_precision: str | None = None):
+ """Load and process params by restoring via JAX model loader first.
+ This respects dtype conversions that occur during model restore.
+ """
+ # Use repository restore utility to load a pure dict of params (value suffix removed)
+ params = openpi.models.model.restore_params(
+ f"{checkpoint_dir}/params/", restore_type=np.ndarray, dtype=restore_precision
+ )
+
+ return {"paligemma_params": traversals.flatten_mapping(params["PaliGemma"], sep="/"), "projection_params": params}
+
+
+def load_jax_model_and_print_keys(checkpoint_dir: str):
+ """
+ Load JAX model from checkpoint and print all parameter keys.
+
+ Args:
+ checkpoint_dir: Path to the checkpoint directory
+ """
+ checkpoint_dir = os.path.abspath(checkpoint_dir) if not checkpoint_dir.startswith("gs://") else checkpoint_dir
+ # Initialize checkpointer
+ checkpointer = ocp.PyTreeCheckpointer()
+ metadata = checkpointer.metadata(f"{checkpoint_dir}/params")
+ print(utils.array_tree_to_info(metadata))
+
+
+def convert_pi0_checkpoint(
+ checkpoint_dir: str, precision: str, output_path: str, model_config: openpi.models.pi0_config.Pi0Config
+):
+ """
+ Convert PI0 JAX checkpoint to PyTorch format.
+
+ Args:
+ checkpoint_dir: Path to the JAX checkpoint
+ precision: Model precision (float32, bfloat16, float16)
+ output_path: Path to save the converted PyTorch model
+ model_config: Model config
+ """
+ print(f"Converting PI0 checkpoint from {checkpoint_dir} to {output_path}")
+ print(f"Model config: {model_config}")
+
+ # Break down orbax ckpts by restoring via JAX to respect dtype
+ initial_params = slice_initial_orbax_checkpoint(checkpoint_dir=checkpoint_dir, restore_precision="float32")
+
+ # Process projection params
+ if model_config.pi05:
+ keys = [
+ "action_in_proj",
+ "action_out_proj",
+ "time_mlp_in",
+ "time_mlp_out",
+ ]
+ else:
+ keys = [
+ "state_proj",
+ "action_in_proj",
+ "action_out_proj",
+ "action_time_mlp_in",
+ "action_time_mlp_out",
+ ]
+
+ projection_params = {}
+ for key in keys:
+ kernel_params = initial_params["projection_params"][key]["kernel"]
+ bias_params = initial_params["projection_params"][key]["bias"]
+ if isinstance(kernel_params, dict):
+ weight = kernel_params["value"]
+ bias = bias_params["value"]
+ else:
+ weight = kernel_params
+ bias = bias_params
+
+ pytorch_weight_key = f"{key}.weight"
+ pytorch_bias_key = f"{key}.bias"
+
+ projection_params[pytorch_weight_key] = torch.from_numpy(np.array(weight)).T
+ projection_params[pytorch_bias_key] = torch.from_numpy(np.array(bias))
+
+ # Create configs based on checkpoint path
+ # All models use the same PaliGemma config structure
+ class PaliGemmaConfig:
+ def __init__(self):
+ self.vision_config = type(
+ "obj",
+ (object,),
+ {
+ "hidden_size": 1152,
+ "num_hidden_layers": 27,
+ "num_attention_heads": 16,
+ "intermediate_size": 4304,
+ "patch_size": 14,
+ "projection_dim": 2048,
+ },
+ )()
+ self.text_config = type(
+ "obj",
+ (object,),
+ {
+ "hidden_size": 2048,
+ "num_hidden_layers": 18,
+ "num_attention_heads": 8,
+ "head_dim": 256,
+ "intermediate_size": 16384,
+ },
+ )()
+
+ paligemma_config = PaliGemmaConfig()
+ action_expert_config = openpi.models.gemma.get_config("gemma_300m")
+
+ # Process PaliGemma weights
+ paligemma_params, expert_params = slice_paligemma_state_dict(initial_params["paligemma_params"], paligemma_config)
+
+ # Process Gemma weights from expert_params
+ gemma_params = slice_gemma_state_dict(
+ expert_params, action_expert_config, num_expert=1, checkpoint_dir=checkpoint_dir, pi05=model_config.pi05
+ )
+
+ # Instantiate model
+ pi0_model = openpi.models_pytorch.pi0_pytorch.PI0Pytorch(model_config)
+
+ # Combine all parameters (no prefix needed for our model structure)
+ all_params = {**paligemma_params, **gemma_params, **projection_params}
+
+ # Load state dict
+ pi0_model.load_state_dict(all_params, strict=False)
+
+ if precision == "float32":
+ pi0_model = pi0_model.to(torch.float32)
+ elif precision == "bfloat16":
+ pi0_model = pi0_model.to(torch.bfloat16)
+ else:
+ raise ValueError(f"Invalid precision: {precision}")
+
+ # Save the converted model using safetensors
+ os.makedirs(output_path, exist_ok=True)
+
+ # Save model weights as SafeTensors using save_model to handle tied weights
+ safetensors.torch.save_model(pi0_model, os.path.join(output_path, "model.safetensors"))
+
+ # Copy assets folder if it exists
+ assets_source = pathlib.Path(checkpoint_dir).parent / "assets"
+ if assets_source.exists():
+ assets_dest = pathlib.Path(output_path) / "assets"
+ if assets_dest.exists():
+ shutil.rmtree(assets_dest)
+ shutil.copytree(assets_source, assets_dest)
+
+ # Save config as JSON for reference
+ config_dict = {
+ "action_dim": model_config.action_dim,
+ "action_horizon": model_config.action_horizon,
+ "paligemma_variant": model_config.paligemma_variant,
+ "action_expert_variant": model_config.action_expert_variant,
+ "precision": precision,
+ }
+ with open(os.path.join(output_path, "config.json"), "w") as f:
+ json.dump(config_dict, f, indent=2)
+
+ print("Model conversion completed successfully!")
+ print(f"Model saved to {output_path}")
+
+
+def main(
+ checkpoint_dir: str,
+ config_name: str,
+ output_path: str | None = None,
+ precision: Literal["float32", "bfloat16", "float16"] = "bfloat16",
+ *,
+ inspect_only: bool = False,
+):
+ """Load JAX model and optionally convert to PyTorch.
+
+ Args:
+ checkpoint_dir: Path to the JAX checkpoint directory
+ output_path: Path to save converted PyTorch model (required for conversion)
+ precision: Precision for model conversion
+ inspect_only: Only inspect parameter keys, don't convert
+ """
+ model_config = _config.get_config(config_name).model
+ if not isinstance(model_config, openpi.models.pi0_config.Pi0Config):
+ raise ValueError(f"Config {config_name} is not a Pi0Config")
+ if inspect_only:
+ load_jax_model_and_print_keys(checkpoint_dir)
+ else:
+ if not output_path:
+ print("Error: --output_path is required for conversion. Use --inspect_only to only view keys.")
+ return
+ convert_pi0_checkpoint(checkpoint_dir, precision, output_path, model_config)
+
+
+if __name__ == "__main__":
+ tyro.cli(main)
diff --git a/openpi-umi/packages/openpi-client/pyproject.toml b/openpi-umi/packages/openpi-client/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..fba7b66f62be7ff209d46717b1eed1d1b232ca2e
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/pyproject.toml
@@ -0,0 +1,23 @@
+[project]
+name = "openpi-client"
+version = "0.1.0"
+requires-python = ">=3.7"
+dependencies = [
+ "dm-tree>=0.1.8",
+ "msgpack>=1.0.5",
+ "numpy>=1.22.4,<2.0.0",
+ "pillow>=9.0.0",
+ "tree>=0.2.4",
+ "websockets>=11.0",
+]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.uv]
+dev-dependencies = ["pytest>=8.3.4"]
+
+[tool.ruff]
+line-length = 120
+target-version = "py37"
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/__init__.py b/openpi-umi/packages/openpi-client/src/openpi_client/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dc1f76bc69e3f559bee6253b24fc93acee9e1f9
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/__init__.py
@@ -0,0 +1 @@
+__version__ = "0.1.0"
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/action_chunk_broker.py b/openpi-umi/packages/openpi-client/src/openpi_client/action_chunk_broker.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fa9d83d023b7c0c60a1d05531343af01e72d09b
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/action_chunk_broker.py
@@ -0,0 +1,50 @@
+from typing import Dict
+
+import numpy as np
+import tree
+from typing_extensions import override
+
+from openpi_client import base_policy as _base_policy
+
+
+class ActionChunkBroker(_base_policy.BasePolicy):
+ """Wraps a policy to return action chunks one-at-a-time.
+
+ Assumes that the first dimension of all action fields is the chunk size.
+
+ A new inference call to the inner policy is only made when the current
+ list of chunks is exhausted.
+ """
+
+ def __init__(self, policy: _base_policy.BasePolicy, action_horizon: int):
+ self._policy = policy
+ self._action_horizon = action_horizon
+ self._cur_step: int = 0
+
+ self._last_results: Dict[str, np.ndarray] | None = None
+
+ @override
+ def infer(self, obs: Dict) -> Dict: # noqa: UP006
+ if self._last_results is None:
+ self._last_results = self._policy.infer(obs)
+ self._cur_step = 0
+
+ def slicer(x):
+ if isinstance(x, np.ndarray):
+ return x[self._cur_step, ...]
+ else:
+ return x
+
+ results = tree.map_structure(slicer, self._last_results)
+ self._cur_step += 1
+
+ if self._cur_step >= self._action_horizon:
+ self._last_results = None
+
+ return results
+
+ @override
+ def reset(self) -> None:
+ self._policy.reset()
+ self._last_results = None
+ self._cur_step = 0
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/base_policy.py b/openpi-umi/packages/openpi-client/src/openpi_client/base_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f4290651b1b7bab3bd9549b47876838f5b51629
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/base_policy.py
@@ -0,0 +1,12 @@
+import abc
+from typing import Dict
+
+
+class BasePolicy(abc.ABC):
+ @abc.abstractmethod
+ def infer(self, obs: Dict) -> Dict:
+ """Infer actions from observations."""
+
+ def reset(self) -> None:
+ """Reset the policy to its initial state."""
+ pass
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/image_tools.py b/openpi-umi/packages/openpi-client/src/openpi_client/image_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a971b9d5f6b1495fd6cdea202ffa607d8b34bf0
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/image_tools.py
@@ -0,0 +1,58 @@
+import numpy as np
+from PIL import Image
+
+
+def convert_to_uint8(img: np.ndarray) -> np.ndarray:
+ """Converts an image to uint8 if it is a float image.
+
+ This is important for reducing the size of the image when sending it over the network.
+ """
+ if np.issubdtype(img.dtype, np.floating):
+ img = (255 * img).astype(np.uint8)
+ return img
+
+
+def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray:
+ """Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height.
+
+ Args:
+ images: A batch of images in [..., height, width, channel] format.
+ height: The target height of the image.
+ width: The target width of the image.
+ method: The interpolation method to use. Default is bilinear.
+
+ Returns:
+ The resized images in [..., height, width, channel].
+ """
+ # If the images are already the correct size, return them as is.
+ if images.shape[-3:-1] == (height, width):
+ return images
+
+ original_shape = images.shape
+
+ images = images.reshape(-1, *original_shape[-3:])
+ resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images])
+ return resized.reshape(*original_shape[:-3], *resized.shape[-3:])
+
+
+def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image:
+ """Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and
+ width without distortion by padding with zeros.
+
+ Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c].
+ """
+ cur_width, cur_height = image.size
+ if cur_width == width and cur_height == height:
+ return image # No need to resize if the image is already the correct size.
+
+ ratio = max(cur_width / width, cur_height / height)
+ resized_height = int(cur_height / ratio)
+ resized_width = int(cur_width / ratio)
+ resized_image = image.resize((resized_width, resized_height), resample=method)
+
+ zero_image = Image.new(resized_image.mode, (width, height), 0)
+ pad_height = max(0, int((height - resized_height) / 2))
+ pad_width = max(0, int((width - resized_width) / 2))
+ zero_image.paste(resized_image, (pad_width, pad_height))
+ assert zero_image.size == (width, height)
+ return zero_image
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/image_tools_test.py b/openpi-umi/packages/openpi-client/src/openpi_client/image_tools_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d4b4b92030ea869712b312581e26243035aafba
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/image_tools_test.py
@@ -0,0 +1,37 @@
+import numpy as np
+
+import openpi_client.image_tools as image_tools
+
+
+def test_resize_with_pad_shapes():
+ # Test case 1: Resize image with larger dimensions
+ images = np.zeros((2, 10, 10, 3), dtype=np.uint8) # Input images of shape (batch_size, height, width, channels)
+ height = 20
+ width = 20
+ resized_images = image_tools.resize_with_pad(images, height, width)
+ assert resized_images.shape == (2, height, width, 3)
+ assert np.all(resized_images == 0)
+
+ # Test case 2: Resize image with smaller dimensions
+ images = np.zeros((3, 30, 30, 3), dtype=np.uint8)
+ height = 15
+ width = 15
+ resized_images = image_tools.resize_with_pad(images, height, width)
+ assert resized_images.shape == (3, height, width, 3)
+ assert np.all(resized_images == 0)
+
+ # Test case 3: Resize image with the same dimensions
+ images = np.zeros((1, 50, 50, 3), dtype=np.uint8)
+ height = 50
+ width = 50
+ resized_images = image_tools.resize_with_pad(images, height, width)
+ assert resized_images.shape == (1, height, width, 3)
+ assert np.all(resized_images == 0)
+
+ # Test case 3: Resize image with odd-numbered padding
+ images = np.zeros((1, 256, 320, 3), dtype=np.uint8)
+ height = 60
+ width = 80
+ resized_images = image_tools.resize_with_pad(images, height, width)
+ assert resized_images.shape == (1, height, width, 3)
+ assert np.all(resized_images == 0)
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy.py b/openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..007f755edf54565579376b077eec7f7f715e1b96
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy.py
@@ -0,0 +1,57 @@
+"""Adds NumPy array support to msgpack.
+
+msgpack is good for (de)serializing data over a network for multiple reasons:
+- msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution)
+- msgpack is widely used and has good cross-language support
+- msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed
+ languages like Python and JavaScript
+- msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster
+ than pickle for serializing large arrays using the below strategy
+
+The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is
+that it falls back to pickle for object arrays.
+"""
+
+import functools
+
+import msgpack
+import numpy as np
+
+
+def pack_array(obj):
+ if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
+ raise ValueError(f"Unsupported dtype: {obj.dtype}")
+
+ if isinstance(obj, np.ndarray):
+ return {
+ b"__ndarray__": True,
+ b"data": obj.tobytes(),
+ b"dtype": obj.dtype.str,
+ b"shape": obj.shape,
+ }
+
+ if isinstance(obj, np.generic):
+ return {
+ b"__npgeneric__": True,
+ b"data": obj.item(),
+ b"dtype": obj.dtype.str,
+ }
+
+ return obj
+
+
+def unpack_array(obj):
+ if b"__ndarray__" in obj:
+ return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
+
+ if b"__npgeneric__" in obj:
+ return np.dtype(obj[b"dtype"]).type(obj[b"data"])
+
+ return obj
+
+
+Packer = functools.partial(msgpack.Packer, default=pack_array)
+packb = functools.partial(msgpack.packb, default=pack_array)
+
+Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
+unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py b/openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c774ba468aa6948e154cb2008bac8f6128a4593
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py
@@ -0,0 +1,45 @@
+import numpy as np
+import pytest
+import tree
+
+from openpi_client import msgpack_numpy
+
+
+def _check(expected, actual):
+ if isinstance(expected, np.ndarray):
+ assert expected.shape == actual.shape
+ assert expected.dtype == actual.dtype
+ assert np.array_equal(expected, actual, equal_nan=expected.dtype.kind == "f")
+ else:
+ assert expected == actual
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ 1, # int
+ 1.0, # float
+ "hello", # string
+ np.bool_(True), # boolean scalar
+ np.array([1, 2, 3])[0], # int scalar
+ np.str_("asdf"), # string scalar
+ [1, 2, 3], # list
+ {"key": "value"}, # dict
+ {"key": [1, 2, 3]}, # nested dict
+ np.array(1.0), # 0D array
+ np.array([1, 2, 3], dtype=np.int32), # 1D integer array
+ np.array(["asdf", "qwer"]), # string array
+ np.array([True, False]), # boolean array
+ np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), # 2D float array
+ np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.int16), # 3D integer array
+ np.array([np.nan, np.inf, -np.inf]), # special float values
+ {"arr": np.array([1, 2, 3]), "nested": {"arr": np.array([4, 5, 6])}}, # nested dict with arrays
+ [np.array([1, 2]), np.array([3, 4])], # list of arrays
+ np.zeros((3, 4, 5), dtype=np.float32), # 3D zeros
+ np.ones((2, 3), dtype=np.float64), # 2D ones with double precision
+ ],
+)
+def test_pack_unpack(data):
+ packed = msgpack_numpy.packb(data)
+ unpacked = msgpack_numpy.unpackb(packed)
+ tree.map_structure(_check, data, unpacked)
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/runtime/agent.py b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2c3ab66ef618ad9ecbff7b81ad9340a4604128c
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/agent.py
@@ -0,0 +1,17 @@
+import abc
+
+
+class Agent(abc.ABC):
+ """An Agent is the thing with agency, i.e. the entity that makes decisions.
+
+ Agents receive observations about the state of the world, and return actions
+ to take in response.
+ """
+
+ @abc.abstractmethod
+ def get_action(self, observation: dict) -> dict:
+ """Query the agent for the next action."""
+
+ @abc.abstractmethod
+ def reset(self) -> None:
+ """Reset the agent to its initial state."""
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..65227c44dae667d9b2743b6bc1026e791cec35c4
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py
@@ -0,0 +1,18 @@
+from typing_extensions import override
+
+from openpi_client import base_policy as _base_policy
+from openpi_client.runtime import agent as _agent
+
+
+class PolicyAgent(_agent.Agent):
+ """An agent that uses a policy to determine actions."""
+
+ def __init__(self, policy: _base_policy.BasePolicy) -> None:
+ self._policy = policy
+
+ @override
+ def get_action(self, observation: dict) -> dict:
+ return self._policy.infer(observation)
+
+ def reset(self) -> None:
+ self._policy.reset()
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/runtime/environment.py b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/environment.py
new file mode 100644
index 0000000000000000000000000000000000000000..664ac4678aaaa3aecf52268a6a09d1d1fc974226
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/environment.py
@@ -0,0 +1,32 @@
+import abc
+
+
+class Environment(abc.ABC):
+ """An Environment represents the robot and the environment it inhabits.
+
+ The primary contract of environments is that they can be queried for observations
+ about their state, and have actions applied to them to change that state.
+ """
+
+ @abc.abstractmethod
+ def reset(self) -> None:
+ """Reset the environment to its initial state.
+
+ This will be called once before starting each episode.
+ """
+
+ @abc.abstractmethod
+ def is_episode_complete(self) -> bool:
+ """Allow the environment to signal that the episode is complete.
+
+ This will be called after each step. It should return `True` if the episode is
+ complete (either successfully or unsuccessfully), and `False` otherwise.
+ """
+
+ @abc.abstractmethod
+ def get_observation(self) -> dict:
+ """Query the environment for the current state."""
+
+ @abc.abstractmethod
+ def apply_action(self, action: dict) -> None:
+ """Take an action in the environment."""
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/runtime/runtime.py b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..9552be091a26e163d60cab8071df4716524bf2e8
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/runtime.py
@@ -0,0 +1,92 @@
+import logging
+import threading
+import time
+
+from openpi_client.runtime import agent as _agent
+from openpi_client.runtime import environment as _environment
+from openpi_client.runtime import subscriber as _subscriber
+
+
+class Runtime:
+ """The core module orchestrating interactions between key components of the system."""
+
+ def __init__(
+ self,
+ environment: _environment.Environment,
+ agent: _agent.Agent,
+ subscribers: list[_subscriber.Subscriber],
+ max_hz: float = 0,
+ num_episodes: int = 1,
+ max_episode_steps: int = 0,
+ ) -> None:
+ self._environment = environment
+ self._agent = agent
+ self._subscribers = subscribers
+ self._max_hz = max_hz
+ self._num_episodes = num_episodes
+ self._max_episode_steps = max_episode_steps
+
+ self._in_episode = False
+ self._episode_steps = 0
+
+ def run(self) -> None:
+ """Runs the runtime loop continuously until stop() is called or the environment is done."""
+ for _ in range(self._num_episodes):
+ self._run_episode()
+
+ # Final reset, this is important for real environments to move the robot to its home position.
+ self._environment.reset()
+
+ def run_in_new_thread(self) -> threading.Thread:
+ """Runs the runtime loop in a new thread."""
+ thread = threading.Thread(target=self.run)
+ thread.start()
+ return thread
+
+ def mark_episode_complete(self) -> None:
+ """Marks the end of an episode."""
+ self._in_episode = False
+
+ def _run_episode(self) -> None:
+ """Runs a single episode."""
+ logging.info("Starting episode...")
+ self._environment.reset()
+ self._agent.reset()
+ for subscriber in self._subscribers:
+ subscriber.on_episode_start()
+
+ self._in_episode = True
+ self._episode_steps = 0
+ step_time = 1 / self._max_hz if self._max_hz > 0 else 0
+ last_step_time = time.time()
+
+ while self._in_episode:
+ self._step()
+ self._episode_steps += 1
+
+ # Sleep to maintain the desired frame rate
+ now = time.time()
+ dt = now - last_step_time
+ if dt < step_time:
+ time.sleep(step_time - dt)
+ last_step_time = time.time()
+ else:
+ last_step_time = now
+
+ logging.info("Episode completed.")
+ for subscriber in self._subscribers:
+ subscriber.on_episode_end()
+
+ def _step(self) -> None:
+ """A single step of the runtime loop."""
+ observation = self._environment.get_observation()
+ action = self._agent.get_action(observation)
+ self._environment.apply_action(action)
+
+ for subscriber in self._subscribers:
+ subscriber.on_step(observation, action)
+
+ if self._environment.is_episode_complete() or (
+ self._max_episode_steps > 0 and self._episode_steps >= self._max_episode_steps
+ ):
+ self.mark_episode_complete()
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/runtime/subscriber.py b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/subscriber.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c69edaa8e814dfcfe56b78b774578fe37f79428
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/runtime/subscriber.py
@@ -0,0 +1,20 @@
+import abc
+
+
+class Subscriber(abc.ABC):
+ """Subscribes to events in the runtime.
+
+ Subscribers can be used to save data, visualize, etc.
+ """
+
+ @abc.abstractmethod
+ def on_episode_start(self) -> None:
+ """Called when an episode starts."""
+
+ @abc.abstractmethod
+ def on_step(self, observation: dict, action: dict) -> None:
+ """Append a step to the episode."""
+
+ @abc.abstractmethod
+ def on_episode_end(self) -> None:
+ """Called when an episode ends."""
diff --git a/openpi-umi/packages/openpi-client/src/openpi_client/websocket_client_policy.py b/openpi-umi/packages/openpi-client/src/openpi_client/websocket_client_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..466685e00d004ff8c7dd5694636a8ec3e6439d11
--- /dev/null
+++ b/openpi-umi/packages/openpi-client/src/openpi_client/websocket_client_policy.py
@@ -0,0 +1,58 @@
+import logging
+import time
+from typing import Dict, Optional, Tuple
+
+from typing_extensions import override
+import websockets.sync.client
+
+from openpi_client import base_policy as _base_policy
+from openpi_client import msgpack_numpy
+
+
+class WebsocketClientPolicy(_base_policy.BasePolicy):
+ """Implements the Policy interface by communicating with a server over websocket.
+
+ See WebsocketPolicyServer for a corresponding server implementation.
+ """
+
+ def __init__(self, host: str = "0.0.0.0", port: Optional[int] = None, api_key: Optional[str] = None) -> None:
+ if host.startswith("ws"):
+ self._uri = host
+ else:
+ self._uri = f"ws://{host}"
+ if port is not None:
+ self._uri += f":{port}"
+ self._packer = msgpack_numpy.Packer()
+ self._api_key = api_key
+ self._ws, self._server_metadata = self._wait_for_server()
+
+ def get_server_metadata(self) -> Dict:
+ return self._server_metadata
+
+ def _wait_for_server(self) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
+ logging.info(f"Waiting for server at {self._uri}...")
+ while True:
+ try:
+ headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
+ conn = websockets.sync.client.connect(
+ self._uri, compression=None, max_size=None, additional_headers=headers
+ )
+ metadata = msgpack_numpy.unpackb(conn.recv())
+ return conn, metadata
+ except ConnectionRefusedError:
+ logging.info("Still waiting for server...")
+ time.sleep(5)
+
+ @override
+ def infer(self, obs: Dict) -> Dict: # noqa: UP006
+ data = self._packer.pack(obs)
+ self._ws.send(data)
+ response = self._ws.recv()
+ if isinstance(response, str):
+ # we're expecting bytes; if the server sends a string, it's an error.
+ raise RuntimeError(f"Error in inference server:\n{response}")
+ return msgpack_numpy.unpackb(response)
+
+ @override
+ def reset(self) -> None:
+ pass
diff --git a/openpi-umi/pyproject.toml b/openpi-umi/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..c4a06e53284ecc78a05923e374c15e700a20676c
--- /dev/null
+++ b/openpi-umi/pyproject.toml
@@ -0,0 +1,137 @@
+[project]
+name = "openpi"
+version = "0.1.0"
+description = "Physical Intelligence open source repo"
+readme = "README.md"
+requires-python = ">=3.11"
+license = { file = "LICENSE" }
+dependencies = [
+ "augmax>=0.3.4",
+ "dm-tree>=0.1.8",
+ "einops>=0.8.0",
+ "equinox>=0.11.8",
+ "flatbuffers>=24.3.25",
+ "flax==0.10.2",
+ "fsspec[gcs]>=2024.6.0",
+ "gym-aloha>=0.1.1",
+ "imageio>=2.36.1",
+ "jax[cuda12]==0.5.3",
+ "jaxtyping==0.2.36",
+ "lerobot",
+ "ml_collections==1.0.0",
+ "numpy>=1.22.4,<2.0.0",
+ "numpydantic>=1.6.6",
+ "opencv-python>=4.10.0.84",
+ "openpi-client",
+ "orbax-checkpoint==0.11.13",
+ "pillow>=11.0.0",
+ "sentencepiece>=0.2.0",
+ "torch==2.7.1",
+ "tqdm-loggable>=0.2",
+ "typing-extensions>=4.12.2",
+ "tyro>=0.9.5",
+ "wandb>=0.19.1",
+ "filelock>=3.16.1",
+ "beartype==0.19.0",
+ "treescope>=0.1.7",
+ "transformers==4.53.2",
+ "rich>=14.0.0",
+ "polars>=1.30.0",
+]
+
+
+[project.urls]
+Repository = "https://github.com/Physical-Intelligence/openpi"
+
+[dependency-groups]
+dev = [
+ "pytest>=8.3.4",
+ "ruff>=0.8.6",
+ "pre-commit>=4.0.1",
+ "ipykernel>=6.29.5",
+ "ipywidgets>=8.1.5",
+ "matplotlib>=3.10.0",
+ "pynvml>=12.0.0",
+]
+rlds = [
+ "dlimp",
+ "tensorflow-cpu==2.15.0",
+ "tensorflow-datasets==4.9.9",
+]
+
+[tool.uv]
+override-dependencies = ["ml-dtypes==0.4.1", "tensorstore==0.1.74"]
+
+[tool.uv.sources]
+openpi-client = { workspace = true }
+lerobot = { git = "https://github.com/huggingface/lerobot", rev = "0cf864870cf29f4738d3ade893e6fd13fbd7cdb5" }
+dlimp = { git = "https://github.com/kvablack/dlimp", rev = "ad72ce3a9b414db2185bc0b38461d4101a65477a" }
+
+[tool.uv.workspace]
+members = ["packages/*"]
+
+[tool.ruff]
+line-length = 120
+target-version = "py311"
+extend-exclude = ["docker", "third_party", "src/openpi/models_pytorch/transformers_replace/*"]
+
+[tool.ruff.lint]
+# https://docs.astral.sh/ruff/rules/
+select = [
+ "B",
+ "C4",
+ "DTZ",
+ "E4",
+ "E7",
+ "E9",
+ "F",
+ "FBT",
+ "FURB",
+ "I",
+ "ICN",
+ "ISC",
+ "LOG",
+ "N",
+ "PD",
+ "PERF",
+ "PIE",
+ "PLC",
+ "PLE",
+ "PLR1",
+ "PLR5",
+ "PLW",
+ "PT",
+ "Q",
+ "RET",
+ "RUF",
+ "SIM",
+ "SLF",
+ "T10",
+ "T20",
+ "UP",
+ "W",
+]
+ignore = [
+ "F722", # Conflicts with array typing.
+ "T201", # We use print statements.
+ "PD008", # Lots of false positives.
+ "ISC001", # Disabling to support ruff format.
+ "LOG015", # Use logger.info.
+]
+unfixable = [
+ "B905", # Fix defaults to strict=False, which is not what we want.
+]
+
+[tool.ruff.lint.isort]
+force-single-line = true
+force-sort-within-sections = true
+single-line-exclusions = ["collections.abc", "typing", "typing_extensions"]
+known-third-party = ["wandb"]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.pytest.ini_options]
+markers = ["manual: should be run manually."]
+testpaths = ["src", "scripts", "packages"]
diff --git a/openpi-umi/scripts/__init__.py b/openpi-umi/scripts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/openpi-umi/scripts/build_destatic_manifest.py b/openpi-umi/scripts/build_destatic_manifest.py
new file mode 100644
index 0000000000000000000000000000000000000000..e76a6fb1cf297c3ee3e1ca3977207f4f32c0594b
--- /dev/null
+++ b/openpi-umi/scripts/build_destatic_manifest.py
@@ -0,0 +1,84 @@
+"""Build a pi05_umi_v3 episode manifest with de-static sample ranges (5th column: anchor_ranges).
+
+Each episode is scanned with umi_v3_dataset._scan_episode (same rules as the manifest the trainer builds
+itself). Sample ranges are derived from per-episode keep_ranges: sample t reads frames t+OFF_MIN .. t+OFF_MAX
+(pi05_umi_v3 = range(-1, 51)), and the whole window must fall inside one keep segment, so removed static
+frames are never touched. Segments that touch the true episode start/end (0 / n) keep the reader's clip
+semantics.
+
+Cut file format: {"episodes": {"": {"n_frames": int, "keep_ranges": [[start, end), ...]}}}
+
+Usage: python scripts/build_destatic_manifest.py --root DATA_ROOT --sessions S.txt --cuts A.json [B.json ...] --out M.json
+"""
+import argparse, collections, hashlib, json, os, sys
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+IMAGE_KEYS = ("observation.images.left_ego", "observation.images.right_ego")
+OFF_MIN, OFF_MAX = -1, 50
+
+
+def anchors(keep, n):
+ out = []
+ for x, y in keep:
+ lo = 0 if x == 0 else x - OFF_MIN
+ hi = n if y == n else y - OFF_MAX
+ if hi > lo:
+ out.append([lo, hi])
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--root", required=True, help="directory holding one LeRobot v3.0 dataset per session")
+ ap.add_argument("--prompt", default="fold the clothes")
+ ap.add_argument("--sessions", type=Path, required=True)
+ ap.add_argument("--cuts", type=Path, nargs="+", required=True)
+ ap.add_argument("--out", type=Path, required=True)
+ ap.add_argument("--code", default=".", help="openpi checkout (for umi_v3_dataset)")
+ a = ap.parse_args()
+ sys.path.insert(0, os.path.join(a.code, "src"))
+ from openpi.training import umi_v3_dataset as U
+ if a.out.exists():
+ raise FileExistsError(a.out)
+ cut = {}
+ for p in a.cuts:
+ for s, e in json.loads(p.read_text())["episodes"].items():
+ if s in cut:
+ raise ValueError("session in two cut files: " + s)
+ cut[s] = e
+ ss = [l.strip() for l in a.sessions.read_text().splitlines() if l.strip()]
+ if len(set(ss)) != len(ss) or set(ss) - set(cut):
+ raise ValueError(f"dup sessions or missing cuts: {sorted(set(ss) - set(cut))[:5]}")
+ with ThreadPoolExecutor(32) as ex:
+ entries = list(ex.map(lambda s: U._scan_episode(os.path.join(a.root, s), IMAGE_KEYS), ss))
+ rows, drop, st = [], [], collections.Counter()
+ for s, e in zip(ss, entries):
+ if e is None:
+ raise ValueError("scan rejected " + s)
+ c = cut[s]
+ if e.num_frames != c["n_frames"] or abs(e.fps - 30.0) > 1e-6:
+ raise ValueError(f"{s}: frames {e.num_frames} vs cut {c['n_frames']}, fps {e.fps}")
+ task = e.task
+ if task != a.prompt:
+ st["prompt_overridden:" + s] = 1
+ task = a.prompt
+ r = anchors(c["keep_ranges"], e.num_frames)
+ if not r:
+ drop.append(s)
+ continue
+ rows.append([e.path, e.num_frames, task, e.fps, r])
+ st["frames"] += e.num_frames; st["samples"] += sum(hi - lo for lo, hi in r); st["segments"] += len(r)
+ st["task:" + task] += 1
+ payload = {"version": U.MANIFEST_VERSION, "roots": [a.root], "image_keys": sorted(IMAGE_KEYS), "episodes": rows}
+ a.out.parent.mkdir(parents=True, exist_ok=True)
+ a.out.write_text(json.dumps(payload))
+ meta = {"sessions_file": str(a.sessions), "cuts": {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in a.cuts},
+ "window_offsets": [OFF_MIN, OFF_MAX], "episodes": len(rows), "dropped_empty": drop, **st,
+ "manifest_sha256": hashlib.sha256(a.out.read_bytes()).hexdigest()}
+ a.out.with_suffix(".meta.json").write_text(json.dumps(meta, indent=1, ensure_ascii=False))
+ print(json.dumps(meta, ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/openpi-umi/scripts/compute_norm_stats.py b/openpi-umi/scripts/compute_norm_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..6008f67ac2ec4314dec74292b4a688a1b68c0e79
--- /dev/null
+++ b/openpi-umi/scripts/compute_norm_stats.py
@@ -0,0 +1,143 @@
+"""Compute normalization statistics for a config.
+
+This script is used to compute the normalization statistics for a given config. It
+will compute the mean and standard deviation of the data in the dataset and save it
+to the config assets directory.
+"""
+
+import dataclasses
+import pathlib
+
+import numpy as np
+import tqdm
+import tyro
+
+import openpi.models.model as _model
+import openpi.shared.normalize as normalize
+import openpi.training.config as _config
+import openpi.training.data_loader as _data_loader
+import openpi.transforms as transforms
+
+
+class RemoveStrings(transforms.DataTransformFn):
+ def __call__(self, x: dict) -> dict:
+ return {k: v for k, v in x.items() if not np.issubdtype(np.asarray(v).dtype, np.str_)}
+
+
+def create_torch_dataloader(
+ data_config: _config.DataConfig,
+ action_horizon: int,
+ batch_size: int,
+ model_config: _model.BaseModelConfig,
+ num_workers: int,
+ max_frames: int | None = None,
+) -> tuple[_data_loader.Dataset, int]:
+ if data_config.repo_id is None:
+ raise ValueError("Data config must have a repo_id")
+ dataset = _data_loader.create_torch_dataset(data_config, action_horizon, model_config)
+ dataset = _data_loader.TransformedDataset(
+ dataset,
+ [
+ *data_config.repack_transforms.inputs,
+ *data_config.data_transforms.inputs,
+ # Remove strings since they are not supported by JAX and are not needed to compute norm stats.
+ RemoveStrings(),
+ ],
+ )
+ if max_frames is not None and max_frames < len(dataset):
+ num_batches = max_frames // batch_size
+ shuffle = True
+ else:
+ num_batches = len(dataset) // batch_size
+ shuffle = False
+ data_loader = _data_loader.TorchDataLoader(
+ dataset,
+ local_batch_size=batch_size,
+ num_workers=num_workers,
+ shuffle=shuffle,
+ num_batches=num_batches,
+ )
+ return data_loader, num_batches
+
+
+def create_rlds_dataloader(
+ data_config: _config.DataConfig,
+ action_horizon: int,
+ batch_size: int,
+ max_frames: int | None = None,
+) -> tuple[_data_loader.Dataset, int]:
+ dataset = _data_loader.create_rlds_dataset(data_config, action_horizon, batch_size, shuffle=False)
+ dataset = _data_loader.IterableTransformedDataset(
+ dataset,
+ [
+ *data_config.repack_transforms.inputs,
+ *data_config.data_transforms.inputs,
+ # Remove strings since they are not supported by JAX and are not needed to compute norm stats.
+ RemoveStrings(),
+ ],
+ is_batched=True,
+ )
+ if max_frames is not None and max_frames < len(dataset):
+ num_batches = max_frames // batch_size
+ else:
+ # NOTE: this length is currently hard-coded for DROID.
+ num_batches = len(dataset) // batch_size
+ data_loader = _data_loader.RLDSDataLoader(
+ dataset,
+ num_batches=num_batches,
+ )
+ return data_loader, num_batches
+
+
+def main(
+ config_name: str,
+ max_frames: int | None = None,
+ output_path: str | None = None,
+ action_horizon: int | None = None,
+):
+ """Compute normalization statistics for a config.
+
+ Args:
+ config_name: Name of the config to compute stats for.
+ max_frames: Maximum number of frames to use for computing stats. If None, use all frames.
+ output_path: Custom output path for saving norm stats. If None, use default path
+ (config.assets_dirs / data_config.repo_id).
+ action_horizon: Override model.action_horizon. Must match the training run's
+ --model.action-horizon: UMI action labels are relative to the current
+ frame, so their spread grows with the horizon and stats computed on a
+ longer window mis-scale a shorter-horizon run.
+ """
+ config = _config.get_config(config_name)
+ if action_horizon is not None:
+ config = dataclasses.replace(config, model=dataclasses.replace(config.model, action_horizon=action_horizon))
+ data_config = config.data.create(config.assets_dirs, config.model)
+
+ if data_config.rlds_data_dir is not None:
+ data_loader, num_batches = create_rlds_dataloader(
+ data_config, config.model.action_horizon, config.batch_size, max_frames
+ )
+ else:
+ data_loader, num_batches = create_torch_dataloader(
+ data_config, config.model.action_horizon, config.batch_size, config.model, config.num_workers, max_frames
+ )
+
+ keys = ["state", "actions"]
+ stats = {key: normalize.RunningStats() for key in keys}
+
+ for batch in tqdm.tqdm(data_loader, total=num_batches, desc="Computing stats"):
+ for key in keys:
+ stats[key].update(np.asarray(batch[key]))
+
+ norm_stats = {key: stats.get_statistics() for key, stats in stats.items()}
+
+ # Use custom output path if provided, otherwise use default
+ if output_path is not None:
+ final_output_path = pathlib.Path(output_path)
+ else:
+ final_output_path = config.assets_dirs / data_config.repo_id
+ print(f"Writing stats to: {final_output_path}")
+ normalize.save(final_output_path, norm_stats)
+
+
+if __name__ == "__main__":
+ tyro.cli(main)
diff --git a/openpi-umi/scripts/train_pytorch.py b/openpi-umi/scripts/train_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bdba9ac2ec6b408018cbe090ab9b85dccba4ead
--- /dev/null
+++ b/openpi-umi/scripts/train_pytorch.py
@@ -0,0 +1,868 @@
+"""
+PyTorch training entrypoint for PI0/PI05 with multi-GPU and multi-node (DDP) support.
+This script mirrors the behavior of the JAX trainer (`scripts/train.py` in upstream openpi) but runs
+entirely in PyTorch using the `PI0Pytorch` model and your existing config/data
+pipeline from `src/openpi/training/config.py` and `src/openpi/training/data_loader.py`.
+
+Usage
+Single GPU:
+ python scripts/train_pytorch.py --exp_name --save_interval
+ Example:
+ python scripts/train_pytorch.py debug --exp_name pytorch_ddp_test
+ python scripts/train_pytorch.py debug --exp_name pytorch_ddp_test --resume # Resume from latest checkpoint
+Multi-GPU (single node):
+ torchrun --standalone --nnodes=1 --nproc_per_node= scripts/train_pytorch.py --exp_name
+ Example:
+ torchrun --standalone --nnodes=1 --nproc_per_node=2 scripts/train_pytorch.py pi0_aloha_sim --exp_name pytorch_ddp_test
+ torchrun --standalone --nnodes=1 --nproc_per_node=2 scripts/train_pytorch.py pi0_aloha_sim --exp_name pytorch_ddp_test --resume
+Multi-Node Training:
+ torchrun \
+ --nnodes= --nproc_per_node= --node_rank= \
+ --master_addr= --master_port= \
+ scripts/train_pytorch.py --exp_name= --save_interval
+
+"""
+
+import dataclasses
+import collections
+import collections.abc
+import gc
+import logging
+import os
+import platform
+import shutil
+import time
+
+import jax
+import numpy as np
+import safetensors.torch
+import torch
+import torch.distributed as dist
+import torch.nn.parallel
+import tqdm
+
+# Some AIStudio image dependencies still import legacy aliases removed in
+# Python 3.12, for example pyparsing -> collections.MutableMapping.
+for _name in ("Mapping", "MutableMapping", "Sequence", "MutableSequence", "Set", "MutableSet", "Iterable", "Callable"):
+ if not hasattr(collections, _name):
+ setattr(collections, _name, getattr(collections.abc, _name))
+
+class _DisabledWandb:
+ class Image:
+ def __init__(self, *_args, **_kwargs):
+ pass
+
+ class _Run:
+ id = "disabled"
+
+ run = _Run()
+
+ @staticmethod
+ def init(*_args, **_kwargs):
+ return _DisabledWandb.run
+
+ @staticmethod
+ def log(*_args, **_kwargs):
+ pass
+
+ @staticmethod
+ def finish():
+ pass
+
+
+try:
+ import wandb
+except ImportError:
+ print("Warning: wandb not installed, disabling training tracking")
+ wandb = _DisabledWandb()
+
+import openpi.models.pi0_config
+import openpi.models_pytorch.pi0_pytorch
+import openpi.shared.normalize as _normalize
+import openpi.training.config as _config
+import openpi.training.data_loader as _data
+
+
+def init_logging():
+ level_mapping = {"DEBUG": "D", "INFO": "I", "WARNING": "W", "ERROR": "E", "CRITICAL": "C"}
+
+ class CustomFormatter(logging.Formatter):
+ def format(self, record):
+ record.levelname = level_mapping.get(record.levelname, record.levelname)
+ return super().format(record)
+
+ formatter = CustomFormatter(
+ fmt="%(asctime)s.%(msecs)03d [%(levelname)s] %(message)-80s (%(process)d:%(filename)s:%(lineno)s)",
+ datefmt="%H:%M:%S",
+ )
+ logger = logging.getLogger()
+ logger.setLevel(logging.INFO)
+ if not logger.handlers:
+ ch = logging.StreamHandler()
+ ch.setFormatter(formatter)
+ logger.addHandler(ch)
+ else:
+ logger.handlers[0].setFormatter(formatter)
+
+
+def init_wandb(config: _config.TrainConfig, *, resuming: bool, enabled: bool = True):
+ """Initialize wandb logging."""
+ if not enabled:
+ wandb.init(mode="disabled")
+ return
+
+ ckpt_dir = config.checkpoint_dir
+ if not ckpt_dir.exists():
+ raise FileNotFoundError(f"Checkpoint directory {ckpt_dir} does not exist.")
+
+ if resuming:
+ run_id = (ckpt_dir / "wandb_id.txt").read_text().strip()
+ wandb.init(id=run_id, resume="must", project=config.project_name)
+ else:
+ wandb.init(
+ name=config.exp_name,
+ config=dataclasses.asdict(config),
+ project=config.project_name,
+ )
+ (ckpt_dir / "wandb_id.txt").write_text(wandb.run.id)
+
+
+def setup_ddp():
+ from datetime import timedelta
+
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
+ use_ddp = world_size > 1
+ if use_ddp and not torch.distributed.is_initialized():
+ backend = "nccl" if torch.cuda.is_available() else "gloo"
+
+ # Set up debugging environment variables for DDP issues
+ if os.environ.get("TORCH_DISTRIBUTED_DEBUG") is None:
+ os.environ["TORCH_DISTRIBUTED_DEBUG"] = "INFO"
+
+ # Long timeout (4 h): data loading can take very long
+ timeout_seconds = int(os.environ.get("DDP_TIMEOUT", "14400")) # 4 hours default
+ rank = int(os.environ.get("RANK", "0"))
+ logging.info(f"[Rank {rank}] Initializing process group: backend={backend}, world_size={world_size}, timeout={timeout_seconds}s")
+
+ torch.distributed.init_process_group(
+ backend=backend,
+ init_method="env://",
+ timeout=timedelta(seconds=timeout_seconds),
+ )
+ logging.info(f"[Rank {rank}] Process group initialized successfully")
+
+ local_rank = int(os.environ.get("LOCAL_RANK", os.environ.get("RANK", "0")))
+ device = torch.device(f"cuda:{local_rank}" if torch.cuda.is_available() else "cpu")
+ if torch.cuda.is_available():
+ torch.cuda.set_device(device)
+ return use_ddp, local_rank, device
+
+
+def cleanup_ddp():
+ if torch.distributed.is_initialized():
+ torch.distributed.barrier()
+ torch.distributed.destroy_process_group()
+
+
+def set_seed(seed: int, local_rank: int):
+ torch.manual_seed(seed + local_rank)
+ np.random.seed(seed + local_rank)
+ if torch.cuda.is_available():
+ torch.cuda.manual_seed_all(seed + local_rank)
+
+
+def build_datasets(config: _config.TrainConfig, *, epoch_based: bool = False):
+ # Use the unified data loader with PyTorch framework
+ data_loader = _data.create_data_loader(config, framework="pytorch", shuffle=True, epoch_based=epoch_based)
+ return data_loader, data_loader.data_config()
+
+
+def get_dataset_size(config: _config.TrainConfig) -> int:
+ """Get the number of samples in the dataset."""
+ data_config = config.data.create(config.assets_dirs, config.model)
+ if data_config.rlds_data_dir is not None:
+ raise NotImplementedError("Dataset size calculation for RLDS data loader is not supported yet")
+ dataset = _data.create_torch_dataset(data_config, config.model.action_horizon, config.model)
+ return len(dataset)
+
+
+def get_model_state_dict(model):
+ """Get state dict from model, handling DDP wrapper."""
+ return (
+ model.module.state_dict()
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel)
+ else model.state_dict()
+ )
+
+
+def get_model_parameters(model):
+ """Get parameters from model, handling DDP wrapper."""
+ return (
+ model.module.parameters()
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel)
+ else model.parameters()
+ )
+
+
+def save_checkpoint(
+ model,
+ optimizer,
+ global_step,
+ config,
+ is_main,
+ data_config,
+ *,
+ current_epoch: int | None = None,
+ epoch_just_finished: bool = False,
+):
+ """Save a checkpoint with model state, optimizer state, and metadata.
+
+ Args:
+ model: The model to save.
+ optimizer: The optimizer to save.
+ global_step: The current global step.
+ config: The training config.
+ is_main: Whether this is the main process.
+ data_config: The data config.
+ current_epoch: The current epoch (1-indexed, after completion).
+ epoch_just_finished: Whether an epoch just finished (for epoch-based saving).
+ """
+ if not is_main:
+ return
+
+ # Determine if we should save
+ should_save = False
+ is_final_step = global_step == config.num_train_steps
+
+ if config.num_epochs is not None and current_epoch is not None:
+ # Epoch-based saving: save every save_interval epochs
+ if epoch_just_finished and (current_epoch % config.save_interval == 0 or is_final_step):
+ should_save = True
+ else:
+ # Step-based saving: save every save_interval steps
+ if (global_step % config.save_interval == 0 and global_step > 0) or is_final_step:
+ should_save = True
+
+ if should_save:
+ # Determine checkpoint directory name
+ if config.num_epochs is not None and current_epoch is not None:
+ # Epoch-based training: use epoch number as directory name
+ ckpt_name = f"epoch_{current_epoch}"
+ else:
+ # Step-based training: use step number as directory name
+ ckpt_name = f"{global_step}"
+
+ # Create temporary directory for atomic checkpoint saving
+ final_ckpt_dir = config.checkpoint_dir / ckpt_name
+ tmp_ckpt_dir = config.checkpoint_dir / f"tmp_{ckpt_name}"
+
+ # Remove any existing temp directory and create new one
+ if tmp_ckpt_dir.exists():
+ shutil.rmtree(tmp_ckpt_dir)
+ tmp_ckpt_dir.mkdir(parents=True, exist_ok=True)
+
+ # Save model state using safetensors (handle shared tensors)
+ model_to_save = model.module if isinstance(model, torch.nn.parallel.DistributedDataParallel) else model
+ safetensors.torch.save_model(model_to_save, tmp_ckpt_dir / "model.safetensors")
+
+ # Save optimizer state using PyTorch format
+ torch.save(optimizer.state_dict(), tmp_ckpt_dir / "optimizer.pt")
+
+ # Save training metadata (avoid saving full config to prevent JAX/Flax compatibility issues)
+ metadata = {
+ "global_step": global_step,
+ "config": dataclasses.asdict(config),
+ "timestamp": time.time(),
+ }
+ if current_epoch is not None:
+ metadata["epoch"] = current_epoch
+ torch.save(metadata, tmp_ckpt_dir / "metadata.pt")
+
+ # save norm stats
+ norm_stats = data_config.norm_stats
+ if norm_stats is not None and data_config.asset_id is not None:
+ _normalize.save(tmp_ckpt_dir / "assets" / data_config.asset_id, norm_stats)
+
+ # Atomically move temp directory to final location
+ if final_ckpt_dir.exists():
+ shutil.rmtree(final_ckpt_dir)
+ tmp_ckpt_dir.rename(final_ckpt_dir)
+
+ if current_epoch is not None:
+ logging.info(f"Saved checkpoint at epoch {current_epoch}, step {global_step} -> {final_ckpt_dir}")
+ else:
+ logging.info(f"Saved checkpoint at step {global_step} -> {final_ckpt_dir}")
+
+ # Log checkpoint to wandb
+ if config.wandb_enabled:
+ wandb.log({"checkpoint_step": global_step}, step=global_step)
+
+
+def load_checkpoint(model, optimizer, checkpoint_dir, device):
+ """Load the latest checkpoint and return the global step."""
+ checkpoint_steps = [
+ int(d.name)
+ for d in checkpoint_dir.iterdir()
+ if d.is_dir() and d.name.isdigit() and not d.name.startswith("tmp_")
+ ]
+
+ if not checkpoint_steps:
+ raise FileNotFoundError(f"No checkpoints found in {checkpoint_dir}")
+
+ latest_step = max(checkpoint_steps)
+ ckpt_dir = checkpoint_dir / f"{latest_step}"
+
+ # Clear memory before loading checkpoints
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ gc.collect()
+ log_memory_usage(device, latest_step, "before_loading_checkpoint")
+
+ try:
+ # Load model state with error handling
+ logging.info("Loading model state...")
+ safetensors_path = ckpt_dir / "model.safetensors"
+
+ if safetensors_path.exists():
+ model_to_load = model.module if isinstance(model, torch.nn.parallel.DistributedDataParallel) else model
+ safetensors.torch.load_model(model_to_load, safetensors_path, device=str(device))
+ logging.info("Loaded model state from safetensors format")
+ else:
+ raise FileNotFoundError(f"No model checkpoint found at {ckpt_dir}")
+
+ torch.cuda.empty_cache()
+ gc.collect()
+ log_memory_usage(device, latest_step, "after_loading_model")
+
+ # Load optimizer state with error handling
+ logging.info("Loading optimizer state...")
+ optimizer_path = ckpt_dir / "optimizer.pt"
+
+ if optimizer_path.exists():
+ optimizer_state_dict = torch.load(optimizer_path, map_location=device, weights_only=False)
+ logging.info("Loaded optimizer state from pt format")
+ else:
+ raise FileNotFoundError(f"No optimizer checkpoint found at {ckpt_dir}")
+
+ optimizer.load_state_dict(optimizer_state_dict)
+ del optimizer_state_dict
+ torch.cuda.empty_cache()
+ gc.collect()
+ log_memory_usage(device, latest_step, "after_loading_optimizer")
+
+ # Load metadata
+ logging.info("Loading metadata...")
+ metadata = torch.load(ckpt_dir / "metadata.pt", map_location=device, weights_only=False)
+ global_step = metadata.get("global_step", latest_step)
+ del metadata
+ torch.cuda.empty_cache()
+ gc.collect()
+ log_memory_usage(device, latest_step, "after_loading_metadata")
+
+ logging.info(f"Successfully loaded all checkpoint components from step {latest_step}")
+ return global_step
+
+ except RuntimeError as e:
+ if "out of memory" in str(e):
+ # Clear memory and provide detailed error message
+ torch.cuda.empty_cache()
+ gc.collect()
+ logging.error(f"Out of memory error while loading checkpoint: {e!s}")
+ log_memory_usage(device, latest_step, "after_oom_error")
+ raise RuntimeError(
+ "Out of memory while loading checkpoint. Try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True"
+ ) from e
+ raise
+
+
+def get_latest_checkpoint_step(checkpoint_dir):
+ """Get the latest checkpoint step number from a checkpoint directory."""
+ checkpoint_steps = [
+ int(d.name)
+ for d in checkpoint_dir.iterdir()
+ if d.is_dir() and d.name.isdigit() and not d.name.startswith("tmp_")
+ ]
+ return max(checkpoint_steps) if checkpoint_steps else None
+
+
+def log_memory_usage(device, step, phase="unknown"):
+ """Log detailed memory usage information."""
+ if not torch.cuda.is_available():
+ return
+
+ memory_allocated = torch.cuda.memory_allocated(device) / 1e9
+ memory_reserved = torch.cuda.memory_reserved(device) / 1e9
+ memory_free = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)
+ memory_free = memory_free / 1e9
+
+ # Get more detailed memory info
+ memory_stats = torch.cuda.memory_stats(device)
+ max_memory_allocated = memory_stats.get("allocated_bytes.all.peak", 0) / 1e9
+ max_memory_reserved = memory_stats.get("reserved_bytes.all.peak", 0) / 1e9
+
+ # Get DDP info if available
+ ddp_info = ""
+ if dist.is_initialized():
+ ddp_info = f" | DDP: rank={dist.get_rank()}, world_size={dist.get_world_size()}"
+
+ logging.info(
+ f"Step {step} ({phase}): GPU memory - allocated: {memory_allocated:.2f}GB, reserved: {memory_reserved:.2f}GB, free: {memory_free:.2f}GB, peak_allocated: {max_memory_allocated:.2f}GB, peak_reserved: {max_memory_reserved:.2f}GB{ddp_info}"
+ )
+
+
+def train_loop(config: _config.TrainConfig):
+ use_ddp, local_rank, device = setup_ddp()
+ is_main = (not use_ddp) or (dist.get_rank() == 0)
+ set_seed(config.seed, local_rank)
+
+ # Calculate num_train_steps from num_epochs if specified
+ if config.num_epochs is not None:
+ dataset_size = get_dataset_size(config)
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
+ effective_batch_size = config.batch_size # Total batch size across all GPUs
+ steps_per_epoch = dataset_size // effective_batch_size
+ epoch_based_steps = steps_per_epoch * config.num_epochs
+ logging.info(
+ f"Epoch-based training: {config.num_epochs} epochs, {dataset_size} samples, "
+ f"batch_size={effective_batch_size}, steps_per_epoch={steps_per_epoch}, epoch_based_steps={epoch_based_steps}"
+ )
+ # When using epoch-based training, use the epoch-based steps
+ # (ignore the default num_train_steps unless explicitly set to a smaller value via CLI)
+ num_train_steps = epoch_based_steps
+ logging.info(f"Using epoch_based_steps={epoch_based_steps} as num_train_steps")
+
+ # Convert warmup_steps and decay_steps from epoch-based to step-based
+ # In epoch-based training, these values are always interpreted as epoch counts
+ # e.g., warmup_steps=0.1 means warmup for 0.1 epochs
+ lr_schedule = config.lr_schedule
+ if hasattr(lr_schedule, "warmup_steps") and hasattr(lr_schedule, "decay_steps"):
+ warmup_epochs = lr_schedule.warmup_steps
+ decay_epochs = lr_schedule.decay_steps
+
+ warmup_steps = int(warmup_epochs * steps_per_epoch)
+ decay_steps = int(decay_epochs * steps_per_epoch)
+ hold_epochs = getattr(lr_schedule, "hold_steps", 0)
+ hold_steps = int(hold_epochs * steps_per_epoch)
+
+ logging.info(
+ f"Converting lr_schedule: warmup_steps={warmup_epochs} epochs -> {warmup_steps} steps, "
+ f"decay_steps={decay_epochs} epochs -> {decay_steps} steps, hold_steps={hold_epochs} epochs -> {hold_steps} steps"
+ )
+
+ # Update lr_schedule with converted values
+ lr_schedule = dataclasses.replace(
+ lr_schedule,
+ warmup_steps=warmup_steps,
+ decay_steps=decay_steps,
+ **({"hold_steps": hold_steps} if hasattr(lr_schedule, "hold_steps") else {}),
+ )
+ config = dataclasses.replace(config, lr_schedule=lr_schedule)
+
+ # Update config with calculated num_train_steps
+ config = dataclasses.replace(config, num_train_steps=num_train_steps)
+ else:
+ steps_per_epoch = None
+
+ # Initialize checkpoint directory and wandb
+ resuming = False
+ if config.resume:
+ # Find checkpoint directory based on experiment name
+ exp_checkpoint_dir = config.checkpoint_dir
+ if exp_checkpoint_dir.exists():
+ # Use validation to find the latest working checkpoint
+ latest_step = get_latest_checkpoint_step(exp_checkpoint_dir)
+ if latest_step is not None:
+ resuming = True
+ logging.info(
+ f"Resuming from experiment checkpoint directory: {exp_checkpoint_dir} at step {latest_step}"
+ )
+ else:
+ raise FileNotFoundError(f"No valid checkpoints found in {exp_checkpoint_dir} for resume")
+ else:
+ raise FileNotFoundError(f"Experiment checkpoint directory {exp_checkpoint_dir} does not exist for resume")
+ elif config.overwrite and config.checkpoint_dir.exists():
+ shutil.rmtree(config.checkpoint_dir)
+ logging.info(f"Overwriting checkpoint directory: {config.checkpoint_dir}")
+
+ # Create checkpoint directory with experiment name
+ if not resuming:
+ # For new runs, create experiment-specific checkpoint directory
+ exp_checkpoint_dir = config.checkpoint_dir
+ exp_checkpoint_dir.mkdir(parents=True, exist_ok=True)
+ logging.info(f"Created experiment checkpoint directory: {exp_checkpoint_dir}")
+ else:
+ # For resume, checkpoint_dir is already set to the experiment directory
+ logging.info(f"Using existing experiment checkpoint directory: {config.checkpoint_dir}")
+
+ # Initialize wandb (only on main process)
+ if is_main:
+ init_wandb(config, resuming=resuming, enabled=config.wandb_enabled)
+
+ # Build data loader using the unified data loader
+ # Calculate effective batch size per GPU for DDP
+ # For N GPUs, each GPU should get batch_size/N samples, so total across all GPUs is batch_size
+ world_size = torch.distributed.get_world_size() if use_ddp else 1
+ rank = dist.get_rank() if use_ddp else 0
+ effective_batch_size = config.batch_size // world_size
+ logging.info(
+ f"Using batch size per GPU: {effective_batch_size} (total batch size across {world_size} GPUs: {config.batch_size})"
+ )
+
+ # Pass the original batch size to data loader - it will handle DDP splitting internally
+ logging.info(f"[Rank {rank}] Starting data loading...")
+ data_load_start = time.time()
+ # Use epoch_based=True when using num_epochs to allow proper epoch tracking
+ loader, data_config = build_datasets(config, epoch_based=(config.num_epochs is not None))
+ data_load_time = time.time() - data_load_start
+ logging.info(f"[Rank {rank}] Data loading completed in {data_load_time:.1f}s")
+
+ # Barrier so every rank finishes data loading
+ # Long timeout: data loading can take very long
+ if use_ddp:
+ logging.info(f"[Rank {rank}] Waiting for all ranks to complete data loading...")
+ # 4 h timeout, enough for large datasets
+ dist.barrier()
+ logging.info(f"[Rank {rank}] All ranks completed data loading")
+
+ # Log sample images to wandb on first batch
+ if is_main and config.wandb_enabled and not resuming:
+ # Create a separate data loader for sample batch to avoid consuming the main loader
+ sample_data_loader = _data.create_data_loader(config, framework="pytorch", shuffle=False)
+ sample_batch = next(iter(sample_data_loader))
+ # Convert observation and actions to torch tensors
+ observation, actions = sample_batch
+ sample_batch = observation.to_dict()
+ sample_batch["actions"] = actions
+
+ # Create sample images for wandb
+ images_to_log = []
+ # Get batch size from the first image tensor
+ batch_size = next(iter(sample_batch["image"].values())).shape[0]
+ for i in range(min(5, batch_size)):
+ # Concatenate all camera views horizontally for this batch item
+ # Convert from NCHW to NHWC format for wandb
+ img_concatenated = torch.cat([img[i].permute(1, 2, 0) for img in sample_batch["image"].values()], axis=1)
+ img_concatenated = img_concatenated.cpu().numpy()
+ images_to_log.append(wandb.Image(img_concatenated))
+
+ wandb.log({"camera_views": images_to_log}, step=0)
+
+ # Clear sample batch from memory aggressively
+ del sample_batch, observation, actions, images_to_log, img_concatenated
+ del sample_data_loader # Also delete the sample data loader
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ logging.info("Cleared sample batch and data loader from memory")
+
+ # Barrier after wandb logging to ensure all ranks are synchronized before model creation
+ if use_ddp:
+ logging.info(f"[Rank {local_rank}] Waiting for all ranks after wandb logging...")
+ dist.barrier()
+ logging.info(f"[Rank {local_rank}] All ranks synchronized, proceeding to model creation")
+
+ # Build model
+ if not isinstance(config.model, openpi.models.pi0_config.Pi0Config):
+ # Convert dataclass to Pi0Config if needed
+ model_cfg = openpi.models.pi0_config.Pi0Config(
+ dtype=config.pytorch_training_precision,
+ action_dim=config.model.action_dim,
+ action_horizon=config.model.action_horizon,
+ max_token_len=config.model.max_token_len,
+ paligemma_variant=getattr(config.model, "paligemma_variant", "gemma_2b"),
+ action_expert_variant=getattr(config.model, "action_expert_variant", "gemma_300m"),
+ pi05=getattr(config.model, "pi05", False),
+ )
+ else:
+ model_cfg = config.model
+ # Update dtype to match pytorch_training_precision
+ object.__setattr__(model_cfg, "dtype", config.pytorch_training_precision)
+
+ model = openpi.models_pytorch.pi0_pytorch.PI0Pytorch(model_cfg).to(device)
+
+ # Enable gradient checkpointing if configured
+ enable_gradient_checkpointing = False
+ if config.gradient_checkpointing and hasattr(model, "gradient_checkpointing_enable"):
+ enable_gradient_checkpointing = True
+ model.gradient_checkpointing_enable()
+ logging.info("Enabled gradient checkpointing for memory optimization")
+ elif config.gradient_checkpointing:
+ logging.info("Gradient checkpointing requested but not supported for this model")
+ else:
+ logging.info("Gradient checkpointing disabled")
+
+ # Log initial memory usage after model creation
+ if is_main and torch.cuda.is_available():
+ log_memory_usage(device, 0, "after_model_creation")
+
+ # Enable memory optimizations for large-scale training
+ if world_size >= 8:
+ torch.backends.cudnn.benchmark = True
+ torch.backends.cuda.matmul.allow_tf32 = True
+ torch.backends.cudnn.allow_tf32 = True
+ # Set memory allocation configuration
+ os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128,expandable_segments:True"
+ logging.info("Enabled memory optimizations for 8+ GPU training")
+
+ if use_ddp:
+ model = torch.nn.parallel.DistributedDataParallel(
+ model,
+ device_ids=[device.index] if device.type == "cuda" else None,
+ find_unused_parameters=True, # Disable for memory efficiency
+ gradient_as_bucket_view=True, # Enable for memory efficiency
+ static_graph=world_size >= 8, # Enable for 8+ GPUs
+ )
+
+ # Load weights from weight_loader if specified (for fine-tuning)
+ if config.pytorch_weight_path is not None:
+ logging.info(f"Loading weights from: {config.pytorch_weight_path}")
+
+ model_path = os.path.join(config.pytorch_weight_path, "model.safetensors")
+ safetensors.torch.load_model(
+ (model.module if isinstance(model, torch.nn.parallel.DistributedDataParallel) else model), model_path
+ )
+ logging.info(f"Loaded PyTorch weights from {config.pytorch_weight_path}")
+
+ # Optimizer + learning rate schedule from config
+ warmup_steps = config.lr_schedule.warmup_steps
+ peak_lr = config.lr_schedule.peak_lr
+ decay_steps = config.lr_schedule.decay_steps
+ end_lr = config.lr_schedule.decay_lr
+ hold_steps = max(warmup_steps, getattr(config.lr_schedule, "hold_steps", 0))
+ decay_shape = getattr(config.lr_schedule, "decay_shape", "cosine")
+ assert decay_shape in ("cosine", "linear"), decay_shape
+
+ # Create optimizer with config parameters
+ optim = torch.optim.AdamW(
+ model.parameters(),
+ lr=peak_lr,
+ betas=(config.optimizer.b1, config.optimizer.b2),
+ eps=config.optimizer.eps,
+ weight_decay=config.optimizer.weight_decay,
+ )
+
+ # Load checkpoint if resuming
+ global_step = 0
+ if resuming:
+ global_step = load_checkpoint(model, optim, config.checkpoint_dir, device)
+ logging.info(f"Resumed training from step {global_step}")
+
+ def lr_schedule(step: int):
+ if step < warmup_steps:
+ # Match JAX behavior: start from peak_lr / (warmup_steps + 1)
+ init_lr = peak_lr / (warmup_steps + 1)
+ return init_lr + (peak_lr - init_lr) * step / warmup_steps
+ if step < hold_steps:
+ return peak_lr
+ progress = min(1.0, (step - hold_steps) / max(1, decay_steps - hold_steps))
+ if decay_shape == "linear":
+ return peak_lr + (end_lr - peak_lr) * progress
+ # cosine decay
+ cos = 0.5 * (1 + np.cos(np.pi * progress))
+ return end_lr + (peak_lr - end_lr) * cos
+
+ model.train()
+ start_time = time.time()
+ infos = [] # Collect stats over log interval
+ current_epoch = 0
+ if is_main:
+ logging.info(
+ f"Running on: {platform.node()} | world_size={torch.distributed.get_world_size() if use_ddp else 1}"
+ )
+ if config.num_epochs is not None:
+ logging.info(
+ f"Training config: batch_size={config.batch_size}, effective_batch_size={effective_batch_size}, "
+ f"num_epochs={config.num_epochs}, steps_per_epoch={steps_per_epoch}, num_train_steps={config.num_train_steps}"
+ )
+ else:
+ logging.info(
+ f"Training config: batch_size={config.batch_size}, effective_batch_size={effective_batch_size}, num_train_steps={config.num_train_steps}"
+ )
+ logging.info(f"Memory optimizations: gradient_checkpointing={enable_gradient_checkpointing}")
+ logging.info(
+ f"LR schedule: warmup={warmup_steps}, peak_lr={peak_lr:.2e}, decay_steps={decay_steps}, end_lr={end_lr:.2e}"
+ )
+ logging.info(
+ f"Optimizer: {type(config.optimizer).__name__}, weight_decay={config.optimizer.weight_decay}, clip_norm={config.optimizer.clip_gradient_norm}"
+ )
+ logging.info("EMA is not supported for PyTorch training")
+ logging.info(f"Training precision: {model_cfg.dtype}")
+
+ # Training loop - iterate until we reach num_train_steps
+ pbar = (
+ tqdm.tqdm(total=config.num_train_steps, initial=global_step, desc="Training", disable=not is_main)
+ if is_main
+ else None
+ )
+
+ while global_step < config.num_train_steps:
+ # Set epoch for distributed training
+ if use_ddp and hasattr(loader, "set_epoch"):
+ loader.set_epoch(current_epoch)
+
+ # Log epoch start
+ if is_main and steps_per_epoch is not None:
+ logging.info(f"Starting epoch {current_epoch + 1}/{config.num_epochs}")
+
+ for observation, actions in loader:
+ # Check if we've reached the target number of steps
+ if global_step >= config.num_train_steps:
+ break
+
+ # The unified data loader returns (observation, actions) tuple
+ observation = jax.tree.map(lambda x: x.to(device), observation) # noqa: PLW2901
+ actions = actions.to(torch.float32) # noqa: PLW2901
+ actions = actions.to(device) # noqa: PLW2901
+
+ # Update LR
+ for pg in optim.param_groups:
+ pg["lr"] = lr_schedule(global_step)
+
+ # Forward pass
+ losses = model(observation, actions)
+ # Ensure losses is a tensor and handle different return types
+ if isinstance(losses, list | tuple):
+ losses = torch.stack(losses)
+ elif not isinstance(losses, torch.Tensor):
+ losses = torch.tensor(losses, device=device, dtype=torch.float32)
+
+ loss = losses.mean()
+
+ # Backward pass
+ loss.backward()
+
+ # Log memory usage after backward pass
+ if global_step < 5 and is_main and torch.cuda.is_available():
+ log_memory_usage(device, global_step, "after_backward")
+
+ # Gradient clipping
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=config.optimizer.clip_gradient_norm)
+
+ # Optimizer step
+ optim.step()
+ optim.zero_grad(set_to_none=True)
+
+ # Clear gradients more aggressively
+ for param in model.parameters():
+ if param.grad is not None:
+ param.grad.detach_()
+ param.grad = None
+
+ # Collect stats
+ if is_main:
+ infos.append(
+ {
+ "loss": loss.item(),
+ "learning_rate": optim.param_groups[0]["lr"],
+ "grad_norm": float(grad_norm) if isinstance(grad_norm, torch.Tensor) else grad_norm,
+ }
+ )
+
+ if is_main and (global_step % config.log_interval == 0):
+ elapsed = time.time() - start_time
+
+ # Average stats over log interval
+ avg_loss = sum(info["loss"] for info in infos) / len(infos)
+ avg_lr = sum(info["learning_rate"] for info in infos) / len(infos)
+
+ avg_grad_norm = None
+ if any("grad_norm" in info for info in infos):
+ vals = [
+ info["grad_norm"] for info in infos if "grad_norm" in info and info["grad_norm"] is not None
+ ]
+ if len(vals) > 0:
+ avg_grad_norm = sum(vals) / len(vals)
+
+ # Build log message with optional epoch info
+ epoch_info = f" epoch={current_epoch + 1}/{config.num_epochs}" if steps_per_epoch is not None else ""
+ if avg_grad_norm is not None:
+ logging.info(
+ f"step={global_step}{epoch_info} loss={avg_loss:.4f} lr={avg_lr:.2e} grad_norm={avg_grad_norm:.2f} time={elapsed:.1f}s"
+ )
+ else:
+ logging.info(
+ f"step={global_step}{epoch_info} loss={avg_loss:.4f} lr={avg_lr:.2e} time={elapsed:.1f}s"
+ )
+
+ # Log to wandb
+ if config.wandb_enabled and len(infos) > 0:
+ log_payload = {
+ "loss": avg_loss,
+ "learning_rate": avg_lr,
+ "step": global_step,
+ "time_per_step": elapsed / config.log_interval,
+ }
+ if avg_grad_norm is not None:
+ log_payload["grad_norm"] = avg_grad_norm
+ if steps_per_epoch is not None:
+ log_payload["epoch"] = current_epoch + 1
+ wandb.log(log_payload, step=global_step)
+
+ start_time = time.time()
+ infos = [] # Reset stats collection
+
+ global_step += 1
+ # Save checkpoint using the new mechanism (step-based saving only when not using epochs)
+ if config.num_epochs is None:
+ save_checkpoint(model, optim, global_step, config, is_main, data_config)
+
+ # Update progress bar
+ if pbar is not None:
+ pbar.update(1)
+ if steps_per_epoch is not None:
+ pbar.set_postfix(
+ {
+ "loss": f"{loss.item():.4f}",
+ "lr": f"{optim.param_groups[0]['lr']:.2e}",
+ "epoch": f"{current_epoch + 1}/{config.num_epochs}",
+ }
+ )
+ else:
+ pbar.set_postfix(
+ {"loss": f"{loss.item():.4f}", "lr": f"{optim.param_groups[0]['lr']:.2e}", "step": global_step}
+ )
+
+ # End of epoch - synchronize all ranks before proceeding
+ if use_ddp:
+ dist.barrier()
+
+ current_epoch += 1
+ if is_main and steps_per_epoch is not None:
+ logging.info(f"Completed epoch {current_epoch}/{config.num_epochs}, global_step={global_step}")
+
+ # Epoch-based checkpoint saving
+ if config.num_epochs is not None:
+ save_checkpoint(
+ model,
+ optim,
+ global_step,
+ config,
+ is_main,
+ data_config,
+ current_epoch=current_epoch,
+ epoch_just_finished=True,
+ )
+
+ # Barrier after checkpoint saving to ensure all ranks are ready for next epoch
+ if use_ddp:
+ dist.barrier()
+
+ # Close progress bar
+ if pbar is not None:
+ pbar.close()
+
+ # Finish wandb run
+ if is_main and config.wandb_enabled:
+ wandb.finish()
+
+ cleanup_ddp()
+
+
+def main():
+ init_logging()
+ config = _config.cli()
+ train_loop(config)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/openpi-umi/scripts/train_umi_v3.sh b/openpi-umi/scripts/train_umi_v3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7fe0c7f03284f59d5bcfe44d710711989a50f954
--- /dev/null
+++ b/openpi-umi/scripts/train_umi_v3.sh
@@ -0,0 +1,104 @@
+#!/bin/bash
+# ============================================================================
+# pi05_umi_v3 single-node training (smoke or full run).
+#
+# * Runs from this checkout via PYTHONPATH (no pip install).
+# * transformers is patched in a local shadow copy prepended to PYTHONPATH,
+# so site-packages is left untouched.
+# * Builds the episode manifest once up front, so torchrun ranks don't each
+# rescan thousands of episode directories.
+# * Norm stats skip video decoding (OPENPI_UMI_V3_SKIP_VIDEOS=1, state/action only).
+#
+# Usage:
+# DATA_ROOT=/path/to/lerobot_v3 PYTORCH_WEIGHT_PATH=/path/to/pi05_base_pytorch \
+# [TOKENIZER_DIR=/path/to/dir_containing_paligemma-3b-pt-224] # optional, for offline machines
+# bash scripts/train_umi_v3.sh # smoke: 30 steps
+# NUM_TRAIN_STEPS=50000 (or NUM_EPOCHS=2) BATCH_SIZE=32 EXP_NAME=xxx ... # full run
+# bash scripts/train_umi_v3.sh --lr-schedule.peak-lr 7.5e-5 ... # extra args go to train_pytorch.py
+# DATA_ROOT may hold several roots separated by ':'. The manifest file is keyed by the
+# md5 of DATA_ROOT; norm stats are recomputed whenever DATA_ROOT changes.
+# ============================================================================
+set -e
+
+CONFIG_NAME=pi05_umi_v3
+: "${DATA_ROOT:?set DATA_ROOT to the directory holding one LeRobot v3.0 dataset per episode}"
+: "${PYTORCH_WEIGHT_PATH:?set PYTORCH_WEIGHT_PATH to a PyTorch pi05 checkpoint dir (model.safetensors)}"
+EXP_NAME=${EXP_NAME:-umi_v3_smoke_$(date +%Y%m%d_%H%M%S)}
+NUM_GPUS=${NUM_GPUS:-$(nvidia-smi -L 2>/dev/null | wc -l)}
+BATCH_SIZE=${BATCH_SIZE:-16} # smoke default; scale with GPUs / memory
+NUM_TRAIN_STEPS=${NUM_TRAIN_STEPS:-30} # smoke default; ignored when NUM_EPOCHS is set
+NUM_WORKERS=${NUM_WORKERS:-16} # video decoding dominates sample latency
+NORM_MAX_FRAMES=${NORM_MAX_FRAMES:-100000} # frames sampled for norm stats; empty = all
+WORK_DIR=$(cd "$(dirname "$0")/.." && pwd)
+cd "$WORK_DIR"
+
+echo "### STEP 0: env (shadow transformers + PYTHONPATH)"
+TF_DIR=$(python3 -c 'import transformers, os; print(os.path.dirname(transformers.__file__))')
+SHADOW="$WORK_DIR/.tf_shadow"
+if [ ! -d "$SHADOW/transformers" ]; then
+ mkdir -p "$SHADOW"
+ cp -r "$TF_DIR" "$SHADOW/transformers"
+fi
+cp -r src/openpi/models_pytorch/transformers_replace/* "$SHADOW/transformers/"
+export PYTHONPATH="$SHADOW:$WORK_DIR/src:$WORK_DIR/packages/openpi-client/src${PYTHONPATH:+:$PYTHONPATH}"
+
+export USE_TF=0 TRANSFORMERS_NO_TF=1 HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1
+export WANDB_MODE=${WANDB_MODE:-disabled}
+export OPENPI_UMI_V3_ROOTS="$DATA_ROOT"
+ROOT_HASH=$(echo -n "$DATA_ROOT" | md5sum | cut -c1-12)
+export OPENPI_UMI_V3_MANIFEST=${MANIFEST:-$WORK_DIR/assets/umi_v3_manifests/${ROOT_HASH}.json}
+
+echo "=== CONFIG=$CONFIG_NAME EXP=$EXP_NAME"
+echo "=== DATA_ROOT=$DATA_ROOT"
+echo "=== MANIFEST=$OPENPI_UMI_V3_MANIFEST"
+echo "=== gpus=$NUM_GPUS bs=$BATCH_SIZE steps=$NUM_TRAIN_STEPS workers=$NUM_WORKERS"
+
+echo "### STEP 1: sanity checks"
+for r in ${DATA_ROOT//:/ }; do [ -d "$r" ] || { echo "DATA_ROOT not found: $r"; exit 1; }; done
+[ -f "$PYTORCH_WEIGHT_PATH/model.safetensors" ] || { echo "no model.safetensors in $PYTORCH_WEIGHT_PATH"; exit 1; }
+echo "ok base weights: $PYTORCH_WEIGHT_PATH"
+
+echo "### STEP 2: tokenizer model dir"
+if [ ! -e model/paligemma-3b-pt-224/tokenizer.model ] && [ -n "$TOKENIZER_DIR" ]; then
+ ln -sfn "$TOKENIZER_DIR" model
+fi
+if [ -e model/paligemma-3b-pt-224/tokenizer.model ]; then
+ echo "ok tokenizer: $(readlink -f model)/paligemma-3b-pt-224"
+else
+ echo "no local tokenizer; it will be downloaded from gs://big_vision on first use"
+fi
+
+echo "### STEP 3: prebuild episode manifest"
+python3 - </dev/null)" != "$DATA_ROOT" ]; then
+ # Exit code is ignored (worker teardown on network filesystems can raise); the output file decides.
+ OPENPI_UMI_V3_SKIP_VIDEOS=1 python3 scripts/compute_norm_stats.py \
+ --config-name "$CONFIG_NAME" ${NORM_MAX_FRAMES:+--max-frames "$NORM_MAX_FRAMES"} || true
+ [ -f "$NORM_DIR/norm_stats.json" ] || { echo "norm stats not produced: $NORM_DIR/norm_stats.json"; exit 1; }
+ echo -n "$DATA_ROOT" > "$NORM_MARKER"
+else
+ echo "ok reusing norm stats: $NORM_DIR (FORCE_NORM=1 to recompute)"
+fi
+
+echo "### STEP 5: train ($NUM_GPUS GPUs)"
+torchrun --standalone --nproc_per_node="$NUM_GPUS" \
+ scripts/train_pytorch.py "$CONFIG_NAME" \
+ --exp-name "$EXP_NAME" \
+ --batch-size "$BATCH_SIZE" \
+ $([ -n "$NUM_EPOCHS" ] && echo --num-epochs "$NUM_EPOCHS" || echo --num-train-steps "$NUM_TRAIN_STEPS") \
+ --num-workers "$NUM_WORKERS" \
+ --pytorch-weight-path "$PYTORCH_WEIGHT_PATH" \
+ "$@"
+
+echo "ok DONE: checkpoints -> $WORK_DIR/checkpoints/$CONFIG_NAME/$EXP_NAME"
diff --git a/openpi-umi/src/openpi/__init__.py b/openpi-umi/src/openpi/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/openpi-umi/src/openpi/conftest.py b/openpi-umi/src/openpi/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..5002b629de77953e03f24157f6ba4c88fc448468
--- /dev/null
+++ b/openpi-umi/src/openpi/conftest.py
@@ -0,0 +1,17 @@
+import os
+
+import pynvml
+import pytest
+
+
+def set_jax_cpu_backend_if_no_gpu() -> None:
+ try:
+ pynvml.nvmlInit()
+ pynvml.nvmlShutdown()
+ except pynvml.NVMLError:
+ # No GPU found.
+ os.environ["JAX_PLATFORMS"] = "cpu"
+
+
+def pytest_configure(config: pytest.Config) -> None:
+ set_jax_cpu_backend_if_no_gpu()
diff --git a/openpi-umi/src/openpi/models/__init__.py b/openpi-umi/src/openpi/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/openpi-umi/src/openpi/models/gemma.py b/openpi-umi/src/openpi/models/gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1623d19d12517977d55e193361c5ced481efbc8
--- /dev/null
+++ b/openpi-umi/src/openpi/models/gemma.py
@@ -0,0 +1,459 @@
+# Copyright 2024 Big Vision Authors.
+#
+# 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.
+
+"""Gemma adaptation for Pi, taken from big_vision.
+
+We follow this einsum axis naming convention:
+ B: batch
+ T: query length
+ S: k/v length
+ N: num query heads
+ K: num k/v heads
+ G: num query heads per k/v head
+ H: head dim
+ D: d_model ("features")
+"""
+
+from collections.abc import Sequence
+import dataclasses
+from typing import Literal, TypeAlias
+
+import einops
+import flax.linen as nn
+import jax
+import jax.numpy as jnp
+
+import openpi.models.lora as lora
+import openpi.shared.array_typing as at
+import openpi.training.sharding as sharding
+
+PALIGEMMA_VOCAB_SIZE = 257_152
+
+
+@dataclasses.dataclass
+class Config:
+ width: int
+ depth: int
+ mlp_dim: int
+ num_heads: int
+ num_kv_heads: int
+ head_dim: int
+ lora_configs: dict[str, lora.LoRAConfig] = dataclasses.field(default_factory=dict)
+
+
+Variant = Literal["dummy", "gemma_300m", "gemma_300m_lora", "gemma_2b", "gemma_2b_lora"]
+
+
+def get_config(variant: Variant) -> Config:
+ """Returns config for specified gemma variant."""
+ if variant == "dummy":
+ return Config(
+ width=64,
+ depth=4,
+ mlp_dim=128,
+ num_heads=8,
+ num_kv_heads=1,
+ head_dim=16,
+ )
+ if variant == "gemma_300m":
+ # 311M params
+ return Config(
+ width=1024,
+ depth=18,
+ mlp_dim=4096,
+ num_heads=8,
+ num_kv_heads=1,
+ head_dim=256,
+ )
+ if variant == "gemma_2b":
+ return Config(
+ width=2048,
+ depth=18,
+ mlp_dim=16_384,
+ num_heads=8,
+ num_kv_heads=1,
+ head_dim=256,
+ )
+ if variant == "gemma_2b_lora":
+ return Config(
+ width=2048,
+ depth=18,
+ mlp_dim=16_384,
+ num_heads=8,
+ num_kv_heads=1,
+ head_dim=256,
+ lora_configs={"attn": lora.LoRAConfig(rank=16, alpha=16.0), "ffn": lora.LoRAConfig(rank=16, alpha=16.0)},
+ )
+ if variant == "gemma_300m_lora":
+ # 311M params
+ return Config(
+ width=1024,
+ depth=18,
+ mlp_dim=4096,
+ num_heads=8,
+ num_kv_heads=1,
+ head_dim=256,
+ lora_configs={"attn": lora.LoRAConfig(rank=32, alpha=32.0), "ffn": lora.LoRAConfig(rank=32, alpha=32.0)},
+ )
+ raise ValueError(f"Unknown variant: {variant}")
+
+
+@at.typecheck
+class RMSNorm(nn.Module):
+ @nn.compact
+ def __call__(self, x, cond):
+ dtype = x.dtype # original dtype, could be half-precision
+ var = jnp.mean(jnp.square(x.astype(jnp.float32)), axis=-1, keepdims=True) # compute variance in float32
+ normed_inputs = jnp.asarray(x * jnp.reciprocal(jnp.sqrt(var + 1e-06))) # compute normalization in float32
+ if cond is None:
+ # regular RMSNorm
+ scale = self.param("scale", nn.initializers.zeros_init(), (x.shape[-1]))
+ normed_inputs = normed_inputs * (
+ 1 + scale
+ ) # scale by learned parameter in float32 (matches Flax implementation)
+ return normed_inputs.astype(dtype), None # return in original dtype
+
+ # adaptive RMSNorm
+ modulation = nn.Dense(x.shape[-1] * 3, kernel_init=nn.initializers.zeros, dtype=dtype)(cond)
+ scale, shift, gate = jnp.split(modulation[:, None, :], 3, axis=-1)
+ normed_inputs = normed_inputs * (1 + scale) + shift # scale and shift in float32
+ return normed_inputs.astype(dtype), gate
+
+
+@at.typecheck
+class Embedder(nn.Module):
+ """Embedder module."""
+
+ vocab_size: int
+ embed_dim: int
+
+ def setup(self):
+ self.input_embedding_table = self.param(
+ "input_embedding",
+ nn.initializers.normal(),
+ (self.vocab_size, self.embed_dim),
+ )
+
+ def encode(self, x):
+ x = self.input_embedding_table[(x,)]
+ x *= jnp.sqrt(self.embed_dim).astype(x.dtype)
+ return x
+
+ def decode(self, x):
+ return jnp.dot(x, self.input_embedding_table.T)
+
+
+@at.typecheck
+class Attention(nn.Module):
+ """Attention module."""
+
+ configs: Sequence[Config]
+
+ @nn.compact
+ def __call__(self, xs, positions, attn_mask, kv_cache):
+ # all experts must share the same head dim, num heads, and num kv heads for self-attention to work
+ assert all(config.head_dim == self.configs[0].head_dim for config in self.configs)
+ assert all(config.num_heads == self.configs[0].num_heads for config in self.configs)
+ assert all(config.num_kv_heads == self.configs[0].num_kv_heads for config in self.configs)
+
+ dtype = next(x.dtype for x in xs if x is not None) # original dtype, could be half-precision
+
+ qkvs = []
+ for i, (x, config) in enumerate(zip(xs, self.configs, strict=True)):
+ if x is None:
+ continue
+ if config.num_kv_heads == config.num_heads:
+ qkv_einsum = lora.Einsum(
+ shape=(3, config.num_heads, config.width, config.head_dim),
+ name=_name("qkv_einsum", i),
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
+ lora_config=config.lora_configs.get("attn"),
+ )
+ qkvs.append(qkv_einsum("BSD,3KDH->3BSKH", x))
+ else:
+ q_einsum = lora.Einsum(
+ shape=(config.num_heads, config.width, config.head_dim),
+ name=_name("q_einsum", i),
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
+ lora_config=config.lora_configs.get("attn"),
+ )
+ q = q_einsum("BTD,NDH->BTNH", x)
+ kv_einsum = lora.Einsum(
+ shape=(2, config.num_kv_heads, config.width, config.head_dim),
+ name=_name("kv_einsum", i),
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
+ lora_config=config.lora_configs.get("attn"),
+ )
+ k, v = kv_einsum("BSD,2KDH->2BSKH", x)
+ qkvs.append((q, k, v))
+
+ q, k, v = (jnp.concatenate(y, axis=1) for y in zip(*qkvs, strict=True))
+
+ q = _apply_rope(q, positions=positions)
+ q *= self.configs[0].head_dim ** -0.5
+
+ k = _apply_rope(k, positions=positions)
+
+ # should still be half-precision here (if input was half-precision)
+ assert q.dtype == k.dtype == v.dtype == dtype
+
+ if kv_cache is not None:
+ cache_k, cache_v = kv_cache
+ k = jnp.concatenate([cache_k, k], axis=1)
+ v = jnp.concatenate([cache_v, v], axis=1)
+
+ q = einops.rearrange(q, "B T (K G) H -> B T K G H", K=self.configs[0].num_kv_heads)
+ logits = jnp.einsum("BTKGH,BSKH->BKGTS", q, k, preferred_element_type=jnp.float32)
+
+ if attn_mask.shape != (q.shape[0], 1, q.shape[1], k.shape[1]):
+ raise ValueError(
+ f"Attention mask with shape {attn_mask.shape} but shapes for q and k are: {q.shape} and {k.shape}"
+ )
+
+ # big_neg = jnp.finfo(logits.dtype).min
+ big_neg = -2.3819763e38 # See gemma/modules.py
+ masked_logits = jnp.where(attn_mask[:, :, None, :, :], logits, big_neg)
+
+ probs = jax.nn.softmax(masked_logits, axis=-1).astype(dtype)
+
+ encoded = jnp.einsum("BKGTS,BSKH->BTKGH", probs, v)
+ encoded = einops.rearrange(encoded, "B T K G H -> B T (K G) H")
+
+ out = []
+ start = 0
+ for i, (x, config) in enumerate(zip(xs, self.configs, strict=True)):
+ if x is not None:
+ end = start + x.shape[1]
+ out_einsum = lora.Einsum(
+ shape=(config.num_heads, config.head_dim, config.width),
+ name=_name("attn_vec_einsum", i),
+ init_fn=nn.initializers.lecun_normal(in_axis=(-3, -2), out_axis=-1),
+ lora_config=config.lora_configs.get("attn"),
+ )
+ out.append(out_einsum("BTNH,NHD->BTD", encoded[:, start:end]))
+ start = end
+ else:
+ out.append(None)
+
+ return out, (k, v)
+
+
+@at.typecheck
+class FeedForward(nn.Module):
+ """Feed forward module."""
+
+ features: int
+ hidden_dim: int
+
+ @nn.compact
+ def __call__(self, x):
+ dtype = x.dtype # original dtype, could be half-precision
+ w_gating = self.param(
+ "gating_einsum",
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
+ (2, self.features, self.hidden_dim),
+ ).astype(dtype)
+ ff_gate = jnp.dot(x, w_gating[0])
+ gate_value = nn.gelu(ff_gate)
+
+ ff1 = jnp.dot(x, w_gating[1])
+ activations = gate_value * ff1
+
+ w_linear = self.param(
+ "linear",
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1),
+ (self.hidden_dim, self.features),
+ ).astype(dtype)
+ outputs = jnp.dot(activations, w_linear)
+ assert outputs.dtype == dtype
+ return outputs
+
+
+@at.typecheck
+class Block(nn.Module):
+ """Transformer block."""
+
+ configs: tuple[Config, ...]
+
+ dropout: float = 0.0
+ dropout_bdims: tuple[int, ...] = ()
+
+ @nn.compact
+ def __call__(self, xs, kv_cache, positions, attn_mask, adarms_cond, deterministic=True): # noqa: FBT002
+ xs = sharding.activation_sharding_constraint(xs)
+ drop = nn.Dropout(self.dropout, self.dropout_bdims) if self.dropout else lambda x, _: x
+
+ attn = Attention(configs=self.configs, name="attn")
+
+ pre_attn = []
+ gates = []
+ for i, x in enumerate(xs):
+ if x is not None:
+ x, gate = RMSNorm(name=_name("pre_attention_norm", i))(x, adarms_cond[i]) # noqa: PLW2901
+ pre_attn.append(x)
+ gates.append(gate if x is not None else None)
+
+ pre_attn = sharding.activation_sharding_constraint(pre_attn)
+ post_attn, kv_cache = attn(pre_attn, positions, attn_mask, kv_cache)
+ post_attn = jax.tree.map(lambda x: drop(x, deterministic), post_attn)
+ post_attn = sharding.activation_sharding_constraint(post_attn)
+ xs = [_gated_residual(x, y, gate) for x, y, gate in zip(xs, post_attn, gates, strict=True)]
+ xs = sharding.activation_sharding_constraint(xs)
+
+ out = []
+ gates = []
+ for i, (x, config) in enumerate(zip(xs, self.configs, strict=True)):
+ if x is not None:
+ x, gate = RMSNorm(name=_name("pre_ffw_norm", i))(x, adarms_cond[i]) # noqa: PLW2901
+ x = lora.FeedForward( # noqa: PLW2901
+ features=config.width,
+ hidden_dim=config.mlp_dim,
+ name=_name("mlp", i),
+ lora_config=config.lora_configs.get("ffn"),
+ )(x)
+ out.append(x)
+ gates.append(gate if x is not None else None)
+
+ out = sharding.activation_sharding_constraint(out)
+ out = jax.tree.map(lambda x: drop(x, deterministic), out)
+ xs = [_gated_residual(x, y, gate) for x, y, gate in zip(xs, out, gates, strict=True)]
+ xs = sharding.activation_sharding_constraint(xs)
+
+ return xs, kv_cache
+
+
+KVCache: TypeAlias = tuple[at.Float[at.Array, "l b _t _k _h"], at.Float[at.Array, "l b _t _v _h"]]
+
+
+@at.typecheck
+class Module(nn.Module):
+ """Transformer model, supporting a mixture of different weights for different tokens."""
+
+ configs: Sequence[Config] # list of configs, one for each expert
+ embed_dtype: str
+
+ dropout: float = 0.0
+ dropout_bdims: tuple[int, ...] = () # Every float is dropped independently.
+ adarms: bool = False
+
+ def setup(self):
+ # all experts must have the same depth
+ assert all(config.depth == self.configs[0].depth for config in self.configs)
+
+ self.embedder = Embedder(
+ vocab_size=PALIGEMMA_VOCAB_SIZE,
+ embed_dim=self.configs[0].width, # embedder for first expert only
+ name="embedder",
+ )
+ block_cls = nn.remat(
+ Block,
+ prevent_cse=False,
+ static_argnums=(5,), # 0=self, 6=deterministic
+ policy=jax.checkpoint_policies.nothing_saveable,
+ )
+ self.layers = nn.scan(
+ block_cls,
+ variable_axes={"params": 0},
+ split_rngs={"params": True, "dropout": True},
+ in_axes=(
+ 0,
+ nn.broadcast,
+ nn.broadcast,
+ nn.broadcast,
+ nn.broadcast,
+ ), # 0=kv_cache, 1=positions, 2=mask, 3=adarms_cond, 4=deterministic
+ length=self.configs[0].depth,
+ )(
+ configs=self.configs,
+ dropout=self.dropout,
+ dropout_bdims=self.dropout_bdims,
+ )
+ self.final_norms = [RMSNorm(name=_name("final_norm", i)) for i in range(len(self.configs))]
+
+ @at.typecheck
+ def embed(self, tokens: at.Int[at.Array, "b t"]) -> at.Float[at.Array, "b t d"]:
+ return self.embedder.encode(tokens).astype(self.embed_dtype)
+
+ @at.typecheck
+ def __call__(
+ self,
+ # list of token arrays, one for each expert, or None if that expert should not be run
+ embedded: Sequence[at.Float[at.Array, "b _t _d"] | None],
+ positions: at.Int[at.Array, "b t"],
+ mask: at.Bool[at.Array, "b t s"],
+ adarms_cond: Sequence[at.Float[at.Array, "b _d"] | None] | None = None,
+ *,
+ kv_cache: KVCache | None = None,
+ deterministic: bool = True,
+ ) -> tuple[Sequence[at.Float[at.Array, "b _t _d"] | None], KVCache]:
+ embedded = jax.tree.map(lambda e: e.astype(self.embed_dtype), embedded)
+ mask = jnp.asarray(mask)[:, None, :, :]
+ if adarms_cond is None:
+ adarms_cond = [None] * len(self.configs)
+
+ embedded, kv_cache = self.layers(embedded, kv_cache, positions, mask, adarms_cond, deterministic)
+
+ assert all(e.dtype == jnp.dtype(self.embed_dtype) for e in embedded if e is not None)
+
+ return [
+ f(e, a)[0] if e is not None else e for f, e, a in zip(self.final_norms, embedded, adarms_cond, strict=True)
+ ], kv_cache
+
+ def init(self, use_adarms: Sequence[bool]):
+ """Convenience method for initializing all parameters, necessary due to the quirks of linen."""
+ self.embed(jnp.zeros((1, 1), dtype=jnp.int32))
+ self(
+ [jnp.zeros((1, 1, c.width)) for c in self.configs],
+ jnp.zeros((1, len(self.configs)), dtype=jnp.int32),
+ jnp.zeros((1, len(self.configs), len(self.configs)), dtype=bool),
+ adarms_cond=[jnp.zeros((1, c.width)) if u else None for u, c in zip(use_adarms, self.configs, strict=True)],
+ )
+
+
+def _apply_rope(x, *, positions, max_wavelength=10_000):
+ """Applies RoPE positions [B, L] to x [B, L, H, D]."""
+ freq_exponents = (2.0 / x.shape[-1]) * jnp.arange(x.shape[-1] // 2, dtype=jnp.float32)
+ timescale = max_wavelength**freq_exponents
+ radians = positions[..., None] / timescale[None, None, :]
+ radians = radians[..., None, :]
+ assert radians.dtype == jnp.float32
+ # radians.shape = [...,L,1,d=D/2]
+ sin, cos = jnp.sin(radians), jnp.cos(radians)
+ x1, x2 = jnp.split(x, 2, axis=-1)
+ res = jnp.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1)
+ assert res.dtype == jnp.float32
+ # The original bigvision impl allows RoPE to upcast to float32. It is then immediately downcast again to the cache
+ # dtype when in inference mode (but not in training mode). I don't think any of this was intentional. Based on the
+ # original DeepMind impl, as well as the widely-used transformers impl, it is ok to always downcast back to bfloat16
+ # here.
+ return res.astype(x.dtype)
+
+
+def _name(name, i):
+ # we name layers like this because we want the first expert's weights to have no suffix (e.g., "attn"), so that they
+ # can be loaded seamlessly from the existing PaliGemma checkpoint. subsequent experts will have a suffix (e.g.,
+ # "attn_1") and their weights will be initialized from scratch. in practice, we only use two experts -- PaliGemma,
+ # and the action expert.
+ if i == 0:
+ return name
+ return f"{name}_{i}"
+
+
+def _gated_residual(x, y, gate):
+ assert (x is None) == (y is None)
+ if x is None:
+ return None
+ if gate is None:
+ return x + y
+ return x + y * gate
diff --git a/openpi-umi/src/openpi/models/gemma_fast.py b/openpi-umi/src/openpi/models/gemma_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..eee39b4317dd3f42aa4d73e11dceee37e394c39d
--- /dev/null
+++ b/openpi-umi/src/openpi/models/gemma_fast.py
@@ -0,0 +1,437 @@
+# Copyright 2024 Big Vision Authors.
+#
+# 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.
+
+"""
+Gemma model implementation from big_vision/models/ppp/gemma.py (with small modifications for NNX compatibility)
+Used for FAST autoregressive policies.
+"""
+
+import dataclasses
+from typing import Literal, TypeAlias
+
+import einops
+import flax.linen as nn
+import jax
+import jax.numpy as jnp
+import ml_collections
+
+import openpi.models.lora as lora
+import openpi.shared.array_typing as at
+
+Variant = Literal["gemma_2b", "gemma_2b_lora"]
+
+
+def get_config(variant):
+ """Returns config for specified gemma variant."""
+ if variant == "gemma_2b":
+ return ml_collections.ConfigDict(
+ {
+ "variant": variant,
+ "width": 2048,
+ "depth": 18,
+ "mlp_dim": 16_384,
+ "num_heads": 8,
+ "num_kv_heads": 1,
+ "head_dim": 256,
+ "norm_eps": 1e-6,
+ "vocab_size": 257_152,
+ "scan": True,
+ "remat_policy": "nothing_saveable",
+ }
+ )
+ if variant == "gemma_2b_lora":
+ return ml_collections.ConfigDict(
+ {
+ "variant": variant,
+ "width": 2048,
+ "depth": 18,
+ "mlp_dim": 16_384,
+ "num_heads": 8,
+ "num_kv_heads": 1,
+ "head_dim": 256,
+ "norm_eps": 1e-6,
+ "vocab_size": 257_152,
+ "scan": True,
+ "remat_policy": "nothing_saveable",
+ "lora_configs": {
+ "attn": lora.LoRAConfig(rank=16, alpha=16.0),
+ "ffn": lora.LoRAConfig(rank=16, alpha=16.0),
+ },
+ }
+ )
+ raise ValueError(f"Unknown variant: {variant}")
+
+
+@at.typecheck
+class Einsum(nn.Module):
+ shape: tuple[int, ...]
+
+ @nn.compact
+ def __call__(self, eqn, x):
+ dtype = x.dtype # original dtype, could be half-precision
+ w = self.param("w", nn.initializers.zeros_init(), self.shape).astype(dtype)
+ return jnp.einsum(eqn, x, w)
+
+
+@at.typecheck
+class RMSNorm(nn.Module):
+ @nn.compact
+ def __call__(self, x):
+ dtype = x.dtype # original dtype, could be half-precision
+ scale = self.param("scale", nn.initializers.zeros_init(), (x.shape[-1]))
+ var = jnp.mean(jnp.square(x.astype(jnp.float32)), axis=-1, keepdims=True) # compute variance in float32
+ normed_inputs = jnp.asarray(x * jnp.reciprocal(jnp.sqrt(var + 1e-06))) # compute normalization in float32
+ normed_inputs = normed_inputs * (
+ 1 + scale
+ ) # scale by learned parameter in float32 (matches Flax implementation)
+ return normed_inputs.astype(dtype) # return in original dtype
+
+
+@at.typecheck
+class Embedder(nn.Module):
+ """Embedder module."""
+
+ vocab_size: int
+ embed_dim: int
+
+ def setup(self):
+ self.input_embedding_table = self.param(
+ "input_embedding",
+ nn.initializers.zeros_init(),
+ (self.vocab_size, self.embed_dim),
+ )
+
+ def encode(self, x):
+ x = self.input_embedding_table[(x,)]
+ x *= jnp.sqrt(self.embed_dim).astype(x.dtype)
+ return x
+
+ def decode(self, x):
+ return jnp.dot(x, self.input_embedding_table.T)
+
+
+@at.typecheck
+class Attention(nn.Module):
+ """Attention module."""
+
+ num_heads: int
+ num_kv_heads: int
+ features: int
+ head_dim: int
+
+ cache_dtype: str | None = None
+
+ lora_config: lora.LoRAConfig | None = None
+
+ def setup(self):
+ if self.num_kv_heads == self.num_heads:
+ self.qkv_einsum = lora.Einsum(
+ shape=(3, self.num_heads, self.features, self.head_dim),
+ name="qkv_einsum",
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
+ lora_config=self.lora_config,
+ )
+ else:
+ self.q_einsum = lora.Einsum(
+ shape=(self.num_heads, self.features, self.head_dim),
+ name="q_einsum",
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
+ lora_config=self.lora_config,
+ )
+ self.kv_einsum = lora.Einsum(
+ shape=(2, self.num_kv_heads, self.features, self.head_dim),
+ name="kv_einsum",
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0, 1)),
+ lora_config=self.lora_config,
+ )
+ self.attn_vec_einsum = lora.Einsum(
+ shape=(self.num_heads, self.head_dim, self.features),
+ name="attn_vec_einsum",
+ init_fn=nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
+ lora_config=self.lora_config,
+ )
+
+ def _init_cache(self, k, v, cache_size):
+ """Initialize KV cache"""
+ prefill_len = k.shape[1]
+ pad_width = ((0, 0), (0, cache_size - prefill_len), (0, 0), (0, 0))
+ cache_dtype = self.cache_dtype or k.dtype
+ k_cache = jnp.pad(k.astype(cache_dtype), pad_width)
+ v_cache = jnp.pad(v.astype(cache_dtype), pad_width)
+ idx = jnp.zeros((k.shape[0],), dtype=jnp.int32) + prefill_len
+ return idx, k_cache, v_cache
+
+ def _update_cache(self, k, v, idx, k_cache, v_cache):
+ """Update KV cache with new values"""
+ assert k.shape[1] == 1, "Only support kv-cache updates of length 1"
+ indices = (0, idx[0], 0, 0)
+ cache_dtype = self.cache_dtype or k.dtype
+ k_new = jax.lax.dynamic_update_slice(k_cache, k.astype(cache_dtype), indices)
+ v_new = jax.lax.dynamic_update_slice(v_cache, v.astype(cache_dtype), indices)
+ idx_new = idx + 1
+ return idx_new, k_new, v_new
+
+ @nn.compact
+ def __call__(self, x, positions, attn_mask, kv_cache, decode, deterministic=True): # noqa: FBT002
+ dtype = x.dtype # original dtype, could be half-precision
+ if self.num_kv_heads == self.num_heads:
+ q, k, v = self.qkv_einsum("BSD,3KDH->3BSKH", x)
+ else:
+ q = self.q_einsum("BTD,NDH->BTNH", x)
+ k, v = self.kv_einsum("BSD,2KDH->2BSKH", x)
+
+ q = _apply_rope(q, positions=positions) # promotes to float32
+ q *= self.head_dim**-0.5
+
+ k = _apply_rope(k, positions=positions) # promotes to float32
+
+ if kv_cache is None:
+ idx, k_cache, v_cache = self._init_cache(k, v, attn_mask.shape[-1])
+ else:
+ idx, k_cache, v_cache = kv_cache
+ idx, k_cache, v_cache = self._update_cache(k, v, idx, k_cache, v_cache)
+
+ k, v = k_cache, v_cache
+ kv_cache = (idx, k_cache, v_cache)
+
+ q = einops.rearrange(q, "B T (K G) H -> B T K G H", K=self.num_kv_heads)
+ logits = jnp.einsum("BTKGH,BSKH->BKGTS", q, k, preferred_element_type=jnp.float32)
+
+ if attn_mask.shape != (q.shape[0], 1, q.shape[1], k.shape[1]):
+ raise ValueError(
+ f"Attention mask with shape {attn_mask.shape} but shapes for q and k are: {q.shape} and {k.shape}"
+ )
+
+ # big_neg = jnp.finfo(logits.dtype).min
+ big_neg = -2.3819763e38 # See gemma/modules.py
+ masked_logits = jnp.where(attn_mask[:, :, None, :, :], logits, big_neg)
+
+ probs = jax.nn.softmax(masked_logits, axis=-1).astype(dtype)
+
+ encoded = jnp.einsum("BKGTS,BSKH->BTKGH", probs, v)
+ encoded = einops.rearrange(encoded, "B T K G H -> B T (K G) H")
+ return self.attn_vec_einsum("BTNH,NHD->BTD", encoded), kv_cache
+
+
+@at.typecheck
+class Block(nn.Module):
+ """Transformer block."""
+
+ num_heads: int
+ num_kv_heads: int
+ embed_dim: int
+ head_dim: int
+ hidden_dim: int
+
+ dropout: float = 0.0
+ dropout_bdims: tuple[int, ...] = ()
+ cache_dtype: str | None = None
+ lora_configs: ml_collections.ConfigDict = dataclasses.field(default_factory=ml_collections.ConfigDict)
+
+ def setup(self):
+ self.pre_attention_norm = RMSNorm()
+ self.attn = Attention(
+ num_heads=self.num_heads,
+ num_kv_heads=self.num_kv_heads,
+ features=self.embed_dim,
+ head_dim=self.head_dim,
+ cache_dtype=self.cache_dtype,
+ lora_config=self.lora_configs.get("attn"),
+ )
+ self.pre_ffw_norm = RMSNorm()
+ self.mlp = lora.FeedForward(
+ features=self.embed_dim, hidden_dim=self.hidden_dim, name="mlp", lora_config=self.lora_configs.get("ffn")
+ )
+ if self.dropout:
+ self.drop = nn.Dropout(self.dropout, self.dropout_bdims)
+ else:
+ self.drop = lambda x, _: x
+
+ def __call__(self, x, kv_cache, positions, attn_mask, decode, deterministic=True): # noqa: FBT002
+ x = nn.with_logical_constraint(x, ("act_batch", "act_len", "act_emb"))
+ inputs_normalized = self.pre_attention_norm(x)
+ attn_output, kv_cache = self.attn(inputs_normalized, positions, attn_mask, kv_cache, decode, deterministic)
+ attn_output = self.drop(attn_output, deterministic)
+ attn_output += x
+ residual = attn_output
+ attn_output = self.pre_ffw_norm(attn_output)
+ outputs = self.mlp(attn_output)
+ outputs = self.drop(outputs, deterministic)
+ outputs = residual + outputs
+ return outputs, kv_cache
+
+
+KVCache: TypeAlias = tuple[at.Int[at.Array, " b"], at.Float[at.Array, "b _t _k _h"], at.Float[at.Array, "b _t _v _h"]]
+
+
+@at.typecheck
+class Module(nn.Module):
+ """gemma model."""
+
+ variant: str
+
+ width: int
+ depth: int
+ mlp_dim: int
+ num_heads: int
+ num_kv_heads: int
+ head_dim: int
+ norm_eps: float
+ vocab_size: int
+ embed_dtype: str
+
+ dropout: float = 0.0
+ dropout_bdims: tuple[int, ...] = () # Every float is dropped independently.
+ cache_dtype: str | None = None
+
+ scan: bool = False
+ remat_policy: str = "none"
+ lora_configs: ml_collections.ConfigDict = dataclasses.field(default_factory=ml_collections.ConfigDict)
+
+ @nn.compact
+ def __call__(
+ self,
+ tokens=None,
+ embedded_prefix=None,
+ embed_only=False, # noqa: FBT002
+ pre_logits=None,
+ positions=None,
+ mask=None,
+ decode=False, # noqa: FBT002
+ kv_cache=None,
+ deterministic=True, # noqa: FBT002
+ return_prelogits=False, # noqa: FBT002
+ ):
+ """Embed only, or complete forward pass.
+
+ Args:
+ tokens: Embedded, then and appended to `embedded_prefix`. Can be None.
+ embedded_prefix: Optional prefix that is already embedded.
+ embed_only: Whether to compute embeddings only.
+ pre_logits: If present computes logits from pre_logits and returns.
+ positions: Optional `[B, T]` allows to specify the absolute position of
+ the tokens.
+ mask: Optional attention mask `[B, T, S]`.
+ decode: Whether to use kv-cache. Caller must pass masks and positions.
+ deterministic: Forwarded to all dropout layers.
+ return_prelogits: Whether to return the pre-logits.
+
+ Returns:
+ If `embed_only=False`, then `(logits, out)` will be returned.
+ If `embed_only=True`, then the embeddings will be returned.
+ If `return_prelogits=True`, then the pre-logits will be returned.
+ """
+ out = {}
+
+ embedder = Embedder(vocab_size=self.vocab_size, embed_dim=self.width, name="embedder")
+
+ if pre_logits is not None:
+ x = out["pre_logits"] = pre_logits
+ logits = out["logits"] = embedder.decode(x)
+ return logits, out
+
+ x = []
+ if embedded_prefix is not None:
+ x.append(embedded_prefix)
+ if tokens is not None:
+ x.append(embedder.encode(tokens))
+
+ x = jnp.concatenate(x, axis=-2)
+ x = x.astype(self.embed_dtype)
+ batch_size, seq_len, width = x.shape
+
+ if embed_only:
+ return x
+
+ if decode:
+ assert positions is not None and mask is not None, ( # noqa: PT018
+ "Must explicitly pass positions and mask for decoding."
+ )
+
+ if positions is None:
+ positions = jnp.arange(seq_len).astype(jnp.int32)[None, :]
+ assert positions.shape[1] == x.shape[1], (positions.shape, x.shape)
+
+ if mask is None:
+ mask = nn.attention.make_causal_mask(jnp.ones([batch_size, seq_len]))
+ if mask.ndim == 3:
+ mask = mask[:, None, :, :]
+ cache_size = max(seq_len, mask.shape[-1])
+ assert mask.shape == (batch_size, 1, seq_len, cache_size), mask.shape
+
+ if self.remat_policy == "none":
+ block_cls = Block
+ else:
+ block_cls = nn.remat(
+ Block,
+ prevent_cse=not self.scan,
+ static_argnums=(5, 6), # 0=self, 5=decode, 6=deterministic
+ policy=getattr(jax.checkpoint_policies, self.remat_policy),
+ )
+
+ block_kw = {
+ "num_heads": self.num_heads,
+ "head_dim": self.head_dim,
+ "num_kv_heads": self.num_kv_heads,
+ "embed_dim": width,
+ "hidden_dim": self.mlp_dim,
+ "dropout": self.dropout,
+ "dropout_bdims": self.dropout_bdims,
+ "cache_dtype": self.cache_dtype,
+ "lora_configs": self.lora_configs,
+ }
+ layers = self.scope.push("layers")
+ blocks = [
+ nn.scan(
+ block_cls,
+ variable_axes={"params": 0},
+ split_rngs={"params": True, "dropout": True},
+ in_axes=(0, nn.broadcast, nn.broadcast, nn.broadcast, nn.broadcast), # 0=kv_cache, 1=positions, 2=mask
+ length=self.depth,
+ )(parent=layers, **block_kw)
+ ]
+ for block in blocks:
+ x, kv_cache = block(x, kv_cache, positions, mask, decode, deterministic)
+
+ assert x.dtype == jnp.dtype(self.embed_dtype) # Sanity check.
+ out["encoded"] = x
+
+ x = RMSNorm(name="final_norm")(x)
+ out["pre_logits"] = x
+ if return_prelogits:
+ return x, kv_cache, out
+
+ x = embedder.decode(x)
+ out["logits"] = x
+
+ return x, kv_cache, out
+
+ def init(self):
+ """Convenience method for initializing all parameters, necessary due to the quirks of linen."""
+ self(jnp.zeros((1, 1), dtype=jnp.int32))
+
+
+def _apply_rope(x, *, positions, max_wavelength=10_000):
+ """Applies RoPE positions [B, L] to x [B, L, H, D]."""
+ freq_exponents = (2.0 / x.shape[-1]) * jnp.arange(x.shape[-1] // 2, dtype=jnp.float32)
+ timescale = max_wavelength**freq_exponents
+ radians = positions[..., None] / timescale[None, None, :]
+ radians = radians[..., None, :]
+ assert radians.dtype == jnp.float32
+ # radians.shape = [...,L,1,d=D/2]
+ sin, cos = jnp.sin(radians), jnp.cos(radians)
+ x1, x2 = jnp.split(x, 2, axis=-1)
+ res = jnp.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1)
+ assert res.dtype == jnp.float32
+ return res
diff --git a/openpi-umi/src/openpi/models/lora.py b/openpi-umi/src/openpi/models/lora.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dfff5b4f22ff42f73298037a77df900c6b11d75
--- /dev/null
+++ b/openpi-umi/src/openpi/models/lora.py
@@ -0,0 +1,148 @@
+import math
+import re
+
+import flax.linen as nn
+import flax.struct as struct
+import jax.numpy as jnp
+
+import openpi.shared.array_typing as at
+
+
+@struct.dataclass
+class LoRAConfig:
+ """Configuration for LoRA."""
+
+ # LoRA rank.
+ rank: int
+ # LoRA scaling factor.
+ alpha: float = 1.0
+ # Initialization function for LoRA parameters.
+ init_fn: nn.initializers.Initializer = nn.initializers.normal(stddev=0.01)
+ # Enable rank-stabilized LoRA: https://arxiv.org/pdf/2312.03732
+ rslora: bool = False
+ # Axes in the weight to apply LoRA to. Should typically be the last two axes.
+ axes: tuple[int, int] = (-2, -1)
+ # Axis label which is used by LoRA in einsum equations. Must not be present in the original equation.
+ label: str = "L"
+
+ @property
+ def scaling_value(self) -> float:
+ return self.alpha / math.sqrt(self.rank) if self.rslora else self.alpha / self.rank
+
+
+class Einsum(nn.Module):
+ """Einsum with LoRA support. Can be used as a drop-in replacement for the Gemma Einsum."""
+
+ # Shape of the weight.
+ shape: tuple[int, ...]
+ # Initialization function for the weight.
+ init_fn: nn.initializers.Initializer = nn.initializers.zeros
+ # If not None, apply LoRA to the weight.
+ lora_config: LoRAConfig | None = None
+
+ def setup(self):
+ self.w = self.param("w", self.init_fn, self.shape)
+
+ if config := self.lora_config:
+ # Setup LoRA parameters.
+ shape_a, shape_b = list(self.shape), list(self.shape)
+ shape_a[config.axes[1]] = config.rank
+ shape_b[config.axes[0]] = config.rank
+ self.w_a = self.param("lora_a", config.init_fn, shape_a)
+ self.w_b = self.param("lora_b", config.init_fn, shape_b)
+
+ @nn.compact
+ def __call__(self, eqn: str, x):
+ dtype = x.dtype # original dtype, could be half-precision
+ result = jnp.einsum(eqn, x, self.w.astype(dtype))
+
+ if config := self.lora_config:
+ eqn_a, eqn_b = self._make_lora_eqns(eqn)
+ lora = jnp.einsum(eqn_a, x, self.w_a.astype(dtype))
+ lora = jnp.einsum(eqn_b, lora, self.w_b.astype(dtype))
+ result = result + lora * config.scaling_value
+
+ return result
+
+ def _make_lora_eqns(self, eqn: str) -> tuple[str, str]:
+ if "L" in eqn:
+ raise ValueError(f"L already in eqn: {eqn}")
+ if not (m := re.match("(.*),(.*)->(.*)", eqn)):
+ raise ValueError(f"Unsupported einsum eqn: {eqn}")
+ lhs, rhs, out = m.groups()
+
+ assert self.lora_config is not None
+ a_label, b_label = (rhs[x] for x in self.lora_config.axes)
+ label = self.lora_config.label
+
+ a_rhs = rhs.replace(b_label, label)
+ a_out = out.replace(b_label, label)
+ eqn_a = f"{lhs},{a_rhs}->{a_out}"
+
+ b_rhs = rhs.replace(a_label, label)
+ eqn_b = f"{a_out},{b_rhs}->{out}"
+
+ return eqn_a, eqn_b
+
+
+class FeedForward(nn.Module):
+ """Feed forward module."""
+
+ features: int
+ hidden_dim: int
+ # If not None, apply LoRA to the weight.
+ lora_config: LoRAConfig | None = None
+
+ def setup(self):
+ self.w_gating = self.param(
+ "gating_einsum",
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1, batch_axis=(0,)),
+ (2, self.features, self.hidden_dim),
+ )
+ self.w_linear = self.param(
+ "linear",
+ nn.initializers.lecun_normal(in_axis=-2, out_axis=-1),
+ (self.hidden_dim, self.features),
+ )
+ self.w_gating_lora = None
+ self.w_linear_lora = None
+ if self.lora_config:
+ # Setup LoRA parameters.
+ # TODO: follow up with a simplified init_fn api.
+ self.w_gating_lora = (
+ self.param("gating_einsum_lora_a", self.lora_config.init_fn, (2, self.features, self.lora_config.rank)),
+ self.param(
+ "gating_einsum_lora_b", self.lora_config.init_fn, (2, self.lora_config.rank, self.hidden_dim)
+ ),
+ )
+ self.w_linear_lora = (
+ self.param("linear_lora_a", self.lora_config.init_fn, (self.hidden_dim, self.lora_config.rank)),
+ self.param("linear_lora_b", self.lora_config.init_fn, (self.lora_config.rank, self.features)),
+ )
+
+ @nn.compact
+ def __call__(self, x):
+ dtype = x.dtype # original dtype, could be half-precision
+ ff_gate = self._dot(
+ x,
+ self.w_gating[0],
+ None if self.w_gating_lora is None else (self.w_gating_lora[0][0], self.w_gating_lora[1][0]),
+ )
+ gate_value = nn.gelu(ff_gate)
+
+ ff1 = self._dot(
+ x,
+ self.w_gating[1],
+ None if self.w_gating_lora is None else (self.w_gating_lora[0][1], self.w_gating_lora[1][1]),
+ )
+ activations = gate_value * ff1
+
+ outputs = self._dot(activations, self.w_linear, self.w_linear_lora)
+ assert outputs.dtype == dtype
+ return outputs
+
+ def _dot(self, x: at.Array, w: at.Array, lora_weights: tuple[at.Array, at.Array] | None) -> at.Array:
+ base = jnp.dot(x, w.astype(x.dtype))
+ if lora_weights is None:
+ return base
+ return base + jnp.dot(jnp.dot(x, lora_weights[0].astype(x.dtype)), lora_weights[1].astype(x.dtype))
diff --git a/openpi-umi/src/openpi/models/lora_test.py b/openpi-umi/src/openpi/models/lora_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..48b65b6ae282c6bb0e6a410ee71204a4837ffc48
--- /dev/null
+++ b/openpi-umi/src/openpi/models/lora_test.py
@@ -0,0 +1,94 @@
+import flax.linen as nn
+import jax
+import jax.numpy as jnp
+
+import openpi.models.lora as lora
+
+
+def test_lora_einsum_params_shape():
+ shape = (3, 8, 32, 4) # (3KDH)
+ einsum = lora.Einsum(shape)
+ lora0 = lora.Einsum(shape, lora_config=lora.LoRAConfig(rank=2))
+ lora1 = lora.Einsum(shape, lora_config=lora.LoRAConfig(rank=2, axes=(1, 2)))
+
+ key = jax.random.key(0)
+ x = jax.random.normal(key, (8, 64, 32)) # (BSD)
+ eqn = "BSD,3KDH->3BSKH"
+
+ # Ensure that lora parameters are not initialized when LoRA is not used.
+ params = einsum.init(key, eqn, x)
+ assert "lora_a" not in params["params"]
+ assert "lora_b" not in params["params"]
+
+ # Check that default axes work.
+ params_lora0 = lora0.init(key, eqn, x)
+ assert params_lora0["params"]["lora_a"].shape == (3, 8, 32, 2)
+ assert params_lora0["params"]["lora_b"].shape == (3, 8, 2, 4)
+
+ # Check that user provided axes work.
+ params_lora1 = lora1.init(key, eqn, x)
+ assert params_lora1["params"]["lora_a"].shape == (3, 8, 2, 4)
+ assert params_lora1["params"]["lora_b"].shape == (3, 2, 32, 4)
+
+
+def test_lora_einsum_same_output():
+ shape = (3, 8, 32, 4) # (3KDH)
+ einsum = lora.Einsum(shape)
+ einsum_lora = lora.Einsum(shape, lora_config=lora.LoRAConfig(rank=2, init_fn=nn.initializers.zeros))
+
+ key = jax.random.key(0)
+ x = jax.random.normal(key, (8, 64, 32)) # (BSD)
+ eqn = "BSD,3KDH->3BSKH"
+
+ params = einsum.init(key, eqn, x)
+ output = einsum.apply(params, eqn, x)
+
+ params_lora = einsum_lora.init(key, eqn, x)
+ output_lora = einsum_lora.apply(params_lora, eqn, x)
+
+ # Results are the same since the LoRA parameters are initialized to zeros.
+ assert jnp.allclose(output, output_lora)
+
+
+def test_lora_ffn_params_shape():
+ ffn = lora.FeedForward(features=8, hidden_dim=32)
+ ffn_lora = lora.FeedForward(
+ features=8,
+ hidden_dim=32,
+ lora_config=lora.LoRAConfig(rank=2),
+ )
+
+ key = jax.random.key(0)
+ x = jax.random.normal(key, (2, 8))
+
+ params = ffn.init(key, x)
+ assert params["params"]["gating_einsum"].shape == (2, 8, 32)
+ assert params["params"]["linear"].shape == (32, 8)
+
+ params_lora = ffn_lora.init(key, x)
+ assert params_lora["params"]["gating_einsum"].shape == (2, 8, 32)
+ assert params_lora["params"]["linear"].shape == (32, 8)
+ assert params_lora["params"]["gating_einsum_lora_a"].shape == (2, 8, 2)
+ assert params_lora["params"]["gating_einsum_lora_b"].shape == (2, 2, 32)
+ assert params_lora["params"]["linear_lora_a"].shape == (32, 2)
+ assert params_lora["params"]["linear_lora_b"].shape == (2, 8)
+
+
+def test_lora_ffn_same_output():
+ ffn = lora.FeedForward(features=8, hidden_dim=32)
+ ffn_lora = lora.FeedForward(
+ features=8,
+ hidden_dim=32,
+ lora_config=lora.LoRAConfig(rank=2, init_fn=nn.initializers.zeros),
+ )
+
+ key = jax.random.key(0)
+ x = jax.random.normal(key, (2, 8))
+
+ params = ffn.init(key, x)
+ output = ffn.apply(params, x)
+
+ params_lora = ffn_lora.init(key, x)
+ output_lora = ffn_lora.apply(params_lora, x)
+
+ assert jnp.allclose(output, output_lora)
diff --git a/openpi-umi/src/openpi/models/model.py b/openpi-umi/src/openpi/models/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..29618b49453742266fe6e4a5815ceee06d815f3b
--- /dev/null
+++ b/openpi-umi/src/openpi/models/model.py
@@ -0,0 +1,332 @@
+import abc
+from collections.abc import Sequence
+import dataclasses
+import enum
+import logging
+import pathlib
+from typing import Generic, TypeVar
+
+import augmax
+from flax import nnx
+from flax import struct
+from flax import traverse_util
+import jax
+import jax.numpy as jnp
+import numpy as np
+import orbax.checkpoint as ocp
+import safetensors
+import torch
+
+from openpi.models_pytorch import pi0_pytorch
+from openpi.shared import image_tools
+import openpi.shared.array_typing as at
+
+logger = logging.getLogger("openpi")
+
+# Type variable for array types (JAX arrays, PyTorch tensors, or numpy arrays)
+ArrayT = TypeVar("ArrayT", bound=jax.Array | torch.Tensor | np.ndarray)
+
+
+class ModelType(enum.Enum):
+ """Supported model types."""
+
+ PI0 = "pi0"
+ PI0_FAST = "pi0_fast"
+ PI05 = "pi05"
+
+
+# The model always expects these images
+IMAGE_KEYS = (
+ "base_0_rgb",
+ "left_wrist_0_rgb",
+ "right_wrist_0_rgb",
+)
+
+
+# This may need change if we release a small model.
+IMAGE_RESOLUTION = (224, 224)
+
+
+# Data format
+#
+# Data transforms produce the model input as a nested dictionary which is later converted
+# into `Obesrvation` and `Actions` objects. See below.
+#
+# In the dictory form, this data should look like:
+# {
+# # Observation data.
+# "image": {
+# "base_0_rgb": (float32|uint8)[*b, h, w, 3], # RGB image in [-1, 1] or [0, 255]
+# ... # Additional camera views
+# },
+# "image_mask": {
+# "base_0_rgb": bool[*b], # True if image is valid
+# ... # Masks for additional views
+# },
+# "state": float32[*b, s], # Low-dimensional robot state
+# "tokenized_prompt": int32[*b, l], # Optional, tokenized language prompt
+# "tokenized_prompt_mask": bool[*b, l], # Optional, mask for tokenized prompt
+# "token_ar_mask": int32[*b, l], # Optional, autoregressive mask for FAST model
+# "token_loss_mask": bool[*b, l], # Optional, loss mask for FAST model
+#
+# # Actions data.
+# "actions": float32[*b ah ad]
+# }
+# where:
+# *b = batch dimensions
+# h,w = image height/width
+# s = state dimension
+# l = sequence length
+#
+@at.typecheck
+@struct.dataclass
+class Observation(Generic[ArrayT]):
+ """Holds observations, i.e., inputs to the model.
+
+ See `Observation.from_dict` to see the expected dictionary form. This is the format
+ that should be produced by the data transforms.
+ """
+
+ # Images, in [-1, 1] float32.
+ images: dict[str, at.Float[ArrayT, "*b h w c"]]
+ # Image masks, with same keys as images.
+ image_masks: dict[str, at.Bool[ArrayT, "*b"]]
+ # Low-dimensional robot state.
+ state: at.Float[ArrayT, "*b s"]
+
+ # Tokenized prompt.
+ tokenized_prompt: at.Int[ArrayT, "*b l"] | None = None
+ # Tokenized prompt mask.
+ tokenized_prompt_mask: at.Bool[ArrayT, "*b l"] | None = None
+
+ # pi0-fast model specific fields.
+
+ # Token auto-regressive mask (for FAST autoregressive model).
+ token_ar_mask: at.Int[ArrayT, "*b l"] | None = None
+ # Token loss mask (for FAST autoregressive model).
+ token_loss_mask: at.Bool[ArrayT, "*b l"] | None = None
+
+ @classmethod
+ def from_dict(cls, data: at.PyTree[ArrayT]) -> "Observation[ArrayT]":
+ """This method defines the mapping between unstructured data (i.e., nested dict) to the structured Observation format."""
+ # Ensure that tokenized_prompt and tokenized_prompt_mask are provided together.
+ if ("tokenized_prompt" in data) != ("tokenized_prompt_mask" in data):
+ raise ValueError("tokenized_prompt and tokenized_prompt_mask must be provided together.")
+ # If images are uint8, convert them to [-1, 1] float32.
+ for key in data["image"]:
+ if data["image"][key].dtype == np.uint8:
+ data["image"][key] = data["image"][key].astype(np.float32) / 255.0 * 2.0 - 1.0
+ elif hasattr(data["image"][key], "dtype") and data["image"][key].dtype == torch.uint8:
+ data["image"][key] = data["image"][key].to(torch.float32).permute(0, 3, 1, 2) / 255.0 * 2.0 - 1.0
+ return cls(
+ images=data["image"],
+ image_masks=data["image_mask"],
+ state=data["state"],
+ tokenized_prompt=data.get("tokenized_prompt"),
+ tokenized_prompt_mask=data.get("tokenized_prompt_mask"),
+ token_ar_mask=data.get("token_ar_mask"),
+ token_loss_mask=data.get("token_loss_mask"),
+ )
+
+ def to_dict(self) -> at.PyTree[ArrayT]:
+ """Convert the Observation to a nested dict."""
+ result = dataclasses.asdict(self)
+ result["image"] = result.pop("images")
+ result["image_mask"] = result.pop("image_masks")
+ return result
+
+
+# Defines the format of the actions. This field is included as "actions" inside the dictionary
+# produced by the data transforms.
+Actions = at.Float[ArrayT, "*b ah ad"]
+
+
+def preprocess_observation(
+ rng: at.KeyArrayLike | None,
+ observation: Observation,
+ *,
+ train: bool = False,
+ image_keys: Sequence[str] = IMAGE_KEYS,
+ image_resolution: tuple[int, int] = IMAGE_RESOLUTION,
+) -> Observation:
+ """Preprocess the observations by performing image augmentations (if train=True), resizing (if necessary), and
+ filling in a default image mask (if necessary).
+ """
+
+ if not set(image_keys).issubset(observation.images):
+ raise ValueError(f"images dict missing keys: expected {image_keys}, got {list(observation.images)}")
+
+ batch_shape = observation.state.shape[:-1]
+
+ out_images = {}
+ for key in image_keys:
+ image = observation.images[key]
+ if image.shape[1:3] != image_resolution:
+ logger.info(f"Resizing image {key} from {image.shape[1:3]} to {image_resolution}")
+ image = image_tools.resize_with_pad(image, *image_resolution)
+
+ if train:
+ # Convert from [-1, 1] to [0, 1] for augmax.
+ image = image / 2.0 + 0.5
+
+ transforms = []
+ if "wrist" not in key:
+ height, width = image.shape[1:3]
+ transforms += [
+ augmax.RandomCrop(int(width * 0.95), int(height * 0.95)),
+ augmax.Resize(width, height),
+ augmax.Rotate((-5, 5)),
+ ]
+ transforms += [
+ augmax.ColorJitter(brightness=0.3, contrast=0.4, saturation=0.5),
+ ]
+ sub_rngs = jax.random.split(rng, image.shape[0])
+ image = jax.vmap(augmax.Chain(*transforms))(sub_rngs, image)
+
+ # Back to [-1, 1].
+ image = image * 2.0 - 1.0
+
+ out_images[key] = image
+
+ # obtain mask
+ out_masks = {}
+ for key in out_images:
+ if key not in observation.image_masks:
+ # do not mask by default
+ out_masks[key] = jnp.ones(batch_shape, dtype=jnp.bool)
+ else:
+ out_masks[key] = jnp.asarray(observation.image_masks[key])
+
+ return Observation(
+ images=out_images,
+ image_masks=out_masks,
+ state=observation.state,
+ tokenized_prompt=observation.tokenized_prompt,
+ tokenized_prompt_mask=observation.tokenized_prompt_mask,
+ token_ar_mask=observation.token_ar_mask,
+ token_loss_mask=observation.token_loss_mask,
+ )
+
+
+@dataclasses.dataclass(frozen=True)
+class BaseModelConfig(abc.ABC):
+ """Configuration shared by all models. Specific models should inherit from this class, and implement the `create`
+ method to create the corresponding model.
+ """
+
+ # Action space dimension.
+ action_dim: int
+ # Action sequence length.
+ action_horizon: int
+ # Tokenized prompt maximum length.
+ max_token_len: int
+
+ @property
+ @abc.abstractmethod
+ def model_type(self) -> ModelType:
+ """The model type."""
+
+ @abc.abstractmethod
+ def create(self, rng: at.KeyArrayLike) -> "BaseModel":
+ """Create a new model, initializing parameters."""
+
+ def load(self, params: at.Params, *, remove_extra_params: bool = True) -> "BaseModel":
+ """Create a model with the given parameters."""
+ model = nnx.eval_shape(self.create, jax.random.key(0))
+ graphdef, state = nnx.split(model)
+ if remove_extra_params:
+ params = ocp.transform_utils.intersect_trees(state.to_pure_dict(), params)
+ at.check_pytree_equality(expected=state.to_pure_dict(), got=params, check_shapes=True, check_dtypes=False)
+ state.replace_by_pure_dict(params)
+ return nnx.merge(graphdef, state)
+
+ def load_pytorch(self, train_config, weight_path: str):
+ logger.info(f"train_config: {train_config}")
+ model = pi0_pytorch.PI0Pytorch(config=train_config.model)
+ safetensors.torch.load_model(model, weight_path)
+ return model
+
+ @abc.abstractmethod
+ def inputs_spec(self, *, batch_size: int = 1) -> tuple[Observation, Actions]:
+ """Returns the input specification for the model. Values are jax.ShapeDtypeStruct."""
+
+ def fake_obs(self, batch_size: int = 1) -> Observation:
+ observation_spec, _ = self.inputs_spec(batch_size=batch_size)
+ return jax.tree.map(lambda x: jnp.ones(x.shape, x.dtype), observation_spec)
+
+ def fake_act(self, batch_size: int = 1) -> Actions:
+ _, action_spec = self.inputs_spec(batch_size=batch_size)
+ return jax.tree.map(lambda x: jnp.ones(x.shape, x.dtype), action_spec)
+
+
+@dataclasses.dataclass
+class BaseModel(nnx.Module, abc.ABC):
+ """Base class for all model implementations. Specific models should inherit from this class. They should call
+ super().__init__() to initialize the shared attributes (action_dim, action_horizon, and max_token_len).
+ """
+
+ action_dim: int
+ action_horizon: int
+ max_token_len: int
+
+ @abc.abstractmethod
+ def compute_loss(
+ self,
+ rng: at.KeyArrayLike,
+ observation: Observation,
+ actions: Actions,
+ *,
+ train: bool = False,
+ ) -> at.Float[at.Array, "*b ah"]: ...
+
+ @abc.abstractmethod
+ def sample_actions(self, rng: at.KeyArrayLike, observation: Observation, **kwargs) -> Actions: ...
+
+
+def restore_params(
+ params_path: pathlib.Path | str,
+ *,
+ restore_type: type[np.ndarray] | type[jax.Array] = jax.Array,
+ dtype: jnp.dtype | None = None,
+ sharding: jax.sharding.Sharding | None = None,
+) -> at.Params:
+ """Restores unstructured params PyTree from a checkpoint.
+
+ This works with checkpoints saved with `save_state` during openpi training (see `training/checkpoints.py`) as
+ well as pre-trained checkpoints released for openpi.
+
+ Args:
+ params_path: The local path to the checkpoint directory.
+ restore_type: The type to restore the params as. Can be set to `np.ndarray` to load the params as a numpy array.
+ dtype: The dtype to restore all params as. If not provided, will use the original dtype from the checkpoint.
+ sharding: The sharding to use for the params. If not provided, the params will be replicated across all devices.
+
+ Returns:
+ The restored params.
+ """
+ params_path = pathlib.Path(params_path).resolve() if not str(params_path).startswith("gs://") else params_path
+
+ if restore_type is jax.Array and sharding is None:
+ mesh = jax.sharding.Mesh(jax.devices(), ("x",))
+ sharding = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec())
+
+ with ocp.PyTreeCheckpointer() as ckptr:
+ metadata = ckptr.metadata(params_path)
+ item = {"params": metadata["params"]}
+
+ params = ckptr.restore(
+ params_path,
+ ocp.args.PyTreeRestore(
+ item=item,
+ restore_args=jax.tree.map(
+ lambda _: ocp.ArrayRestoreArgs(sharding=sharding, restore_type=restore_type, dtype=dtype), item
+ ),
+ ),
+ )["params"]
+
+ # If the params were saved with `save_state` during openpi training, every key path will end with "value", which is
+ # added by `nnx.State`. We remove the "value" suffix here and always return what NNX calls a "pure dict".
+ flat_params = traverse_util.flatten_dict(params)
+ if all(kp[-1] == "value" for kp in flat_params):
+ flat_params = {kp[:-1]: v for kp, v in flat_params.items()}
+ return traverse_util.unflatten_dict(flat_params)
diff --git a/openpi-umi/src/openpi/models/model_test.py b/openpi-umi/src/openpi/models/model_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..495dc18b5f0fbb4405a49d33d676b0ef31e2aeef
--- /dev/null
+++ b/openpi-umi/src/openpi/models/model_test.py
@@ -0,0 +1,94 @@
+from flax import nnx
+import jax
+import pytest
+
+from openpi.models import model as _model
+from openpi.models import pi0_config
+from openpi.models import pi0_fast
+from openpi.shared import download
+from openpi.shared import nnx_utils
+
+
+def test_pi0_model():
+ key = jax.random.key(0)
+ config = pi0_config.Pi0Config()
+ model = config.create(key)
+
+ batch_size = 2
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
+
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
+ assert loss.shape == (batch_size, config.action_horizon)
+
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs, num_steps=10)
+ assert actions.shape == (batch_size, model.action_horizon, model.action_dim)
+
+
+def test_pi0_lora_model():
+ key = jax.random.key(0)
+ config = pi0_config.Pi0Config(paligemma_variant="gemma_2b_lora")
+ model = config.create(key)
+
+ batch_size = 2
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
+
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
+ assert loss.shape == (batch_size, config.action_horizon)
+
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs, num_steps=10)
+ assert actions.shape == (batch_size, model.action_horizon, model.action_dim)
+
+
+def test_pi0_fast_model():
+ key = jax.random.key(0)
+ config = pi0_fast.Pi0FASTConfig()
+ model = config.create(key)
+
+ batch_size = 2
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
+
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
+ assert loss.shape == (batch_size,)
+
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs)
+ assert actions.shape == (batch_size, 256)
+
+
+def test_pi0_fast_lora_model():
+ key = jax.random.key(0)
+ config = pi0_fast.Pi0FASTConfig(paligemma_variant="gemma_2b_lora")
+ model = config.create(key)
+
+ batch_size = 2
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
+
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
+ assert loss.shape == (batch_size,)
+
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs)
+ assert actions.shape == (batch_size, 256)
+
+ lora_filter = nnx_utils.PathRegex(".*lora.*")
+ model_state = nnx.state(model)
+
+ lora_state_elems = list(model_state.filter(lora_filter))
+ assert len(lora_state_elems) > 0
+
+
+@pytest.mark.manual
+def test_model_restore():
+ key = jax.random.key(0)
+ config = pi0_config.Pi0Config()
+
+ batch_size = 2
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
+
+ model = config.load(
+ _model.restore_params(download.maybe_download("gs://openpi-assets/checkpoints/pi0_base/params"))
+ )
+
+ loss = model.compute_loss(key, obs, act)
+ assert loss.shape == (batch_size, config.action_horizon)
+
+ actions = model.sample_actions(key, obs, num_steps=10)
+ assert actions.shape == (batch_size, model.action_horizon, model.action_dim)
diff --git a/openpi-umi/src/openpi/models/pi0.py b/openpi-umi/src/openpi/models/pi0.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae7c4590f330f160aa9baa713d5b77fc060120de
--- /dev/null
+++ b/openpi-umi/src/openpi/models/pi0.py
@@ -0,0 +1,279 @@
+import logging
+
+import einops
+import flax.nnx as nnx
+import flax.nnx.bridge as nnx_bridge
+import jax
+import jax.numpy as jnp
+from typing_extensions import override
+
+from openpi.models import model as _model
+from openpi.models import pi0_config
+import openpi.models.gemma as _gemma
+import openpi.models.siglip as _siglip
+from openpi.shared import array_typing as at
+
+logger = logging.getLogger("openpi")
+
+
+def make_attn_mask(input_mask, mask_ar):
+ """Adapted from big_vision.
+
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
+ smaller or equal to theirs. This way `mask_ar` bool[?B, N] can be used to
+ setup several types of attention, for example:
+
+ [[1 1 1 1 1 1]]: pure causal attention.
+
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
+ themselves and the last 3 tokens have a causal attention. The first
+ entry could also be a 1 without changing behaviour.
+
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
+ block can attend all previous blocks and all tokens on the same block.
+
+ Args:
+ input_mask: bool[B, N] true if its part of the input, false if padding.
+ mask_ar: bool[?B, N] mask that's true where previous tokens cannot depend on
+ it and false where it shares the same attention mask as the previous token.
+ """
+ mask_ar = jnp.broadcast_to(mask_ar, input_mask.shape)
+ cumsum = jnp.cumsum(mask_ar, axis=1)
+ attn_mask = cumsum[:, None, :] <= cumsum[:, :, None]
+ valid_mask = input_mask[:, None, :] * input_mask[:, :, None]
+ return jnp.logical_and(attn_mask, valid_mask)
+
+
+@at.typecheck
+def posemb_sincos(
+ pos: at.Real[at.Array, " b"], embedding_dim: int, min_period: float, max_period: float
+) -> at.Float[at.Array, "b {embedding_dim}"]:
+ """Computes sine-cosine positional embedding vectors for scalar positions."""
+ if embedding_dim % 2 != 0:
+ raise ValueError(f"embedding_dim ({embedding_dim}) must be divisible by 2")
+
+ fraction = jnp.linspace(0.0, 1.0, embedding_dim // 2)
+ period = min_period * (max_period / min_period) ** fraction
+ sinusoid_input = jnp.einsum(
+ "i,j->ij",
+ pos,
+ 1.0 / period * 2 * jnp.pi,
+ precision=jax.lax.Precision.HIGHEST,
+ )
+ return jnp.concatenate([jnp.sin(sinusoid_input), jnp.cos(sinusoid_input)], axis=-1)
+
+
+class Pi0(_model.BaseModel):
+ def __init__(self, config: pi0_config.Pi0Config, rngs: nnx.Rngs):
+ super().__init__(config.action_dim, config.action_horizon, config.max_token_len)
+ self.pi05 = config.pi05
+ paligemma_config = _gemma.get_config(config.paligemma_variant)
+ action_expert_config = _gemma.get_config(config.action_expert_variant)
+ # TODO: rewrite gemma in NNX. For now, use bridge.
+ llm = nnx_bridge.ToNNX(
+ _gemma.Module(
+ configs=[paligemma_config, action_expert_config],
+ embed_dtype=config.dtype,
+ adarms=config.pi05,
+ )
+ )
+ llm.lazy_init(rngs=rngs, method="init", use_adarms=[False, True] if config.pi05 else [False, False])
+ img = nnx_bridge.ToNNX(
+ _siglip.Module(
+ num_classes=paligemma_config.width,
+ variant="So400m/14",
+ pool_type="none",
+ scan=True,
+ dtype_mm=config.dtype,
+ )
+ )
+ img.lazy_init(next(iter(config.fake_obs().images.values())), train=False, rngs=rngs)
+ self.PaliGemma = nnx.Dict(llm=llm, img=img)
+ self.action_in_proj = nnx.Linear(config.action_dim, action_expert_config.width, rngs=rngs)
+ if config.pi05:
+ self.time_mlp_in = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
+ self.time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
+ else:
+ self.state_proj = nnx.Linear(config.action_dim, action_expert_config.width, rngs=rngs)
+ self.action_time_mlp_in = nnx.Linear(2 * action_expert_config.width, action_expert_config.width, rngs=rngs)
+ self.action_time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
+ self.action_out_proj = nnx.Linear(action_expert_config.width, config.action_dim, rngs=rngs)
+
+ # This attribute gets automatically set by model.train() and model.eval().
+ self.deterministic = True
+
+ @at.typecheck
+ def embed_prefix(
+ self, obs: _model.Observation
+ ) -> tuple[at.Float[at.Array, "b s emb"], at.Bool[at.Array, "b s"], at.Bool[at.Array, " s"]]:
+ input_mask = []
+ ar_mask = []
+ tokens = []
+ # embed images
+ for name in obs.images:
+ image_tokens, _ = self.PaliGemma.img(obs.images[name], train=False)
+
+ tokens.append(image_tokens)
+ input_mask.append(
+ einops.repeat(
+ obs.image_masks[name],
+ "b -> b s",
+ s=image_tokens.shape[1],
+ )
+ )
+ # image tokens attend to each other
+ ar_mask += [False] * image_tokens.shape[1]
+
+ # add language (aka tokenized inputs)
+ if obs.tokenized_prompt is not None:
+ tokenized_inputs = self.PaliGemma.llm(obs.tokenized_prompt, method="embed")
+ tokens.append(tokenized_inputs)
+ input_mask.append(obs.tokenized_prompt_mask)
+ # full attention between image and language inputs
+ ar_mask += [False] * tokenized_inputs.shape[1]
+ tokens = jnp.concatenate(tokens, axis=1)
+ input_mask = jnp.concatenate(input_mask, axis=1)
+ ar_mask = jnp.array(ar_mask)
+ return tokens, input_mask, ar_mask
+
+ @at.typecheck
+ def embed_suffix(
+ self, obs: _model.Observation, noisy_actions: _model.Actions, timestep: at.Float[at.Array, " b"]
+ ) -> tuple[
+ at.Float[at.Array, "b s emb"],
+ at.Bool[at.Array, "b s"],
+ at.Bool[at.Array, " s"],
+ at.Float[at.Array, "b emb"] | None,
+ ]:
+ input_mask = []
+ ar_mask = []
+ tokens = []
+ if not self.pi05:
+ # add a single state token
+ state_token = self.state_proj(obs.state)[:, None, :]
+ tokens.append(state_token)
+ input_mask.append(jnp.ones((obs.state.shape[0], 1), dtype=jnp.bool_))
+ # image/language inputs do not attend to state or actions
+ ar_mask += [True]
+
+ action_tokens = self.action_in_proj(noisy_actions)
+ # embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1]
+ time_emb = posemb_sincos(timestep, self.action_in_proj.out_features, min_period=4e-3, max_period=4.0)
+ if self.pi05:
+ # time MLP (for adaRMS)
+ time_emb = self.time_mlp_in(time_emb)
+ time_emb = nnx.swish(time_emb)
+ time_emb = self.time_mlp_out(time_emb)
+ time_emb = nnx.swish(time_emb)
+ action_expert_tokens = action_tokens
+ adarms_cond = time_emb
+ else:
+ # mix timestep + action information using an MLP (no adaRMS)
+ time_tokens = einops.repeat(time_emb, "b emb -> b s emb", s=self.action_horizon)
+ action_time_tokens = jnp.concatenate([action_tokens, time_tokens], axis=-1)
+ action_time_tokens = self.action_time_mlp_in(action_time_tokens)
+ action_time_tokens = nnx.swish(action_time_tokens)
+ action_time_tokens = self.action_time_mlp_out(action_time_tokens)
+ action_expert_tokens = action_time_tokens
+ adarms_cond = None
+ tokens.append(action_expert_tokens)
+ input_mask.append(jnp.ones(action_expert_tokens.shape[:2], dtype=jnp.bool_))
+ # image/language/state inputs do not attend to action tokens
+ ar_mask += [True] + ([False] * (self.action_horizon - 1))
+ tokens = jnp.concatenate(tokens, axis=1)
+ input_mask = jnp.concatenate(input_mask, axis=1)
+ ar_mask = jnp.array(ar_mask)
+ return tokens, input_mask, ar_mask, adarms_cond
+
+ @override
+ def compute_loss(
+ self, rng: at.KeyArrayLike, observation: _model.Observation, actions: _model.Actions, *, train: bool = False
+ ) -> at.Float[at.Array, "*b ah"]:
+ preprocess_rng, noise_rng, time_rng = jax.random.split(rng, 3)
+ observation = _model.preprocess_observation(preprocess_rng, observation, train=train)
+
+ batch_shape = actions.shape[:-2]
+ noise = jax.random.normal(noise_rng, actions.shape)
+ time = jax.random.beta(time_rng, 1.5, 1, batch_shape) * 0.999 + 0.001
+ time_expanded = time[..., None, None]
+ x_t = time_expanded * noise + (1 - time_expanded) * actions
+ u_t = noise - actions
+
+ # one big forward pass of prefix + suffix at once
+ prefix_tokens, prefix_mask, prefix_ar_mask = self.embed_prefix(observation)
+ suffix_tokens, suffix_mask, suffix_ar_mask, adarms_cond = self.embed_suffix(observation, x_t, time)
+ input_mask = jnp.concatenate([prefix_mask, suffix_mask], axis=1)
+ ar_mask = jnp.concatenate([prefix_ar_mask, suffix_ar_mask], axis=0)
+ attn_mask = make_attn_mask(input_mask, ar_mask)
+ positions = jnp.cumsum(input_mask, axis=1) - 1
+ (prefix_out, suffix_out), _ = self.PaliGemma.llm(
+ [prefix_tokens, suffix_tokens], mask=attn_mask, positions=positions, adarms_cond=[None, adarms_cond]
+ )
+ v_t = self.action_out_proj(suffix_out[:, -self.action_horizon :])
+
+ return jnp.mean(jnp.square(v_t - u_t), axis=-1)
+
+ @override
+ def sample_actions(
+ self,
+ rng: at.KeyArrayLike,
+ observation: _model.Observation,
+ *,
+ num_steps: int | at.Int[at.Array, ""] = 10,
+ noise: at.Float[at.Array, "b ah ad"] | None = None,
+ ) -> _model.Actions:
+ observation = _model.preprocess_observation(None, observation, train=False)
+ # note that we use the convention more common in diffusion literature, where t=1 is noise and t=0 is the target
+ # distribution. yes, this is the opposite of the pi0 paper, and I'm sorry.
+ dt = -1.0 / num_steps
+ batch_size = observation.state.shape[0]
+ if noise is None:
+ noise = jax.random.normal(rng, (batch_size, self.action_horizon, self.action_dim))
+
+ # first fill KV cache with a forward pass of the prefix
+ prefix_tokens, prefix_mask, prefix_ar_mask = self.embed_prefix(observation)
+ prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
+ positions = jnp.cumsum(prefix_mask, axis=1) - 1
+ _, kv_cache = self.PaliGemma.llm([prefix_tokens, None], mask=prefix_attn_mask, positions=positions)
+
+ def step(carry):
+ x_t, time = carry
+ suffix_tokens, suffix_mask, suffix_ar_mask, adarms_cond = self.embed_suffix(
+ observation, x_t, jnp.broadcast_to(time, batch_size)
+ )
+ # `suffix_attn_mask` is shape (b, suffix_len, suffix_len) indicating how the suffix tokens can attend to each
+ # other
+ suffix_attn_mask = make_attn_mask(suffix_mask, suffix_ar_mask)
+ # `prefix_attn_mask` is shape (b, suffix_len, prefix_len) indicating how the suffix tokens can attend to the
+ # prefix tokens
+ prefix_attn_mask = einops.repeat(prefix_mask, "b p -> b s p", s=suffix_tokens.shape[1])
+ # `combined_mask` is shape (b, suffix_len, prefix_len + suffix_len) indicating how the suffix tokens (which
+ # generate the queries) can attend to the full prefix + suffix sequence (which generates the keys and values)
+ full_attn_mask = jnp.concatenate([prefix_attn_mask, suffix_attn_mask], axis=-1)
+ assert full_attn_mask.shape == (
+ batch_size,
+ suffix_tokens.shape[1],
+ prefix_tokens.shape[1] + suffix_tokens.shape[1],
+ )
+ # `positions` is shape (b, suffix_len) indicating the positions of the suffix tokens
+ positions = jnp.sum(prefix_mask, axis=-1)[:, None] + jnp.cumsum(suffix_mask, axis=-1) - 1
+
+ (prefix_out, suffix_out), _ = self.PaliGemma.llm(
+ [None, suffix_tokens],
+ mask=full_attn_mask,
+ positions=positions,
+ kv_cache=kv_cache,
+ adarms_cond=[None, adarms_cond],
+ )
+ assert prefix_out is None
+ v_t = self.action_out_proj(suffix_out[:, -self.action_horizon :])
+
+ return x_t + dt * v_t, time + dt
+
+ def cond(carry):
+ x_t, time = carry
+ # robust to floating-point error
+ return time >= -dt / 2
+
+ x_0, _ = jax.lax.while_loop(cond, step, (noise, 1.0))
+ return x_0
diff --git a/openpi-umi/src/openpi/models/pi0_config.py b/openpi-umi/src/openpi/models/pi0_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0f6b662ac1450e31721f9860145496720e26b5e
--- /dev/null
+++ b/openpi-umi/src/openpi/models/pi0_config.py
@@ -0,0 +1,108 @@
+import dataclasses
+from typing import TYPE_CHECKING
+
+import flax.nnx as nnx
+import jax
+import jax.numpy as jnp
+from typing_extensions import override
+
+from openpi.models import model as _model
+import openpi.models.gemma as _gemma
+from openpi.shared import array_typing as at
+import openpi.shared.nnx_utils as nnx_utils
+
+if TYPE_CHECKING:
+ from openpi.models.pi0 import Pi0
+
+
+@dataclasses.dataclass(frozen=True)
+class Pi0Config(_model.BaseModelConfig):
+ dtype: str = "bfloat16"
+ paligemma_variant: _gemma.Variant = "gemma_2b"
+ action_expert_variant: _gemma.Variant = "gemma_300m"
+
+ # Set the model specific defaults.
+ action_dim: int = 32
+ action_horizon: int = 50
+ max_token_len: int = None # type: ignore
+ # Pi05 has two differences from Pi0:
+ # - the state input is part of the discrete language tokens rather than a continuous input that is part of the suffix
+ # - the action expert uses adaRMSNorm to inject the flow matching timestep
+ pi05: bool = False
+ # This config option is not used directly by the model, but it is read by the ModelTransformFactory.
+ discrete_state_input: bool = None # type: ignore
+
+ def __post_init__(self):
+ if self.max_token_len is None:
+ object.__setattr__(self, "max_token_len", 200 if self.pi05 else 48)
+ if self.discrete_state_input is None:
+ object.__setattr__(self, "discrete_state_input", self.pi05)
+
+ @property
+ @override
+ def model_type(self) -> _model.ModelType:
+ if self.pi05:
+ return _model.ModelType.PI05
+ return _model.ModelType.PI0
+
+ @override
+ def create(self, rng: at.KeyArrayLike) -> "Pi0":
+ from openpi.models.pi0 import Pi0
+
+ return Pi0(self, rngs=nnx.Rngs(rng))
+
+ @override
+ def inputs_spec(self, *, batch_size: int = 1) -> tuple[_model.Observation, _model.Actions]:
+ image_spec = jax.ShapeDtypeStruct([batch_size, *_model.IMAGE_RESOLUTION, 3], jnp.float32)
+ image_mask_spec = jax.ShapeDtypeStruct([batch_size], jnp.bool_)
+
+ with at.disable_typechecking():
+ observation_spec = _model.Observation(
+ images={
+ "base_0_rgb": image_spec,
+ "left_wrist_0_rgb": image_spec,
+ "right_wrist_0_rgb": image_spec,
+ },
+ image_masks={
+ "base_0_rgb": image_mask_spec,
+ "left_wrist_0_rgb": image_mask_spec,
+ "right_wrist_0_rgb": image_mask_spec,
+ },
+ state=jax.ShapeDtypeStruct([batch_size, self.action_dim], jnp.float32),
+ tokenized_prompt=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.int32),
+ tokenized_prompt_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], bool),
+ )
+ action_spec = jax.ShapeDtypeStruct([batch_size, self.action_horizon, self.action_dim], jnp.float32)
+
+ return observation_spec, action_spec
+
+ def get_freeze_filter(self) -> nnx.filterlib.Filter:
+ """Returns the freeze filter based on the model config."""
+ filters = []
+ has_lora = False
+ gemma_params_filter = nnx_utils.PathRegex(".*llm.*")
+ action_expert_params_filter = nnx_utils.PathRegex(".*llm.*_1.*")
+ if "lora" in self.paligemma_variant:
+ filters.append(
+ gemma_params_filter,
+ )
+ if "lora" not in self.action_expert_variant:
+ # If only freeze gemma params, exclude action expert params.
+ filters.append(
+ nnx.Not(action_expert_params_filter),
+ )
+ has_lora = True
+ elif "lora" in self.action_expert_variant:
+ filters.append(
+ action_expert_params_filter,
+ )
+ has_lora = True
+
+ if has_lora:
+ # If any lora is used, exclude all lora params.
+ filters.append(
+ nnx.Not(nnx_utils.PathRegex(".*lora.*")),
+ )
+ if not filters:
+ return nnx.Nothing
+ return nnx.All(*filters)
diff --git a/openpi-umi/src/openpi/models/pi0_fast.py b/openpi-umi/src/openpi/models/pi0_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6b5bd15e27a58a37e8db3f9f9b9707806fec7a5
--- /dev/null
+++ b/openpi-umi/src/openpi/models/pi0_fast.py
@@ -0,0 +1,313 @@
+import dataclasses
+import logging
+from typing import Any
+
+import einops
+import flax.nnx as nnx
+import flax.nnx.bridge as nnx_bridge
+import jax
+import jax.numpy as jnp
+from typing_extensions import override
+
+from openpi.models import model as _model
+import openpi.models.gemma_fast as _gemma
+import openpi.models.siglip as _siglip
+from openpi.shared import array_typing as at
+import openpi.shared.nnx_utils as nnx_utils
+
+logger = logging.getLogger("openpi")
+
+PALIGEMMA_EOS_TOKEN = 1
+
+
+def make_attn_mask(input_mask, mask_ar):
+ """Adapted from big_vision.
+
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
+ smaller or equal to theirs. This way `mask_ar` bool[?B, N] can be used to
+ setup several types of attention, for example:
+
+ [[1 1 1 1 1 1]]: pure causal attention.
+
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
+ themselves and the last 3 tokens have a causal attention. The first
+ entry could also be a 1 without changing behaviour.
+
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
+ block can attend all previous blocks and all tokens on the same block.
+
+ Args:
+ input_mask: bool[B, N] true if its part of the input, false if padding.
+ mask_ar: bool[?B, N] mask that's true where previous tokens cannot depend on
+ it and false where it shares the same attention mask as the previous token.
+ """
+ mask_ar = jnp.broadcast_to(mask_ar, input_mask.shape)
+ cumsum = jnp.cumsum(mask_ar, axis=1)
+ attn_mask = cumsum[:, None, :] <= cumsum[:, :, None]
+ valid_mask = input_mask[:, None, :] * input_mask[:, :, None]
+ return jnp.logical_and(attn_mask, valid_mask)
+
+
+@jax.vmap
+def left_to_right_align(x, input_mask, attn_mask):
+ """Converts input from left-align to right-aligned."""
+ # Due to vmap, this is operating in a single example (not batch level).
+ assert x.ndim == 2
+ assert input_mask.ndim == 1
+ assert attn_mask.ndim == 2
+ assert x.shape[0] == input_mask.shape[0]
+ assert attn_mask.shape[0] == attn_mask.shape[1], attn_mask.shape
+ seqlen = jnp.max(input_mask * jnp.arange(input_mask.shape[0])) + 1
+ x = jnp.roll(x, -seqlen, axis=0)
+ input_mask = jnp.roll(input_mask, -seqlen, axis=0)
+ attn_mask = jnp.roll(attn_mask, -seqlen, axis=(0, 1))
+ return x, input_mask, attn_mask
+
+
+def put_along_last_axis(arr, indices, values):
+ """Like np.put_along_axis(..., axis=-1), since jax is missing it."""
+ assert arr.ndim == indices.ndim == values.ndim, (arr.ndim, indices.ndim, values.ndim)
+ onehot = jax.nn.one_hot(indices, arr.shape[-1], dtype=values.dtype)
+ put_mask = jnp.einsum("...i,...in->...n", jnp.ones(values.shape, jnp.int32), onehot)
+ put_values = jnp.einsum("...i,...in->...n", values, onehot)
+ return jnp.where(put_mask, put_values, arr)
+
+
+@dataclasses.dataclass(frozen=True)
+class Pi0FASTConfig(_model.BaseModelConfig):
+ dtype: str = "bfloat16"
+ paligemma_variant: _gemma.Variant = "gemma_2b"
+
+ # Set the model specific defaults.
+ action_dim: int = 32
+ action_horizon: int = 32
+ max_token_len: int = 250
+
+ # Tokenizer for the fast model.
+ fast_model_tokenizer: Any | None = None
+ # Keyword arguments for the fast model tokenizer.
+ fast_model_tokenizer_kwargs: dict[str, Any] | None = None
+
+ @property
+ @override
+ def model_type(self) -> _model.ModelType:
+ return _model.ModelType.PI0_FAST
+
+ @override
+ def create(self, rng: at.KeyArrayLike) -> "Pi0FAST":
+ return Pi0FAST(self, rngs=nnx.Rngs(rng))
+
+ @override
+ def inputs_spec(self, *, batch_size: int = 1) -> tuple[_model.Observation, _model.Actions]:
+ image_spec = jax.ShapeDtypeStruct([batch_size, *_model.IMAGE_RESOLUTION, 3], jnp.float32)
+ image_mask_spec = jax.ShapeDtypeStruct([batch_size], jnp.bool_)
+
+ with at.disable_typechecking():
+ observation_spec = _model.Observation(
+ images={
+ "base_0_rgb": image_spec,
+ "base_1_rgb": image_spec,
+ "wrist_0_rgb": image_spec,
+ },
+ image_masks={
+ "base_0_rgb": image_mask_spec,
+ "base_1_rgb": image_mask_spec,
+ "wrist_0_rgb": image_mask_spec,
+ },
+ state=jax.ShapeDtypeStruct([batch_size, self.action_dim], jnp.float32),
+ tokenized_prompt=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.int32),
+ tokenized_prompt_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], bool),
+ token_ar_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.int32),
+ token_loss_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.bool_),
+ )
+ action_spec = jax.ShapeDtypeStruct([batch_size, self.action_horizon, self.action_dim], jnp.float32)
+
+ return observation_spec, action_spec
+
+ def get_freeze_filter(self) -> nnx.filterlib.Filter:
+ """Returns the freeze filter based on the model config."""
+ if "lora" in self.paligemma_variant:
+ return nnx.All(nnx_utils.PathRegex(".*llm.*"), nnx.Not(nnx_utils.PathRegex(".*lora.*")))
+ return nnx.Nothing
+
+
+class Pi0FAST(_model.BaseModel):
+ def __init__(self, config: Pi0FASTConfig, rngs: nnx.Rngs):
+ super().__init__(config.action_dim, config.action_horizon, config.max_token_len)
+ paligemma_config = _gemma.get_config(config.paligemma_variant)
+ # TODO: rewrite gemma in NNX. For now, use bridge.
+ llm = nnx_bridge.ToNNX(
+ _gemma.Module(
+ **paligemma_config,
+ embed_dtype=config.dtype,
+ cache_dtype=config.dtype,
+ )
+ )
+ llm.lazy_init(rngs=rngs, method="init")
+ img = nnx_bridge.ToNNX(
+ _siglip.Module(
+ num_classes=paligemma_config.width,
+ variant="So400m/14",
+ pool_type="none",
+ scan=True,
+ dtype_mm=config.dtype,
+ )
+ )
+ img.lazy_init(next(iter(config.fake_obs().images.values())), train=False, rngs=rngs)
+ self.PaliGemma = nnx.Dict(llm=llm, img=img)
+
+ @at.typecheck
+ def embed_inputs(
+ self, obs: _model.Observation
+ ) -> tuple[at.Float[at.Array, "b s emb"], at.Bool[at.Array, "b s"], at.Int[at.Array, "b s"]]:
+ input_mask = []
+ ar_mask = []
+ token_embeddings = []
+ # embed images
+ for name in obs.images:
+ image_token_embeddings, _ = self.PaliGemma.img(obs.images[name], train=False)
+
+ token_embeddings.append(image_token_embeddings)
+ input_mask.append(
+ einops.repeat(
+ obs.image_masks[name],
+ "b -> b s",
+ s=image_token_embeddings.shape[1],
+ )
+ )
+ # image tokens attend to each other --> AR mask = 0
+ ar_mask.append(0 * input_mask[-1])
+
+ # add tokenized inputs
+ assert obs.tokenized_prompt is not None, "Tokenized prompt is required"
+ assert obs.tokenized_prompt_mask is not None, "Tokenized prompt mask is required"
+ assert obs.token_ar_mask is not None, "Token auto-regressive mask is required"
+ tokenized_inputs_embeddings = self.PaliGemma.llm(obs.tokenized_prompt, embed_only=True)
+ token_embeddings.append(tokenized_inputs_embeddings)
+ input_mask.append(obs.tokenized_prompt_mask)
+ ar_mask.append(obs.token_ar_mask)
+
+ # return embeddings, input mask, and ar mask
+ return (
+ jnp.concatenate(token_embeddings, axis=1),
+ jnp.concatenate(input_mask, axis=1),
+ jnp.concatenate(ar_mask, axis=1),
+ )
+
+ @override
+ def compute_loss(
+ self, rng: at.KeyArrayLike, observation: _model.Observation, actions: _model.Actions, *, train: bool = False
+ ) -> at.Float[at.Array, "*b ah"]:
+ observation = _model.preprocess_observation(
+ rng, observation, train=train, image_keys=list(observation.images.keys())
+ )
+
+ # Compute inputs: one big forward pass of prefix + suffix at once
+ input_token_embeddings, input_mask, ar_mask = self.embed_inputs(observation)
+ attn_mask = make_attn_mask(input_mask, ar_mask)
+
+ # Compute one-hot targets: we predict *next* token, so shift the input tokens by one.
+ targets = jax.nn.one_hot(
+ observation.tokenized_prompt[:, 1:],
+ self.PaliGemma.llm.module.vocab_size,
+ )
+
+ # Each input predicts *next* token, so we don't input the last token.
+ pre_logits, _, _ = self.PaliGemma.llm(
+ embedded_prefix=input_token_embeddings[:, :-1],
+ mask=attn_mask[:, :-1, :-1],
+ return_prelogits=True,
+ )
+
+ # Only decode logits for the target tokens to save memory
+ # (decoding matmul is large because it is a seq_len x vocab_size dense layer).
+ logits, _ = self.PaliGemma.llm(
+ pre_logits=pre_logits[:, -targets.shape[1] :],
+ )
+ logp = jax.nn.log_softmax(logits, axis=-1)
+
+ # Compute CE loss on token targets
+ assert observation.token_loss_mask is not None, "Token loss mask is required"
+ loss_mask = observation.token_loss_mask[:, 1:]
+ token_pplx = jnp.sum(targets * logp, axis=-1)
+ return -jnp.sum(token_pplx * loss_mask, axis=-1) / jnp.clip(jnp.sum(loss_mask, -1), 1)
+
+ @override
+ def sample_actions(
+ self,
+ rng: at.KeyArrayLike,
+ observation: _model.Observation,
+ *,
+ max_decoding_steps: int | at.Int[at.Array, ""] = 256,
+ temperature: float = 0.0,
+ ) -> _model.Actions:
+ # TODO: this is a hack to get the image keys.
+ observation = _model.preprocess_observation(
+ None, observation, train=False, image_keys=list(observation.images.keys())
+ )
+
+ # embed inputs
+ prefix_token_embeddings, prefix_mask, prefix_ar_mask = self.embed_inputs(observation)
+ prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
+
+ # left to right align all input token sequences
+ prefix_token_embeddings, prefix_mask, prefix_attn_mask = left_to_right_align(
+ prefix_token_embeddings, prefix_mask, prefix_attn_mask
+ )
+ prefill_size = prefix_token_embeddings.shape[1]
+ prefill_len = jnp.sum(prefix_mask, axis=-1)
+ prefix_start = prefill_size - prefill_len
+
+ # first fill KV cache with a forward pass of the prefix
+ # pad attention mask to set the size of the KV cache (prefill_size + max_decoding_steps)
+ prefix_attn_mask = jnp.pad(prefix_attn_mask, ((0, 0), (0, 0), (0, max_decoding_steps)))
+ prefix_positions = jnp.cumsum(prefix_mask, axis=-1) - 1
+ prefix_logits, kv_cache, _ = self.PaliGemma.llm(
+ embedded_prefix=prefix_token_embeddings, mask=prefix_attn_mask, positions=prefix_positions, decode=True
+ )
+
+ # prepare decoding -- final logit decodes the first token
+ last_logit = prefix_logits[:, -1:]
+ output_tokens = jnp.zeros((last_logit.shape[0], max_decoding_steps))
+
+ def step(carry):
+ rng, last_logit, output_tokens, cache, _, step = carry
+
+ # Sample token from last logit
+ # Split RNG for this step
+ rng, rng_step = jax.random.split(rng)
+ token = jax.lax.cond(
+ temperature > 0.0,
+ lambda _: jax.random.categorical(rng_step, last_logit / temperature, axis=-1),
+ lambda _: jnp.argmax(last_logit, axis=-1),
+ operand=None,
+ )
+ output_tokens = put_along_last_axis(output_tokens, jnp.broadcast_to(step, (token.shape[0], 1)), token)
+
+ # Check for early stopping --> stop if all batch elements have EOS token
+ has_eos = jnp.any(token == PALIGEMMA_EOS_TOKEN, axis=-1)
+ all_eos = jnp.all(has_eos)
+
+ # Decode one step
+ token_embedding = self.PaliGemma.llm(token, embed_only=True)
+ positions = prefill_len[:, None] + step + 1
+ mask = jnp.logical_and(
+ jnp.arange(prefill_size + max_decoding_steps)[None, None, :] >= prefix_start[:, None, None],
+ jnp.arange(prefill_size + max_decoding_steps)[None, None, :]
+ < (jnp.broadcast_to(prefill_size + step + 1, (prefix_start.shape[0], 1, 1))),
+ )
+ last_logit, kv_cache, _ = self.PaliGemma.llm(
+ embedded_prefix=token_embedding, mask=mask, positions=positions, decode=True, kv_cache=cache
+ )
+
+ return rng, last_logit, output_tokens, kv_cache, all_eos, step + 1
+
+ def cond(carry):
+ _, _, _, _, all_eos, step = carry
+ return (~all_eos) & (step < max_decoding_steps)
+
+ # Use lax.while_loop so we can jit the full decoding loop.
+ _, _, output_tokens, _, _, _ = jax.lax.while_loop(
+ cond, step, (rng, last_logit, output_tokens, kv_cache, False, 0)
+ )
+ return output_tokens
diff --git a/openpi-umi/src/openpi/models/pi0_test.py b/openpi-umi/src/openpi/models/pi0_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5f0f84e7e831db37883ec3181eadf6e175840ef
--- /dev/null
+++ b/openpi-umi/src/openpi/models/pi0_test.py
@@ -0,0 +1,46 @@
+import flax.nnx as nnx
+import jax
+
+import openpi.models.pi0_config as _pi0_config
+
+
+def _get_frozen_state(config: _pi0_config.Pi0Config) -> nnx.State:
+ abstract_model = nnx.eval_shape(config.create, jax.random.key(0))
+
+ freeze_filter = config.get_freeze_filter()
+ return nnx.state(abstract_model, nnx.All(nnx.Param, freeze_filter)).flat_state()
+
+
+def test_pi0_full_finetune():
+ config = _pi0_config.Pi0Config()
+ state = _get_frozen_state(config)
+ assert len(state) == 0
+
+
+def test_pi0_gemma_lora():
+ config = _pi0_config.Pi0Config(paligemma_variant="gemma_2b_lora")
+ state = _get_frozen_state(config)
+ assert len(state) == 9
+ assert all("lora" not in p for p in state)
+ assert all("llm" in p for p in state)
+ assert all("_1" not in p for p in state)
+
+
+def test_pi0_action_expert_lora():
+ config = _pi0_config.Pi0Config(action_expert_variant="gemma_300m_lora")
+ state = _get_frozen_state(config)
+ # excluding embedder, rest of the params should be same as gemma_lora.
+ assert len(state) == 8
+ assert all("lora" not in p for p in state)
+ assert all("llm" in p for p in state)
+ # all frozen params should have _1 in their path since it's the action expert.
+ assert all(any("_1" in p for p in path) for path in state)
+
+
+def test_pi0_all_lora():
+ config = _pi0_config.Pi0Config(paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora")
+ state = _get_frozen_state(config)
+ # sum of gemma_lora and action_expert_lora's frozen params.
+ assert len(state) == 17
+ assert all("lora" not in p for p in state)
+ assert all("llm" in p for p in state)
diff --git a/openpi-umi/src/openpi/models/siglip.py b/openpi-umi/src/openpi/models/siglip.py
new file mode 100644
index 0000000000000000000000000000000000000000..c74c99e75fa45308fcadff115a7fd4ed12c9e96c
--- /dev/null
+++ b/openpi-umi/src/openpi/models/siglip.py
@@ -0,0 +1,373 @@
+# Copyright 2024 Big Vision Authors.
+#
+# 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.
+
+"""A refactored and simplified ViT adoptation for Pi, taken from big_vision."""
+
+from collections.abc import Sequence
+
+import flax.linen as nn
+import jax
+import jax.numpy as jnp
+import numpy as np
+
+import openpi.training.sharding as sharding
+
+
+def posemb_sincos_2d(h, w, width, temperature=10_000.0, dtype=jnp.float32):
+ """Follows the MoCo v3 logic."""
+ y, x = jnp.mgrid[:h, :w]
+
+ assert width % 4 == 0, "Width must be mult of 4 for sincos posemb"
+ omega = jnp.arange(width // 4) / (width // 4 - 1)
+ omega = 1.0 / (temperature**omega)
+ y = jnp.einsum("m,d->md", y.flatten(), omega)
+ x = jnp.einsum("m,d->md", x.flatten(), omega)
+ pe = jnp.concatenate([jnp.sin(x), jnp.cos(x), jnp.sin(y), jnp.cos(y)], axis=1)
+ return jnp.asarray(pe, dtype)[None, :, :]
+
+
+def get_posemb(self, typ, seqshape, width, name, dtype=jnp.float32):
+ if typ == "learn":
+ return self.param(
+ name,
+ nn.initializers.normal(stddev=1 / np.sqrt(width)),
+ (1, np.prod(seqshape), width),
+ dtype,
+ )
+ if typ == "sincos2d":
+ return posemb_sincos_2d(*seqshape, width, dtype=dtype)
+ raise ValueError(f"Unknown posemb type: {typ}")
+
+
+class MlpBlock(nn.Module):
+ """Transformer MLP / feed-forward block."""
+
+ mlp_dim: int | None = None # Defaults to 4x input dim
+ dropout: float = 0.0
+ dtype_mm: str = "float32"
+
+ @nn.compact
+ def __call__(self, x, deterministic=True): # noqa: FBT002
+ """Applies Transformer MlpBlock module."""
+ inits = {
+ "kernel_init": nn.initializers.xavier_uniform(),
+ "bias_init": nn.initializers.normal(stddev=1e-6),
+ }
+
+ _, _, d = x.shape # n,l,d
+ x = nn.Dense(self.mlp_dim or 4 * d, dtype=self.dtype_mm, **inits)(x)
+ x = nn.gelu(x)
+ x = nn.Dropout(rate=self.dropout)(x, deterministic)
+ return nn.Dense(d, dtype=self.dtype_mm, **inits)(x)
+
+
+class Encoder1DBlock(nn.Module):
+ """Single transformer encoder block (MHSA + MLP)."""
+
+ mlp_dim: int | None = None # Defaults to 4x input dim
+ num_heads: int = 12
+ dropout: float = 0.0
+ dtype_mm: str = "float32"
+
+ @nn.compact
+ def __call__(self, x, deterministic=True): # noqa: FBT002
+ out = {}
+ x = sharding.activation_sharding_constraint(x)
+ y = nn.LayerNorm(dtype=self.dtype_mm)(x)
+ y = out["sa"] = nn.MultiHeadDotProductAttention(
+ num_heads=self.num_heads,
+ kernel_init=nn.initializers.xavier_uniform(),
+ deterministic=deterministic,
+ dtype=self.dtype_mm,
+ )(y, y)
+ y = sharding.activation_sharding_constraint(y)
+ y = nn.Dropout(rate=self.dropout)(y, deterministic)
+ x = out["+sa"] = x + y
+
+ y = nn.LayerNorm(dtype=self.dtype_mm)(x)
+ y = out["mlp"] = MlpBlock(
+ mlp_dim=self.mlp_dim,
+ dropout=self.dropout,
+ dtype_mm=self.dtype_mm,
+ )(y, deterministic)
+ y = sharding.activation_sharding_constraint(y)
+ y = nn.Dropout(rate=self.dropout)(y, deterministic)
+ x = out["+mlp"] = x + y
+ x = sharding.activation_sharding_constraint(x)
+ return x, out
+
+
+class Encoder(nn.Module):
+ """Transformer Model Encoder for sequence to sequence translation."""
+
+ depth: int
+ mlp_dim: int | None = None # Defaults to 4x input dim
+ num_heads: int = 12
+ dropout: float = 0.0
+ scan: bool = False
+ remat_policy: str = "nothing_saveable"
+ dtype_mm: str = "float32"
+
+ @nn.compact
+ def __call__(self, x, deterministic=True): # noqa: FBT002
+ out = {}
+
+ if self.scan:
+ block = nn.remat(
+ Encoder1DBlock,
+ prevent_cse=False,
+ static_argnums=(2,), # 0=self, 2=deterministic
+ policy=getattr(jax.checkpoint_policies, self.remat_policy, None),
+ )
+ x, scan_out = nn.scan(
+ block,
+ variable_axes={"params": 0},
+ split_rngs={"params": True, "dropout": True},
+ in_axes=nn.broadcast,
+ length=self.depth,
+ )(
+ name="encoderblock",
+ dtype_mm=self.dtype_mm,
+ mlp_dim=self.mlp_dim,
+ num_heads=self.num_heads,
+ dropout=self.dropout,
+ )(x, deterministic)
+ for lyr in range(self.depth):
+ out[f"block{lyr:02d}"] = jax.tree.map(lambda o, lyr=lyr: o[lyr], scan_out)
+ else:
+ # Input Encoder
+ for lyr in range(self.depth):
+ block_cur = Encoder1DBlock(
+ name=f"encoderblock_{lyr}",
+ dtype_mm=self.dtype_mm,
+ mlp_dim=self.mlp_dim,
+ num_heads=self.num_heads,
+ dropout=self.dropout,
+ )
+ x, out[f"block{lyr:02d}"] = block_cur(x, deterministic)
+ out["pre_ln"] = x # Alias for last block, but without the number in it.
+
+ return nn.LayerNorm(name="encoder_norm", dtype=self.dtype_mm)(x), out
+
+
+class MAPHead(nn.Module):
+ """Multihead Attention Pooling."""
+
+ mlp_dim: int | None = None # Defaults to 4x input dim
+ num_heads: int = 12
+ dtype_mm: str = "float32"
+
+ @nn.compact
+ def __call__(self, x):
+ n, _, d = x.shape # n,l,d
+ probe = self.param("probe", nn.initializers.xavier_uniform(), (1, 1, d), x.dtype)
+ probe = jnp.tile(probe, [n, 1, 1])
+
+ x = nn.MultiHeadDotProductAttention(
+ num_heads=self.num_heads,
+ dtype=self.dtype_mm,
+ kernel_init=nn.initializers.xavier_uniform(),
+ )(probe, x)
+
+ y = nn.LayerNorm(dtype=self.dtype_mm)(x)
+ x = x + MlpBlock(mlp_dim=self.mlp_dim, dtype=self.dtype_mm)(y)
+ return x[:, 0]
+
+
+class _Module(nn.Module):
+ """ViT model."""
+
+ num_classes: int | None = None
+ patch_size: Sequence[int] = (16, 16)
+ width: int = 768
+ depth: int = 12
+ mlp_dim: int | None = None # Defaults to 4x input dim
+ num_heads: int = 12
+ posemb: str = "learn" # Can also be "sincos2d"
+ rep_size: int | bool = False
+ dropout: float = 0.0
+ pool_type: str = "gap" # Can also be "map" or "tok"
+ head_zeroinit: bool = True
+ scan: bool = False
+ # or "dots_with_no_batch_dims_saveable" for more speed (memory costly)
+ remat_policy: str = "nothing_saveable"
+ dtype_mm: str = "float32"
+
+ @nn.compact
+ def __call__(self, image, *, train=False):
+ out = {}
+
+ # Kevin edit: do patch extraction and posemb in float32,
+ # because I feel like it's a bit safer.
+ image = jnp.asarray(image, jnp.float32)
+
+ # Patch extraction
+ x = out["stem"] = nn.Conv(
+ self.width,
+ self.patch_size,
+ strides=self.patch_size,
+ padding="VALID",
+ name="embedding",
+ dtype=jnp.float32,
+ )(image)
+
+ n, h, w, c = x.shape
+ x = jnp.reshape(x, [n, h * w, c])
+
+ # Add posemb before adding extra token.
+ x = out["with_posemb"] = x + get_posemb(self, self.posemb, (h, w), c, "pos_embedding", jnp.float32)
+
+ if self.pool_type == "tok":
+ cls = self.param("cls", nn.initializers.zeros, (1, 1, c), x.dtype)
+ x = jnp.concatenate([jnp.tile(cls, [n, 1, 1]), x], axis=1)
+
+ n, _, c = x.shape # n,l,d
+ x = nn.Dropout(rate=self.dropout)(x, not train)
+
+ # Kevin edit: now cast back to dtype_mm (potentially half precision)
+ x = x.astype(self.dtype_mm)
+
+ x, out["encoder"] = Encoder(
+ depth=self.depth,
+ mlp_dim=self.mlp_dim,
+ num_heads=self.num_heads,
+ dropout=self.dropout,
+ scan=self.scan,
+ remat_policy=self.remat_policy,
+ dtype_mm=self.dtype_mm,
+ name="Transformer",
+ )(x, deterministic=not train)
+ encoded = out["encoded"] = x
+
+ if self.pool_type == "map":
+ x = out["head_input"] = MAPHead(
+ num_heads=self.num_heads,
+ mlp_dim=self.mlp_dim,
+ dtype=self.dtype_mm,
+ )(x)
+ elif self.pool_type == "gap":
+ x = out["head_input"] = jnp.mean(x, axis=1)
+ elif self.pool_type == "0":
+ x = out["head_input"] = x[:, 0]
+ elif self.pool_type == "tok":
+ x = out["head_input"] = x[:, 0]
+ encoded = encoded[:, 1:]
+ elif self.pool_type == "none":
+ pass
+ else:
+ raise ValueError(f"Unknown pool type: '{self.pool_type}'")
+
+ x_2d = jnp.reshape(encoded, [n, h, w, -1])
+
+ if self.rep_size:
+ rep_size = self.width if self.rep_size is True else self.rep_size
+ hid = nn.Dense(rep_size, dtype=self.dtype_mm, name="pre_logits")
+ # NOTE: In the past we did not include tanh in pre_logits.
+ # For few-shot, it should not matter much, as it whitens anyways.
+ x_2d = nn.tanh(hid(x_2d))
+ x = nn.tanh(hid(x))
+
+ out["pre_logits_2d"] = x_2d
+ out["pre_logits"] = x
+
+ if self.num_classes:
+ kw = {"kernel_init": nn.initializers.zeros} if self.head_zeroinit else {}
+ head = nn.Dense(self.num_classes, dtype=self.dtype_mm, name="head", **kw)
+ x_2d = out["logits_2d"] = head(x_2d)
+ x = out["logits"] = head(x)
+
+ return x, out
+
+
+def Module(num_classes=None, *, variant=None, **kw): # pylint: disable=invalid-name # noqa: N802
+ """Factory function, because linen really don't like what I'm doing!"""
+ return _Module(num_classes, **{**decode_variant(variant), **kw})
+
+
+def decode_variant(variant):
+ """Converts a string like "B" or "B/32" into a params dict."""
+ if variant is None:
+ return {}
+
+ v, patch = variant, {}
+ if "/" in variant:
+ v, patch = variant.split("/")
+ patch = {"patch_size": (int(patch), int(patch))}
+
+ return {
+ # pylint:disable=line-too-long
+ # Reference: Table 2 of https://arxiv.org/abs/2106.04560.
+ "width": {
+ "mu": 32,
+ "Ti": 192,
+ "S": 384,
+ "M": 512,
+ "B": 768,
+ "L": 1024,
+ "So400m": 1152,
+ "H": 1280,
+ "g": 1408,
+ "g-opt": 1536,
+ "G": 1664,
+ "G-opt": 1536,
+ "e": 1792,
+ }[v],
+ "depth": {
+ "mu": 1,
+ "Ti": 12,
+ "S": 12,
+ "M": 12,
+ "B": 12,
+ "L": 24,
+ "So400m": 27,
+ "H": 32,
+ "g": 40,
+ "g-opt": 40,
+ "G": 48,
+ "G-opt": 48,
+ "e": 56,
+ }[v],
+ "mlp_dim": {
+ "mu": 128,
+ "Ti": 768,
+ "S": 1536,
+ "M": 2048,
+ "B": 3072,
+ "L": 4096,
+ "So400m": 4304,
+ "H": 5120,
+ "g": 6144,
+ "g-opt": 6144,
+ "G": 8192,
+ "G-opt": 8192,
+ "e": 15360,
+ }[v],
+ "num_heads": {
+ "mu": 2,
+ "Ti": 3,
+ "S": 6,
+ "M": 8,
+ "B": 12,
+ "L": 16,
+ "So400m": 16,
+ "H": 16,
+ "g": 16,
+ "g-opt": 16,
+ "G": 16,
+ "G-opt": 16,
+ "e": 16,
+ }[v],
+ # pylint:enable=line-too-long
+ **patch,
+ }
diff --git a/openpi-umi/src/openpi/models/tokenizer.py b/openpi-umi/src/openpi/models/tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..07b9b225cab82dc6bd908720422f294c1e49f1f6
--- /dev/null
+++ b/openpi-umi/src/openpi/models/tokenizer.py
@@ -0,0 +1,384 @@
+import logging
+import os
+import pathlib
+
+import jax
+import numpy as np
+import orbax.checkpoint as ocp
+import sentencepiece
+from transformers import AutoProcessor
+
+import openpi.models.utils.fsq_tokenizer as fsq_tokenizer
+import openpi.shared.download as download
+
+
+class PaligemmaTokenizer:
+ def __init__(self, max_len: int = 48):
+ self._max_len = max_len
+
+ # Offline clusters can place the tokenizer at ./model/paligemma-3b-pt-224/; otherwise download it.
+ local = pathlib.Path("model/paligemma-3b-pt-224/tokenizer.model")
+ path = local if local.exists() else download.maybe_download(
+ "gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"}
+ )
+ with path.open("rb") as f:
+ self._tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
+
+ def tokenize(
+ self, prompt: str, state: np.ndarray | None = None, *, drop_state: bool = False
+ ) -> tuple[np.ndarray, np.ndarray]:
+ cleaned_text = prompt.strip().replace("_", " ").replace("\n", " ")
+ if state is not None:
+ if drop_state:
+ # CFG-style null conditioning: the State section is omitted entirely (a
+ # zeroed state would discretize to the middle bin and read as a plausible
+ # "mean" state instead of "no state").
+ full_prompt = f"Task: {cleaned_text};\nAction: "
+ else:
+ # This is the Pi05 format, where the state is part of the discrete language input.
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
+ state_str = " ".join(map(str, discretized_state))
+ full_prompt = f"Task: {cleaned_text}, State: {state_str};\nAction: "
+ tokens = self._tokenizer.encode(full_prompt, add_bos=True)
+ else:
+ # This is the Pi0 format, where the state is part of the continuous action expert input.
+ # tokenize "\n" separately as the "start of answer" token
+ tokens = self._tokenizer.encode(cleaned_text, add_bos=True) + self._tokenizer.encode("\n")
+ tokens_len = len(tokens)
+ if tokens_len < self._max_len:
+ padding = [False] * (self._max_len - tokens_len)
+ mask = [True] * tokens_len + padding
+ tokens = tokens + padding
+ else:
+ if len(tokens) > self._max_len:
+ logging.warning(
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
+ )
+ tokens = tokens[: self._max_len]
+ mask = [True] * self._max_len
+
+ return np.asarray(tokens), np.asarray(mask)
+
+
+class FASTTokenizer:
+ def __init__(self, max_len: int = 256, fast_tokenizer_path: str = "physical-intelligence/fast"):
+ self._max_len = max_len
+
+ # Download base PaliGemma tokenizer
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
+ with path.open("rb") as f:
+ self._paligemma_tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
+
+ # Instantiate FAST tokenizer
+ self._fast_tokenizer = AutoProcessor.from_pretrained(fast_tokenizer_path, trust_remote_code=True)
+ self._fast_skip_tokens = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
+
+ def tokenize(
+ self, prompt: str, state: np.ndarray, actions: np.ndarray | None
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ cleaned_text = prompt.lower().strip().replace("_", " ")
+
+ # Convention: state gets discretized into 256 discrete bins (assumed range after normalization: [-1, 1])
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
+
+ # Convention: prefix includes prompt and string-representation of state, followed by ';'
+ state_str = " ".join(map(str, discretized_state))
+ prefix = f"Task: {cleaned_text}, State: {state_str};\n"
+ prefix_tokens = self._paligemma_tokenizer.encode(prefix, add_bos=True)
+
+ if actions is not None:
+ # Tokenize actions with FAST tokenizer --> map to last tokens in PaliGemma vocab
+ action_tokens = self._fast_tokenizer(actions[None])[0]
+ action_tokens_in_pg = self._act_tokens_to_paligemma_tokens(action_tokens)
+
+ # Convention: postfix contains 'Action:' followed by FAST tokens, followed by '|'
+ postfix_tokens = (
+ self._paligemma_tokenizer.encode("Action: ")
+ + action_tokens_in_pg.tolist()
+ + self._paligemma_tokenizer.encode("|", add_eos=True)
+ )
+ else:
+ postfix_tokens = []
+
+ # Create output token sequence & masks
+ # AR mask is 0 on prefix (bidirectional attention) and 1 on postfix (causal attention to all previous tokens)
+ tokens = prefix_tokens + postfix_tokens
+ token_mask = [True] * len(tokens)
+ ar_mask = [0] * len(prefix_tokens) + [1] * len(postfix_tokens)
+ loss_mask = [False] * len(prefix_tokens) + [True] * len(postfix_tokens) # Loss on postfix only
+
+ # Pad tokens to max length
+ tokens_len = len(tokens)
+ if tokens_len < self._max_len:
+ padding = [False] * (self._max_len - tokens_len)
+ tokens = tokens + padding
+ token_mask = token_mask + padding
+ ar_mask = ar_mask + padding
+ loss_mask = loss_mask + padding
+ else:
+ if len(tokens) > self._max_len:
+ logging.warning(
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
+ )
+ tokens = tokens[: self._max_len]
+ token_mask = token_mask[: self._max_len]
+ ar_mask = ar_mask[: self._max_len]
+ loss_mask = loss_mask[: self._max_len]
+
+ return np.asarray(tokens), np.asarray(token_mask), np.asarray(ar_mask), np.asarray(loss_mask)
+
+ def extract_actions(self, tokens: np.ndarray, action_horizon: int, action_dim: int) -> np.ndarray:
+ # Decode predicted output tokens
+ decoded_tokens = self._paligemma_tokenizer.decode(tokens.tolist())
+
+ # Extract actions from FAST model outputs
+ if "Action: " not in decoded_tokens:
+ return np.zeros((action_horizon, action_dim), dtype=np.float32)
+
+ # Extract actions from decoded tokens
+ raw_action_tokens = np.array(
+ self._paligemma_tokenizer.encode(decoded_tokens.split("Action: ")[1].split("|")[0].strip())
+ )
+ action_tokens = self._act_tokens_to_paligemma_tokens(raw_action_tokens)
+ return self._fast_tokenizer.decode(
+ [action_tokens.tolist()], time_horizon=action_horizon, action_dim=action_dim
+ )[0]
+
+ def _act_tokens_to_paligemma_tokens(self, tokens: np.ndarray | list[int]) -> np.ndarray:
+ if isinstance(tokens, list):
+ tokens = np.array(tokens)
+ return self._paligemma_tokenizer.vocab_size() - 1 - self._fast_skip_tokens - tokens
+
+
+###########################################################################
+## The tokenizers below are used for RoboArena baseline implementations. ##
+## They are *not* used for pi0-style models. ##
+###########################################################################
+
+
+class BinningTokenizer:
+ """
+ Standard RT-2 / OpenVLA style binning tokenizer.
+ """
+
+ def __init__(self, max_len: int = 256, n_bins: int = 256):
+ self._max_len = max_len
+ self._n_bins = n_bins
+
+ # Download base PaliGemma tokenizer
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
+ with path.open("rb") as f:
+ self._paligemma_tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
+
+ self._fast_skip_tokens = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
+
+ def tokenize(
+ self, prompt: str, state: np.ndarray, actions: np.ndarray | None
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Tokenize a prompt and state into a sequence of tokens.
+
+ Args:
+ prompt: The text prompt to tokenize.
+ state: The state array to discretize and tokenize.
+ actions: Must be None. Action encoding is not currently supported.
+
+ Returns:
+ A tuple of (tokens, token_mask, ar_mask, targets).
+
+ Raises:
+ NotImplementedError: If actions is not None.
+ """
+ cleaned_text = prompt.lower().strip().replace("_", " ")
+
+ # Convention: state gets discretized into 256 discrete bins (assumed range after normalization: [-1, 1])
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
+
+ # Convention: prefix includes prompt and string-representation of state, followed by ';'
+ state_str = " ".join(map(str, discretized_state))
+ prefix = f"Task: {cleaned_text}, State: {state_str};\n"
+ prefix_tokens = self._paligemma_tokenizer.encode(prefix, add_bos=True)
+
+ if actions is not None:
+ raise NotImplementedError("BinningTokenizer does not support encoding actions atm (only for inference use)")
+ postfix_tokens = []
+
+ # Create output token sequence & masks
+ # AR mask is 0 on prefix (bidirectional attention) and 1 on postfix (causal attention to all previous tokens)
+ tokens = prefix_tokens + postfix_tokens
+ token_mask = [True] * len(tokens)
+ ar_mask = [0] * len(prefix_tokens) + [1] * len(postfix_tokens)
+ loss_mask = [False] * len(prefix_tokens) + [True] * len(postfix_tokens) # Loss on postfix only
+
+ # Pad tokens to max length
+ tokens_len = len(tokens)
+ if tokens_len < self._max_len:
+ padding = [False] * (self._max_len - tokens_len)
+ tokens = tokens + padding
+ token_mask = token_mask + padding
+ ar_mask = ar_mask + padding
+ loss_mask = loss_mask + padding
+ else:
+ if len(tokens) > self._max_len:
+ logging.warning(
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
+ )
+ tokens = tokens[: self._max_len]
+ token_mask = token_mask[: self._max_len]
+ ar_mask = ar_mask[: self._max_len]
+ loss_mask = loss_mask[: self._max_len]
+
+ return np.asarray(tokens), np.asarray(token_mask), np.asarray(ar_mask), np.asarray(loss_mask)
+
+ def extract_actions(self, tokens: np.ndarray, action_horizon: int, action_dim: int) -> np.ndarray:
+ # Decode predicted output tokens
+ decoded_tokens = self._paligemma_tokenizer.decode(tokens.tolist())
+
+ # Extract actions from FAST model outputs
+ if "Action: " not in decoded_tokens:
+ return np.zeros((action_horizon, action_dim), dtype=np.float32)
+
+ # Extract actions from decoded tokens
+ raw_action_tokens = np.array(
+ self._paligemma_tokenizer.encode(decoded_tokens.split("Action: ")[1].split("|")[0].strip())
+ )
+ action_tokens = self._act_tokens_to_paligemma_tokens(raw_action_tokens)
+ if len(action_tokens) < action_horizon * action_dim:
+ return np.zeros([action_horizon, action_dim], dtype=np.float32)
+ action_tokens = action_tokens[: (action_horizon * action_dim)].reshape([action_horizon, action_dim])
+ return action_tokens / self._n_bins * 2 - 1
+
+ def _act_tokens_to_paligemma_tokens(self, tokens: np.ndarray | list[int]) -> np.ndarray:
+ if isinstance(tokens, list):
+ tokens = np.array(tokens)
+ return self._paligemma_tokenizer.vocab_size() - 1 - self._fast_skip_tokens - tokens
+
+
+class FSQTokenizer:
+ """
+ FSQ tokenizer from the FAST paper baselines.
+ """
+
+ def __init__(self, max_len: int = 256, fsq_tokenizer_path: str | None = None):
+ self._max_len = max_len
+
+ assert fsq_tokenizer_path is not None, "fsq_tokenizer_path must be provided"
+ # Download tokenizer
+ path = download.maybe_download(fsq_tokenizer_path)
+ tok_path = os.path.join(path, os.listdir(path)[0])
+
+ # Split step from path
+ step = int(tok_path.split("/")[-1])
+ base_path = tok_path.rsplit("/", 1)[0]
+
+ mgr = ocp.CheckpointManager(
+ base_path,
+ item_handlers={
+ "params": ocp.StandardCheckpointHandler(),
+ "opt_state": ocp.StandardCheckpointHandler(),
+ "config": ocp.JsonCheckpointHandler(),
+ },
+ options=ocp.CheckpointManagerOptions(max_to_keep=1),
+ )
+
+ try:
+ restored = mgr.restore(
+ step, args=ocp.args.Composite(config=ocp.args.JsonRestore(), params=ocp.args.StandardRestore())
+ )
+ config = restored["config"]
+ self._params = restored["params"]
+ self._fsq_tokenizer = fsq_tokenizer.FsqAttentionTokenizer(**config)
+ except Exception as e:
+ raise RuntimeError(
+ f"Failed to load FSQ tokenizer checkpoint from {fsq_tokenizer_path}. Error: {e!s}"
+ ) from e
+
+ # Compile tokenize and detokenize functions
+ self._tokenize_fn = jax.jit(
+ lambda params, x: self._fsq_tokenizer.apply({"params": params}, x, method=self._fsq_tokenizer.tokenize)
+ )
+ self._detokenize_fn = jax.jit(
+ lambda params, x: self._fsq_tokenizer.apply({"params": params}, x, method=self._fsq_tokenizer.detokenize)
+ )
+
+ # Download base PaliGemma tokenizer
+ path = download.maybe_download("gs://big_vision/paligemma_tokenizer.model", gs={"token": "anon"})
+ with path.open("rb") as f:
+ self._paligemma_tokenizer = sentencepiece.SentencePieceProcessor(model_proto=f.read())
+
+ self._fast_skip_tokens = 128 # Skip last 128 tokens in PaliGemma vocab since they are special tokens
+
+ def tokenize(
+ self, prompt: str, state: np.ndarray, actions: np.ndarray | None
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ cleaned_text = prompt.lower().strip().replace("_", " ")
+
+ # Convention: state gets discretized into 256 discrete bins (assumed range after normalization: [-1, 1])
+ discretized_state = np.digitize(state, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1
+
+ # Convention: prefix includes prompt and string-representation of state, followed by ';'
+ state_str = " ".join(map(str, discretized_state))
+ prefix = f"Task: {cleaned_text}, State: {state_str};\n"
+ prefix_tokens = self._paligemma_tokenizer.encode(prefix, add_bos=True)
+
+ if actions is not None:
+ raise NotImplementedError("FSQTokenizer does not support encoding actions atm (only for inference use)")
+ postfix_tokens = []
+
+ # Create output token sequence & masks
+ # AR mask is 0 on prefix (bidirectional attention) and 1 on postfix (causal attention to all previous tokens)
+ tokens = prefix_tokens + postfix_tokens
+ token_mask = [True] * len(tokens)
+ ar_mask = [0] * len(prefix_tokens) + [1] * len(postfix_tokens)
+ loss_mask = [False] * len(prefix_tokens) + [True] * len(postfix_tokens) # Loss on postfix only
+
+ # Pad tokens to max length
+ tokens_len = len(tokens)
+ if tokens_len < self._max_len:
+ padding = [False] * (self._max_len - tokens_len)
+ tokens = tokens + padding
+ token_mask = token_mask + padding
+ ar_mask = ar_mask + padding
+ loss_mask = loss_mask + padding
+ else:
+ if len(tokens) > self._max_len:
+ logging.warning(
+ f"Token length ({len(tokens)}) exceeds max length ({self._max_len}), truncating. "
+ "Consider increasing the `max_token_len` in your model config if this happens frequently."
+ )
+ tokens = tokens[: self._max_len]
+ token_mask = token_mask[: self._max_len]
+ ar_mask = ar_mask[: self._max_len]
+ loss_mask = loss_mask[: self._max_len]
+
+ return np.asarray(tokens), np.asarray(token_mask), np.asarray(ar_mask), np.asarray(loss_mask)
+
+ def extract_actions(self, tokens: np.ndarray, action_horizon: int, action_dim: int) -> np.ndarray:
+ # Decode predicted output tokens
+ decoded_tokens = self._paligemma_tokenizer.decode(tokens.tolist())
+
+ # Extract actions from FAST model outputs
+ if "Action: " not in decoded_tokens:
+ return np.zeros((action_horizon, action_dim), dtype=np.float32)
+
+ # Extract actions from decoded tokens
+ raw_action_tokens = np.array(
+ self._paligemma_tokenizer.encode(decoded_tokens.split("Action: ")[1].split("|")[0].strip())
+ )
+ action_tokens = self._act_tokens_to_paligemma_tokens(raw_action_tokens)
+ try:
+ # Move computation to CPU and compile on-demand
+ device = jax.devices("cpu")[0]
+ with jax.default_device(device):
+ detok_act = self._detokenize_fn(self._params, action_tokens[None, ...])[0]
+ return detok_act[: action_horizon * action_dim].reshape([action_horizon, action_dim])
+ except Exception as e:
+ logging.warning(f"Error decoding FSQ: {e}")
+ return np.zeros((action_horizon, action_dim))
+
+ def _act_tokens_to_paligemma_tokens(self, tokens: np.ndarray | list[int]) -> np.ndarray:
+ if isinstance(tokens, list):
+ tokens = np.array(tokens)
+ return self._paligemma_tokenizer.vocab_size() - 1 - self._fast_skip_tokens - tokens
diff --git a/openpi-umi/src/openpi/models/tokenizer_test.py b/openpi-umi/src/openpi/models/tokenizer_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..092c4ae3b2330db9f89344dc4bae150457fa4310
--- /dev/null
+++ b/openpi-umi/src/openpi/models/tokenizer_test.py
@@ -0,0 +1,27 @@
+import numpy as np
+
+from openpi.models import tokenizer as _tokenizer
+
+
+def test_tokenize():
+ tokenizer = _tokenizer.PaligemmaTokenizer(max_len=10)
+ tokens, masks = tokenizer.tokenize("Hello, world!")
+
+ assert tokens.shape == (10,)
+ assert masks.shape == (10,)
+
+
+def test_fast_tokenizer():
+ prompt = "Hello, world!"
+ state = np.random.rand(5).astype(np.float32)
+ action = np.random.rand(3, 2).astype(np.float32)
+ tokenizer = _tokenizer.FASTTokenizer(max_len=256)
+ tokens, token_masks, ar_masks, loss_masks = tokenizer.tokenize(prompt, state, action)
+
+ assert tokens.shape == (256,)
+ assert token_masks.shape == (256,)
+ assert ar_masks.shape == (256,)
+ assert loss_masks.shape == (256,)
+
+ act = tokenizer.extract_actions(tokens, 3, 2)
+ assert act.shape == (3, 2)
diff --git a/openpi-umi/src/openpi/models/utils/fsq_tokenizer.py b/openpi-umi/src/openpi/models/utils/fsq_tokenizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..574d7733de0ebd25898d8f82fdc6e37bd0aa75ab
--- /dev/null
+++ b/openpi-umi/src/openpi/models/utils/fsq_tokenizer.py
@@ -0,0 +1,472 @@
+import math
+from typing import Any, Literal
+
+import chex
+from einops import einops
+from flax import linen as nn
+from flax.linen.module import Module
+from flax.linen.module import compact
+from flax.struct import dataclass
+from flax.typing import Array
+import jax
+import jax.numpy as jnp
+
+
+class FsqCodebook(nn.Module):
+ input_dim: int
+ target_codebook_size: int
+ codebook_type: Literal["fsq", "lfq"]
+
+ _bins_per_dim: tuple[int] | None = None
+
+ @property
+ def bins_per_dim(self) -> tuple[int]:
+ if self._bins_per_dim is not None:
+ return self._bins_per_dim
+
+ if self.codebook_type == "fsq":
+ return self._get_bins_fsq(self.target_codebook_size)
+ elif self.codebook_type == "lfq": # noqa: RET505
+ return self._get_bins_lfq(self.target_codebook_size)
+ elif self.codebook_type == "custom":
+ return self._get_bins_custom(self.target_codebook_size)
+ else:
+ raise ValueError(f"Codebook type {self.codebook_type} not supported.")
+
+ @property
+ def place_values(self) -> jnp.ndarray:
+ place_values = [1]
+ for b in self.bins_per_dim[:-1]:
+ place_values.append(place_values[-1] * b)
+ return jnp.array(place_values)
+
+ @staticmethod
+ def _get_bins_fsq(target_codebook_size: int) -> tuple[int]:
+ """
+ Get bins per dimension based on codebook size, from the original FSQ paper.
+ """
+ if target_codebook_size == 2**8:
+ return (8, 6, 5)
+ elif target_codebook_size == 2**10: # noqa: RET505
+ return (8, 5, 5, 5)
+ elif target_codebook_size == 2**12:
+ return (7, 5, 5, 5, 5)
+ elif target_codebook_size == 2**14:
+ return (8, 8, 8, 6, 5)
+ elif target_codebook_size == 2**16:
+ return (8, 8, 8, 5, 5, 5)
+ else:
+ raise ValueError(f"Codebook size {target_codebook_size} not supported.")
+
+ @staticmethod
+ def _get_bins_custom(target_codebook_size: int) -> tuple[int]:
+ if target_codebook_size == 2**8:
+ return (16, 16)
+ elif target_codebook_size == 2**10: # noqa: RET505
+ return (32, 32)
+ elif target_codebook_size == 2**12:
+ return (64, 64)
+ elif target_codebook_size == 2**14:
+ return (128, 128)
+ elif target_codebook_size == 2**16:
+ return (256, 256)
+ return None
+
+ @staticmethod
+ def _get_bins_lfq(target_codebook_size: int) -> tuple[int]:
+ """
+ Get bins per dimension according to the Lookup-Free Quantization paper (2 bins per dimension)
+ """
+ assert target_codebook_size & (target_codebook_size - 1) == 0, "Codebook size should be a power of two for LFQ"
+
+ return (2,) * int(math.log2(target_codebook_size))
+
+ def setup(self):
+ self.proj_down = nn.Dense(len(self.bins_per_dim))
+ self.proj_up = nn.Dense(self.input_dim)
+
+ def __call__(self, inputs: jnp.ndarray) -> tuple[jnp.ndarray, jnp.ndarray]:
+ tokens, z = self.encode(inputs)
+ output = self.decode(tokens, z_grad=z)
+ return tokens, output
+
+ def encode(self, inputs: jnp.ndarray) -> tuple[jnp.ndarray, jnp.ndarray]:
+ bases = jnp.array(self.bins_per_dim)
+
+ x = self.proj_down(inputs)
+ z = jnp.tanh(x)
+
+ # Quantize
+ digits = jnp.round((z + 1) * (bases - 1) / 2).astype(jnp.int32)
+ tokens = self.undigitize(digits)
+
+ return tokens, z
+
+ def decode(self, tokens: jnp.ndarray, z_grad: jax.Array | None = None) -> jnp.ndarray:
+ bases = jnp.array(self.bins_per_dim)
+ digits = self.digitize(tokens)
+
+ z_q = digits / (bases - 1) * 2 - 1
+
+ if z_grad is not None:
+ chex.assert_equal_shape([z_q, z_grad])
+ z_q = jax.lax.stop_gradient(z_q - z_grad) + z_grad
+
+ return self.proj_up(z_q)
+
+ def undigitize(self, digits: jnp.ndarray) -> jnp.ndarray:
+ return jnp.sum(digits * jnp.array(self.place_values), axis=-1)
+
+ def digitize(self, tokens: jnp.ndarray) -> jnp.ndarray:
+ return (tokens[..., None] // jnp.array(self.place_values)) % jnp.array(self.bins_per_dim)
+
+ @property
+ def vocab_size(self) -> int:
+ return math.prod(self.bins_per_dim)
+
+
+class ResNetDownBlock(nn.Module):
+ stride: int = 1
+ n_filters: int = 64
+ dropout_rate: float = 0.0
+ group_size: int = 32
+
+ @nn.compact
+ def __call__(self, x: jnp.ndarray, *, train: bool = True) -> jnp.ndarray:
+ skip = x
+
+ if self.stride > 1 or x.shape[-1] != self.n_filters:
+ skip = nn.Conv(self.n_filters, (self.stride,), (self.stride,), "SAME")(skip)
+
+ x = nn.Conv(self.n_filters, (3,), (self.stride,), "SAME")(x)
+ x = nn.GroupNorm(num_groups=self.n_filters // self.group_size)(x)
+ x = nn.Dropout(self.dropout_rate)(x, deterministic=not train)
+ x = nn.relu(x)
+ x = nn.Conv(self.n_filters, (3,), (1,), "SAME")(x)
+
+ return skip + x
+
+
+class ResNetUpBlock(nn.Module):
+ stride: int = 1
+ n_filters: int = 64
+ dropout_rate: float = 0.0
+ group_size: int = 32
+
+ @nn.compact
+ def __call__(self, x: jnp.ndarray, *, train: bool = True) -> jnp.ndarray:
+ skip = x
+
+ if self.stride > 1:
+ skip = nn.ConvTranspose(self.n_filters, (self.stride,), (self.stride,), "SAME")(skip)
+
+ x = nn.ConvTranspose(self.n_filters, (3,), (self.stride,), "SAME")(x)
+ x = nn.GroupNorm(num_groups=self.n_filters // self.group_size)(x)
+ x = nn.Dropout(self.dropout_rate)(x, deterministic=not train)
+ x = nn.relu(x)
+ x = nn.ConvTranspose(self.n_filters, (3,), (1,), "SAME")(x)
+
+ return skip + x
+
+
+@dataclass
+class LfqCodebookOutput:
+ tokens: jnp.ndarray
+ z: jnp.ndarray
+ z_q: jnp.ndarray
+ token_log_probs: jnp.ndarray
+ commit_loss: jnp.ndarray
+
+
+class LookupFreeQuantization(nn.Module):
+ num_dims: int
+ latent_dim: int
+
+ def setup(self):
+ self.codebook = jnp.array([-1, 1])
+ self.activation = nn.tanh
+
+ self.project_down = nn.Dense(self.num_dims)
+ self.project_up = nn.Dense(self.latent_dim)
+
+ def encode(self, z: jnp.ndarray) -> jnp.ndarray:
+ z = self.project_down(z)
+ token_squared_distances = jnp.square(z[..., None] - self.codebook)
+ token_bits = jnp.argmin(token_squared_distances, axis=-1)
+ return jnp.sum(token_bits * (2 ** jnp.arange(self.num_dims)), axis=-1)
+
+ def decode(self, tokens: jnp.ndarray) -> jnp.ndarray:
+ token_bits = (tokens[..., None] & (2 ** jnp.arange(self.num_dims))).astype(jnp.int32)
+ return self.project_up(self.codebook[token_bits])
+
+ def loss(self, x: jnp.ndarray) -> LfqCodebookOutput:
+ z = self.project_down(x)
+ z = self.activation(z)
+
+ token_squared_distances = jnp.square(z[..., None] - self.codebook)
+ tokens = jnp.argmin(token_squared_distances, axis=-1)
+
+ token_bit_log_probs = -token_squared_distances
+ # Compute token log probs for tokens 0..2^num_dims-1 by summing corresponding log-probs
+ token_bit_expansions = jnp.bitwise_and(
+ jnp.arange(2**self.num_dims)[None, :], 2 ** jnp.arange(self.num_dims)[:, None]
+ ).astype(jnp.int32)
+ token_log_probs = (
+ token_bit_log_probs[..., 0] @ (1 - token_bit_expansions)
+ + token_bit_log_probs[..., 1] @ token_bit_expansions
+ ) # (batch_size, num_tokens, 2 ** num_dims)
+ token_log_probs = jax.lax.stop_gradient(jax.nn.log_softmax(token_log_probs, axis=-1))
+ chex.assert_shape(token_log_probs, (*x.shape[:-1], 2**self.num_dims))
+
+ z_q = self.codebook[tokens]
+ commit_loss = jnp.square(z - z_q).mean()
+ z_q = jax.lax.stop_gradient(z_q - z) + z
+
+ z_q = self.project_up(z_q)
+ z = self.project_up(z)
+
+ tokens = jnp.sum(tokens * (len(self.codebook) ** jnp.arange(self.num_dims)), axis=-1)
+ return LfqCodebookOutput(
+ tokens=tokens,
+ z=z,
+ z_q=z_q,
+ token_log_probs=jnp.zeros(()),
+ commit_loss=commit_loss,
+ )
+
+
+def make_block_causal_attention_matrix(q: jnp.ndarray, k: jnp.ndarray, bs_q: int, bs_k: int) -> jnp.ndarray:
+ return nn.make_attention_mask(q, k, pairwise_fn=lambda x, y: jnp.greater_equal(x // bs_k, y // bs_q))
+
+
+class GeGLU(Module):
+ """Gated Linear Unit with GELU (GeGLU) activation function.
+ GeGLU is a Flax layer that combines a linear transformation with a GELU
+ activation function in a gating mechanism. It is often used in Transformer models
+ to provide non-linear capabilities while preserving a strong linear component.
+
+ Attributes:
+ features: the number of output features (default: None).
+ """
+
+ output_dim: int = -1
+
+ @compact
+ def __call__(self, inputs: Array) -> Array:
+ """Applies the GeGLU activation to the inputs.
+ Args:
+ inputs: the nd-array to apply the GeGLU activation function to.
+ Returns:
+ The transformed input.
+ """
+ output_dim = inputs.shape[-1] if self.output_dim == -1 else self.output_dim
+
+ x = nn.Dense(output_dim * 2)(inputs)
+ x, gate = x[..., :output_dim], x[..., output_dim:]
+ return x * nn.gelu(gate)
+
+
+class CrossAttentionLayer(nn.Module):
+ dropout_rate: float = 0.0
+ num_heads: int = None
+ causal: bool = False
+ mlp_ratio: float = 4.0
+
+ @nn.compact
+ def __call__(
+ self,
+ x: jnp.ndarray,
+ y: jnp.ndarray,
+ *,
+ mask_self: jnp.ndarray | None = None,
+ mask_cross: jnp.ndarray | None = None,
+ train: bool = True,
+ ) -> jnp.ndarray:
+ d_embed = x.shape[-1]
+ seq_len_q = x.shape[-2]
+ seq_len_k = y.shape[-2]
+
+ if self.causal:
+ # One block size will be 1
+ bs_q = max(seq_len_q // seq_len_k, 1)
+ bs_k = max(seq_len_k // seq_len_q, 1)
+
+ mask_self = nn.make_causal_mask(x[..., 0])
+ mask_cross = make_block_causal_attention_matrix(x[..., 0], y[..., 0], bs_q, bs_k)
+
+ # Self-attention block
+ skip = x
+ x = nn.LayerNorm()(x)
+ x = nn.MultiHeadDotProductAttention(
+ num_heads=self.num_heads or d_embed // 64,
+ dropout_rate=self.dropout_rate,
+ deterministic=not train,
+ )(x, x, x, mask=mask_self)
+ x = skip + x
+
+ # Cross-attention block
+ skip = x
+ x = nn.LayerNorm()(x)
+ x = nn.MultiHeadDotProductAttention(
+ num_heads=self.num_heads or d_embed // 64,
+ dropout_rate=self.dropout_rate,
+ deterministic=not train,
+ )(x, y, y, mask=mask_cross)
+ x = skip + x
+
+ # MLP block
+ skip = x
+ x = nn.LayerNorm()(x)
+ x = nn.Dense(int(d_embed * self.mlp_ratio))(x)
+ x = nn.Dropout(self.dropout_rate)(x, deterministic=not train)
+ x = GeGLU()(x)
+ x = nn.Dense(d_embed)(x)
+ return skip + x
+
+
+def sinusoidal_pe_init(_, shape: tuple[int, int]) -> jnp.ndarray:
+ seq_len, d_embed = shape
+
+ position = jnp.arange(0, seq_len, 1)
+ div_term = jnp.exp(jnp.arange(0, d_embed, 2) * -(jnp.log(10000.0) / d_embed))
+ return jnp.concatenate(
+ [
+ jnp.sin(position[:, jnp.newaxis] * div_term),
+ jnp.cos(position[:, jnp.newaxis] * div_term),
+ ],
+ axis=-1,
+ )
+
+
+class TokenizerEncoderDecoder(nn.Module):
+ num_tokens: int
+ num_cross_tokens: int
+ num_layers: int
+ causal: bool
+
+ mlp_ratio: float = 4.0
+ use_state_conditioning: bool = False
+
+ @nn.compact
+ def __call__(
+ self,
+ y: jnp.ndarray,
+ *,
+ train: bool = True,
+ state_conditioning: jnp.ndarray | None = None,
+ mask: jnp.ndarray | None = None,
+ ) -> jnp.ndarray:
+ x = self.param("q_embed", sinusoidal_pe_init, (self.num_tokens, y.shape[-1]))
+ x = jax.numpy.broadcast_to(x, y.shape[:-2] + x.shape[-2:])
+
+ if mask is not None:
+ # mask is (batch_dims..., num_cross_tokens)
+ chex.assert_equal_shape([y[..., 0], mask])
+ attn_mask = einops.repeat(mask, "... kv -> ... 1 q kv", q=self.num_tokens)
+ else:
+ attn_mask = jnp.ones((*y.shape[:-2], 1, self.num_tokens, self.num_cross_tokens))
+
+ if self.use_state_conditioning:
+ assert state_conditioning is not None, "State conditioning is required for this model."
+ state_embed = nn.Dense(y.shape[-1], name="state_proj")(state_conditioning)[..., None, :]
+ y = jnp.concatenate([y, state_embed], axis=-2)
+ attn_mask = jnp.concatenate([attn_mask, jnp.ones_like(attn_mask[..., 0:1])], axis=-1)
+
+ y = y + self.param("y_pos_enc", sinusoidal_pe_init, y.shape[-2:])
+
+ for _ in range(self.num_layers):
+ x = CrossAttentionLayer(causal=self.causal, mlp_ratio=self.mlp_ratio)(
+ x, y, train=train, mask_self=None, mask_cross=attn_mask
+ )
+
+ return x
+
+
+class FsqAttentionTokenizer(nn.Module):
+ embed_dim: int
+ data_dim: int
+ data_horizon: int
+ num_tokens: int
+ num_layers: int
+ target_codebook_size: int
+ causal: bool = False
+ mlp_ratio: float = 2.0
+
+ bound: float | None = None
+
+ use_state_conditioning: bool = False
+
+ @property
+ def vocab_size(self) -> int:
+ return math.prod(FsqCodebook._get_bins_fsq(self.target_codebook_size)) # noqa: SLF001
+
+ def setup(self):
+ self.proj = nn.Dense(self.embed_dim)
+ self.encoder = TokenizerEncoderDecoder(
+ num_tokens=self.num_tokens,
+ num_cross_tokens=self.data_horizon,
+ num_layers=self.num_layers,
+ causal=self.causal,
+ use_state_conditioning=self.use_state_conditioning,
+ mlp_ratio=self.mlp_ratio,
+ )
+ self.codebook = FsqCodebook(
+ input_dim=self.embed_dim,
+ target_codebook_size=self.target_codebook_size,
+ codebook_type="custom",
+ )
+ self.decoder = TokenizerEncoderDecoder(
+ num_tokens=self.data_horizon,
+ num_cross_tokens=self.num_tokens,
+ num_layers=self.num_layers,
+ causal=self.causal,
+ use_state_conditioning=self.use_state_conditioning,
+ mlp_ratio=self.mlp_ratio,
+ )
+
+ self.proj_mean = nn.Dense(self.data_dim)
+ self.out_scale = self.param("out_scale", lambda _: jnp.full((), 1.0))
+
+ def tokenize(
+ self, action: jnp.ndarray, *, obs: jnp.ndarray | None = None, train: bool = False
+ ) -> tuple[jnp.ndarray, jnp.ndarray]:
+ if self.bound is not None:
+ action = jnp.clip(action, -self.bound, self.bound)
+
+ x = self.proj(action)
+ x = self.encoder(x, train=train, state_conditioning=obs)
+
+ return self.codebook.encode(x)
+
+ def detokenize(self, tokens: jnp.ndarray, *, obs: jnp.ndarray | None = None) -> jnp.ndarray:
+ x = self.decoder(self.codebook.decode(tokens), state_conditioning=obs)
+ mean = self.proj_mean(x)
+ return mean * self.out_scale
+
+ def loss(
+ self, action: jnp.ndarray, *, obs: jnp.ndarray | None = None, train: bool = True
+ ) -> tuple[jnp.ndarray, dict[str, jnp.ndarray]]:
+ # Encode
+ x = self.proj(action)
+ z = self.encoder(x, train=train, state_conditioning=obs)
+
+ # Quantize
+ tokens, z = self.codebook(z)
+
+ # Decode
+ x = self.decoder(z, train=train, state_conditioning=obs)
+ mean = self.proj_mean(x) * self.out_scale
+
+ mse = jnp.mean(jnp.square(action - mean))
+ mae = jnp.mean(jnp.abs(action - mean))
+
+ return mse, {
+ "mse": mse,
+ "mae": mae,
+ }
+
+ def __call__(self, *args: Any, **kwargs: Any) -> tuple[jnp.ndarray, dict[str, jnp.ndarray]]:
+ """
+ Dummy for .init
+ """
+ return self.loss(*args, **kwargs)
diff --git a/openpi-umi/src/openpi/models/vit.py b/openpi-umi/src/openpi/models/vit.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7901d097b86d36e3564d2b664ed50af8a194080
--- /dev/null
+++ b/openpi-umi/src/openpi/models/vit.py
@@ -0,0 +1,307 @@
+# Copyright 2024 Google LLC.
+#
+# 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.
+"""ViT implementation adapted from https://github.com/google-research/vision_transformer/blob/main/vit_jax/models_vit.py."""
+
+from collections.abc import Callable
+from typing import Any
+
+import flax.linen as nn
+import jax
+import jax.numpy as jnp
+
+from openpi.models import resnet as models_resnet
+
+Array = Any
+PRNGKey = Any
+Shape = tuple[int]
+Dtype = Any
+
+
+class IdentityLayer(nn.Module):
+ """Identity layer, convenient for giving a name to an array."""
+
+ @nn.compact
+ def __call__(self, x):
+ return x
+
+
+class AddPositionEmbs(nn.Module):
+ """Adds learned positional embeddings to the inputs.
+
+ Attributes:
+ posemb_init: positional embedding initializer.
+ """
+
+ posemb_init: Callable[[PRNGKey, Shape, Dtype], Array]
+ param_dtype: Dtype = jnp.float32
+
+ @nn.compact
+ def __call__(self, inputs):
+ """Applies the AddPositionEmbs module.
+
+ Args:
+ inputs: Inputs to the layer.
+
+ Returns:
+ Output tensor with shape `(bs, timesteps, in_dim)`.
+ """
+ # inputs.shape is (batch_size, seq_len, emb_dim).
+ assert inputs.ndim == 3, f"Number of dimensions should be 3, but it is: {inputs.ndim}"
+ pos_emb_shape = (1, inputs.shape[1], inputs.shape[2])
+ pe = self.param("pos_embedding", self.posemb_init, pos_emb_shape, self.param_dtype)
+ return inputs + pe
+
+
+class MlpBlock(nn.Module):
+ """Transformer MLP / feed-forward block."""
+
+ mlp_dim: int
+ dtype: Dtype = jnp.float32
+ param_dtype: Dtype = jnp.float32
+ out_dim: int | None = None
+ dropout_rate: float = 0.1
+ kernel_init: Callable[[PRNGKey, Shape, Dtype], Array] = nn.initializers.xavier_uniform()
+ bias_init: Callable[[PRNGKey, Shape, Dtype], Array] = nn.initializers.normal(stddev=1e-6)
+
+ @nn.compact
+ def __call__(self, inputs, *, deterministic):
+ """Applies Transformer MlpBlock module."""
+ actual_out_dim = inputs.shape[-1] if self.out_dim is None else self.out_dim
+ x = nn.Dense(
+ features=self.mlp_dim,
+ dtype=self.dtype,
+ param_dtype=self.param_dtype,
+ kernel_init=self.kernel_init,
+ bias_init=self.bias_init,
+ )( # pytype: disable=wrong-arg-types
+ inputs
+ )
+ x = nn.gelu(x)
+ x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=deterministic)
+ output = nn.Dense(
+ features=actual_out_dim,
+ dtype=self.dtype,
+ param_dtype=self.param_dtype,
+ kernel_init=self.kernel_init,
+ bias_init=self.bias_init,
+ )( # pytype: disable=wrong-arg-types
+ x
+ )
+ return nn.Dropout(rate=self.dropout_rate)(output, deterministic=deterministic)
+
+
+class Encoder1DBlock(nn.Module):
+ """Transformer encoder layer.
+
+ Attributes:
+ inputs: input data.
+ mlp_dim: dimension of the mlp on top of attention block.
+ dtype: the dtype of the computation (default: float32).
+ dropout_rate: dropout rate.
+ attention_dropout_rate: dropout for attention heads.
+ deterministic: bool, deterministic or not (to apply dropout).
+ num_heads: Number of heads in nn.MultiHeadDotProductAttention
+ """
+
+ mlp_dim: int
+ num_heads: int
+ dtype: Dtype = jnp.float32
+ dropout_rate: float = 0.1
+ attention_dropout_rate: float = 0.1
+
+ @nn.compact
+ def __call__(self, inputs, deterministic):
+ """Applies Encoder1DBlock module.
+
+ Args:
+ inputs: Inputs to the layer.
+ deterministic: Dropout will not be applied when set to true.
+
+ Returns:
+ output after transformer encoder block.
+ """
+
+ # Attention block.
+ assert inputs.ndim == 3, f"Expected (batch, seq, hidden) got {inputs.shape}"
+ x = nn.LayerNorm(dtype=self.dtype)(inputs)
+ x = nn.MultiHeadDotProductAttention(
+ dtype=self.dtype,
+ kernel_init=nn.initializers.xavier_uniform(),
+ broadcast_dropout=False,
+ deterministic=deterministic,
+ dropout_rate=self.attention_dropout_rate,
+ num_heads=self.num_heads,
+ # why isn't this true by default???
+ force_fp32_for_softmax=True,
+ )(x, x)
+ x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=deterministic)
+ x = x + inputs
+
+ # MLP block.
+ y = nn.LayerNorm(dtype=self.dtype)(x)
+ y = MlpBlock(mlp_dim=self.mlp_dim, dtype=self.dtype, dropout_rate=self.dropout_rate)(
+ y, deterministic=deterministic
+ )
+
+ return x + y, None
+
+
+class Encoder(nn.Module):
+ """Transformer Model Encoder for sequence to sequence translation.
+
+ Attributes:
+ num_layers: number of layers
+ mlp_dim: dimension of the mlp on top of attention block
+ num_heads: Number of heads in nn.MultiHeadDotProductAttention
+ dropout_rate: dropout rate.
+ attention_dropout_rate: dropout rate in self attention.
+ """
+
+ dtype: jax.typing.DTypeLike
+ num_layers: int
+ mlp_dim: int
+ num_heads: int
+ dropout_rate: float = 0.1
+ attention_dropout_rate: float = 0.1
+ add_position_embedding: bool = True
+
+ @nn.compact
+ def __call__(self, x, *, train):
+ """Applies Transformer model on the inputs.
+
+ Args:
+ x: Inputs to the layer.
+ train: Set to `True` when training.
+
+ Returns:
+ output of a transformer encoder.
+ """
+ assert x.ndim == 3 # (batch, len, emb)
+
+ if self.add_position_embedding:
+ x = AddPositionEmbs(
+ posemb_init=nn.initializers.normal(stddev=0.02), # from BERT.
+ name="posembed_input",
+ )(x)
+ x = nn.Dropout(rate=self.dropout_rate)(x, deterministic=not train)
+
+ x = x.astype(self.dtype)
+ # Input Encoder
+ block = nn.remat(Encoder1DBlock, prevent_cse=False, static_argnums=(2,))
+ x, _ = nn.scan(
+ block,
+ variable_axes={"params": 0},
+ split_rngs={"params": True, "dropout": True},
+ in_axes=nn.broadcast,
+ length=self.num_layers,
+ )(
+ name="encoderblock",
+ mlp_dim=self.mlp_dim,
+ dropout_rate=self.dropout_rate,
+ attention_dropout_rate=self.attention_dropout_rate,
+ dtype=self.dtype,
+ num_heads=self.num_heads,
+ )(x, not train)
+ return nn.LayerNorm(name="encoder_norm", dtype=self.dtype)(x)
+
+
+class VisionTransformer(nn.Module):
+ """VisionTransformer."""
+
+ dtype: jax.typing.DTypeLike
+ num_classes: int
+ patches: Any
+ transformer: Any
+ hidden_size: int
+ resnet: Any | None = None
+ representation_size: int | None = None
+ classifier: str = "token"
+ head_bias_init: float = 0.0
+ encoder: type[nn.Module] = Encoder
+ model_name: str | None = None
+
+ @nn.compact
+ def __call__(self, inputs, *, train):
+ x = inputs
+ # (Possibly partial) ResNet root.
+ if self.resnet is not None:
+ width = int(64 * self.resnet.width_factor)
+
+ # Root block.
+ x = models_resnet.StdConv(
+ features=width, kernel_size=(7, 7), strides=(2, 2), use_bias=False, name="conv_root"
+ )(x)
+ x = nn.GroupNorm(name="gn_root")(x)
+ x = nn.relu(x)
+ x = nn.max_pool(x, window_shape=(3, 3), strides=(2, 2), padding="SAME")
+
+ # ResNet stages.
+ if self.resnet.num_layers:
+ x = models_resnet.ResNetStage(
+ block_size=self.resnet.num_layers[0], nout=width, first_stride=(1, 1), name="block1"
+ )(x)
+ for i, block_size in enumerate(self.resnet.num_layers[1:], 1):
+ x = models_resnet.ResNetStage(
+ block_size=block_size, nout=width * 2**i, first_stride=(2, 2), name=f"block{i + 1}"
+ )(x)
+
+ n, h, w, c = x.shape
+
+ # We can merge s2d+emb into a single conv; it's the same.
+ x = nn.Conv(
+ features=self.hidden_size,
+ kernel_size=self.patches.size,
+ strides=self.patches.size,
+ padding="VALID",
+ name="embedding",
+ )(x)
+
+ # Here, x is a grid of embeddings.
+
+ # (Possibly partial) Transformer.
+ if self.transformer is not None:
+ n, h, w, c = x.shape
+ x = jnp.reshape(x, [n, h * w, c])
+
+ # If we want to add a class token, add it here.
+ if self.classifier in ["token", "token_unpooled"]:
+ cls = self.param("cls", nn.initializers.zeros, (1, 1, c))
+ cls = jnp.tile(cls, [n, 1, 1])
+ x = jnp.concatenate([cls, x], axis=1)
+
+ x = self.encoder(name="Transformer", **self.transformer, dtype=self.dtype)(x, train=train)
+
+ if self.classifier == "token":
+ x = x[:, 0]
+ elif self.classifier == "gap":
+ x = jnp.mean(x, axis=list(range(1, x.ndim - 1))) # (1,) or (1,2)
+ elif self.classifier in ["unpooled", "token_unpooled"]:
+ pass
+ else:
+ raise ValueError(f"Invalid classifier={self.classifier}")
+
+ if self.representation_size is not None:
+ x = nn.Dense(features=self.representation_size, name="pre_logits")(x)
+ x = nn.tanh(x)
+ else:
+ x = IdentityLayer(name="pre_logits")(x)
+
+ if self.num_classes:
+ x = nn.Dense(
+ features=self.num_classes,
+ name="head",
+ kernel_init=nn.initializers.zeros,
+ bias_init=nn.initializers.constant(self.head_bias_init),
+ )(x)
+ return x
diff --git a/openpi-umi/src/openpi/models_pytorch/gemma_pytorch.py b/openpi-umi/src/openpi/models_pytorch/gemma_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..203b36be8ae4c525422c93aa50926c03ded7deb5
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/gemma_pytorch.py
@@ -0,0 +1,281 @@
+from typing import Literal
+
+import pytest
+import torch
+from torch import nn
+from transformers import GemmaForCausalLM
+from transformers import PaliGemmaForConditionalGeneration
+from transformers.models.auto import CONFIG_MAPPING
+from transformers.models.gemma import modeling_gemma
+
+
+class PaliGemmaWithExpertModel(nn.Module):
+ def __init__(
+ self,
+ vlm_config,
+ action_expert_config,
+ use_adarms=None,
+ precision: Literal["bfloat16", "float32"] = "bfloat16",
+ ):
+ if use_adarms is None:
+ use_adarms = [False, False]
+ super().__init__()
+
+ vlm_config_hf = CONFIG_MAPPING["paligemma"]()
+ vlm_config_hf._vocab_size = 257152 # noqa: SLF001
+ vlm_config_hf.image_token_index = 257152
+ vlm_config_hf.text_config.hidden_size = vlm_config.width
+ vlm_config_hf.text_config.intermediate_size = vlm_config.mlp_dim
+ vlm_config_hf.text_config.num_attention_heads = vlm_config.num_heads
+ vlm_config_hf.text_config.head_dim = vlm_config.head_dim
+ vlm_config_hf.text_config.num_hidden_layers = vlm_config.depth
+ vlm_config_hf.text_config.num_key_value_heads = vlm_config.num_kv_heads
+ vlm_config_hf.text_config.hidden_activation = "gelu_pytorch_tanh"
+ vlm_config_hf.text_config.torch_dtype = "float32"
+ vlm_config_hf.text_config.vocab_size = 257152
+ vlm_config_hf.text_config.use_adarms = use_adarms[0]
+ vlm_config_hf.text_config.adarms_cond_dim = vlm_config.width if use_adarms[0] else None
+ vlm_config_hf.vision_config.intermediate_size = 4304
+ vlm_config_hf.vision_config.projection_dim = 2048
+ vlm_config_hf.vision_config.projector_hidden_act = "gelu_fast"
+ vlm_config_hf.vision_config.torch_dtype = "float32"
+
+ action_expert_config_hf = CONFIG_MAPPING["gemma"](
+ head_dim=action_expert_config.head_dim,
+ hidden_size=action_expert_config.width,
+ intermediate_size=action_expert_config.mlp_dim,
+ num_attention_heads=action_expert_config.num_heads,
+ num_hidden_layers=action_expert_config.depth,
+ num_key_value_heads=action_expert_config.num_kv_heads,
+ vocab_size=257152,
+ hidden_activation="gelu_pytorch_tanh",
+ torch_dtype="float32",
+ use_adarms=use_adarms[1],
+ adarms_cond_dim=action_expert_config.width if use_adarms[1] else None,
+ )
+
+ self.paligemma = PaliGemmaForConditionalGeneration(config=vlm_config_hf)
+ self.gemma_expert = GemmaForCausalLM(config=action_expert_config_hf)
+ self.gemma_expert.model.embed_tokens = None
+
+ self.to_bfloat16_for_selected_params(precision)
+
+ def to_bfloat16_for_selected_params(self, precision: Literal["bfloat16", "float32"] = "bfloat16"):
+ if precision == "bfloat16":
+ self.to(dtype=torch.bfloat16)
+ elif precision == "float32":
+ self.to(dtype=torch.float32)
+ return
+ else:
+ raise ValueError(f"Invalid precision: {precision}")
+
+ params_to_keep_float32 = [
+ "vision_tower.vision_model.embeddings.patch_embedding.weight",
+ "vision_tower.vision_model.embeddings.patch_embedding.bias",
+ "vision_tower.vision_model.embeddings.position_embedding.weight",
+ "input_layernorm",
+ "post_attention_layernorm",
+ "model.norm",
+ ]
+
+ for name, param in self.named_parameters():
+ if any(selector in name for selector in params_to_keep_float32):
+ param.data = param.data.to(dtype=torch.float32)
+
+ def embed_image(self, image: torch.Tensor):
+ return self.paligemma.model.get_image_features(image)
+
+ def embed_language_tokens(self, tokens: torch.Tensor):
+ return self.paligemma.language_model.embed_tokens(tokens)
+
+ def forward(
+ self,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ past_key_values: list[torch.FloatTensor] | pytest.Cache | None = None,
+ inputs_embeds: list[torch.FloatTensor] | None = None,
+ use_cache: bool | None = None,
+ adarms_cond: list[torch.Tensor] | None = None,
+ ):
+ if adarms_cond is None:
+ adarms_cond = [None, None]
+ if inputs_embeds[1] is None:
+ prefix_output = self.paligemma.language_model.forward(
+ inputs_embeds=inputs_embeds[0],
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ adarms_cond=adarms_cond[0] if adarms_cond is not None else None,
+ )
+ prefix_past_key_values = prefix_output.past_key_values
+ prefix_output = prefix_output.last_hidden_state
+ suffix_output = None
+ elif inputs_embeds[0] is None:
+ suffix_output = self.gemma_expert.model.forward(
+ inputs_embeds=inputs_embeds[1],
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ adarms_cond=adarms_cond[1] if adarms_cond is not None else None,
+ )
+ suffix_output = suffix_output.last_hidden_state
+ prefix_output = None
+ prefix_past_key_values = None
+ else:
+ models = [self.paligemma.language_model, self.gemma_expert.model]
+ num_layers = self.paligemma.config.text_config.num_hidden_layers
+
+ # Check if gradient checkpointing is enabled for any of the models
+ use_gradient_checkpointing = (
+ hasattr(self.gemma_expert.model, "gradient_checkpointing")
+ and self.gemma_expert.model.gradient_checkpointing
+ and self.training
+ ) or (hasattr(self, "gradient_checkpointing") and self.gradient_checkpointing and self.training)
+
+ # Force enable gradient checkpointing if we're in training mode and the model supports it
+ if self.training and hasattr(self.gemma_expert.model, "gradient_checkpointing"):
+ if not self.gemma_expert.model.gradient_checkpointing:
+ print("Forcing gradient checkpointing to be enabled for Gemma expert model")
+ self.gemma_expert.model.gradient_checkpointing = True
+ use_gradient_checkpointing = True
+
+ # Debug gradient checkpointing status
+ if hasattr(self, "_debug_gc_printed") and not self._debug_gc_printed:
+ print(f"Gemma expert model gradient checkpointing: {use_gradient_checkpointing}")
+ print(f"Model training mode: {self.training}")
+ print(
+ f"Gemma expert model has gradient_checkpointing attr: {hasattr(self.gemma_expert.model, 'gradient_checkpointing')}"
+ )
+ if hasattr(self.gemma_expert.model, "gradient_checkpointing"):
+ print(
+ f"Gemma expert model gradient_checkpointing value: {self.gemma_expert.model.gradient_checkpointing}"
+ )
+ self._debug_gc_printed = True
+
+ # Define the complete layer computation function for gradient checkpointing
+ def compute_layer_complete(layer_idx, inputs_embeds, attention_mask, position_ids, adarms_cond):
+ models = [self.paligemma.language_model, self.gemma_expert.model]
+
+ query_states = []
+ key_states = []
+ value_states = []
+ gates = []
+ for i, hidden_states in enumerate(inputs_embeds):
+ layer = models[i].layers[layer_idx]
+ hidden_states, gate = layer.input_layernorm(hidden_states, cond=adarms_cond[i]) # noqa: PLW2901
+ gates.append(gate)
+
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, layer.self_attn.head_dim)
+ query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_state = layer.self_attn.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ query_states.append(query_state)
+ key_states.append(key_state)
+ value_states.append(value_state)
+
+ # Concatenate and process attention
+ query_states = torch.cat(query_states, dim=2)
+ key_states = torch.cat(key_states, dim=2)
+ value_states = torch.cat(value_states, dim=2)
+
+ dummy_tensor = torch.zeros(
+ query_states.shape[0],
+ query_states.shape[2],
+ query_states.shape[-1],
+ device=query_states.device,
+ dtype=query_states.dtype,
+ )
+ cos, sin = self.paligemma.model.language_model.rotary_emb(dummy_tensor, position_ids)
+ query_states, key_states = modeling_gemma.apply_rotary_pos_emb(
+ query_states, key_states, cos, sin, unsqueeze_dim=1
+ )
+
+ batch_size = query_states.shape[0]
+ scaling = self.paligemma.language_model.layers[layer_idx].self_attn.scaling
+
+ # Attention computation
+ att_output, _ = modeling_gemma.eager_attention_forward(
+ self.paligemma.language_model.layers[layer_idx].self_attn,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ scaling,
+ )
+ # Get head_dim from the current layer, not from the model
+ head_dim = self.paligemma.language_model.layers[layer_idx].self_attn.head_dim
+ att_output = att_output.reshape(batch_size, -1, 1 * 8 * head_dim)
+
+ # Process layer outputs
+ outputs_embeds = []
+ start_pos = 0
+ for i, hidden_states in enumerate(inputs_embeds):
+ layer = models[i].layers[layer_idx]
+ end_pos = start_pos + hidden_states.shape[1]
+
+ if att_output.dtype != layer.self_attn.o_proj.weight.dtype:
+ att_output = att_output.to(layer.self_attn.o_proj.weight.dtype)
+ out_emb = layer.self_attn.o_proj(att_output[:, start_pos:end_pos])
+
+ # first residual
+ out_emb = modeling_gemma._gated_residual(hidden_states, out_emb, gates[i]) # noqa: SLF001
+ after_first_residual = out_emb.clone()
+ out_emb, gate = layer.post_attention_layernorm(out_emb, cond=adarms_cond[i])
+ # Convert to bfloat16 if the next layer (mlp) uses bfloat16
+ if layer.mlp.up_proj.weight.dtype == torch.bfloat16:
+ out_emb = out_emb.to(dtype=torch.bfloat16)
+
+ out_emb = layer.mlp(out_emb)
+ # second residual
+ out_emb = modeling_gemma._gated_residual(after_first_residual, out_emb, gate) # noqa: SLF001
+ outputs_embeds.append(out_emb)
+ start_pos = end_pos
+
+ return outputs_embeds
+
+ # Process all layers with gradient checkpointing if enabled
+ for layer_idx in range(num_layers):
+ if use_gradient_checkpointing:
+ inputs_embeds = torch.utils.checkpoint.checkpoint(
+ compute_layer_complete,
+ layer_idx,
+ inputs_embeds,
+ attention_mask,
+ position_ids,
+ adarms_cond,
+ use_reentrant=False,
+ preserve_rng_state=False,
+ )
+ else:
+ inputs_embeds = compute_layer_complete(
+ layer_idx, inputs_embeds, attention_mask, position_ids, adarms_cond
+ )
+
+ # Old code removed - now using compute_layer_complete function above
+
+ # final norm
+ # Define final norm computation function for gradient checkpointing
+ def compute_final_norms(inputs_embeds, adarms_cond):
+ outputs_embeds = []
+ for i, hidden_states in enumerate(inputs_embeds):
+ out_emb, _ = models[i].norm(hidden_states, cond=adarms_cond[i])
+ outputs_embeds.append(out_emb)
+ return outputs_embeds
+
+ # Apply gradient checkpointing to final norm if enabled
+ if use_gradient_checkpointing:
+ outputs_embeds = torch.utils.checkpoint.checkpoint(
+ compute_final_norms, inputs_embeds, adarms_cond, use_reentrant=False, preserve_rng_state=False
+ )
+ else:
+ outputs_embeds = compute_final_norms(inputs_embeds, adarms_cond)
+
+ prefix_output = outputs_embeds[0]
+ suffix_output = outputs_embeds[1]
+ prefix_past_key_values = None
+
+ return [prefix_output, suffix_output], prefix_past_key_values
diff --git a/openpi-umi/src/openpi/models_pytorch/pi0_pytorch.py b/openpi-umi/src/openpi/models_pytorch/pi0_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..25f0580ba818d55aadeab444a5293cac558f6804
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/pi0_pytorch.py
@@ -0,0 +1,461 @@
+import logging
+import math
+
+import torch
+from torch import Tensor
+from torch import nn
+import torch.nn.functional as F # noqa: N812
+
+import openpi.models.gemma as _gemma
+from openpi.models_pytorch.gemma_pytorch import PaliGemmaWithExpertModel
+import openpi.models_pytorch.preprocessing_pytorch as _preprocessing
+
+
+def get_safe_dtype(target_dtype, device_type):
+ """Get a safe dtype for the given device type."""
+ if device_type == "cpu":
+ # CPU doesn't support bfloat16, use float32 instead
+ if target_dtype == torch.bfloat16:
+ return torch.float32
+ if target_dtype == torch.float64:
+ return torch.float64
+ return target_dtype
+
+
+def create_sinusoidal_pos_embedding(
+ time: torch.tensor, dimension: int, min_period: float, max_period: float, device="cpu"
+) -> Tensor:
+ """Computes sine-cosine positional embedding vectors for scalar positions."""
+ if dimension % 2 != 0:
+ raise ValueError(f"dimension ({dimension}) must be divisible by 2")
+
+ if time.ndim != 1:
+ raise ValueError("The time tensor is expected to be of shape `(batch_size, )`.")
+
+ dtype = get_safe_dtype(torch.float64, device.type)
+ fraction = torch.linspace(0.0, 1.0, dimension // 2, dtype=dtype, device=device)
+ period = min_period * (max_period / min_period) ** fraction
+
+ # Compute the outer product
+ scaling_factor = 1.0 / period * 2 * math.pi
+ sin_input = scaling_factor[None, :] * time[:, None]
+ return torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1)
+
+
+def sample_beta(alpha, beta, bsize, device):
+ alpha_t = torch.as_tensor(alpha, dtype=torch.float32, device=device)
+ beta_t = torch.as_tensor(beta, dtype=torch.float32, device=device)
+ dist = torch.distributions.Beta(alpha_t, beta_t)
+ return dist.sample((bsize,))
+
+
+def make_att_2d_masks(pad_masks, att_masks):
+ """Copied from big_vision.
+
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
+ smaller or equal to theirs. This way `mask_ar` int[B, N] can be used to
+ setup several types of attention, for example:
+
+ [[1 1 1 1 1 1]]: pure causal attention.
+
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
+ themselves and the last 3 tokens have a causal attention. The first
+ entry could also be a 1 without changing behaviour.
+
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
+ block can attend all previous blocks and all tokens on the same block.
+
+ Args:
+ input_mask: bool[B, N] true if its part of the input, false if padding.
+ mask_ar: int32[B, N] mask that's 1 where previous tokens cannot depend on
+ it and 0 where it shares the same attention mask as the previous token.
+ """
+ if att_masks.ndim != 2:
+ raise ValueError(att_masks.ndim)
+ if pad_masks.ndim != 2:
+ raise ValueError(pad_masks.ndim)
+
+ cumsum = torch.cumsum(att_masks, dim=1)
+ att_2d_masks = cumsum[:, None, :] <= cumsum[:, :, None]
+ pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None]
+ return att_2d_masks & pad_2d_masks
+
+
+class PI0Pytorch(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.pi05 = config.pi05
+
+ paligemma_config = _gemma.get_config(config.paligemma_variant)
+ action_expert_config = _gemma.get_config(config.action_expert_variant)
+
+ self.paligemma_with_expert = PaliGemmaWithExpertModel(
+ paligemma_config,
+ action_expert_config,
+ use_adarms=[False, True] if self.pi05 else [False, False],
+ precision=config.dtype,
+ )
+
+ self.action_in_proj = nn.Linear(32, action_expert_config.width)
+ self.action_out_proj = nn.Linear(action_expert_config.width, 32)
+
+ if self.pi05:
+ self.time_mlp_in = nn.Linear(action_expert_config.width, action_expert_config.width)
+ self.time_mlp_out = nn.Linear(action_expert_config.width, action_expert_config.width)
+ else:
+ self.state_proj = nn.Linear(32, action_expert_config.width)
+ self.action_time_mlp_in = nn.Linear(2 * action_expert_config.width, action_expert_config.width)
+ self.action_time_mlp_out = nn.Linear(action_expert_config.width, action_expert_config.width)
+
+ torch.set_float32_matmul_precision("high")
+ self.sample_actions = torch.compile(self.sample_actions, mode="max-autotune")
+
+ # Initialize gradient checkpointing flag
+ self.gradient_checkpointing_enabled = False
+
+ msg = "transformers_replace is not installed correctly. Please install it with `uv pip install transformers==4.53.2` and `cp -r ./src/openpi/models_pytorch/transformers_replace/* .venv/lib/python3.11/site-packages/transformers/`."
+ try:
+ from transformers.models.siglip import check
+
+ if not check.check_whether_transformers_replace_is_installed_correctly():
+ raise ValueError(msg)
+ except ImportError:
+ raise ValueError(msg) from None
+
+ def gradient_checkpointing_enable(self):
+ """Enable gradient checkpointing for memory optimization."""
+ self.gradient_checkpointing_enabled = True
+ self.paligemma_with_expert.paligemma.language_model.gradient_checkpointing = True
+ self.paligemma_with_expert.paligemma.vision_tower.gradient_checkpointing = True
+ self.paligemma_with_expert.gemma_expert.model.gradient_checkpointing = True
+
+ logging.info("Enabled gradient checkpointing for PI0Pytorch model")
+
+ def gradient_checkpointing_disable(self):
+ """Disable gradient checkpointing."""
+ self.gradient_checkpointing_enabled = False
+ self.paligemma_with_expert.paligemma.language_model.gradient_checkpointing = False
+ self.paligemma_with_expert.paligemma.vision_tower.gradient_checkpointing = False
+ self.paligemma_with_expert.gemma_expert.model.gradient_checkpointing = False
+
+ logging.info("Disabled gradient checkpointing for PI0Pytorch model")
+
+ def is_gradient_checkpointing_enabled(self):
+ """Check if gradient checkpointing is enabled."""
+ return self.gradient_checkpointing_enabled
+
+ def _apply_checkpoint(self, func, *args, **kwargs):
+ """Helper method to apply gradient checkpointing if enabled."""
+ if self.gradient_checkpointing_enabled and self.training:
+ return torch.utils.checkpoint.checkpoint(
+ func, *args, use_reentrant=False, preserve_rng_state=False, **kwargs
+ )
+ return func(*args, **kwargs)
+
+ def _prepare_attention_masks_4d(self, att_2d_masks):
+ """Helper method to prepare 4D attention masks for transformer."""
+ att_2d_masks_4d = att_2d_masks[:, None, :, :]
+ return torch.where(att_2d_masks_4d, 0.0, -2.3819763e38)
+
+ def _preprocess_observation(self, observation, *, train=True):
+ """Helper method to preprocess observation."""
+ observation = _preprocessing.preprocess_observation_pytorch(observation, train=train)
+ return (
+ list(observation.images.values()),
+ list(observation.image_masks.values()),
+ observation.tokenized_prompt,
+ observation.tokenized_prompt_mask,
+ observation.state,
+ )
+
+ def sample_noise(self, shape, device):
+ return torch.normal(
+ mean=0.0,
+ std=1.0,
+ size=shape,
+ dtype=torch.float32,
+ device=device,
+ )
+
+ def sample_time(self, bsize, device):
+ time_beta = sample_beta(1.5, 1.0, bsize, device)
+ time = time_beta * 0.999 + 0.001
+ return time.to(dtype=torch.float32, device=device)
+
+ def embed_prefix(
+ self, images, img_masks, lang_tokens, lang_masks
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Embed images with SigLIP and language tokens with embedding layer to prepare
+ for PaliGemma transformer processing.
+ """
+ embs = []
+ pad_masks = []
+ att_masks = []
+
+ # Process images
+ for img, img_mask in zip(images, img_masks, strict=True):
+
+ def image_embed_func(img):
+ return self.paligemma_with_expert.embed_image(img)
+
+ img_emb = self._apply_checkpoint(image_embed_func, img)
+
+ bsize, num_img_embs = img_emb.shape[:2]
+
+ embs.append(img_emb)
+ pad_masks.append(img_mask[:, None].expand(bsize, num_img_embs))
+
+ # Create attention masks so that image tokens attend to each other
+ att_masks += [0] * num_img_embs
+
+ # Process language tokens
+ def lang_embed_func(lang_tokens):
+ lang_emb = self.paligemma_with_expert.embed_language_tokens(lang_tokens)
+ lang_emb_dim = lang_emb.shape[-1]
+ return lang_emb * math.sqrt(lang_emb_dim)
+
+ lang_emb = self._apply_checkpoint(lang_embed_func, lang_tokens)
+
+ embs.append(lang_emb)
+ pad_masks.append(lang_masks)
+
+ # full attention between image and language inputs
+ num_lang_embs = lang_emb.shape[1]
+ att_masks += [0] * num_lang_embs
+
+ embs = torch.cat(embs, dim=1)
+ pad_masks = torch.cat(pad_masks, dim=1)
+ att_masks = torch.tensor(att_masks, dtype=torch.bool, device=pad_masks.device)
+
+ # Get batch size from the first dimension of the concatenated tensors
+ bsize = pad_masks.shape[0]
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
+
+ return embs, pad_masks, att_masks
+
+ def embed_suffix(self, state, noisy_actions, timestep):
+ """Embed state, noisy_actions, timestep to prepare for Expert Gemma processing."""
+ embs = []
+ pad_masks = []
+ att_masks = []
+
+ if not self.pi05:
+ if self.state_proj.weight.dtype == torch.float32:
+ state = state.to(torch.float32)
+
+ # Embed state
+ def state_proj_func(state):
+ return self.state_proj(state)
+
+ state_emb = self._apply_checkpoint(state_proj_func, state)
+
+ embs.append(state_emb[:, None, :])
+ bsize = state_emb.shape[0]
+ device = state_emb.device
+
+ state_mask = torch.ones(bsize, 1, dtype=torch.bool, device=device)
+ pad_masks.append(state_mask)
+
+ # Set attention masks so that image and language inputs do not attend to state or actions
+ att_masks += [1]
+
+ # Embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1]
+ time_emb = create_sinusoidal_pos_embedding(
+ timestep, self.action_in_proj.out_features, min_period=4e-3, max_period=4.0, device=timestep.device
+ )
+ time_emb = time_emb.type(dtype=timestep.dtype)
+
+ # Fuse timestep + action information using an MLP
+ def action_proj_func(noisy_actions):
+ return self.action_in_proj(noisy_actions)
+
+ action_emb = self._apply_checkpoint(action_proj_func, noisy_actions)
+
+ if not self.pi05:
+ time_emb = time_emb[:, None, :].expand_as(action_emb)
+ action_time_emb = torch.cat([action_emb, time_emb], dim=2)
+
+ # Apply MLP layers
+ def mlp_func(action_time_emb):
+ x = self.action_time_mlp_in(action_time_emb)
+ x = F.silu(x) # swish == silu
+ return self.action_time_mlp_out(x)
+
+ action_time_emb = self._apply_checkpoint(mlp_func, action_time_emb)
+ adarms_cond = None
+ else:
+ # time MLP (for adaRMS)
+ def time_mlp_func(time_emb):
+ x = self.time_mlp_in(time_emb)
+ x = F.silu(x) # swish == silu
+ x = self.time_mlp_out(x)
+ return F.silu(x)
+
+ time_emb = self._apply_checkpoint(time_mlp_func, time_emb)
+ action_time_emb = action_emb
+ adarms_cond = time_emb
+
+ # Add to input tokens
+ embs.append(action_time_emb)
+
+ bsize, action_time_dim = action_time_emb.shape[:2]
+ action_time_mask = torch.ones(bsize, action_time_dim, dtype=torch.bool, device=timestep.device)
+ pad_masks.append(action_time_mask)
+
+ # Set attention masks so that image, language and state inputs do not attend to action tokens
+ att_masks += [1] + ([0] * (self.config.action_horizon - 1))
+
+ embs = torch.cat(embs, dim=1)
+ pad_masks = torch.cat(pad_masks, dim=1)
+ att_masks = torch.tensor(att_masks, dtype=embs.dtype, device=embs.device)
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
+
+ return embs, pad_masks, att_masks, adarms_cond
+
+ def forward(self, observation, actions, noise=None, time=None) -> Tensor:
+ """Do a full training forward pass and compute the loss (batch_size x num_steps x num_motors)"""
+ images, img_masks, lang_tokens, lang_masks, state = self._preprocess_observation(observation, train=True)
+
+ if noise is None:
+ noise = self.sample_noise(actions.shape, actions.device)
+
+ if time is None:
+ time = self.sample_time(actions.shape[0], actions.device)
+
+ time_expanded = time[:, None, None]
+ x_t = time_expanded * noise + (1 - time_expanded) * actions
+ u_t = noise - actions
+
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(images, img_masks, lang_tokens, lang_masks)
+ suffix_embs, suffix_pad_masks, suffix_att_masks, adarms_cond = self.embed_suffix(state, x_t, time)
+ if (
+ self.paligemma_with_expert.paligemma.language_model.layers[0].self_attn.q_proj.weight.dtype
+ == torch.bfloat16
+ ):
+ suffix_embs = suffix_embs.to(dtype=torch.bfloat16)
+ prefix_embs = prefix_embs.to(dtype=torch.bfloat16)
+
+ pad_masks = torch.cat([prefix_pad_masks, suffix_pad_masks], dim=1)
+ att_masks = torch.cat([prefix_att_masks, suffix_att_masks], dim=1)
+
+ att_2d_masks = make_att_2d_masks(pad_masks, att_masks)
+ position_ids = torch.cumsum(pad_masks, dim=1) - 1
+
+ # Prepare attention masks
+ att_2d_masks_4d = self._prepare_attention_masks_4d(att_2d_masks)
+
+ # Apply gradient checkpointing if enabled
+ def forward_func(prefix_embs, suffix_embs, att_2d_masks_4d, position_ids, adarms_cond):
+ (_, suffix_out), _ = self.paligemma_with_expert.forward(
+ attention_mask=att_2d_masks_4d,
+ position_ids=position_ids,
+ past_key_values=None,
+ inputs_embeds=[prefix_embs, suffix_embs],
+ use_cache=False,
+ adarms_cond=[None, adarms_cond],
+ )
+ return suffix_out
+
+ suffix_out = self._apply_checkpoint(
+ forward_func, prefix_embs, suffix_embs, att_2d_masks_4d, position_ids, adarms_cond
+ )
+
+ suffix_out = suffix_out[:, -self.config.action_horizon :]
+ suffix_out = suffix_out.to(dtype=torch.float32)
+
+ # Apply gradient checkpointing to final action projection if enabled
+ def action_out_proj_func(suffix_out):
+ return self.action_out_proj(suffix_out)
+
+ v_t = self._apply_checkpoint(action_out_proj_func, suffix_out)
+
+ return F.mse_loss(u_t, v_t, reduction="none")
+
+ @torch.no_grad()
+ def sample_actions(self, device, observation, noise=None, num_steps=10) -> Tensor:
+ """Do a full inference forward and compute the action (batch_size x num_steps x num_motors)"""
+ bsize = observation.state.shape[0]
+ if noise is None:
+ actions_shape = (bsize, self.config.action_horizon, self.config.action_dim)
+ noise = self.sample_noise(actions_shape, device)
+
+ images, img_masks, lang_tokens, lang_masks, state = self._preprocess_observation(observation, train=False)
+
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(images, img_masks, lang_tokens, lang_masks)
+ prefix_att_2d_masks = make_att_2d_masks(prefix_pad_masks, prefix_att_masks)
+ prefix_position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1
+
+ # Compute image and language key value cache
+ prefix_att_2d_masks_4d = self._prepare_attention_masks_4d(prefix_att_2d_masks)
+ self.paligemma_with_expert.paligemma.language_model.config._attn_implementation = "eager" # noqa: SLF001
+
+ _, past_key_values = self.paligemma_with_expert.forward(
+ attention_mask=prefix_att_2d_masks_4d,
+ position_ids=prefix_position_ids,
+ past_key_values=None,
+ inputs_embeds=[prefix_embs, None],
+ use_cache=True,
+ )
+
+ dt = -1.0 / num_steps
+ dt = torch.tensor(dt, dtype=torch.float32, device=device)
+
+ x_t = noise
+ time = torch.tensor(1.0, dtype=torch.float32, device=device)
+ while time >= -dt / 2:
+ expanded_time = time.expand(bsize)
+ v_t = self.denoise_step(
+ state,
+ prefix_pad_masks,
+ past_key_values,
+ x_t,
+ expanded_time,
+ )
+
+ # Euler step - use new tensor assignment instead of in-place operation
+ x_t = x_t + dt * v_t
+ time += dt
+ return x_t
+
+ def denoise_step(
+ self,
+ state,
+ prefix_pad_masks,
+ past_key_values,
+ x_t,
+ timestep,
+ ):
+ """Apply one denoising step of the noise `x_t` at a given timestep."""
+ suffix_embs, suffix_pad_masks, suffix_att_masks, adarms_cond = self.embed_suffix(state, x_t, timestep)
+
+ suffix_len = suffix_pad_masks.shape[1]
+ batch_size = prefix_pad_masks.shape[0]
+ prefix_len = prefix_pad_masks.shape[1]
+
+ prefix_pad_2d_masks = prefix_pad_masks[:, None, :].expand(batch_size, suffix_len, prefix_len)
+
+ suffix_att_2d_masks = make_att_2d_masks(suffix_pad_masks, suffix_att_masks)
+
+ full_att_2d_masks = torch.cat([prefix_pad_2d_masks, suffix_att_2d_masks], dim=2)
+
+ prefix_offsets = torch.sum(prefix_pad_masks, dim=-1)[:, None]
+ position_ids = prefix_offsets + torch.cumsum(suffix_pad_masks, dim=1) - 1
+
+ # Prepare attention masks
+ full_att_2d_masks_4d = self._prepare_attention_masks_4d(full_att_2d_masks)
+ self.paligemma_with_expert.gemma_expert.model.config._attn_implementation = "eager" # noqa: SLF001
+
+ outputs_embeds, _ = self.paligemma_with_expert.forward(
+ attention_mask=full_att_2d_masks_4d,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=[None, suffix_embs],
+ use_cache=False,
+ adarms_cond=[None, adarms_cond],
+ )
+
+ suffix_out = outputs_embeds[1]
+ suffix_out = suffix_out[:, -self.config.action_horizon :]
+ suffix_out = suffix_out.to(dtype=torch.float32)
+ return self.action_out_proj(suffix_out)
diff --git a/openpi-umi/src/openpi/models_pytorch/preprocessing_pytorch.py b/openpi-umi/src/openpi/models_pytorch/preprocessing_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..33c94a59b18a7e45732a02200f0daef5b0f93018
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/preprocessing_pytorch.py
@@ -0,0 +1,173 @@
+from collections.abc import Sequence
+import logging
+
+import torch
+
+from openpi.shared import image_tools
+
+logger = logging.getLogger("openpi")
+
+# Constants moved from model.py
+IMAGE_KEYS = (
+ "base_0_rgb",
+ "left_wrist_0_rgb",
+ "right_wrist_0_rgb",
+)
+
+IMAGE_RESOLUTION = (224, 224)
+
+
+def preprocess_observation_pytorch(
+ observation,
+ *,
+ train: bool = False,
+ image_keys: Sequence[str] = IMAGE_KEYS,
+ image_resolution: tuple[int, int] = IMAGE_RESOLUTION,
+):
+ """Torch.compile-compatible version of preprocess_observation_pytorch with simplified type annotations.
+
+ This function avoids complex type annotations that can cause torch.compile issues.
+ """
+ if not set(image_keys).issubset(observation.images):
+ raise ValueError(f"images dict missing keys: expected {image_keys}, got {list(observation.images)}")
+
+ batch_shape = observation.state.shape[:-1]
+
+ out_images = {}
+ for key in image_keys:
+ image = observation.images[key]
+
+ # TODO: This is a hack to handle both [B, C, H, W] and [B, H, W, C] formats
+ # Handle both [B, C, H, W] and [B, H, W, C] formats
+ is_channels_first = image.shape[1] == 3 # Check if channels are in dimension 1
+
+ if is_channels_first:
+ # Convert [B, C, H, W] to [B, H, W, C] for processing
+ image = image.permute(0, 2, 3, 1)
+
+ if image.shape[1:3] != image_resolution:
+ logger.info(f"Resizing image {key} from {image.shape[1:3]} to {image_resolution}")
+ image = image_tools.resize_with_pad_torch(image, *image_resolution)
+
+ if train:
+ # Convert from [-1, 1] to [0, 1] for PyTorch augmentations
+ image = image / 2.0 + 0.5
+
+ # Apply PyTorch-based augmentations
+ if "wrist" not in key:
+ # Geometric augmentations for non-wrist cameras
+ height, width = image.shape[1:3]
+
+ # Random crop and resize
+ crop_height = int(height * 0.95)
+ crop_width = int(width * 0.95)
+
+ # Random crop
+ max_h = height - crop_height
+ max_w = width - crop_width
+ if max_h > 0 and max_w > 0:
+ # Use tensor operations instead of .item() for torch.compile compatibility
+ start_h = torch.randint(0, max_h + 1, (1,), device=image.device)
+ start_w = torch.randint(0, max_w + 1, (1,), device=image.device)
+ image = image[:, start_h : start_h + crop_height, start_w : start_w + crop_width, :]
+
+ # Resize back to original size
+ image = torch.nn.functional.interpolate(
+ image.permute(0, 3, 1, 2), # [b, h, w, c] -> [b, c, h, w]
+ size=(height, width),
+ mode="bilinear",
+ align_corners=False,
+ ).permute(0, 2, 3, 1) # [b, c, h, w] -> [b, h, w, c]
+
+ # Random rotation (small angles)
+ # Use tensor operations instead of .item() for torch.compile compatibility
+ angle = torch.rand(1, device=image.device) * 10 - 5 # Random angle between -5 and 5 degrees
+ if torch.abs(angle) > 0.1: # Only rotate if angle is significant
+ # Convert to radians
+ angle_rad = angle * torch.pi / 180.0
+
+ # Create rotation matrix
+ cos_a = torch.cos(angle_rad)
+ sin_a = torch.sin(angle_rad)
+
+ # Apply rotation using grid_sample
+ grid_x = torch.linspace(-1, 1, width, device=image.device)
+ grid_y = torch.linspace(-1, 1, height, device=image.device)
+
+ # Create meshgrid
+ grid_y, grid_x = torch.meshgrid(grid_y, grid_x, indexing="ij")
+
+ # Expand to batch dimension
+ grid_x = grid_x.unsqueeze(0).expand(image.shape[0], -1, -1)
+ grid_y = grid_y.unsqueeze(0).expand(image.shape[0], -1, -1)
+
+ # Apply rotation transformation
+ grid_x_rot = grid_x * cos_a - grid_y * sin_a
+ grid_y_rot = grid_x * sin_a + grid_y * cos_a
+
+ # Stack and reshape for grid_sample
+ grid = torch.stack([grid_x_rot, grid_y_rot], dim=-1)
+
+ image = torch.nn.functional.grid_sample(
+ image.permute(0, 3, 1, 2), # [b, h, w, c] -> [b, c, h, w]
+ grid,
+ mode="bilinear",
+ padding_mode="zeros",
+ align_corners=False,
+ ).permute(0, 2, 3, 1) # [b, c, h, w] -> [b, h, w, c]
+
+ # Color augmentations for all cameras
+ # Random brightness
+ # Use tensor operations instead of .item() for torch.compile compatibility
+ brightness_factor = 0.7 + torch.rand(1, device=image.device) * 0.6 # Random factor between 0.7 and 1.3
+ image = image * brightness_factor
+
+ # Random contrast
+ # Use tensor operations instead of .item() for torch.compile compatibility
+ contrast_factor = 0.6 + torch.rand(1, device=image.device) * 0.8 # Random factor between 0.6 and 1.4
+ mean = image.mean(dim=[1, 2, 3], keepdim=True)
+ image = (image - mean) * contrast_factor + mean
+
+ # Random saturation (convert to HSV, modify S, convert back)
+ # For simplicity, we'll just apply a random scaling to the color channels
+ # Use tensor operations instead of .item() for torch.compile compatibility
+ saturation_factor = 0.5 + torch.rand(1, device=image.device) * 1.0 # Random factor between 0.5 and 1.5
+ gray = image.mean(dim=-1, keepdim=True)
+ image = gray + (image - gray) * saturation_factor
+
+ # Clamp values to [0, 1]
+ image = torch.clamp(image, 0, 1)
+
+ # Back to [-1, 1]
+ image = image * 2.0 - 1.0
+
+ # Convert back to [B, C, H, W] format if it was originally channels-first
+ if is_channels_first:
+ image = image.permute(0, 3, 1, 2) # [B, H, W, C] -> [B, C, H, W]
+
+ out_images[key] = image
+
+ # obtain mask
+ out_masks = {}
+ for key in out_images:
+ if key not in observation.image_masks:
+ # do not mask by default
+ out_masks[key] = torch.ones(batch_shape, dtype=torch.bool, device=observation.state.device)
+ else:
+ out_masks[key] = observation.image_masks[key]
+
+ # Create a simple object with the required attributes instead of using the complex Observation class
+ class SimpleProcessedObservation:
+ def __init__(self, **kwargs):
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ return SimpleProcessedObservation(
+ images=out_images,
+ image_masks=out_masks,
+ state=observation.state,
+ tokenized_prompt=observation.tokenized_prompt,
+ tokenized_prompt_mask=observation.tokenized_prompt_mask,
+ token_ar_mask=observation.token_ar_mask,
+ token_loss_mask=observation.token_loss_mask,
+ )
diff --git a/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..a42abe1341d4cf30574cc5f239369cb5e55bfdbb
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py
@@ -0,0 +1,173 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_gemma.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# coding=utf-8
+# Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# 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.
+from typing import Optional
+from ...configuration_utils import PretrainedConfig
+
+
+class GemmaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`GemmaModel`]. It is used to instantiate an Gemma
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the Gemma-7B.
+ e.g. [google/gemma-7b](https://huggingface.co/google/gemma-7b)
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+ Args:
+ vocab_size (`int`, *optional*, defaults to 256000):
+ Vocabulary size of the Gemma model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`GemmaModel`]
+ hidden_size (`int`, *optional*, defaults to 3072):
+ Dimension of the hidden representations.
+ intermediate_size (`int`, *optional*, defaults to 24576):
+ Dimension of the MLP representations.
+ num_hidden_layers (`int`, *optional*, defaults to 28):
+ Number of hidden layers in the Transformer decoder.
+ num_attention_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer decoder.
+ num_key_value_heads (`int`, *optional*, defaults to 16):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
+ `num_attention_heads`.
+ head_dim (`int`, *optional*, defaults to 256):
+ The attention head dimension.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
+ The legacy activation function. It is overwritten by the `hidden_activation`.
+ hidden_activation (`str` or `function`, *optional*):
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
+ The maximum sequence length that this model might ever be used with.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
+ The epsilon used by the rms normalization layers.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ pad_token_id (`int`, *optional*, defaults to 0):
+ Padding token id.
+ eos_token_id (`int`, *optional*, defaults to 1):
+ End of stream token id.
+ bos_token_id (`int`, *optional*, defaults to 2):
+ Beginning of stream token id.
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
+ Whether to tie weight embeddings
+ rope_theta (`float`, *optional*, defaults to 10000.0):
+ The base period of the RoPE embeddings.
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
+ attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ use_adarms (`bool`, *optional*, defaults to `False`):
+ Whether to use ADARMS.
+ adarms_cond_dim (`int`, *optional*, defaults to `None`):
+ The dimension of the ADARMS condition.
+ ```python
+ >>> from transformers import GemmaModel, GemmaConfig
+ >>> # Initializing a Gemma gemma-7b style configuration
+ >>> configuration = GemmaConfig()
+ >>> # Initializing a model from the gemma-7b style configuration
+ >>> model = GemmaModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "gemma"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+
+ def __init__(
+ self,
+ vocab_size=256000,
+ hidden_size=3072,
+ intermediate_size=24576,
+ num_hidden_layers=28,
+ num_attention_heads=16,
+ num_key_value_heads=16,
+ head_dim=256,
+ hidden_act="gelu_pytorch_tanh",
+ hidden_activation=None,
+ max_position_embeddings=8192,
+ initializer_range=0.02,
+ rms_norm_eps=1e-6,
+ use_cache=True,
+ pad_token_id=0,
+ eos_token_id=1,
+ bos_token_id=2,
+ tie_word_embeddings=True,
+ rope_theta=10000.0,
+ attention_bias=False,
+ attention_dropout=0.0,
+ use_adarms: bool = False,
+ adarms_cond_dim: Optional[int] = None,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.intermediate_size = intermediate_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.head_dim = head_dim
+ self.num_key_value_heads = num_key_value_heads
+ self.hidden_act = hidden_act
+ self.hidden_activation = hidden_activation
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+ self.use_cache = use_cache
+ self.rope_theta = rope_theta
+ self.attention_bias = attention_bias
+ self.attention_dropout = attention_dropout
+ self.use_adarms = use_adarms
+ self.adarms_cond_dim = adarms_cond_dim
+
+ # Set default for adarms_cond_dim if use_adarms is True
+ if self.use_adarms and self.adarms_cond_dim is None:
+ self.adarms_cond_dim = self.hidden_size
+
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ tie_word_embeddings=tie_word_embeddings,
+ **kwargs,
+ )
+
+
+__all__ = ["GemmaConfig"]
\ No newline at end of file
diff --git a/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0529778bba56e0a45279aa44e29ef9a379026d9
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py
@@ -0,0 +1,862 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_gemma.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# coding=utf-8
+# Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
+#
+#
+# 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.
+from typing import Callable, Optional, Union
+
+import torch
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache
+from ...generation import GenerationMixin
+from ...masking_utils import create_causal_mask
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPast,
+ CausalLMOutputWithPast,
+ SequenceClassifierOutputWithPast,
+ TokenClassifierOutput,
+)
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import LossKwargs, auto_docstring, can_return_tuple, logging
+from .configuration_gemma import GemmaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class GemmaRMSNorm(nn.Module):
+ def __init__(self, dim: int, eps: float = 1e-6, cond_dim: Optional[int] = None):
+ super().__init__()
+ self.eps = eps
+ self.dim = dim
+ self.cond_dim = cond_dim
+
+ # Dense layer for adaptive normalization (if cond_dim is provided)
+ if cond_dim is not None:
+ #self.dense = nn.Linear(cond_dim, dim * 3, bias=True, dtype=torch.bfloat16)
+ self.dense = nn.Linear(cond_dim, dim * 3, bias=True)
+ # Initialize with zeros (matches source implementation)
+ nn.init.zeros_(self.dense.weight)
+ else:
+ self.weight = nn.Parameter(torch.zeros(dim, dtype=torch.bfloat16))
+ self.dense = None
+
+ def _norm(self, x):
+ # Compute variance in float32 (like the source implementation)
+ var = torch.mean(torch.square(x.float()), dim=-1, keepdim=True)
+ # Compute normalization in float32
+ normed_inputs = x * torch.rsqrt(var + self.eps)
+ return normed_inputs
+
+ def forward(self, x, cond=None):
+ dtype = x.dtype # original dtype, could be half-precision
+ normed_inputs = self._norm(x)
+
+ if cond is None or self.dense is None:
+ # regular RMSNorm
+ # scale by learned parameter in float32 (matches source implementation)
+ normed_inputs = normed_inputs * (1.0 + self.weight.float())
+ return normed_inputs.to(dtype), None # return in original dtype with None gate
+
+ # adaptive RMSNorm (if cond is provided and dense layer exists)
+ if cond.shape[-1] != self.cond_dim:
+ raise ValueError(f"Expected cond dimension {self.cond_dim}, got {cond.shape[-1]}")
+
+ #self.dense.to(dtype=torch.bfloat16).to(dtype=torch.float32)
+ modulation = self.dense(cond)
+ # Reshape modulation to broadcast properly: [batch, 1, features] for [batch, seq, features]
+ if len(x.shape) == 3: # [batch, seq, features]
+ modulation = modulation.unsqueeze(1)
+
+ scale, shift, gate = torch.chunk(modulation, 3, dim=-1)
+
+ # Apply adaptive normalization: use model weight dtype to ensure compatibility
+ # model_dtype = self.dense.weight.dtype # Use the model's dtype (bfloat16)
+ # scale = scale.to(model_dtype)
+ # shift = shift.to(model_dtype)
+ # gate = gate.to(model_dtype)
+ # normed_inputs = normed_inputs.to(model_dtype) # Convert normed_inputs to model dtype
+
+ normed_inputs = normed_inputs * (1 + scale.to(torch.float32)) + shift.to(torch.float32)
+
+ return normed_inputs.to(dtype), gate.to(dtype)
+
+ def extra_repr(self):
+ repr_str = f"{tuple(self.weight.shape)}, eps={self.eps}"
+ if self.dense is not None:
+ repr_str += f", adaptive=True, cond_dim={self.cond_dim}"
+ return repr_str
+
+
+class GemmaMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class GemmaRotaryEmbedding(nn.Module):
+ def __init__(self, config: GemmaConfig, device=None):
+ super().__init__()
+ # BC: "rope_type" was originally "type"
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
+ else:
+ self.rope_type = "default"
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.original_inv_freq = self.inv_freq
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`, *optional*):
+ Deprecated and unused.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def _gated_residual(x, y, gate):
+ """
+ Applies gated residual connection with optional gate parameter.
+
+ Args:
+ x: Input tensor (residual)
+ y: Output tensor to be added
+ gate: Optional gate tensor to modulate the addition
+
+ Returns:
+ x + y if gate is None, otherwise x + y * gate
+ """
+ if x is None and y is None:
+ return None
+ if x is None or y is None:
+ return x if x is not None else y
+ if gate is None:
+ return x + y
+ return x + y * gate
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
+ attn_weights = attn_weights + causal_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class GemmaAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: GemmaConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ self.is_causal = True
+
+ self.q_proj = nn.Linear(
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.k_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.v_proj = nn.Linear(
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
+ )
+ self.o_proj = nn.Linear(
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: Optional[torch.Tensor],
+ past_key_value: Optional[Cache] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ use_cache: bool = False,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ # Use cache if provided
+ if past_key_value is not None:
+ if use_cache:
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
+ else:
+ key_states = torch.cat([past_key_value[self.layer_idx][0], key_states], dim=2)
+ value_states = torch.cat([past_key_value[self.layer_idx][1], value_states], dim=2)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class GemmaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: GemmaConfig, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.self_attn = GemmaAttention(config=config, layer_idx=layer_idx)
+
+ self.mlp = GemmaMLP(config)
+ cond_dim = getattr(config, 'adarms_cond_dim', None) if getattr(config, 'use_adarms', False) else None
+ self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim)
+ self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ cache_position: Optional[torch.LongTensor] = None,
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
+ adarms_cond: Optional[torch.Tensor] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ residual = hidden_states
+ hidden_states, gate = self.input_layernorm(hidden_states, adarms_cond)
+
+ # Self Attention
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+ hidden_states = _gated_residual(residual, hidden_states, gate)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states, gate = self.post_attention_layernorm(hidden_states, adarms_cond)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = _gated_residual(residual, hidden_states, gate)
+
+ outputs = (hidden_states,)
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ return outputs
+
+
+@auto_docstring
+class GemmaPreTrainedModel(PreTrainedModel):
+ config_class = GemmaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["GemmaDecoderLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn_3 = True
+ _supports_flash_attn_2 = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_cache_class = True
+ _supports_quantized_cache = True
+ _supports_static_cache = True
+ _supports_attention_backend = True
+
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, GemmaRMSNorm):
+ if hasattr(module, 'weight'):
+ module.weight.data.fill_(1.0)
+
+
+@auto_docstring
+class GemmaModel(GemmaPreTrainedModel):
+ def __init__(self, config: GemmaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ self.layers = nn.ModuleList(
+ [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+
+ cond_dim = getattr(config, 'adarms_cond_dim', None) if getattr(config, 'use_adarms', False) else None
+ self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim)
+ self.rotary_emb = GemmaRotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.embed_tokens = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ adarms_cond: Optional[torch.Tensor] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> BaseModelOutputWithPast:
+ """
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
+ Condition for ADARMS.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if self.gradient_checkpointing and self.training and use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
+ )
+ use_cache = False
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache()
+
+ if cache_position is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ cache_position = torch.arange(
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
+ )
+
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+ causal_mask = create_causal_mask(
+ config=self.config,
+ input_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ cache_position=cache_position,
+ past_key_values=past_key_values,
+ position_ids=position_ids,
+ )
+
+ # embed positions
+ hidden_states = inputs_embeds
+ # Convert to bfloat16 if the first layer uses bfloat16
+ if len(self.layers) > 0 and self.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16:
+ hidden_states = hidden_states.to(torch.bfloat16)
+
+ # create position embeddings to be shared across the decoder layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ # normalized
+ # Gemma downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
+ # See https://github.com/huggingface/transformers/pull/29402
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
+ #hidden_states = hidden_states * normalizer
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_value=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ position_embeddings=position_embeddings,
+ adarms_cond=adarms_cond,
+ **kwargs,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states, _ = self.norm(hidden_states, adarms_cond)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+
+
+class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
+
+
+@auto_docstring
+class GemmaForCausalLM(GemmaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["lm_head.weight"]
+ _tp_plan = {"lm_head": "colwise_rep"}
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = GemmaModel(config)
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def set_decoder(self, decoder):
+ self.model = decoder
+
+ def get_decoder(self):
+ return self.model
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ logits_to_keep: Union[int, torch.Tensor] = 0,
+ adarms_cond: Optional[torch.Tensor] = None,
+ **kwargs: Unpack[KwargsForCausalLM],
+ ) -> CausalLMOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
+ Condition for ADARMS.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
+
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
+
+ >>> prompt = "What is your favorite condiment?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "What is your favorite condiment?"
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ cache_position=cache_position,
+ adarms_cond=adarms_cond,
+ **kwargs,
+ )
+
+ hidden_states = outputs.last_hidden_state
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The Gemma Model transformer with a sequence classification head on top (linear layer).
+
+ [`GemmaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class GemmaForSequenceClassification(GemmaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = GemmaModel(config)
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ adarms_cond: Optional[torch.Tensor] = None,
+ ) -> SequenceClassifierOutputWithPast:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
+ Condition for ADARMS.
+ """
+
+ transformer_outputs: BaseModelOutputWithPast = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ adarms_cond=adarms_cond,
+ )
+ hidden_states = transformer_outputs.last_hidden_state
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class GemmaForTokenClassification(GemmaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = GemmaModel(config)
+ if getattr(config, "classifier_dropout", None) is not None:
+ classifier_dropout = config.classifier_dropout
+ elif getattr(config, "hidden_dropout", None) is not None:
+ classifier_dropout = config.hidden_dropout
+ else:
+ classifier_dropout = 0.1
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.embed_tokens = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ adarms_cond: Optional[torch.Tensor] = None,
+ ) -> TokenClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
+ Condition for ADARMS.
+ """
+
+ outputs: BaseModelOutputWithPast = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ adarms_cond=adarms_cond,
+ )
+ sequence_output = outputs.last_hidden_state
+ sequence_output = self.dropout(sequence_output)
+ logits = self.score(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.config)
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "GemmaModel",
+ "GemmaForCausalLM",
+ "GemmaForSequenceClassification",
+ "GemmaForTokenClassification",
+ "GemmaPreTrainedModel",
+]
diff --git a/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbf0e948909044f1f97ce053cce4ff0fee0378e8
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py
@@ -0,0 +1,622 @@
+# coding=utf-8
+# Copyright 2024 the HuggingFace Inc. team. All rights reserved.
+#
+# 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.
+"""PyTorch PaliGemmamodel."""
+
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+
+from ...cache_utils import Cache, HybridCache, StaticCache
+from ...generation import GenerationMixin
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutputWithPast
+from ...modeling_utils import PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import LossKwargs, ModelOutput, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
+from ..auto import AutoModel
+from .configuration_paligemma import PaliGemmaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Base class for Paligemma outputs, with hidden states and attentions.
+ """
+)
+class PaligemmaModelOutputWithPast(BaseModelOutputWithPast):
+ r"""
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
+ """
+
+ image_hidden_states: Optional[torch.FloatTensor] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Base class for PaliGemma causal language model (or autoregressive) outputs.
+ """
+)
+class PaliGemmaCausalLMOutputWithPast(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
+ `past_key_values` input) to speed up sequential decoding.
+ image_hidden_states (`torch.FloatTensor`, *optional*):
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
+ image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+ image_hidden_states: Optional[torch.FloatTensor] = None
+
+
+class PaliGemmaMultiModalProjector(nn.Module):
+ def __init__(self, config: PaliGemmaConfig):
+ super().__init__()
+ self.linear = nn.Linear(config.vision_config.hidden_size, config.vision_config.projection_dim, bias=True)
+
+ def forward(self, image_features):
+ hidden_states = self.linear(image_features)
+
+ return hidden_states
+
+
+@auto_docstring
+class PaliGemmaPreTrainedModel(PreTrainedModel):
+ config_class = PaliGemmaConfig
+ base_model_prefix = ""
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["PaliGemmaMultiModalProjector"]
+ _skip_keys_device_placement = "past_key_values"
+ _supports_cache_class = True
+ _supports_quantized_cache = True
+ _supports_static_cache = True
+ _supports_flash_attn_2 = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+
+ def _init_weights(self, module):
+ # important: this ported version of PaliGemmaisn't meant for training from scratch - only
+ # inference and fine-tuning
+ std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
+
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+
+
+@auto_docstring(
+ custom_intro="""
+ The Base Paligemma model which consists of a vision backbone and a language model withou language modeling head.,
+ """
+)
+class PaliGemmaModel(PaliGemmaPreTrainedModel):
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
+ accepts_loss_kwargs = False
+
+ def __init__(self, config: PaliGemmaConfig):
+ super().__init__(config)
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
+ self.multi_modal_projector = PaliGemmaMultiModalProjector(config)
+ self.vocab_size = config.text_config.vocab_size
+
+ language_model = AutoModel.from_config(config=config.text_config)
+ self.language_model = language_model
+
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
+ self.post_init()
+
+ # Copied from transformers.models.llava.modeling_llava.LlavaModel.get_input_embeddings with Llava->PaliGemma
+ def get_input_embeddings(self):
+ return self.language_model.get_input_embeddings()
+
+ # Copied from transformers.models.llava.modeling_llava.LlavaModel.set_input_embeddings with Llava->PaliGemma
+ def set_input_embeddings(self, value):
+ self.language_model.set_input_embeddings(value)
+
+ def set_decoder(self, decoder):
+ self.language_model = decoder
+
+ def get_decoder(self):
+ return self.language_model
+
+ def _update_causal_mask(
+ self,
+ attention_mask,
+ token_type_ids=None,
+ past_key_values=None,
+ cache_position=None,
+ input_tensor=None,
+ is_training: Optional[bool] = None,
+ ):
+ if self.config.text_config._attn_implementation == "flash_attention_2":
+ if attention_mask is not None and 0.0 in attention_mask:
+ return attention_mask
+ return None
+ is_training = is_training if is_training is not None else self.training
+ using_static_cache = isinstance(past_key_values, StaticCache)
+ min_dtype = torch.finfo(self.dtype).min
+ if input_tensor is None:
+ input_tensor = attention_mask
+
+ inputs_lead_dim, sequence_length = input_tensor.shape[:2]
+ if using_static_cache:
+ target_length = past_key_values.get_max_cache_shape()
+ elif isinstance(past_key_values, HybridCache):
+ target_length = past_key_values.get_max_cache_shape()
+ else:
+ target_length = (
+ attention_mask.shape[-1]
+ if isinstance(attention_mask, torch.Tensor)
+ else cache_position[0] + sequence_length + 1
+ )
+
+ if attention_mask is not None and attention_mask.dim() == 4:
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
+ return attention_mask
+
+ causal_mask = torch.full(
+ (sequence_length, target_length), fill_value=min_dtype, dtype=self.dtype, device=cache_position.device
+ )
+ # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
+ if sequence_length != 1:
+ if is_training:
+ causal_mask = torch.triu(causal_mask, diagonal=1)
+ else:
+ causal_mask[:, :sequence_length] = 0.0
+
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
+ if attention_mask is not None:
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
+ mask_length = attention_mask.shape[-1]
+
+ # First unmask prefix tokens during training
+ if is_training:
+ if token_type_ids is None:
+ raise ValueError("Token type ids must be provided during training")
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
+ )
+
+ # Then apply padding mask (will mask pad tokens)
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
+ padding_mask = padding_mask == 0
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
+ padding_mask, min_dtype
+ )
+
+ return causal_mask
+
+ def get_image_features(self, pixel_values: torch.FloatTensor):
+ """
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
+
+ Args:
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
+ The tensors corresponding to the input images.
+ Returns:
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
+ """
+ image_outputs = self.vision_tower(pixel_values)
+ selected_image_feature = image_outputs.last_hidden_state
+ image_features = self.multi_modal_projector(selected_image_feature)
+ return image_features
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ pixel_values: torch.FloatTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> Union[tuple, PaligemmaModelOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import requests
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
+
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
+ >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
+
+ >>> prompt = "Where is the cat standing?"
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(**inputs,)
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Where is the cat standing?\nsnow"
+ ```"""
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ is_training = token_type_ids is not None and labels is not None
+
+ # Replace image id woth PAD if the image token if OOV, to avoid index-errors
+ if input_ids is not None and self.config.image_token_id >= self.vocab_size:
+ special_image_mask = input_ids == self.config.image_token_id
+ llm_input_ids = input_ids.clone()
+ llm_input_ids[special_image_mask] = 0
+ else:
+ llm_input_ids = input_ids
+
+ if inputs_embeds is None:
+ inputs_embeds = self.get_input_embeddings()(llm_input_ids)
+
+ if cache_position is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ cache_position = torch.arange(
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
+ )
+
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
+
+ # Merge text and images
+ if pixel_values is not None:
+ image_features = self.get_image_features(pixel_values)
+
+ if input_ids is None:
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
+ )
+ else:
+ special_image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1)
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
+
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
+ image_tokens_in_text = (special_image_mask).sum(dim=1).sum(dim=0)[0]
+ raise ValueError(
+ f"Number of images does not match number of special image tokens in the input text. "
+ f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
+ "tokens from image embeddings."
+ )
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
+
+ causal_mask = self._update_causal_mask(
+ attention_mask, token_type_ids, past_key_values, cache_position, inputs_embeds, is_training
+ )
+ outputs = self.language_model(
+ attention_mask=causal_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=True,
+ cache_position=cache_position,
+ **kwargs,
+ )
+
+ return PaligemmaModelOutputWithPast(
+ last_hidden_state=outputs.last_hidden_state,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=image_features if pixel_values is not None else None,
+ )
+
+
+class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
+
+
+@auto_docstring(
+ custom_intro="""
+ The Base Paligemma model which consists of a vision backbone and a language model without language modeling head.,
+ """
+)
+class PaliGemmaForConditionalGeneration(PaliGemmaPreTrainedModel, GenerationMixin):
+ _checkpoint_conversion_mapping = {
+ "^language_model.model": "model.language_model",
+ "^vision_tower": "model.vision_tower",
+ "^multi_modal_projector": "model.multi_modal_projector",
+ "^language_model.lm_head": "lm_head",
+ }
+ _tied_weights_keys = ["lm_head.weight"]
+
+ def __init__(self, config: PaliGemmaConfig):
+ super().__init__(config)
+ self.model = PaliGemmaModel(config)
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.get_input_embeddings()
+
+ def set_input_embeddings(self, value):
+ self.model.set_input_embeddings(value)
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def set_decoder(self, decoder):
+ self.model.set_decoder(decoder)
+
+ def get_decoder(self):
+ return self.model.get_decoder()
+
+ def get_image_features(self, pixel_values):
+ return self.model.get_image_features(pixel_values)
+
+ # Make modules available throught conditional class for BC
+ @property
+ def language_model(self):
+ return self.model.language_model
+
+ @property
+ def vision_tower(self):
+ return self.model.vision_tower
+
+ @property
+ def multi_modal_projector(self):
+ return self.model.multi_modal_projector
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor = None,
+ pixel_values: torch.FloatTensor = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ logits_to_keep: Union[int, torch.Tensor] = 0,
+ **kwargs: Unpack[KwargsForCausalLM],
+ ) -> Union[tuple, PaliGemmaCausalLMOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import requests
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
+
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
+ >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
+
+ >>> prompt = "Where is the cat standing?"
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(**inputs,)
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Where is the cat standing?\nsnow"
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.model(
+ input_ids=input_ids,
+ pixel_values=pixel_values,
+ token_type_ids=token_type_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ labels=labels,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=True,
+ cache_position=cache_position,
+ **kwargs,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
+ )
+
+ return PaliGemmaCausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ image_hidden_states=outputs.image_hidden_states,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ inputs_embeds=None,
+ cache_position=None,
+ position_ids=None,
+ pixel_values=None,
+ attention_mask=None,
+ token_type_ids=None,
+ use_cache=True,
+ logits_to_keep=None,
+ labels=None,
+ **kwargs,
+ ):
+ # Overwritten -- custom `position_ids` and `pixel_values` handling
+ model_inputs = super().prepare_inputs_for_generation(
+ input_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ cache_position=cache_position,
+ use_cache=use_cache,
+ logits_to_keep=logits_to_keep,
+ token_type_ids=token_type_ids,
+ **kwargs,
+ )
+
+ # position_ids in Paligemma are 1-indexed
+ if model_inputs.get("position_ids") is not None:
+ model_inputs["position_ids"] += 1
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
+ if cache_position[0] == 0:
+ model_inputs["pixel_values"] = pixel_values
+ is_training = token_type_ids is not None and labels is not None
+ if cache_position[0] == 0 and isinstance(past_key_values, HybridCache):
+ input_tensor = inputs_embeds if inputs_embeds is not None else input_ids
+ causal_mask = self.model._update_causal_mask(
+ attention_mask, token_type_ids, past_key_values, cache_position, input_tensor, is_training
+ )
+ model_inputs["attention_mask"] = causal_mask
+
+ return model_inputs
+
+ @staticmethod
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
+ def _prepare_4d_causal_attention_mask_with_cache_position(
+ attention_mask: torch.Tensor,
+ sequence_length: int,
+ target_length: int,
+ dtype: torch.dtype,
+ cache_position: torch.Tensor,
+ batch_size: int,
+ **kwargs,
+ ):
+ """
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
+
+ Args:
+ attention_mask (`torch.Tensor`):
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
+ `(batch_size, 1, query_length, key_value_length)`.
+ sequence_length (`int`):
+ The sequence length being processed.
+ target_length (`int`):
+ The target length: when generating with static cache, the mask should be as long as the static cache,
+ to account for the 0 padding, the part of the cache that is not filled yet.
+ dtype (`torch.dtype`):
+ The dtype to use for the 4D attention mask.
+ cache_position (`torch.Tensor`):
+ Indices depicting the position of the input sequence tokens in the sequence.
+ batch_size (`torch.Tensor`):
+ Batch size.
+ """
+ if attention_mask is not None and attention_mask.dim() == 4:
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
+ causal_mask = attention_mask
+ else:
+ min_dtype = torch.finfo(dtype).min
+ causal_mask = torch.full(
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
+ )
+ if sequence_length != 1:
+ causal_mask = torch.triu(causal_mask, diagonal=1)
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
+ if attention_mask is not None:
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
+ mask_length = attention_mask.shape[-1]
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
+ causal_mask.device
+ )
+ padding_mask = padding_mask == 0
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
+ padding_mask, min_dtype
+ )
+
+ return causal_mask
+
+
+__all__ = ["PaliGemmaForConditionalGeneration", "PaliGemmaPreTrainedModel", "PaliGemmaModel"]
diff --git a/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bb3c96aa57aea42b20452d35eb5ecd9f50d4d59
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py
@@ -0,0 +1,4 @@
+import transformers
+
+def check_whether_transformers_replace_is_installed_correctly():
+ return transformers.__version__ == "4.53.2"
\ No newline at end of file
diff --git a/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ea8acdb31ab5f29de86f4452942137ecb788a1b
--- /dev/null
+++ b/openpi-umi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py
@@ -0,0 +1,1237 @@
+# coding=utf-8
+# Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
+#
+# 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.
+"""PyTorch Siglip model."""
+
+import math
+import warnings
+from dataclasses import dataclass
+from typing import Any, Callable, Optional, Union
+
+import numpy as np
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+from torch.nn.init import _calculate_fan_in_and_fan_out
+
+from ...activations import ACT2FN
+from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, can_return_tuple, logging, torch_int
+from .configuration_siglip import SiglipConfig, SiglipTextConfig, SiglipVisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def _trunc_normal_(tensor, mean, std, a, b):
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
+ def norm_cdf(x):
+ # Computes standard normal cumulative distribution function
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
+
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
+ warnings.warn(
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
+ "The distribution of values may be incorrect.",
+ stacklevel=2,
+ )
+
+ # Values are generated by using a truncated uniform distribution and
+ # then using the inverse CDF for the normal distribution.
+ # Get upper and lower cdf values
+ l = norm_cdf((a - mean) / std)
+ u = norm_cdf((b - mean) / std)
+
+ # Uniformly fill tensor with values from [l, u], then translate to
+ # [2l-1, 2u-1].
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
+
+ # Use inverse cdf transform for normal distribution to get truncated
+ # standard normal
+ tensor.erfinv_()
+
+ # Transform to proper mean, std
+ tensor.mul_(std * math.sqrt(2.0))
+ tensor.add_(mean)
+
+ # Clamp to ensure it's in the proper range
+ tensor.clamp_(min=a, max=b)
+
+
+def trunc_normal_tf_(
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
+) -> torch.Tensor:
+ """Fills the input Tensor with values drawn from a truncated
+ normal distribution. The values are effectively drawn from the
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
+ with values outside :math:`[a, b]` redrawn until they are within
+ the bounds. The method used for generating the random values works
+ best when :math:`a \\leq \text{mean} \\leq b`.
+
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
+ and the result is subsequently scaled and shifted by the mean and std args.
+
+ Args:
+ tensor: an n-dimensional `torch.Tensor`
+ mean: the mean of the normal distribution
+ std: the standard deviation of the normal distribution
+ a: the minimum cutoff value
+ b: the maximum cutoff value
+ """
+ with torch.no_grad():
+ _trunc_normal_(tensor, 0, 1.0, a, b)
+ tensor.mul_(std).add_(mean)
+
+
+def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
+ if mode == "fan_in":
+ denom = fan_in
+ elif mode == "fan_out":
+ denom = fan_out
+ elif mode == "fan_avg":
+ denom = (fan_in + fan_out) / 2
+
+ variance = scale / denom
+
+ if distribution == "truncated_normal":
+ # constant is stddev of standard normal truncated to (-2, 2)
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
+ elif distribution == "normal":
+ with torch.no_grad():
+ tensor.normal_(std=math.sqrt(variance))
+ elif distribution == "uniform":
+ bound = math.sqrt(3 * variance)
+ with torch.no_grad():
+ tensor.uniform_(-bound, bound)
+ else:
+ raise ValueError(f"invalid distribution {distribution}")
+
+
+def lecun_normal_(tensor):
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
+
+
+def default_flax_embed_init(tensor):
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
+ """
+)
+# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
+class SiglipVisionModelOutput(ModelOutput):
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The image embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ image_embeds: Optional[torch.FloatTensor] = None
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+# Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Siglip
+class SiglipTextModelOutput(ModelOutput):
+ r"""
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The text embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ text_embeds: Optional[torch.FloatTensor] = None
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring
+# Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Siglip
+class SiglipOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
+ Contrastive loss for image-text similarity.
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
+ similarity scores.
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
+ similarity scores.
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`].
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`].
+ text_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`SiglipTextModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`SiglipVisionModel`].
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits_per_image: Optional[torch.FloatTensor] = None
+ logits_per_text: Optional[torch.FloatTensor] = None
+ text_embeds: Optional[torch.FloatTensor] = None
+ image_embeds: Optional[torch.FloatTensor] = None
+ text_model_output: BaseModelOutputWithPooling = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
+ for k in self.keys()
+ )
+
+
+class SiglipVisionEmbeddings(nn.Module):
+ def __init__(self, config: SiglipVisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=config.num_channels,
+ out_channels=self.embed_dim,
+ kernel_size=self.patch_size,
+ stride=self.patch_size,
+ padding="valid",
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
+
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing and no class embeddings.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1]
+ num_positions = self.position_embedding.weight.shape[0]
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embedding(self.position_ids)
+
+ patch_pos_embed = self.position_embedding.weight.unsqueeze(0)
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+ return patch_pos_embed
+
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
+ _, _, height, width = pixel_values.shape
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
+
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embedding(self.position_ids)
+ return embeddings
+
+
+# Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Siglip
+class SiglipTextEmbeddings(nn.Module):
+ def __init__(self, config: SiglipTextConfig):
+ super().__init__()
+ embed_dim = config.hidden_size
+
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ ) -> torch.Tensor:
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
+ max_position_embedding = self.position_embedding.weight.shape[0]
+
+ if seq_length > max_position_embedding:
+ raise ValueError(
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
+ )
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ if inputs_embeds is None:
+ inputs_embeds = self.token_embedding(input_ids)
+
+ position_embeddings = self.position_embedding(position_ids)
+ embeddings = inputs_embeds + position_embeddings
+
+ return embeddings
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class SiglipAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ if self.head_dim * self.num_heads != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {self.num_heads})."
+ )
+ self.scale = self.head_dim**-0.5
+ self.dropout = config.attention_dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
+ """Input shape: Batch x Time x Channel"""
+
+ batch_size, seq_length, embed_dim = hidden_states.shape
+
+ queries = self.q_proj(hidden_states)
+ keys = self.k_proj(hidden_states)
+ values = self.v_proj(hidden_states)
+
+ queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
+ keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
+ values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ if self.config._attn_implementation == "sdpa" and output_attentions:
+ logger.warning_once(
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
+ )
+ else:
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask,
+ is_causal=self.is_causal,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.dropout,
+ )
+
+ attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ if not output_attentions:
+ attn_weights = None
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
+class SiglipMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class SiglipEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Union[SiglipVisionConfig, SiglipTextConfig]):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.self_attn = SiglipAttention(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = SiglipMLP(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.FloatTensor]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`):
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
+ attention_mask (`torch.FloatTensor`):
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+@auto_docstring
+class SiglipPreTrainedModel(PreTrainedModel):
+ config_class = SiglipConfig
+ base_model_prefix = "siglip"
+ supports_gradient_checkpointing = True
+
+ _no_split_modules = [
+ "SiglipTextEmbeddings",
+ "SiglipEncoderLayer",
+ "SiglipVisionEmbeddings",
+ "SiglipEncoderLayer",
+ "SiglipMultiheadAttentionPoolingHead",
+ ]
+ _supports_flash_attn_2 = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, SiglipVisionEmbeddings):
+ width = (
+ self.config.vision_config.hidden_size
+ if isinstance(self.config, SiglipConfig)
+ else self.config.hidden_size
+ )
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
+ elif isinstance(module, nn.Embedding):
+ default_flax_embed_init(module.weight)
+ elif isinstance(module, SiglipAttention):
+ nn.init.xavier_uniform_(module.q_proj.weight)
+ nn.init.xavier_uniform_(module.k_proj.weight)
+ nn.init.xavier_uniform_(module.v_proj.weight)
+ nn.init.xavier_uniform_(module.out_proj.weight)
+ nn.init.zeros_(module.q_proj.bias)
+ nn.init.zeros_(module.k_proj.bias)
+ nn.init.zeros_(module.v_proj.bias)
+ nn.init.zeros_(module.out_proj.bias)
+ elif isinstance(module, SiglipMLP):
+ nn.init.xavier_uniform_(module.fc1.weight)
+ nn.init.xavier_uniform_(module.fc2.weight)
+ nn.init.normal_(module.fc1.bias, std=1e-6)
+ nn.init.normal_(module.fc2.bias, std=1e-6)
+ elif isinstance(module, SiglipMultiheadAttentionPoolingHead):
+ nn.init.xavier_uniform_(module.probe.data)
+ nn.init.xavier_uniform_(module.attention.in_proj_weight.data)
+ nn.init.zeros_(module.attention.in_proj_bias.data)
+ elif isinstance(module, SiglipModel):
+ logit_scale_init = torch.log(torch.tensor(1.0))
+ module.logit_scale.data.fill_(logit_scale_init)
+ module.logit_bias.data.zero_()
+ elif isinstance(module, SiglipForImageClassification):
+ nn.init.normal_(
+ module.classifier.weight,
+ std=self.config.vision_config.hidden_size**-0.5 * self.config.initializer_factor,
+ )
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
+ lecun_normal_(module.weight)
+ if module.bias is not None:
+ nn.init.zeros_(module.bias)
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+# Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoder with AltCLIP->Siglip
+class SiglipEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`SiglipEncoderLayer`].
+
+ Args:
+ config: SiglipConfig
+ """
+
+ def __init__(self, config: SiglipConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ # Ignore copy
+ @can_return_tuple
+ def forward(
+ self,
+ inputs_embeds,
+ attention_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ ) -> BaseModelOutput:
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
+ than the model's internal embedding lookup matrix.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+
+ layer_outputs = encoder_layer(
+ hidden_states,
+ attention_mask,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=encoder_states,
+ attentions=all_attentions,
+ )
+
+
+class SiglipTextTransformer(nn.Module):
+ def __init__(self, config: SiglipTextConfig):
+ super().__init__()
+ self.config = config
+ embed_dim = config.hidden_size
+ self.embeddings = SiglipTextEmbeddings(config)
+ self.encoder = SiglipEncoder(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ self.head = nn.Linear(embed_dim, config.projection_size)
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ ) -> BaseModelOutputWithPooling:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ if input_ids is None:
+ raise ValueError("You have to specify input_ids")
+
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
+
+ # note: SigLIP's text model does not use a causal mask, unlike the original CLIP model.
+ # expand attention_mask
+ if attention_mask is not None and not self._use_flash_attention_2:
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
+
+ # Assuming "sticky" EOS tokenization, last token is always EOS.
+ pooled_output = last_hidden_state[:, -1, :]
+ pooled_output = self.head(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The text model from SigLIP without any head or projection on top.
+ """
+)
+class SiglipTextModel(SiglipPreTrainedModel):
+ config_class = SiglipTextConfig
+
+ def __init__(self, config: SiglipTextConfig):
+ super().__init__(config)
+ self.text_model = SiglipTextTransformer(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.text_model.embeddings.token_embedding
+
+ def set_input_embeddings(self, value):
+ self.text_model.embeddings.token_embedding = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ ) -> BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, SiglipTextModel
+
+ >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
+
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
+ ```"""
+
+ return self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+
+
+class SiglipVisionTransformer(nn.Module):
+ def __init__(self, config: SiglipVisionConfig):
+ super().__init__()
+ self.config = config
+ embed_dim = config.hidden_size
+
+ self.embeddings = SiglipVisionEmbeddings(config)
+ self.encoder = SiglipEncoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.use_head = True if not hasattr(config, "vision_use_head") else config.vision_use_head
+ if self.use_head:
+ self.head = SiglipMultiheadAttentionPoolingHead(config)
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: Optional[bool] = False,
+ ) -> BaseModelOutputWithPooling:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+ # Convert to bfloat16 if the encoder uses bfloat16
+ if len(self.encoder.layers) > 0 and self.encoder.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16:
+ hidden_states = hidden_states.to(torch.bfloat16)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.post_layernorm(last_hidden_state)
+
+ pooler_output = self.head(last_hidden_state) if self.use_head else None
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooler_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+class SiglipMultiheadAttentionPoolingHead(nn.Module):
+ """Multihead Attention Pooling."""
+
+ def __init__(self, config: SiglipVisionConfig):
+ super().__init__()
+
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.mlp = SiglipMLP(config)
+
+ def forward(self, hidden_state):
+ batch_size = hidden_state.shape[0]
+ probe = self.probe.repeat(batch_size, 1, 1)
+
+ hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
+
+ residual = hidden_state
+ hidden_state = self.layernorm(hidden_state)
+ hidden_state = residual + self.mlp(hidden_state)
+
+ return hidden_state[:, 0]
+
+
+@auto_docstring(
+ custom_intro="""
+ The vision model from SigLIP without any head or projection on top.
+ """
+)
+class SiglipVisionModel(SiglipPreTrainedModel):
+ config_class = SiglipVisionConfig
+ main_input_name = "pixel_values"
+
+ def __init__(self, config: SiglipVisionConfig):
+ super().__init__(config)
+
+ self.vision_model = SiglipVisionTransformer(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.vision_model.embeddings.patch_embedding
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: bool = False,
+ ) -> BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from PIL import Image
+ >>> import requests
+ >>> from transformers import AutoProcessor, SiglipVisionModel
+
+ >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled features
+ ```"""
+
+ return self.vision_model(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ )
+
+
+@auto_docstring
+class SiglipModel(SiglipPreTrainedModel):
+ config_class = SiglipConfig
+
+ def __init__(self, config: SiglipConfig):
+ super().__init__(config)
+
+ if not isinstance(config.text_config, SiglipTextConfig):
+ raise TypeError(
+ "config.text_config is expected to be of type SiglipTextConfig but is of type"
+ f" {type(config.text_config)}."
+ )
+
+ if not isinstance(config.vision_config, SiglipVisionConfig):
+ raise TypeError(
+ "config.vision_config is expected to be of type SiglipVisionConfig but is of type"
+ f" {type(config.vision_config)}."
+ )
+
+ text_config = config.text_config
+ vision_config = config.vision_config
+
+ # First, initialize the text and vision models with proper attention implementation
+ text_model = SiglipTextModel._from_config(text_config)
+ vision_model = SiglipVisionModel._from_config(vision_config)
+
+ # Second, get the text and vision submodules (for backward compatibility)
+ self.text_model = text_model.text_model
+ self.vision_model = vision_model.vision_model
+
+ self.logit_scale = nn.Parameter(torch.randn(1))
+ self.logit_bias = nn.Parameter(torch.randn(1))
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def get_text_features(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ ) -> torch.FloatTensor:
+ r"""
+ Returns:
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
+ applying the projection layer to the pooled output of [`SiglipTextModel`].
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, AutoModel
+ >>> import torch
+
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
+
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
+ >>> with torch.no_grad():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+
+ pooled_output = text_outputs.pooler_output
+
+ return pooled_output
+
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: bool = False,
+ ) -> torch.FloatTensor:
+ r"""
+ Returns:
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
+ applying the projection layer to the pooled output of [`SiglipVisionModel`].
+
+ Examples:
+
+ ```python
+ >>> from PIL import Image
+ >>> import requests
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> import torch
+
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... image_features = model.get_image_features(**inputs)
+ ```"""
+ # Use SiglipModel's config for some fields (if specified) instead of those of vision & text components.
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ )
+
+ pooled_output = vision_outputs.pooler_output
+
+ return pooled_output
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ pixel_values: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ return_loss: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: bool = False,
+ ) -> SiglipOutput:
+ r"""
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> from PIL import Image
+ >>> import requests
+ >>> from transformers import AutoProcessor, AutoModel
+ >>> import torch
+
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
+ >>> # important: we pass `padding=max_length` since the model was trained with this
+ >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> logits_per_image = outputs.logits_per_image
+ >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
+ >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
+ 31.9% that image 0 is 'a photo of 2 cats'
+ ```"""
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ )
+
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ )
+
+ image_embeds = vision_outputs.pooler_output
+ text_embeds = text_outputs.pooler_output
+
+ # normalized features
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
+
+ # cosine similarity as logits
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
+
+ logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device)
+ logits_per_text = logits_per_text * logit_scale.exp() + logit_bias
+
+ logits_per_image = logits_per_text.t()
+
+ loss = None
+ if return_loss:
+ # Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/siglip.py#L287
+ eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device)
+ m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye
+ loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text)
+ nll = -torch.sum(loglik, dim=-1)
+ loss = nll.mean()
+
+ return SiglipOutput(
+ loss=loss,
+ logits_per_image=logits_per_image,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ image_embeds=image_embeds,
+ text_model_output=text_outputs,
+ vision_model_output=vision_outputs,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ SigLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
+ the patch tokens) e.g. for ImageNet.
+ """
+)
+class SiglipForImageClassification(SiglipPreTrainedModel):
+ main_input_name = "pixel_values"
+
+ def __init__(self, config: SiglipConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+
+ # Create the vision model with proper attention
+ # and take only vision_model submodule (for backward compatibility)
+ vision_model = SiglipVisionModel._from_config(config.vision_config)
+ self.vision_model = vision_model.vision_model
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: bool = False,
+ ) -> ImageClassifierOutput:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, SiglipForImageClassification
+ >>> import torch
+ >>> from PIL import Image
+ >>> import requests
+
+ >>> torch.manual_seed(3) # doctest: +IGNORE_RESULT
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> # note: we are loading a `SiglipModel` from the hub here,
+ >>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
+ >>> image_processor = AutoImageProcessor.from_pretrained("google/siglip-base-patch16-224")
+ >>> model = SiglipForImageClassification.from_pretrained("google/siglip-base-patch16-224")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> logits = outputs.logits
+ >>> # model predicts one of the two classes
+ >>> predicted_class_idx = logits.argmax(-1).item()
+ >>> print("Predicted class:", model.config.id2label[predicted_class_idx])
+ Predicted class: LABEL_1
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ )
+
+ sequence_output = outputs.last_hidden_state
+
+ # average pool the patch tokens
+ sequence_output = torch.mean(sequence_output, dim=1)
+ # apply classifier
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "SiglipModel",
+ "SiglipPreTrainedModel",
+ "SiglipTextModel",
+ "SiglipVisionModel",
+ "SiglipForImageClassification",
+]
\ No newline at end of file
diff --git a/openpi-umi/src/openpi/policies/aloha_policy.py b/openpi-umi/src/openpi/policies/aloha_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..f16be3334584692ba505553220ab20ff7b2719c5
--- /dev/null
+++ b/openpi-umi/src/openpi/policies/aloha_policy.py
@@ -0,0 +1,202 @@
+import dataclasses
+from typing import ClassVar
+
+import einops
+import numpy as np
+
+from openpi import transforms
+
+
+def make_aloha_example() -> dict:
+ """Creates a random input example for the Aloha policy."""
+ return {
+ "state": np.ones((14,)),
+ "images": {
+ "cam_high": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
+ "cam_low": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
+ "cam_left_wrist": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
+ "cam_right_wrist": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
+ },
+ "prompt": "do something",
+ }
+
+
+@dataclasses.dataclass(frozen=True)
+class AlohaInputs(transforms.DataTransformFn):
+ """Inputs for the Aloha policy.
+
+ Expected inputs:
+ - images: dict[name, img] where img is [channel, height, width]. name must be in EXPECTED_CAMERAS.
+ - state: [14]
+ - actions: [action_horizon, 14]
+ """
+
+ # If true, this will convert the joint and gripper values from the standard Aloha space to
+ # the space used by the pi internal runtime which was used to train the base model.
+ adapt_to_pi: bool = True
+
+ # The expected cameras names. All input cameras must be in this set. Missing cameras will be
+ # replaced with black images and the corresponding `image_mask` will be set to False.
+ EXPECTED_CAMERAS: ClassVar[tuple[str, ...]] = ("cam_high", "cam_low", "cam_left_wrist", "cam_right_wrist")
+
+ def __call__(self, data: dict) -> dict:
+ data = _decode_aloha(data, adapt_to_pi=self.adapt_to_pi)
+
+ in_images = data["images"]
+ if set(in_images) - set(self.EXPECTED_CAMERAS):
+ raise ValueError(f"Expected images to contain {self.EXPECTED_CAMERAS}, got {tuple(in_images)}")
+
+ # Assume that base image always exists.
+ base_image = in_images["cam_high"]
+
+ images = {
+ "base_0_rgb": base_image,
+ }
+ image_masks = {
+ "base_0_rgb": np.True_,
+ }
+
+ # Add the extra images.
+ extra_image_names = {
+ "left_wrist_0_rgb": "cam_left_wrist",
+ "right_wrist_0_rgb": "cam_right_wrist",
+ }
+ for dest, source in extra_image_names.items():
+ if source in in_images:
+ images[dest] = in_images[source]
+ image_masks[dest] = np.True_
+ else:
+ images[dest] = np.zeros_like(base_image)
+ image_masks[dest] = np.False_
+
+ inputs = {
+ "image": images,
+ "image_mask": image_masks,
+ "state": data["state"],
+ }
+
+ # Actions are only available during training.
+ if "actions" in data:
+ actions = np.asarray(data["actions"])
+ actions = _encode_actions_inv(actions, adapt_to_pi=self.adapt_to_pi)
+ inputs["actions"] = actions
+
+ if "prompt" in data:
+ inputs["prompt"] = data["prompt"]
+
+ return inputs
+
+
+@dataclasses.dataclass(frozen=True)
+class AlohaOutputs(transforms.DataTransformFn):
+ """Outputs for the Aloha policy."""
+
+ # If true, this will convert the joint and gripper values from the standard Aloha space to
+ # the space used by the pi internal runtime which was used to train the base model.
+ adapt_to_pi: bool = True
+
+ def __call__(self, data: dict) -> dict:
+ # Only return the first 14 dims.
+ actions = np.asarray(data["actions"][:, :14])
+ return {"actions": _encode_actions(actions, adapt_to_pi=self.adapt_to_pi)}
+
+
+def _joint_flip_mask() -> np.ndarray:
+ """Used to convert between aloha and pi joint angles."""
+ return np.array([1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1])
+
+
+def _normalize(x, min_val, max_val):
+ return (x - min_val) / (max_val - min_val)
+
+
+def _unnormalize(x, min_val, max_val):
+ return x * (max_val - min_val) + min_val
+
+
+def _gripper_to_angular(value):
+ # Aloha transforms the gripper positions into a linear space. The following code
+ # reverses this transformation to be consistent with pi0 which is pretrained in
+ # angular space.
+ #
+ # These values are coming from the Aloha code:
+ # PUPPET_GRIPPER_POSITION_OPEN, PUPPET_GRIPPER_POSITION_CLOSED
+ value = _unnormalize(value, min_val=0.01844, max_val=0.05800)
+
+ # This is the inverse of the angular to linear transformation inside the Interbotix code.
+ def linear_to_radian(linear_position, arm_length, horn_radius):
+ value = (horn_radius**2 + linear_position**2 - arm_length**2) / (2 * horn_radius * linear_position)
+ return np.arcsin(np.clip(value, -1.0, 1.0))
+
+ # The constants are taken from the Interbotix code.
+ value = linear_to_radian(value, arm_length=0.036, horn_radius=0.022)
+
+ # pi0 gripper data is normalized (0, 1) between encoder counts (2405, 3110).
+ # There are 4096 total encoder counts and aloha uses a zero of 2048.
+ # Converting this to radians means that the normalized inputs are between (0.5476, 1.6296)
+ return _normalize(value, min_val=0.5476, max_val=1.6296)
+
+
+def _gripper_from_angular(value):
+ # Convert from the gripper position used by pi0 to the gripper position that is used by Aloha.
+ # Note that the units are still angular but the range is different.
+
+ # We do not scale the output since the trossen model predictions are already in radians.
+ # See the comment in _gripper_to_angular for a derivation of the constant
+ value = value + 0.5476
+
+ # These values are coming from the Aloha code:
+ # PUPPET_GRIPPER_JOINT_OPEN, PUPPET_GRIPPER_JOINT_CLOSE
+ return _normalize(value, min_val=-0.6213, max_val=1.4910)
+
+
+def _gripper_from_angular_inv(value):
+ # Directly inverts the gripper_from_angular function.
+ value = _unnormalize(value, min_val=-0.6213, max_val=1.4910)
+ return value - 0.5476
+
+
+def _decode_aloha(data: dict, *, adapt_to_pi: bool = False) -> dict:
+ # state is [left_arm_joint_angles, left_arm_gripper, right_arm_joint_angles, right_arm_gripper]
+ # dim sizes: [6, 1, 6, 1]
+ state = np.asarray(data["state"])
+ state = _decode_state(state, adapt_to_pi=adapt_to_pi)
+
+ def convert_image(img):
+ img = np.asarray(img)
+ # Convert to uint8 if using float images.
+ if np.issubdtype(img.dtype, np.floating):
+ img = (255 * img).astype(np.uint8)
+ # Convert from [channel, height, width] to [height, width, channel].
+ return einops.rearrange(img, "c h w -> h w c")
+
+ images = data["images"]
+ images_dict = {name: convert_image(img) for name, img in images.items()}
+
+ data["images"] = images_dict
+ data["state"] = state
+ return data
+
+
+def _decode_state(state: np.ndarray, *, adapt_to_pi: bool = False) -> np.ndarray:
+ if adapt_to_pi:
+ # Flip the joints.
+ state = _joint_flip_mask() * state
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
+ state[[6, 13]] = _gripper_to_angular(state[[6, 13]])
+ return state
+
+
+def _encode_actions(actions: np.ndarray, *, adapt_to_pi: bool = False) -> np.ndarray:
+ if adapt_to_pi:
+ # Flip the joints.
+ actions = _joint_flip_mask() * actions
+ actions[:, [6, 13]] = _gripper_from_angular(actions[:, [6, 13]])
+ return actions
+
+
+def _encode_actions_inv(actions: np.ndarray, *, adapt_to_pi: bool = False) -> np.ndarray:
+ if adapt_to_pi:
+ actions = _joint_flip_mask() * actions
+ actions[:, [6, 13]] = _gripper_from_angular_inv(actions[:, [6, 13]])
+ return actions
diff --git a/openpi-umi/src/openpi/policies/droid_policy.py b/openpi-umi/src/openpi/policies/droid_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..666b7f76fecb2decacc60df09c577c086df76f1d
--- /dev/null
+++ b/openpi-umi/src/openpi/policies/droid_policy.py
@@ -0,0 +1,81 @@
+import dataclasses
+
+import einops
+import numpy as np
+
+from openpi import transforms
+from openpi.models import model as _model
+
+
+def make_droid_example() -> dict:
+ """Creates a random input example for the Droid policy."""
+ return {
+ "observation/exterior_image_1_left": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
+ "observation/wrist_image_left": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
+ "observation/joint_position": np.random.rand(7),
+ "observation/gripper_position": np.random.rand(1),
+ "prompt": "do something",
+ }
+
+
+def _parse_image(image) -> np.ndarray:
+ image = np.asarray(image)
+ if np.issubdtype(image.dtype, np.floating):
+ image = (255 * image).astype(np.uint8)
+ if image.shape[0] == 3:
+ image = einops.rearrange(image, "c h w -> h w c")
+ return image
+
+
+@dataclasses.dataclass(frozen=True)
+class DroidInputs(transforms.DataTransformFn):
+ # Determines which model will be used.
+ model_type: _model.ModelType
+
+ def __call__(self, data: dict) -> dict:
+ gripper_pos = np.asarray(data["observation/gripper_position"])
+ if gripper_pos.ndim == 0:
+ # Ensure gripper position is a 1D array, not a scalar, so we can concatenate with joint positions
+ gripper_pos = gripper_pos[np.newaxis]
+ state = np.concatenate([data["observation/joint_position"], gripper_pos])
+
+ # Possibly need to parse images to uint8 (H,W,C) since LeRobot automatically
+ # stores as float32 (C,H,W), gets skipped for policy inference
+ base_image = _parse_image(data["observation/exterior_image_1_left"])
+ wrist_image = _parse_image(data["observation/wrist_image_left"])
+
+ match self.model_type:
+ case _model.ModelType.PI0 | _model.ModelType.PI05:
+ names = ("base_0_rgb", "left_wrist_0_rgb", "right_wrist_0_rgb")
+ images = (base_image, wrist_image, np.zeros_like(base_image))
+ image_masks = (np.True_, np.True_, np.False_)
+ case _model.ModelType.PI0_FAST:
+ names = ("base_0_rgb", "base_1_rgb", "wrist_0_rgb")
+ # We don't mask out padding images for FAST models.
+ images = (base_image, np.zeros_like(base_image), wrist_image)
+ image_masks = (np.True_, np.True_, np.True_)
+ case _:
+ raise ValueError(f"Unsupported model type: {self.model_type}")
+
+ inputs = {
+ "state": state,
+ "image": dict(zip(names, images, strict=True)),
+ "image_mask": dict(zip(names, image_masks, strict=True)),
+ }
+
+ if "actions" in data:
+ inputs["actions"] = np.asarray(data["actions"])
+
+ if "prompt" in data:
+ if isinstance(data["prompt"], bytes):
+ data["prompt"] = data["prompt"].decode("utf-8")
+ inputs["prompt"] = data["prompt"]
+
+ return inputs
+
+
+@dataclasses.dataclass(frozen=True)
+class DroidOutputs(transforms.DataTransformFn):
+ def __call__(self, data: dict) -> dict:
+ # Only return the first 8 dims.
+ return {"actions": np.asarray(data["actions"][:, :8])}
diff --git a/openpi-umi/src/openpi/policies/libero_policy.py b/openpi-umi/src/openpi/policies/libero_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..10611f61bed1d7d3a9ca49e6ac455829fda9b61d
--- /dev/null
+++ b/openpi-umi/src/openpi/policies/libero_policy.py
@@ -0,0 +1,100 @@
+import dataclasses
+
+import einops
+import numpy as np
+
+from openpi import transforms
+from openpi.models import model as _model
+
+
+def make_libero_example() -> dict:
+ """Creates a random input example for the Libero policy."""
+ return {
+ "observation/state": np.random.rand(8),
+ "observation/image": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
+ "observation/wrist_image": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
+ "prompt": "do something",
+ }
+
+
+def _parse_image(image) -> np.ndarray:
+ image = np.asarray(image)
+ if np.issubdtype(image.dtype, np.floating):
+ image = (255 * image).astype(np.uint8)
+ if image.shape[0] == 3:
+ image = einops.rearrange(image, "c h w -> h w c")
+ return image
+
+
+@dataclasses.dataclass(frozen=True)
+class LiberoInputs(transforms.DataTransformFn):
+ """
+ This class is used to convert inputs to the model to the expected format. It is used for both training and inference.
+
+ For your own dataset, you can copy this class and modify the keys based on the comments below to pipe
+ the correct elements of your dataset into the model.
+ """
+
+ # Determines which model will be used.
+ # Do not change this for your own dataset.
+ model_type: _model.ModelType
+
+ def __call__(self, data: dict) -> dict:
+ # Possibly need to parse images to uint8 (H,W,C) since LeRobot automatically
+ # stores as float32 (C,H,W), gets skipped for policy inference.
+ # Keep this for your own dataset, but if your dataset stores the images
+ # in a different key than "observation/image" or "observation/wrist_image",
+ # you should change it below.
+ # Pi0 models support three image inputs at the moment: one third-person view,
+ # and two wrist views (left and right). If your dataset does not have a particular type
+ # of image, e.g. wrist images, you can comment it out here and replace it with zeros like we do for the
+ # right wrist image below.
+ base_image = _parse_image(data["observation/image"])
+ wrist_image = _parse_image(data["observation/wrist_image"])
+
+ # Create inputs dict. Do not change the keys in the dict below.
+ inputs = {
+ "state": data["observation/state"],
+ "image": {
+ "base_0_rgb": base_image,
+ "left_wrist_0_rgb": wrist_image,
+ # Pad any non-existent images with zero-arrays of the appropriate shape.
+ "right_wrist_0_rgb": np.zeros_like(base_image),
+ },
+ "image_mask": {
+ "base_0_rgb": np.True_,
+ "left_wrist_0_rgb": np.True_,
+ # We only mask padding images for pi0 model, not pi0-FAST. Do not change this for your own dataset.
+ "right_wrist_0_rgb": np.True_ if self.model_type == _model.ModelType.PI0_FAST else np.False_,
+ },
+ }
+
+ # Pad actions to the model action dimension. Keep this for your own dataset.
+ # Actions are only available during training.
+ if "actions" in data:
+ inputs["actions"] = data["actions"]
+
+ # Pass the prompt (aka language instruction) to the model.
+ # Keep this for your own dataset (but modify the key if the instruction is not
+ # stored in "prompt"; the output dict always needs to have the key "prompt").
+ if "prompt" in data:
+ inputs["prompt"] = data["prompt"]
+
+ return inputs
+
+
+@dataclasses.dataclass(frozen=True)
+class LiberoOutputs(transforms.DataTransformFn):
+ """
+ This class is used to convert outputs from the model back the the dataset specific format. It is
+ used for inference only.
+
+ For your own dataset, you can copy this class and modify the action dimension based on the comments below.
+ """
+
+ def __call__(self, data: dict) -> dict:
+ # Only return the first N actions -- since we padded actions above to fit the model action
+ # dimension, we need to now parse out the correct number of actions in the return dict.
+ # For Libero, we only return the first 7 actions (since the rest is padding).
+ # For your own dataset, replace `7` with the action dimension of your dataset.
+ return {"actions": np.asarray(data["actions"][:, :7])}
diff --git a/openpi-umi/src/openpi/policies/policy.py b/openpi-umi/src/openpi/policies/policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9b708bdcaffa086be4b22b84a29b8cc00c710e4
--- /dev/null
+++ b/openpi-umi/src/openpi/policies/policy.py
@@ -0,0 +1,135 @@
+from collections.abc import Sequence
+import logging
+import pathlib
+import time
+from typing import Any, TypeAlias
+
+import flax
+import flax.traverse_util
+import jax
+import jax.numpy as jnp
+import numpy as np
+from openpi_client import base_policy as _base_policy
+import torch
+from typing_extensions import override
+
+from openpi import transforms as _transforms
+from openpi.models import model as _model
+from openpi.shared import array_typing as at
+from openpi.shared import nnx_utils
+
+BasePolicy: TypeAlias = _base_policy.BasePolicy
+
+
+class Policy(BasePolicy):
+ def __init__(
+ self,
+ model: _model.BaseModel,
+ *,
+ rng: at.KeyArrayLike | None = None,
+ transforms: Sequence[_transforms.DataTransformFn] = (),
+ output_transforms: Sequence[_transforms.DataTransformFn] = (),
+ sample_kwargs: dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
+ pytorch_device: str = "cpu",
+ is_pytorch: bool = False,
+ ):
+ """Initialize the Policy.
+
+ Args:
+ model: The model to use for action sampling.
+ rng: Random number generator key for JAX models. Ignored for PyTorch models.
+ transforms: Input data transformations to apply before inference.
+ output_transforms: Output data transformations to apply after inference.
+ sample_kwargs: Additional keyword arguments to pass to model.sample_actions.
+ metadata: Additional metadata to store with the policy.
+ pytorch_device: Device to use for PyTorch models (e.g., "cpu", "cuda:0").
+ Only relevant when is_pytorch=True.
+ is_pytorch: Whether the model is a PyTorch model. If False, assumes JAX model.
+ """
+ self._model = model
+ self._input_transform = _transforms.compose(transforms)
+ self._output_transform = _transforms.compose(output_transforms)
+ self._sample_kwargs = sample_kwargs or {}
+ self._metadata = metadata or {}
+ self._is_pytorch_model = is_pytorch
+ self._pytorch_device = pytorch_device
+
+ if self._is_pytorch_model:
+ self._model = self._model.to(pytorch_device)
+ self._model.eval()
+ self._sample_actions = model.sample_actions
+ else:
+ # JAX model setup
+ self._sample_actions = nnx_utils.module_jit(model.sample_actions)
+ self._rng = rng or jax.random.key(0)
+
+ @override
+ def infer(self, obs: dict, *, noise: np.ndarray | None = None) -> dict: # type: ignore[misc]
+ # Make a copy since transformations may modify the inputs in place.
+ inputs = jax.tree.map(lambda x: x, obs)
+ inputs = self._input_transform(inputs)
+ if not self._is_pytorch_model:
+ # Make a batch and convert to jax.Array.
+ inputs = jax.tree.map(lambda x: jnp.asarray(x)[np.newaxis, ...], inputs)
+ self._rng, sample_rng_or_pytorch_device = jax.random.split(self._rng)
+ else:
+ # Convert inputs to PyTorch tensors and move to correct device
+ inputs = jax.tree.map(lambda x: torch.from_numpy(np.array(x)).to(self._pytorch_device)[None, ...], inputs)
+ sample_rng_or_pytorch_device = self._pytorch_device
+
+ # Prepare kwargs for sample_actions
+ sample_kwargs = dict(self._sample_kwargs)
+ if noise is not None:
+ noise = torch.from_numpy(noise).to(self._pytorch_device) if self._is_pytorch_model else jnp.asarray(noise)
+
+ if noise.ndim == 2: # If noise is (action_horizon, action_dim), add batch dimension
+ noise = noise[None, ...] # Make it (1, action_horizon, action_dim)
+ sample_kwargs["noise"] = noise
+
+ observation = _model.Observation.from_dict(inputs)
+ start_time = time.monotonic()
+ outputs = {
+ "state": inputs["state"],
+ "actions": self._sample_actions(sample_rng_or_pytorch_device, observation, **sample_kwargs),
+ }
+ model_time = time.monotonic() - start_time
+ if self._is_pytorch_model:
+ outputs = jax.tree.map(lambda x: np.asarray(x[0, ...].detach().cpu()), outputs)
+ else:
+ outputs = jax.tree.map(lambda x: np.asarray(x[0, ...]), outputs)
+
+ outputs = self._output_transform(outputs)
+ outputs["policy_timing"] = {
+ "infer_ms": model_time * 1000,
+ }
+ return outputs
+
+ @property
+ def metadata(self) -> dict[str, Any]:
+ return self._metadata
+
+
+class PolicyRecorder(_base_policy.BasePolicy):
+ """Records the policy's behavior to disk."""
+
+ def __init__(self, policy: _base_policy.BasePolicy, record_dir: str):
+ self._policy = policy
+
+ logging.info(f"Dumping policy records to: {record_dir}")
+ self._record_dir = pathlib.Path(record_dir)
+ self._record_dir.mkdir(parents=True, exist_ok=True)
+ self._record_step = 0
+
+ @override
+ def infer(self, obs: dict) -> dict: # type: ignore[misc]
+ results = self._policy.infer(obs)
+
+ data = {"inputs": obs, "outputs": results}
+ data = flax.traverse_util.flatten_dict(data, sep="/")
+
+ output_path = self._record_dir / f"step_{self._record_step}"
+ self._record_step += 1
+
+ np.save(output_path, np.asarray(data))
+ return results
diff --git a/openpi-umi/src/openpi/policies/policy_config.py b/openpi-umi/src/openpi/policies/policy_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad8554ba7cf9c968bfde378babf6ce8505279b64
--- /dev/null
+++ b/openpi-umi/src/openpi/policies/policy_config.py
@@ -0,0 +1,111 @@
+import logging
+import os
+import pathlib
+from typing import Any
+
+import jax.numpy as jnp
+
+import openpi.models.model as _model
+import openpi.policies.policy as _policy
+import openpi.shared.download as download
+import openpi.shared.normalize as _normalize
+from openpi.training import checkpoints as _checkpoints
+from openpi.training import config as _config
+import openpi.transforms as transforms
+
+
+def create_trained_policy(
+ train_config: _config.TrainConfig,
+ checkpoint_dir: pathlib.Path | str,
+ *,
+ repack_transforms: transforms.Group | None = None,
+ sample_kwargs: dict[str, Any] | None = None,
+ default_prompt: str | None = None,
+ norm_stats: dict[str, transforms.NormStats] | None = None,
+ norm_stats_path: pathlib.Path | str | None = None,
+ pytorch_device: str | None = None,
+) -> _policy.Policy:
+ """Create a policy from a trained checkpoint.
+
+ Args:
+ train_config: The training config to use to create the model.
+ checkpoint_dir: The directory to load the model from.
+ repack_transforms: Optional transforms that will be applied before any other transforms.
+ sample_kwargs: The kwargs to pass to the `sample_actions` method. If not provided, the default
+ kwargs will be used.
+ default_prompt: The default prompt to use for the policy. Will inject the prompt into the input
+ data if it doesn't already exist.
+ norm_stats: The norm stats to use for the policy. If not provided, the norm stats will be loaded
+ from the checkpoint directory.
+ norm_stats_path: Direct path to norm_stats.json file. If provided, will load norm stats from this
+ path instead of from the checkpoint directory. Takes precedence over norm_stats parameter.
+ pytorch_device: Device to use for PyTorch models (e.g., "cpu", "cuda", "cuda:0").
+ If None and is_pytorch=True, will use "cuda" if available, otherwise "cpu".
+
+ Note:
+ The function automatically detects whether the model is PyTorch-based by checking for the
+ presence of "model.safensors" in the checkpoint directory.
+ """
+ repack_transforms = repack_transforms or transforms.Group()
+ checkpoint_dir = download.maybe_download(str(checkpoint_dir))
+
+ # Check if this is a PyTorch model by looking for model.safetensors
+ weight_path = os.path.join(checkpoint_dir, "model.safetensors")
+ is_pytorch = os.path.exists(weight_path)
+
+ logging.info("Loading model...")
+ if is_pytorch:
+ model = train_config.model.load_pytorch(train_config, weight_path)
+ model.paligemma_with_expert.to_bfloat16_for_selected_params("bfloat16")
+ else:
+ model = train_config.model.load(_model.restore_params(checkpoint_dir / "params", dtype=jnp.bfloat16))
+ data_config = train_config.data.create(train_config.assets_dirs, train_config.model)
+
+ # Load norm_stats with priority: norm_stats_path > norm_stats > checkpoint/assets
+ if norm_stats_path is not None:
+ # Load from explicitly specified path
+ norm_stats_path = pathlib.Path(norm_stats_path)
+ if norm_stats_path.is_file():
+ # If it's a file (e.g., norm_stats.json), load directly
+ norm_stats = _normalize.deserialize_json(norm_stats_path.read_text())
+ logging.info(f"Loaded norm stats from: {norm_stats_path}")
+ else:
+ # If it's a directory, look for norm_stats.json inside
+ norm_stats = _normalize.load(norm_stats_path)
+ logging.info(f"Loaded norm stats from directory: {norm_stats_path}")
+ elif norm_stats is None:
+ # We are loading the norm stats from the checkpoint instead of the config assets dir to make sure
+ # that the policy is using the same normalization stats as the original training process.
+ if data_config.asset_id is None:
+ raise ValueError("Asset id is required to load norm stats.")
+ norm_stats = _checkpoints.load_norm_stats(checkpoint_dir / "assets", data_config.asset_id)
+
+ # Determine the device to use for PyTorch models
+ if is_pytorch and pytorch_device is None:
+ try:
+ import torch
+
+ pytorch_device = "cuda" if torch.cuda.is_available() else "cpu"
+ except ImportError:
+ pytorch_device = "cpu"
+
+ return _policy.Policy(
+ model,
+ transforms=[
+ *repack_transforms.inputs,
+ transforms.InjectDefaultPrompt(default_prompt),
+ *data_config.data_transforms.inputs,
+ transforms.Normalize(norm_stats, use_quantiles=data_config.use_quantile_norm),
+ *data_config.model_transforms.inputs,
+ ],
+ output_transforms=[
+ *data_config.model_transforms.outputs,
+ transforms.Unnormalize(norm_stats, use_quantiles=data_config.use_quantile_norm),
+ *data_config.data_transforms.outputs,
+ *repack_transforms.outputs,
+ ],
+ sample_kwargs=sample_kwargs,
+ metadata=train_config.policy_metadata,
+ is_pytorch=is_pytorch,
+ pytorch_device=pytorch_device if is_pytorch else None,
+ )
diff --git a/openpi-umi/src/openpi/policies/policy_test.py b/openpi-umi/src/openpi/policies/policy_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..5808e5274a9d19384d4277ccbde113926da65a50
--- /dev/null
+++ b/openpi-umi/src/openpi/policies/policy_test.py
@@ -0,0 +1,34 @@
+from openpi_client import action_chunk_broker
+import pytest
+
+from openpi.policies import aloha_policy
+from openpi.policies import policy_config as _policy_config
+from openpi.training import config as _config
+
+
+@pytest.mark.manual
+def test_infer():
+ config = _config.get_config("pi0_aloha_sim")
+ policy = _policy_config.create_trained_policy(config, "gs://openpi-assets/checkpoints/pi0_aloha_sim")
+
+ example = aloha_policy.make_aloha_example()
+ result = policy.infer(example)
+
+ assert result["actions"].shape == (config.model.action_horizon, 14)
+
+
+@pytest.mark.manual
+def test_broker():
+ config = _config.get_config("pi0_aloha_sim")
+ policy = _policy_config.create_trained_policy(config, "gs://openpi-assets/checkpoints/pi0_aloha_sim")
+
+ broker = action_chunk_broker.ActionChunkBroker(
+ policy,
+ # Only execute the first half of the chunk.
+ action_horizon=config.model.action_horizon // 2,
+ )
+
+ example = aloha_policy.make_aloha_example()
+ for _ in range(config.model.action_horizon):
+ outputs = broker.infer(example)
+ assert outputs["actions"].shape == (14,)
diff --git a/openpi-umi/src/openpi/py.typed b/openpi-umi/src/openpi/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/openpi-umi/src/openpi/serving/websocket_policy_server.py b/openpi-umi/src/openpi/serving/websocket_policy_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdefa98b879323aca449550bf1985ae877eddd83
--- /dev/null
+++ b/openpi-umi/src/openpi/serving/websocket_policy_server.py
@@ -0,0 +1,90 @@
+import asyncio
+import http
+import logging
+import time
+import traceback
+
+from openpi_client import base_policy as _base_policy
+from openpi_client import msgpack_numpy
+import websockets.asyncio.server as _server
+import websockets.frames
+
+logger = logging.getLogger(__name__)
+
+
+class WebsocketPolicyServer:
+ """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
+
+ Currently only implements the `load` and `infer` methods.
+ """
+
+ def __init__(
+ self,
+ policy: _base_policy.BasePolicy,
+ host: str = "0.0.0.0",
+ port: int | None = None,
+ metadata: dict | None = None,
+ ) -> None:
+ self._policy = policy
+ self._host = host
+ self._port = port
+ self._metadata = metadata or {}
+ logging.getLogger("websockets.server").setLevel(logging.INFO)
+
+ def serve_forever(self) -> None:
+ asyncio.run(self.run())
+
+ async def run(self):
+ async with _server.serve(
+ self._handler,
+ self._host,
+ self._port,
+ compression=None,
+ max_size=None,
+ process_request=_health_check,
+ ) as server:
+ await server.serve_forever()
+
+ async def _handler(self, websocket: _server.ServerConnection):
+ logger.info(f"Connection from {websocket.remote_address} opened")
+ packer = msgpack_numpy.Packer()
+
+ await websocket.send(packer.pack(self._metadata))
+
+ prev_total_time = None
+ while True:
+ try:
+ start_time = time.monotonic()
+ obs = msgpack_numpy.unpackb(await websocket.recv())
+
+ infer_time = time.monotonic()
+ action = self._policy.infer(obs)
+ infer_time = time.monotonic() - infer_time
+
+ action["server_timing"] = {
+ "infer_ms": infer_time * 1000,
+ }
+ if prev_total_time is not None:
+ # We can only record the last total time since we also want to include the send time.
+ action["server_timing"]["prev_total_ms"] = prev_total_time * 1000
+
+ await websocket.send(packer.pack(action))
+ prev_total_time = time.monotonic() - start_time
+
+ except websockets.ConnectionClosed:
+ logger.info(f"Connection from {websocket.remote_address} closed")
+ break
+ except Exception:
+ await websocket.send(traceback.format_exc())
+ await websocket.close(
+ code=websockets.frames.CloseCode.INTERNAL_ERROR,
+ reason="Internal server error. Traceback included in previous frame.",
+ )
+ raise
+
+
+def _health_check(connection: _server.ServerConnection, request: _server.Request) -> _server.Response | None:
+ if request.path == "/healthz":
+ return connection.respond(http.HTTPStatus.OK, "OK\n")
+ # Continue with the normal request handling.
+ return None
diff --git a/openpi-umi/src/openpi/shared/__init__.py b/openpi-umi/src/openpi/shared/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/openpi-umi/src/openpi/shared/array_typing.py b/openpi-umi/src/openpi/shared/array_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..569eafef1401d4a34b0289c0efb2125f71d21dfb
--- /dev/null
+++ b/openpi-umi/src/openpi/shared/array_typing.py
@@ -0,0 +1,89 @@
+import contextlib
+import functools as ft
+import inspect
+from typing import TypeAlias, TypeVar, cast
+
+import beartype
+import jax
+import jax._src.tree_util as private_tree_util
+import jax.core
+from jaxtyping import ArrayLike
+from jaxtyping import Bool # noqa: F401
+from jaxtyping import DTypeLike # noqa: F401
+from jaxtyping import Float
+from jaxtyping import Int # noqa: F401
+from jaxtyping import Key # noqa: F401
+from jaxtyping import Num # noqa: F401
+from jaxtyping import PyTree
+from jaxtyping import Real # noqa: F401
+from jaxtyping import UInt8 # noqa: F401
+from jaxtyping import config
+from jaxtyping import jaxtyped
+import jaxtyping._decorator
+import torch
+
+# patch jaxtyping to handle https://github.com/patrick-kidger/jaxtyping/issues/277.
+# the problem is that custom PyTree nodes are sometimes initialized with arbitrary types (e.g., `jax.ShapeDtypeStruct`,
+# `jax.Sharding`, or even