mxk1998 commited on
Commit
a25598f
·
verified ·
1 Parent(s): e33e274

Release PILOT RoboCasa-GR1 340000 checkpoint and reproducibility bundle

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +9 -3
  2. ARCHIVES.md +0 -28
  3. LICENSE.md +20 -0
  4. LICENSES/Apache-2.0.txt +201 -0
  5. LICENSES/NVIDIA-Open-Model-License.html +43 -0
  6. third_party/robocasa/LICENSE → LICENSES/OpenVLA-MIT.txt +1 -8
  7. LICENSES/StarVLA-MIT.txt +24 -0
  8. Makefile +0 -23
  9. NOTICE +11 -0
  10. README.md +158 -141
  11. README_HF.md +177 -0
  12. README_dinov3.md +0 -882
  13. README_starVLA.md +0 -446
  14. THIRD_PARTY_NOTICES.md +55 -25
  15. TRAINING_PROVENANCE.md +0 -54
  16. VALIDATION.md +0 -222
  17. archives/simulation_assets.manifest.json +0 -11
  18. archives/simulation_assets.tar.gz +2 -2
  19. checkpoints/README.md +0 -9
  20. checkpoints/{steps_280000_pytorch_model.pt → steps_340000_pytorch_model.pt} +2 -2
  21. {provenance/training → configs}/dataset_statistics.json +109 -109
  22. provenance/training/config.yaml → configs/pilot_340000.yaml +28 -22
  23. deployment/model_server/README.md +0 -22
  24. deployment/model_server/server_policy.py +0 -70
  25. deployment/model_server/tools/debug_server_policy.py +0 -4
  26. deployment/model_server/tools/image_tools.py +1 -1
  27. deployment/model_server/tools/websocket_policy_client.py +6 -9
  28. deployment/model_server/tools/websocket_policy_server.py +4 -11
  29. deployment/readme-deployment.md +0 -11
  30. deployment/real_infer/open_loop_eval.py +0 -315
  31. deployment/real_infer/server.py +0 -332
  32. deployment/upload/push_model_to_hf.py +0 -12
  33. deployment_robotwin/model_server/README.md +0 -22
  34. deployment_robotwin/model_server/server_policy.py +0 -91
  35. deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_client-checkpoint.py +0 -149
  36. deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_server-checkpoint.py +0 -207
  37. deployment_robotwin/model_server/tools/debug_server_policy.py +0 -91
  38. deployment_robotwin/model_server/tools/image_tools.py +0 -119
  39. deployment_robotwin/model_server/tools/msgpack_numpy.py +0 -57
  40. deployment_robotwin/model_server/tools/websocket_policy_client.py +0 -149
  41. deployment_robotwin/model_server/tools/websocket_policy_server.py +0 -207
  42. deployment_robotwin/readme-deployment.md +0 -11
  43. deployment_robotwin/real_infer/open_loop_eval.py +0 -418
  44. deployment_robotwin/real_infer/server.py +0 -375
  45. deployment_robotwin/upload/push_model_to_hf.py +0 -12
  46. docs/EVALUATION.md +142 -0
  47. docs/TRAINING.md +125 -0
  48. docs/VALIDATION.md +63 -0
  49. docs/WM4A.md +0 -154
  50. docs/assets/method.svg +0 -0
.gitignore CHANGED
@@ -1,7 +1,13 @@
1
- .runtime/
2
  __pycache__/
3
  *.pyc
 
 
4
  .DS_Store
5
- .env
6
- *.token
7
  .cache/
 
 
 
 
 
 
 
1
  __pycache__/
2
  *.pyc
3
+ *.partial
4
+ *.log
5
  .DS_Store
6
+ ._*
7
+ .runtime/
8
  .cache/
9
+ .venv/
10
+ outputs/
11
+ .env
12
+ .env.*
13
+ LOCAL_STATUS.md
ARCHIVES.md DELETED
@@ -1,28 +0,0 @@
1
- # Simulator Asset Archive
2
-
3
- Run from the downloaded repository root, before environment setup or evaluation:
4
-
5
- ```bash
6
- python tools/unpack_simulation_assets.py
7
- python tools/unpack_simulation_assets.py --verify-only
8
- ```
9
-
10
- The archive contains exactly 44,901 files (9,569,959,833 expanded bytes).
11
- Compressed size: 4,528,296,178 bytes.
12
-
13
- Archive SHA256: `bb84af93bf7fb93afa1068f1532321e473e70bf4dc6e09c8406bff4e8d8f3987`.
14
-
15
- Paths and content are identical to the pinned customized RoboCasa/RoboSuite
16
- release. Compression changes storage only, not simulator code or assets.
17
- The extractor checks the archive hash and every asset hash, rejects links
18
- and traversal paths, and never overwrites modified files. An interrupted
19
- extraction can be rerun; matching existing assets are retained.
20
-
21
- `provenance/simulation_assets.sha256.json` seals expanded asset content.
22
- `provenance/publication/files.sha256.json` inventories the compressed Hub
23
- representation and excludes itself. Keep the archive until extraction
24
- passes. Allow disk space for both compressed and expanded assets, the
25
- checkpoint, environments, and reconstructed runtime backbone weights.
26
-
27
- Compression/extraction verification is not a model-effectiveness test.
28
- All reproduction limitations in `VALIDATION.md` remain applicable.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
LICENSE.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Component-Specific Licensing
2
+
3
+ This repository does not impose a single replacement license on all
4
+ source code, pretrained weights, and simulation assets.
5
+
6
+ - Source files retain their existing copyright and license headers,
7
+ including MIT and Apache-2.0 notices.
8
+ - Complete standalone upstream texts are provided in `LICENSES/`.
9
+ `NOTICE` contains the NVIDIA Cosmos attribution.
10
+ - VJEPA2 source license texts are retained in
11
+ `starVLA/facebookresearch_vjepa2_main/`.
12
+ - RoboCasa, RoboSuite, KDL, PyKDL, and their bundled dependencies retain
13
+ their original license texts and notices in `third_party/`.
14
+ - Pretrained-model terms and robot/object-asset terms remain applicable.
15
+ Access to a private reproducibility snapshot is not a declaration that
16
+ every component may be redistributed commercially or relicensed.
17
+
18
+ See `THIRD_PARTY_NOTICES.md` for component boundaries. Preserve these
19
+ notices when sharing permitted copies. Review the original model and
20
+ asset terms before making a private resource repository public.
LICENSES/Apache-2.0.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2018-2021 William Falcon
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
LICENSES/NVIDIA-Open-Model-License.html ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><title>NVIDIA Open Model License</title></head><body><h1>NVIDIA Open Model License</h1>
2
+ <p>This NVIDIA Open Model License Agreement (the “<u>Agreement</u>”) is a legal agreement between the Legal Entity You represent, or if no entity is identified, You and NVIDIA Corporation and its Affiliates (“<u>NVIDIA</u>”) and governs Your use of the Models that NVIDIA provides to You under this Agreement. NVIDIA and You are each a “<u>party</u>” and collectively the “<u>parties</u>.”</p>
3
+ <p>NVIDIA models released under this Agreement are intended to be used permissively and enable the further development of AI technologies. Subject to the terms of this Agreement, NVIDIA confirms that:</p>
4
+ <ul>
5
+ <li>Models are commercially usable.</li>
6
+ <li>You are free to create and distribute Derivative Models.</li>
7
+ <li>NVIDIA does not claim ownership to any outputs generated using the Models or Derivative Models.</li>
8
+ </ul>
9
+ <p>By using, reproducing, modifying, distributing, performing or displaying any portion or element of the Model or Derivative Model, or otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement.</p>
10
+ <ol>
11
+ <li><p><strong>Definitions.</strong> The following definitions apply to this Agreement:</p>
12
+ <ol>
13
+ <li><p>"<u>Derivative Model</u>" means all (a) modifications to the Model, (b) works based on the Model, and (c) any other derivative works of the Model. An output is not a Derivative Model.</p> </li>
14
+ <li><p>"<u>Legal Entity</u>" means 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, "<u>control</u>" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of fifty percent (50%) or more of the outstanding shares, or (c) beneficial ownership of such entity.</p> </li>
15
+ <li><p>“<u>Model</u>” means the machine learning model, software, checkpoints, learnt weights, algorithms, parameters, configuration files and documentation shared under this Agreement.</p> </li>
16
+ <li><p>"<u>NVIDIA Cosmos Model</u>" means a multimodal Model shared under this Agreement</p> </li>
17
+ <li><p>"<u>Special-Purpose Model</u>" means a Model that is only competent in a narrow set of purpose-specific tasks and should not be used for unintended or general-purpose applications</p> </li>
18
+ <li><p>“<u>You</u>” or “<u>Your</u>” means an individual or Legal Entity exercising permissions granted by this Agreement.</p> </li>
19
+ </ol> </li>
20
+ <li><p><strong>Conditions for Use, License Grant, AI Ethics and IP Ownership.</strong></p>
21
+ <ol>
22
+ <li><p>Conditions for Use. The Model and any Derivative Model are subject to additional terms as described in Section&nbsp;2 and Section&nbsp;3 of this Agreement and govern Your use. If You institute copyright or patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model or a Derivative Model constitutes direct or contributory copyright or patent infringement, then any licenses granted to You under this Agreement for that Model or Derivative Model will terminate as of the date such litigation is filed. If You bypass, disable, reduce the efficacy of, or circumvent any technical limitation, safety guardrail or associated safety guardrail hyperparameter, encryption, security, digital rights management, or authentication mechanism (collectively “<u>Guardrail</u>”)&nbsp;contained in the Model without a substantially similar Guardrail appropriate for your use case, your rights under this Agreement will automatically terminate. NVIDIA may indicate in relevant documentation that a Model is a Special-Purpose Model. NVIDIA may update this Agreement to comply with legal and regulatory requirements at any time and You agree to either comply with any updated license or cease Your copying, use, and distribution of the Model and any Derivative Model.</p> </li>
23
+ <li><p>License Grant. The rights granted herein are explicitly conditioned on Your full compliance with the terms of this Agreement. Subject to the terms and conditions of this Agreement, NVIDIA hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, revocable (as stated in Section 2.1) license to publicly perform, publicly display, reproduce, use, create derivative works of, make, have made, sell, offer for sale, distribute (through multiple tiers of distribution) and import the Model.</p> </li>
24
+ <li><p>AI Ethics. Use of the Models under the Agreement must be consistent with NVIDIA’s Trustworthy AI terms found at <a href="https://www.nvidia.com/en-us/agreements/trustworthy-ai/terms/">https://www.nvidia.com/en-us/agreements/trustworthy-ai/terms/</a>.</p> </li>
25
+ <li><p>NVIDIA owns the Model and any Derivative Models&nbsp;created by NVIDIA. Subject to NVIDIA’s underlying ownership rights in the Model or its Derivative Models, You are and will be the owner of Your Derivative Models. NVIDIA claims no ownership rights in outputs. You are responsible for outputs and their subsequent uses. Except as expressly granted in this Agreement, (a) NVIDIA reserves all rights, interests and remedies in connection with the Model and (b) no other license or right is granted to you by implication, estoppel or otherwise.</p> </li>
26
+ </ol> </li>
27
+ <li><p><strong>Redistribution.</strong> You may reproduce and distribute copies of the Model or Derivative Models thereof in any medium, with or without modifications, provided that You meet the following conditions:</p>
28
+ <ol>
29
+ <li><p>If you distribute the Model, You must give any other recipients of the Model a copy of this Agreement and include the following attribution notice within a “Notice” text file with such copies: “Licensed by NVIDIA Corporation under the NVIDIA Open Model License”;</p> </li>
30
+ <li><p>If you distribute or make available a NVIDIA Cosmos Model, or a product or service (including an AI model) that contains or uses a NVIDIA Cosmos Model, use a NVIDIA Cosmos Model to create a Derivative Model, or use a NVIDIA Cosmos Model or its outputs to create, train, fine tune, or otherwise improve an AI model, you will include “Built on NVIDIA Cosmos” on a related website, user interface, blogpost, about page, or product documentation; and</p> </li>
31
+ <li><p>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 Models as a whole, provided Your use, reproduction, and distribution of the Model otherwise complies with the conditions stated in this Agreement.</p> </li>
32
+ </ol> </li>
33
+ <li><p><strong>Separate Components.</strong> The Models may include or be distributed with components provided with separate legal notices or terms that accompany the components, such as an Open Source Software License or other third-party license. The components are subject to the applicable other licenses, including any proprietary notices, disclaimers, requirements and extended use rights; except that this Agreement will prevail regarding the use of third-party Open Source Software License, unless a third-party Open Source Software License requires its license terms to prevail. “<u>Open Source Software License</u>” means any software, data or documentation subject to any license identified as an open source license by the Open Source Initiative (<a href="https://opensource.org/" target="_blank">https://opensource.org</a>), Free Software Foundation (<a href="https://www.fsf.org/" target="_blank">https://www.fsf.org</a>) or other similar open source organization or listed by the Software Package Data Exchange (SPDX) Workgroup under the Linux Foundation (<a href="https://www.spdx.org/" target="_blank">https://www.spdx.org</a>).<br> </p> </li>
34
+ <li><p><strong>Trademarks.</strong> This Agreement does not grant permission to use the trade names, trademarks, service marks, or product names of NVIDIA, except as required for reasonable and customary use in describing the origin of the Model and reproducing the content of the “Notice” text file.<br> </p> </li>
35
+ <li><p><strong>Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, NVIDIA provides the Model 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 reviewing Model documentation, including any Special-Purpose Model limitations, and determining the appropriateness of using or redistributing the Model, Derivative Models and outputs. You assume any risks associated with Your exercise of permissions under this Agreement.</strong></p> </li>
36
+ <li><p><strong>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, will NVIDIA be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this Agreement or out of the use or inability to use the Model, Derivative Models or outputs (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 NVIDIA has been advised of the possibility of such damages.</strong></p> </li>
37
+ <li><p><strong>Indemnity.</strong> You will indemnify and hold harmless NVIDIA from and against any claim by any third party arising out of or related to your use or distribution of the Model, Derivative Models&nbsp;or outputs.</p> </li>
38
+ <li><p><strong>Feedback.</strong> NVIDIA appreciates your feedback, and You agree that NVIDIA may use it without restriction or compensation to You.</p> </li>
39
+ <li><p><strong>Governing Law.</strong> This Agreement will be governed in all respects by the laws of the United States and the laws of the State of Delaware, without regard to conflict of laws principles or the United Nations Convention on Contracts for the International Sale of Goods. The state and federal courts residing in Santa Clara County, California will have exclusive jurisdiction over any dispute or claim arising out of or related to this Agreement, and the parties irrevocably consent to personal jurisdiction and venue in those courts; except that, either party may apply for injunctive remedies or an equivalent type of urgent legal relief in any jurisdiction.</p> </li>
40
+ <li><p><strong>Trade and Compliance.</strong> You agree to comply with all applicable export, import, trade and economic sanctions laws and regulations, as amended, including without limitation U.S. Export Administration Regulations and Office of Foreign Assets Control regulations. These laws include restrictions on destinations, end-users and end-use.</p> </li>
41
+ </ol>
42
+ <p>Version Release Date: October 24, 2025</p>
43
+ </body></html>
third_party/robocasa/LICENSE → LICENSES/OpenVLA-MIT.txt RENAMED
@@ -1,6 +1,6 @@
1
  MIT License
2
 
3
- Copyright (c) 2025 the NVIDIA GEAR group
4
 
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
  of this software and associated documentation files (the "Software"), to deal
@@ -19,10 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
  SOFTWARE.
22
-
23
- This software includes the partial implementation of Deepmind Mujoco https://github.com/deepmind/mujoco.
24
- Deepmind Mujoco is licensed under the Apache License, Version 2.0 (the "License");
25
- you may not use the files except in compliance with the License.
26
-
27
- You may obtain a copy of the License at
28
- http://www.apache.org/licenses/LICENSE-2.0
 
1
  MIT License
2
 
3
+ Copyright (c) 2024 Moo Jin Kim, Karl Pertsch, Siddharth Karamcheti.
4
 
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
  of this software and associated documentation files (the "Software"), to deal
 
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
  SOFTWARE.
 
 
 
 
 
 
 
LICENSES/StarVLA-MIT.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) StarVLA Team.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ Rebases are allowed for forks and feature branches. When rebasing from upstream StarVLA, use descriptive commit messages, e.g., "chore: clone from StarVLA".
16
+ Preserve attribution: keep at least the two latest upstream StarVLA commits as separate.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE
Makefile DELETED
@@ -1,23 +0,0 @@
1
- .PHONY: help clean check autoformat
2
- .DEFAULT: help
3
-
4
- # Generates a useful overview/help message for various make features - add to this as necessary!
5
- help:
6
- @echo "make clean"
7
- @echo " Remove all temporary pyc/pycache files"
8
- @echo "make check"
9
- @echo " Run code style and linting (black, ruff) *without* changing files!"
10
- @echo "make autoformat"
11
- @echo " Run code styling (black, ruff) and update in place - committing with pre-commit also does this."
12
-
13
- clean:
14
- find . -name "*.pyc" | xargs rm -f && \
15
- find . -name "__pycache__" | xargs rm -rf
16
-
17
- check:
18
- black --check .
19
- ruff check --show-source .
20
-
21
- autoformat:
22
- black .
23
- ruff check --fix --show-fixes .
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
NOTICE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PILOT
2
+
3
+ Built on NVIDIA Cosmos
4
+
5
+ Licensed by NVIDIA Corporation under the NVIDIA Open Model License
6
+
7
+ This research artifact includes adapted model and training code, a
8
+ RoboCasa-GR1 policy fine-tuned from pretrained components, and separate
9
+ third-party simulator resources. It is not an official NVIDIA release.
10
+ The upstream license agreements and source notices remain applicable.
11
+ See LICENSE.md, LICENSES/, and THIRD_PARTY_NOTICES.md.
README.md CHANGED
@@ -1,160 +1,177 @@
1
- # WM4A: RoboCasa Reproducibility Snapshot
2
-
3
- Private reproducibility release for `cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10`.
4
- Target repository: `mxk1998/WM4A`. No token or credential is bundled.
5
-
6
- ## Selected Result
7
-
8
- | Checkpoint | Historical successes | Historical mean |
9
- | --- | --- | --- |
10
- | `steps_280000_pytorch_model.pt` | 674/1200 | 56.17% |
11
-
12
- The historical benchmark uses 24 tasks, 50 episodes per task, one environment,
13
- 720 maximum simulator steps, 12 actions per policy call, and shift 5.0.
14
- The historical top-level inference argument is 5; the action head uses its
15
- saved 20 diffusion steps, independently of that argument.
16
- Original CSVs and logs are under `provenance/evaluation/`; the reference run
17
- is `wm_eval_20260703_054735`. These are historical measurements, not a claim
18
- that a new migration smoke test reproduced the full benchmark.
19
-
20
- See `VALIDATION.md` for the exact current validation level.
21
- The September 26 (Asia/Shanghai) rerun was stopped after 0/50 on the first
22
- task. Open-loop source-path A/B predictions match exactly, but the historical
23
- closed-loop success rate is not yet reproduced. Do not treat this release
24
- as validated for benchmark reproduction.
25
-
26
- The controlled follow-up reproduced one original demonstration using both
27
- recorded joint actions and recorded EE actions through the real client/IK.
28
- The model still failed from the same initial simulator state. Precision and
29
- IK ablations did not recover success; detailed traces and scripts are under
30
- `provenance/validation/wm4a_followup_20260925T170412Z/`.
31
-
32
- Further conditioning tests found no disconnected image, language, or state
33
- input path. Six-step replanning still failed, including one episode with zero
34
- IK residual misses. Model actions conditioned on the complete recorded
35
- demonstration also failed over its 228 transitions. No fix was promoted.
36
- See `provenance/validation/wm4a_conditioning_20260925T175334Z/REPORT.md`.
37
-
38
- Action-component diagnostics then restored this one demonstration by replacing
39
- only predicted EE XYZ with recorded targets, but not by replacing only rotations
40
- or hands. Four non-oracle-action changes (sampling mean, 80 integration steps,
41
- training state casting, and full training inputs) all failed recorded-input
42
- replay. The current 24-dataset min/max statistics match the pinned statistics.
43
- This narrows the investigation, but does not establish the historical regression's
44
- cause or a deployable fix. See
45
- `provenance/validation/wm4a_action_components_20260925T184142Z/REPORT.md`.
46
-
47
- ## What Is Portable
48
-
49
- This repository includes policy and training source, model/tokenizer metadata,
50
- the customized historical RoboCasa/RoboSuite source and assets, GR1 retarget
51
- code and URDF, run-saved configuration/statistics, and provenance hashes.
52
- Original README is preserved at `provenance/original_paths/README.md`.
53
- Do not replace the vendored simulator with an arbitrary recent installation.
54
-
55
- The Mac copy is a source/resource archive. Evaluation requires Linux x86_64,
56
- NVIDIA CUDA, and EGL rendering. Native macOS/MPS execution is not supported or
57
- claimed. Policy and simulation run in separate Python 3.10 environments.
58
-
59
- ## Checkpoint
60
-
61
- Filename: `checkpoints/steps_280000_pytorch_model.pt`
62
-
63
- Bytes: 24232783701
 
64
 
65
  SHA-256:
66
- `eeba9505f715b582a054baac1ef5b599f1da225cabcc060631c23f2f47affe6c`
67
 
68
- This private release includes the selected checkpoint at the path above.
69
- Its original source and pinned hash are recorded in `release_manifest.json`.
70
- A source-only Git clone without large-file contents cannot run inference.
71
-
72
- ## Download
73
 
74
- Authenticate with an account that has access to this private repository.
75
- Run the following on the Linux CUDA evaluation machine:
76
 
77
  ```bash
78
  python -m pip install huggingface_hub
79
  hf auth login
80
- hf download mxk1998/WM4A --local-dir WM4A
81
- cd WM4A
82
- python tools/unpack_simulation_assets.py
 
 
 
 
 
 
 
 
 
83
  ```
84
 
85
- The 44,901 customized simulator asset files are stored in
86
- `archives/simulation_assets.tar.gz`, not as individual Hub files. The
87
- command above verifies the archive and restores every original path with
88
- per-file SHA256 validation. It uses only the Python standard library,
89
- refuses modified existing assets, and needs about 9.57 GB of additional
90
- disk space for extraction. See `ARCHIVES.md` for details.
91
-
92
- The download also includes model metadata. Keep the
93
- repository structure intact. Source and asset integrity can be checked with
94
- `python -m release.verify --assets`; `release.prepare` additionally verifies
95
- the full checkpoint hash. See `provenance/publication/files.sha256.json` for
96
- the publication file inventory. The inventory excludes itself.
97
 
98
- ## Evaluation
99
 
100
- Run from this repository's root on a Linux CUDA machine:
 
101
 
102
  ```bash
103
- bash environment/create_linux_envs.sh /absolute/new/envs
104
- export POLICY_PYTHON=/absolute/new/envs/policy/bin/python
105
- export SIM_PYTHON=/absolute/new/envs/simulation/bin/python
106
-
107
- "$POLICY_PYTHON" -m release.doctor --role policy
108
- "$SIM_PYTHON" -m release.doctor --role simulation
109
- "$POLICY_PYTHON" -m release.verify --assets
110
- "$POLICY_PYTHON" -m release.prepare \
111
- --checkpoint checkpoints/steps_280000_pytorch_model.pt
112
-
113
- # Choose a GPU assigned to you, after inspecting current use.
114
  "$POLICY_PYTHON" -m release.evaluate \
115
- --gpus 0 --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
116
- --episodes 1 \
117
- --task gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env
 
 
118
 
119
- # Full historical task/episode counts:
120
  "$POLICY_PYTHON" -m release.evaluate \
121
- --gpus 0 --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
122
- --episodes 50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  ```
124
 
125
- The first GPU ID is only an example, not a reservation. Up to two explicitly
126
- allocated GPUs may be passed as `--gpus 0,1` to distribute tasks. Never run the
127
- old batch launchers unchanged: they contain machine-specific paths and process
128
- cleanup behavior that is unsuitable for shared servers.
129
-
130
- `release.prepare` verifies the checkpoint and reconstructs backbone loading
131
- files from its complete state dictionary. It does not download a newer base
132
- model. Allow approximately another checkpoint's size for `.runtime/backbones`
133
- and ample host RAM (128 GiB recommended for the larger model). The launcher
134
- requires 42 GiB free per selected GPU, including headroom, and
135
- caps policy allocations at 34 GiB. The tested hardware is H200;
136
- smaller-GPU compatibility has not been validated.
137
-
138
- The launcher binds loopback ports, rejects occupied ports, records GPU/PID
139
- ownership, and stops only its own process groups. It writes per-task episode
140
- outcomes, finite-action traces, logs, and aggregate `summary.csv` /
141
- `summary.json` under `.runtime/evaluations/`.
142
- `--no-video` skips video encoding but leaves future-image model inference
143
- unchanged. `EGL_LIBRARY_PATH` can select the host's NVIDIA EGL libraries.
144
-
145
- The old scripts printed seed 7 without applying it to policy or simulation.
146
- Default evaluation preserves this unseeded behavior. `--seed N` applies a new
147
- controlled seed protocol; it is not claimed to be the historical protocol or
148
- to guarantee deterministic CUDA execution.
149
-
150
- ## Version Discipline
151
-
152
- `provenance/source_snapshot.json` records original source hashes and times.
153
- `provenance/release_sources.sha256.json` seals the relocated evaluation
154
- snapshot; `release.verify` detects edits. Keep future training experiments in
155
- a separate working copy instead of updating this release in place.
156
- Relocation changes and their original versions remain traceable.
157
-
158
- Environment setup and limitations: `environment/README.md`.
159
- Recovered training recipes and missing dependencies: `TRAINING_PROVENANCE.md`.
160
- Third-party notices and publication checks: `THIRD_PARTY_NOTICES.md`.
 
1
+ ---
2
+ language:
3
+ - en
4
+ tags:
5
+ - robotics
6
+ - vision-language-action
7
+ - world-model
8
+ - robocasa
9
+ - pytorch
10
+ license: other
11
+ license_name: component-specific-licenses
12
+ license_link: LICENSE.md
13
+ ---
14
+
15
+ # PILOT: RoboCasa-GR1 340000
16
+
17
+ **Physical Inference for Latent Optimized Trajectories**
18
+
19
+ Built on NVIDIA Cosmos.
20
+
21
+ Model and simulation resources accompanying **Motion Chain of Thought:
22
+ Disentangling Motion Semantics from Visual Appearance for Robotic
23
+ Manipulation**, an anonymous ICLR 2027 submission under review.
24
+
25
+ [Code](https://github.com/pilot-wam-2026/pilot-code) |
26
+ [Project](https://pilot-wam-2026.github.io/) |
27
+ [Evaluation guide](docs/EVALUATION.md) |
28
+ [Training guide](docs/TRAINING.md) |
29
+ [Validation status](docs/VALIDATION.md)
30
+
31
+ ![PILOT architecture from the supplied manuscript](docs/assets/method.svg)
32
+
33
+ The repository ID remains **`mxk1998/WM4A`**. The project and the current
34
+ artifact are named **PILOT**. This snapshot selects the **340000-step**
35
+ RoboCasa-GR1 checkpoint; old 280000-step instructions are not the protocol
36
+ for this artifact.
37
+
38
+ ## Model
39
+
40
+ PILOT combines Cosmos-Predict2.5 context features, a Perceiver-style
41
+ flow-matching action head with learned Motion-CoT queries, and
42
+ training-time Representational Deduction using VJEPA2-AC future features.
43
+ The action head uses current observation, instruction, and robot state.
44
+ Generated future RGB images are optional diagnostics, not required
45
+ intermediate inputs to the action policy.
46
+
47
+ This resource contains the selected checkpoint, compatible framework and
48
+ training code, evaluation scripts, tokenizer/model metadata, custom
49
+ RoboCasa/RoboSuite environment resources, GR1 retargeting data, environment
50
+ setup, and sanitized results. Training demonstrations and other benchmark
51
+ checkpoints are not included.
52
+
53
+ | Property | Value |
54
+ |---|---|
55
+ | Architecture | `CosmoPredict25PerceiverVJEPA2AC` |
56
+ | Checkpoint step | 340000 |
57
+ | File | `checkpoints/steps_340000_pytorch_model.pt` |
58
+ | Bytes | 23,913,608,021 |
59
+ | Tensor entries | 2596 |
60
+ | Latent coordinates | `legacy` |
61
+ | Policy action horizon / executed chunk | 16 / 12 |
62
+ | Action integration | 20 steps |
63
+ | Optional visualization | 5 frames |
64
+ | Platform | Linux x86_64, NVIDIA CUDA, EGL |
65
 
66
  SHA-256:
 
67
 
68
+ ```text
69
+ 34bf115c1c99a33b12c79e1dca20e596cd510f006060687c2f145fecea58e60e
70
+ ```
 
 
71
 
72
+ ## Download And Install
 
73
 
74
  ```bash
75
  python -m pip install huggingface_hub
76
  hf auth login
77
+ hf download mxk1998/WM4A --local-dir PILOT
78
+ cd PILOT
79
+ python -m release.unpack_assets # If assets were distributed as an archive.
80
+ python -m release.verify --assets
81
+
82
+ bash environment/create_linux_envs.sh /absolute/new/pilot-envs
83
+ export POLICY_PYTHON=/absolute/new/pilot-envs/policy/bin/python
84
+ export SIM_PYTHON=/absolute/new/pilot-envs/simulation/bin/python
85
+ source environment/activate_paths.sh
86
+ "$POLICY_PYTHON" -m release.doctor --role policy
87
+ "$SIM_PYTHON" -m release.doctor --role simulation
88
+ "$POLICY_PYTHON" -m release.prepare
89
  ```
90
 
91
+ Use the supplied simulator sources, not a newer stock RoboCasa installation.
92
+ The policy and simulator have separate Python 3.10 environments.
93
+ `release.prepare` reconstructs constructor-compatible components directly
94
+ from the original checkpoint without changing tensor values. Its cache
95
+ requires roughly another checkpoint's worth of disk space. Plan for
96
+ 120 GiB free disk and 128 GiB host RAM. macOS is supported as an archive
97
+ location, not as a native simulation/inference platform.
 
 
 
 
 
98
 
99
+ ## Evaluation Usage
100
 
101
+ Inspect your assigned GPUs with `nvidia-smi`. Replace the example physical
102
+ GPU IDs below with devices actually allocated to you.
103
 
104
  ```bash
105
+ # One-task, one-episode smoke test.
 
 
 
 
 
 
 
 
 
 
106
  "$POLICY_PYTHON" -m release.evaluate \
107
+ --gpus 0 --render-gpu 0 \
108
+ --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
109
+ --episodes 1 --seed 9000 \
110
+ --task gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env \
111
+ --output /absolute/new/pilot-smoke
112
 
113
+ # Complete 24-task protocol, 50 episodes per task.
114
  "$POLICY_PYTHON" -m release.evaluate \
115
+ --gpus 0,1 --render-gpu 1 \
116
+ --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
117
+ --episodes 50 --seed 9000 --workers-per-policy 4 \
118
+ --output /absolute/new/pilot-full-evaluation
119
+ ```
120
+
121
+ The fixed contract uses `Task:` prompts, `legacy` latent coordinates,
122
+ 20 action-sampling steps, chunk 12, and 720 physical steps per episode.
123
+ Success is the native task predicate satisfied at **any executed physical
124
+ step**; successful episodes are not terminated early. Seeded scene
125
+ initialization, per-request policy sampling seeds, and per-environment
126
+ IK-cache clearing are part of the contract.
127
+
128
+ The launcher writes policy logs, per-task simulation logs, episode records,
129
+ action-request seeds/hashes, physical-step diagnostics, task `result.json`
130
+ files, and aggregate `summary.json`. It fails rather than treating an
131
+ incomplete task as a completed evaluation. See [the full guide](docs/EVALUATION.md).
132
+
133
+ ## Results And Limitations
134
+
135
+ The original checkpoint achieved **717/1200 (59.75%)** in the completed
136
+ repaired-protocol source evaluation. The manuscript reports **58.3%** for
137
+ its reported RoboCasa experiment. These are different measurements and
138
+ must not be presented as the same run.
139
+
140
+ Per-task results are in [results/robocasa_340000.json](results/robocasa_340000.json).
141
+ The score belongs to the original 340000 checkpoint, not a later
142
+ 1000-update training-validation export. A fresh-machine installation of
143
+ this portable package has not itself been shown to reproduce the score.
144
+
145
+ The auxiliary image predictor is not a validated long-video model.
146
+ Matched latent coordinates remove the diagnosed scale mismatch, but
147
+ held-out full-image MSE still does not establish superiority to copying
148
+ the current image. Single-rank 1000-update training/resume checks do not
149
+ establish long-horizon convergence or multi-GPU training reproducibility.
150
+ See [training details](docs/TRAINING.md) for the archived recipe and its
151
+ differences from manuscript hyperparameters.
152
+
153
+ ## Training
154
+
155
+ ```bash
156
+ "$POLICY_PYTHON" -m pip install -r environment/training.requirements.txt
157
+ export CUDA_VISIBLE_DEVICES=0
158
+ export PILOT_DATA_ROOT=/absolute/path/to/converted-datasets
159
+ export PILOT_OUTPUT_ROOT=/absolute/new/training-runs
160
+ bash run_training.sh --trainer.max_train_steps 1000
161
  ```
162
 
163
+ This is weight-only fine-tuning with a fresh optimizer, not recovery of the
164
+ historical optimizer. Full-state resume and original-pretrained
165
+ initialization are documented in [docs/TRAINING.md](docs/TRAINING.md).
166
+
167
+ ## License, Attribution And Anonymity
168
+
169
+ Retain all third-party licenses and notices. Code, pretrained components,
170
+ and simulation assets have component-specific terms; this repository
171
+ does not relicense them as a single unrestricted model.
172
+ See [LICENSE.md](LICENSE.md) and
173
+ [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
174
+
175
+ The README omits first-party personal names and affiliations.
176
+ Repository ownership and pre-existing history are not anonymized by
177
+ editing files. Repository visibility must be managed separately.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README_HF.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ tags:
5
+ - robotics
6
+ - vision-language-action
7
+ - world-model
8
+ - robocasa
9
+ - pytorch
10
+ license: other
11
+ license_name: component-specific-licenses
12
+ license_link: LICENSE.md
13
+ ---
14
+
15
+ # PILOT: RoboCasa-GR1 340000
16
+
17
+ **Physical Inference for Latent Optimized Trajectories**
18
+
19
+ Built on NVIDIA Cosmos.
20
+
21
+ Model and simulation resources accompanying **Motion Chain of Thought:
22
+ Disentangling Motion Semantics from Visual Appearance for Robotic
23
+ Manipulation**, an anonymous ICLR 2027 submission under review.
24
+
25
+ [Code](https://github.com/pilot-wam-2026/pilot-code) |
26
+ [Project](https://pilot-wam-2026.github.io/) |
27
+ [Evaluation guide](docs/EVALUATION.md) |
28
+ [Training guide](docs/TRAINING.md) |
29
+ [Validation status](docs/VALIDATION.md)
30
+
31
+ ![PILOT architecture from the supplied manuscript](docs/assets/method.svg)
32
+
33
+ The repository ID remains **`mxk1998/WM4A`**. The project and the current
34
+ artifact are named **PILOT**. This snapshot selects the **340000-step**
35
+ RoboCasa-GR1 checkpoint; old 280000-step instructions are not the protocol
36
+ for this artifact.
37
+
38
+ ## Model
39
+
40
+ PILOT combines Cosmos-Predict2.5 context features, a Perceiver-style
41
+ flow-matching action head with learned Motion-CoT queries, and
42
+ training-time Representational Deduction using VJEPA2-AC future features.
43
+ The action head uses current observation, instruction, and robot state.
44
+ Generated future RGB images are optional diagnostics, not required
45
+ intermediate inputs to the action policy.
46
+
47
+ This resource contains the selected checkpoint, compatible framework and
48
+ training code, evaluation scripts, tokenizer/model metadata, custom
49
+ RoboCasa/RoboSuite environment resources, GR1 retargeting data, environment
50
+ setup, and sanitized results. Training demonstrations and other benchmark
51
+ checkpoints are not included.
52
+
53
+ | Property | Value |
54
+ |---|---|
55
+ | Architecture | `CosmoPredict25PerceiverVJEPA2AC` |
56
+ | Checkpoint step | 340000 |
57
+ | File | `checkpoints/steps_340000_pytorch_model.pt` |
58
+ | Bytes | 23,913,608,021 |
59
+ | Tensor entries | 2596 |
60
+ | Latent coordinates | `legacy` |
61
+ | Policy action horizon / executed chunk | 16 / 12 |
62
+ | Action integration | 20 steps |
63
+ | Optional visualization | 5 frames |
64
+ | Platform | Linux x86_64, NVIDIA CUDA, EGL |
65
+
66
+ SHA-256:
67
+
68
+ ```text
69
+ 34bf115c1c99a33b12c79e1dca20e596cd510f006060687c2f145fecea58e60e
70
+ ```
71
+
72
+ ## Download And Install
73
+
74
+ ```bash
75
+ python -m pip install huggingface_hub
76
+ hf auth login
77
+ hf download mxk1998/WM4A --local-dir PILOT
78
+ cd PILOT
79
+ python -m release.unpack_assets # If assets were distributed as an archive.
80
+ python -m release.verify --assets
81
+
82
+ bash environment/create_linux_envs.sh /absolute/new/pilot-envs
83
+ export POLICY_PYTHON=/absolute/new/pilot-envs/policy/bin/python
84
+ export SIM_PYTHON=/absolute/new/pilot-envs/simulation/bin/python
85
+ source environment/activate_paths.sh
86
+ "$POLICY_PYTHON" -m release.doctor --role policy
87
+ "$SIM_PYTHON" -m release.doctor --role simulation
88
+ "$POLICY_PYTHON" -m release.prepare
89
+ ```
90
+
91
+ Use the supplied simulator sources, not a newer stock RoboCasa installation.
92
+ The policy and simulator have separate Python 3.10 environments.
93
+ `release.prepare` reconstructs constructor-compatible components directly
94
+ from the original checkpoint without changing tensor values. Its cache
95
+ requires roughly another checkpoint's worth of disk space. Plan for
96
+ 120 GiB free disk and 128 GiB host RAM. macOS is supported as an archive
97
+ location, not as a native simulation/inference platform.
98
+
99
+ ## Evaluation Usage
100
+
101
+ Inspect your assigned GPUs with `nvidia-smi`. Replace the example physical
102
+ GPU IDs below with devices actually allocated to you.
103
+
104
+ ```bash
105
+ # One-task, one-episode smoke test.
106
+ "$POLICY_PYTHON" -m release.evaluate \
107
+ --gpus 0 --render-gpu 0 \
108
+ --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
109
+ --episodes 1 --seed 9000 \
110
+ --task gr1_unified/PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_Env \
111
+ --output /absolute/new/pilot-smoke
112
+
113
+ # Complete 24-task protocol, 50 episodes per task.
114
+ "$POLICY_PYTHON" -m release.evaluate \
115
+ --gpus 0,1 --render-gpu 1 \
116
+ --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
117
+ --episodes 50 --seed 9000 --workers-per-policy 4 \
118
+ --output /absolute/new/pilot-full-evaluation
119
+ ```
120
+
121
+ The fixed contract uses `Task:` prompts, `legacy` latent coordinates,
122
+ 20 action-sampling steps, chunk 12, and 720 physical steps per episode.
123
+ Success is the native task predicate satisfied at **any executed physical
124
+ step**; successful episodes are not terminated early. Seeded scene
125
+ initialization, per-request policy sampling seeds, and per-environment
126
+ IK-cache clearing are part of the contract.
127
+
128
+ The launcher writes policy logs, per-task simulation logs, episode records,
129
+ action-request seeds/hashes, physical-step diagnostics, task `result.json`
130
+ files, and aggregate `summary.json`. It fails rather than treating an
131
+ incomplete task as a completed evaluation. See [the full guide](docs/EVALUATION.md).
132
+
133
+ ## Results And Limitations
134
+
135
+ The original checkpoint achieved **717/1200 (59.75%)** in the completed
136
+ repaired-protocol source evaluation. The manuscript reports **58.3%** for
137
+ its reported RoboCasa experiment. These are different measurements and
138
+ must not be presented as the same run.
139
+
140
+ Per-task results are in [results/robocasa_340000.json](results/robocasa_340000.json).
141
+ The score belongs to the original 340000 checkpoint, not a later
142
+ 1000-update training-validation export. A fresh-machine installation of
143
+ this portable package has not itself been shown to reproduce the score.
144
+
145
+ The auxiliary image predictor is not a validated long-video model.
146
+ Matched latent coordinates remove the diagnosed scale mismatch, but
147
+ held-out full-image MSE still does not establish superiority to copying
148
+ the current image. Single-rank 1000-update training/resume checks do not
149
+ establish long-horizon convergence or multi-GPU training reproducibility.
150
+ See [training details](docs/TRAINING.md) for the archived recipe and its
151
+ differences from manuscript hyperparameters.
152
+
153
+ ## Training
154
+
155
+ ```bash
156
+ "$POLICY_PYTHON" -m pip install -r environment/training.requirements.txt
157
+ export CUDA_VISIBLE_DEVICES=0
158
+ export PILOT_DATA_ROOT=/absolute/path/to/converted-datasets
159
+ export PILOT_OUTPUT_ROOT=/absolute/new/training-runs
160
+ bash run_training.sh --trainer.max_train_steps 1000
161
+ ```
162
+
163
+ This is weight-only fine-tuning with a fresh optimizer, not recovery of the
164
+ historical optimizer. Full-state resume and original-pretrained
165
+ initialization are documented in [docs/TRAINING.md](docs/TRAINING.md).
166
+
167
+ ## License, Attribution And Anonymity
168
+
169
+ Retain all third-party licenses and notices. Code, pretrained components,
170
+ and simulation assets have component-specific terms; this repository
171
+ does not relicense them as a single unrestricted model.
172
+ See [LICENSE.md](LICENSE.md) and
173
+ [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
174
+
175
+ The README omits first-party personal names and affiliations.
176
+ Repository ownership and pre-existing history are not anonymized by
177
+ editing files. Repository visibility must be managed separately.
README_dinov3.md DELETED
@@ -1,882 +0,0 @@
1
- :new: [2026-03-10] :fire: The [Canopy Height Maps v2 (CHMv2) model](https://arxiv.org/abs/2603.06382) and inference code are now available (more details on downloading the model weights and using the code [here](#canopy-height-maps-v2-chmv2)). The model weights are also available in [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and [supported](https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/chmv2.md) by the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Building on our original high-resolution canopy height maps released in 2024, CHMv2 delivers substantial improvements in accuracy, detail, and global consistency by leveraging DINOv3.
2
-
3
- [2025-11-20] Distillation code and configurations for ConvNeXt backbones are now released!
4
-
5
- [2025-10-13] [Semantic segmentation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-segmentation-with-data-augmentation-on-ade20k) (ADE20K) and [monocular depth estimation](https://github.com/facebookresearch/dinov3?tab=readme-ov-file#linear-depth-estimation-on-nyuv2-depth) (NYUv2-Depth) linear probing code are now released!
6
-
7
- [2025-09-17] DINOv3 backbones are now supported by the [PyTorch Image Models / timm](https://github.com/huggingface/pytorch-image-models/) library starting with version [1.0.20](https://github.com/huggingface/pytorch-image-models/releases/tag/v1.0.20)
8
-
9
- [2025-08-29] DINOv3 backbones are [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by released versions of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library starting with version [4.56.0](https://github.com/huggingface/transformers/releases/tag/v4.56.0)
10
-
11
- [2025-08-14] DINOv3 backbones are now available in [Hugging Face Hub](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) and [supported](https://huggingface.co/docs/transformers/model_doc/dinov3) by the [development](https://github.com/huggingface/transformers/) version of the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library
12
-
13
- # DINOv3 🦖🦖🦖
14
-
15
- **[Meta AI Research, FAIR](https://ai.meta.com/research/)**
16
-
17
- Oriane Siméoni, Huy V. Vo, Maximilian Seitzer, Federico Baldassarre, Maxime Oquab, <br/>
18
- Cijo Jose, Vasil Khalidov, Marc Szafraniec, Seungeun Yi, Michaël Ramamonjisoa, <br/>
19
- Francisco Massa, Daniel Haziza, Luca Wehrstedt, Jianyuan Wang, <br/>
20
- Timothée Darcet, Théo Moutakanni, Leonel Sentana, Claire Roberts, <br/>
21
- Andrea Vedaldi, Jamie Tolan, John Brandt, Camille Couprie, <br/>
22
- Julien Mairal, Hervé Jégou, Patrick Labatut, Piotr Bojanowski
23
-
24
- [ :scroll: [`Paper`](https://arxiv.org/abs/2508.10104)] [ :newspaper: [`Blog`](https://ai.meta.com/blog/dinov3-self-supervised-vision-model/)] [ :globe_with_meridians: [`Website`](https://ai.meta.com/dinov3/)] [ :book: [`BibTeX`](#citing-dinov3)]
25
-
26
- Reference PyTorch implementation and models for DINOv3. For details, see the **[DINOv3](https://arxiv.org/abs/2508.10104)** paper.
27
-
28
- ## Overview
29
-
30
- <div align="center">
31
- <img width="1364" height="1024" alt="market" src="https://github.com/user-attachments/assets/1411f491-988e-49cb-95ae-d03fe6e3c268" />
32
-
33
- <i></em><b>High-resolution dense features.</b><br/>We visualize the cosine similarity maps obtained with DINOv3 output features<br/> between the patches marked with a red cross and all other patches.</i>
34
- </div>
35
-
36
- <br/>
37
-
38
- An extended family of versatile vision foundation models producing high-quality dense features and achieving outstanding performance on various vision tasks including outperforming the specialized state of the art across a broad range of settings, without fine-tuning
39
-
40
- ## Pretrained models
41
-
42
- :information_source: Please follow the link provided below to get access to all the model weights: once accepted, an e-mail will be sent with the complete list of URLs pointing to all the available model weights (both backbones and adapters). These URLs can then be used to either:
43
- - download the model or adapter weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` or `backbone_weights` parameters, or
44
- - directly invoke `torch.hub.load()` to download and load a backbone or an adapter from its URL via also the `weights` or `backbone_weights` parameters.
45
-
46
- See the example code snippets below.
47
-
48
- :warning: Please use `wget` instead of a web browser to download the weights.
49
-
50
- ViT models pretrained on web dataset (LVD-1689M):
51
- <table style="margin: auto">
52
- <thead>
53
- <tr>
54
- <th>Model</th>
55
- <th>Parameters</th>
56
- <th>Pretraining<br/>Dataset</th>
57
- <th>Download</th>
58
- </tr>
59
- </thead>
60
- <tbody>
61
- <tr>
62
- <td>ViT-S/16 distilled </td>
63
- <td align="right">21M</td>
64
- <td align="center">LVD-1689M</td>
65
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
66
- </tr>
67
- <tr>
68
- <td>ViT-S+/16 distilled</td>
69
- <td align="right">29M</td>
70
- <td align="center">LVD-1689M</td>
71
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
72
- </tr>
73
- <tr>
74
- <td>ViT-B/16 distilled</td>
75
- <td align="right">86M</td>
76
- <td align="center">LVD-1689M</td>
77
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
78
- </tr>
79
- <tr>
80
- <td>ViT-L/16 distilled</td>
81
- <td align="right">300M</td>
82
- <td align="center">LVD-1689M</td>
83
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
84
- </tr>
85
- <tr>
86
- <td>ViT-H+/16 distilled</td>
87
- <td align="right">840M</td>
88
- <td align="center">LVD-1689M</td>
89
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
90
- </tr>
91
- <tr>
92
- <td>ViT-7B/16</td>
93
- <td align="right">6,716M</td>
94
- <td align="center">LVD-1689M</td>
95
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
96
- </tr>
97
- </tbody>
98
- </table>
99
-
100
- ConvNeXt models pretrained on web dataset (LVD-1689M):
101
- <table style="margin: auto">
102
- <thead>
103
- <tr>
104
- <th>Model</th>
105
- <th>Parameters</th>
106
- <th>Pretraining<br/>Dataset</th>
107
- <th>Download</th>
108
- </tr>
109
- </thead>
110
- <tbody>
111
- <tr>
112
- <td>ConvNeXt Tiny</td>
113
- <td align="right">29M</td>
114
- <td align="center">LVD-1689M</td>
115
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
116
- </tr>
117
- <tr>
118
- <td>ConvNeXt Small</td>
119
- <td align="right">50M</td>
120
- <td align="center">LVD-1689M</td>
121
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
122
- </tr>
123
- <tr>
124
- <td>ConvNeXt Base</td>
125
- <td align="right">89M</td>
126
- <td align="center">LVD-1689M</td>
127
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
128
- </tr>
129
- <tr>
130
- <td>ConvNeXt Large</td>
131
- <td align="right">198M</td>
132
- <td align="center">LVD-1689M</td>
133
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
134
- </tr>
135
- </tbody>
136
- </table>
137
-
138
- ViT models pretrained on satellite dataset (SAT-493M):
139
- <table style="margin: auto">
140
- <thead>
141
- <tr>
142
- <th>Model</th>
143
- <th>Parameters</th>
144
- <th>Pretraining<br/>Dataset</th>
145
- <th>Download</th>
146
- </tr>
147
- </thead>
148
- <tbody>
149
- <tr>
150
- <td>ViT-L/16 distilled</td>
151
- <td align="right">300M</td>
152
- <td align="center">SAT-493M</td>
153
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
154
- </tr>
155
- <tr>
156
- <td>ViT-7B/16</td>
157
- <td align="right">6,716M</td>
158
- <td align="center">SAT-493M</td>
159
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
160
- </tr>
161
- </tbody>
162
- </table>
163
-
164
-
165
- ### Pretrained backbones (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html))
166
-
167
- Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install PyTorch (the only required dependency for loading the model). Installing PyTorch with CUDA support is strongly recommended.
168
-
169
- ```python
170
- import torch
171
-
172
- REPO_DIR = <PATH/TO/A/LOCAL/DIRECTORY/WHERE/THE/DINOV3/REPO/WAS/CLONED>
173
-
174
- # DINOv3 ViT models pretrained on web images
175
- dinov3_vits16 = torch.hub.load(REPO_DIR, 'dinov3_vits16', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
176
- dinov3_vits16plus = torch.hub.load(REPO_DIR, 'dinov3_vits16plus', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
177
- dinov3_vitb16 = torch.hub.load(REPO_DIR, 'dinov3_vitb16', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
178
- dinov3_vitl16 = torch.hub.load(REPO_DIR, 'dinov3_vitl16', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
179
- dinov3_vith16plus = torch.hub.load(REPO_DIR, 'dinov3_vith16plus', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
180
- dinov3_vit7b16 = torch.hub.load(REPO_DIR, 'dinov3_vit7b16', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
181
-
182
- # DINOv3 ConvNeXt models pretrained on web images
183
- dinov3_convnext_tiny = torch.hub.load(REPO_DIR, 'dinov3_convnext_tiny', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
184
- dinov3_convnext_small = torch.hub.load(REPO_DIR, 'dinov3_convnext_small', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
185
- dinov3_convnext_base = torch.hub.load(REPO_DIR, 'dinov3_convnext_base', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
186
- dinov3_convnext_large = torch.hub.load(REPO_DIR, 'dinov3_convnext_large', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
187
-
188
- # DINOv3 ViT models pretrained on satellite imagery
189
- dinov3_vitl16 = torch.hub.load(REPO_DIR, 'dinov3_vitl16', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
190
- dinov3_vit7b16 = torch.hub.load(REPO_DIR, 'dinov3_vit7b16', source='local', weights=<CHECKPOINT/URL/OR/PATH>)
191
- ```
192
-
193
- ### Pretrained backbones (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/))
194
-
195
- All the backbones are available in the [DINOv3](https://huggingface.co/collections/facebook/dinov3-68924841bd6b561778e31009) collection on Hugging Face Hub and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library (with released packages from version 4.56.0). Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain an image embedding with either [Pipeline] or the [AutoModel] class.
196
-
197
- ```python
198
- from transformers import pipeline
199
- from transformers.image_utils import load_image
200
-
201
- url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
202
- image = load_image(url)
203
-
204
- feature_extractor = pipeline(
205
- model="facebook/dinov3-convnext-tiny-pretrain-lvd1689m",
206
- task="image-feature-extraction",
207
- )
208
- features = feature_extractor(image)
209
- ```
210
-
211
- ```python
212
- import torch
213
- from transformers import AutoImageProcessor, AutoModel
214
- from transformers.image_utils import load_image
215
-
216
- url = "http://images.cocodataset.org/val2017/000000039769.jpg"
217
- image = load_image(url)
218
-
219
- pretrained_model_name = "facebook/dinov3-convnext-tiny-pretrain-lvd1689m"
220
- processor = AutoImageProcessor.from_pretrained(pretrained_model_name)
221
- model = AutoModel.from_pretrained(
222
- pretrained_model_name,
223
- device_map="auto",
224
- )
225
-
226
- inputs = processor(images=image, return_tensors="pt").to(model.device)
227
- with torch.inference_mode():
228
- outputs = model(**inputs)
229
-
230
- pooled_output = outputs.pooler_output
231
- print("Pooled output shape:", pooled_output.shape)
232
- ```
233
-
234
- where `model` and `pretrained_model_name` above can be one of:
235
- - `facebook/dinov3-vits16-pretrain-lvd1689m`
236
- - `facebook/dinov3-vits16plus-pretrain-lvd1689m`
237
- - `facebook/dinov3-vitb16-pretrain-lvd1689m`
238
- - `facebook/dinov3-vitl16-pretrain-lvd1689m`
239
- - `facebook/dinov3-vith16plus-pretrain-lvd1689m`
240
- - `facebook/dinov3-vit7b16-pretrain-lvd1689m`
241
- - `facebook/dinov3-convnext-base-pretrain-lvd1689m`
242
- - `facebook/dinov3-convnext-large-pretrain-lvd1689m`
243
- - `facebook/dinov3-convnext-small-pretrain-lvd1689m`
244
- - `facebook/dinov3-convnext-tiny-pretrain-lvd1689m`
245
- - `facebook/dinov3-vitl16-pretrain-sat493m`
246
- - `facebook/dinov3-vit7b16-pretrain-sat493m`
247
-
248
- ### Image transforms
249
-
250
- For models using the LVD-1689M weights (pretrained on web images), please use the following transform (standard ImageNet evaluation transform):
251
-
252
- ```python
253
- import torchvision
254
- from torchvision.transforms import v2
255
-
256
- def make_transform(resize_size: int = 256):
257
- to_tensor = v2.ToImage()
258
- resize = v2.Resize((resize_size, resize_size), antialias=True)
259
- to_float = v2.ToDtype(torch.float32, scale=True)
260
- normalize = v2.Normalize(
261
- mean=(0.485, 0.456, 0.406),
262
- std=(0.229, 0.224, 0.225),
263
- )
264
- return v2.Compose([to_tensor, resize, to_float, normalize])
265
- ```
266
-
267
-
268
- For models using the SAT-493M weights (pretrained on satellite imagery), please use the following transform:
269
-
270
-
271
- ```python
272
- import torchvision
273
- from torchvision.transforms import v2
274
-
275
- def make_transform(resize_size: int = 256):
276
- to_tensor = v2.ToImage()
277
- resize = v2.Resize((resize_size, resize_size), antialias=True)
278
- to_float = v2.ToDtype(torch.float32, scale=True)
279
- normalize = v2.Normalize(
280
- mean=(0.430, 0.411, 0.296),
281
- std=(0.213, 0.156, 0.143),
282
- )
283
- return v2.Compose([to_tensor, resize, to_float, normalize])
284
- ```
285
-
286
- ### Pretrained heads - Image classification
287
-
288
- <table style="margin: auto">
289
- <thead>
290
- <tr>
291
- <th>Backbone</th>
292
- <th>Pretraining<br/>Dataset</th>
293
- <th>Head<br/>Dataset</th>
294
- <th>Download</th>
295
- </tr>
296
- </thead>
297
- <tbody>
298
- <tr>
299
- <td>ViT-7B/16</td>
300
- <td align="center">LVD-1689M</td>
301
- <td align="center">ImageNet</td>
302
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
303
- </tr>
304
- </tbody>
305
- </table>
306
-
307
-
308
- The (full) classifier models can be loaded via PyTorch Hub:
309
-
310
- ```python
311
- import torch
312
-
313
- # DINOv3
314
- dinov3_vit7b16_lc = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_lc', source="local", weights=<DEPTHER/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
315
-
316
- ```
317
-
318
- ### Pretrained heads - Depther trained on SYNTHMIX dataset
319
-
320
- <table style="margin: auto">
321
- <thead>
322
- <tr>
323
- <th>Backbone</th>
324
- <th>Pretraining<br/>Dataset</th>
325
- <th>Head<br/>Dataset</th>
326
- <th>Download</th>
327
- </tr>
328
- </thead>
329
- <tbody>
330
- <tr>
331
- <td>ViT-7B/16</td>
332
- <td align="center">LVD-1689M</td>
333
- <td align="center">SYNTHMIX</td>
334
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
335
- </tr>
336
- </tbody>
337
- </table>
338
-
339
-
340
- ```python
341
- depther = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_dd', source="local", weights=<DEPTHER/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
342
- ```
343
-
344
- Full example code of depther on an image
345
-
346
- ```python
347
- from PIL import Image
348
- import torch
349
- from torchvision.transforms import v2
350
- import matplotlib.pyplot as plt
351
- from matplotlib import colormaps
352
-
353
- def get_img():
354
- import requests
355
- url = "http://images.cocodataset.org/val2017/000000039769.jpg"
356
- image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
357
- return image
358
-
359
- def make_transform(resize_size: int | list[int] = 768):
360
- to_tensor = v2.ToImage()
361
- resize = v2.Resize((resize_size, resize_size), antialias=True)
362
- to_float = v2.ToDtype(torch.float32, scale=True)
363
- normalize = v2.Normalize(
364
- mean=(0.485, 0.456, 0.406),
365
- std=(0.229, 0.224, 0.225),
366
- )
367
- return v2.Compose([to_tensor, resize, to_float, normalize])
368
-
369
- depther = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_dd', source="local", weights=<DEPTHER/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
370
-
371
- img_size = 1024
372
- img = get_img()
373
- transform = make_transform(img_size)
374
- with torch.inference_mode():
375
- with torch.autocast('cuda', dtype=torch.bfloat16):
376
- batch_img = transform(img)[None]
377
- batch_img = batch_img
378
- depths = depther(batch_img)
379
-
380
- plt.figure(figsize=(12, 6))
381
- plt.subplot(121)
382
- plt.imshow(img)
383
- plt.axis("off")
384
- plt.subplot(122)
385
- plt.imshow(depths[0,0].cpu(), cmap=colormaps["Spectral"])
386
- plt.axis("off")
387
-
388
- ```
389
-
390
- #### Reproduce paper results
391
-
392
- Make sure the NYU dataset is setup following [this](DATASETS.md#depth-estimation-on-nyu).
393
-
394
- Launch the following to reproduce our paper's depth estimation results on NYUv2 with the pretrained Depther trained on SYNTHMIX:
395
-
396
- ```shell
397
- PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \
398
- config=dinov3/eval/depth/configs/config-nyu-synthmix-dpt-inference.yaml \
399
- datasets.root=<PATH/TO/DATASET> \
400
- load_from=dinov3_vit7b16_dd \
401
- --output-dir <PATH/TO/OUTPUT/DIR>
402
- ```
403
-
404
- Notes:
405
- - if you want to launch the code without dinov3.run.submit, you can do so using python directly or torchrun:
406
-
407
- ```shell
408
- PYTHONPATH=. python dinov3/eval/depth/run.py \
409
- config=dinov3/eval/depth/configs/config-nyu-synthmix-dpt-inference.yaml \
410
- datasets.root=<PATH/TO/DATASET> \
411
- load_from=dinov3_vit7b16_dd \
412
- output_dir=<PATH/TO/OUTPUT/DIR>
413
- ```
414
-
415
- - One can also save prediction results using `result_config.save_results=true`.
416
-
417
-
418
- ### Pretrained heads - Detector trained on COCO2017 dataset
419
-
420
- <table style="margin: auto">
421
- <thead>
422
- <tr>
423
- <th>Backbone</th>
424
- <th>Pretraining<br/>Dataset</th>
425
- <th>Head<br/>Dataset</th>
426
- <th>Download</th>
427
- </tr>
428
- </thead>
429
- <tbody>
430
- <tr>
431
- <td>ViT-7B/16</td>
432
- <td align="center">LVD-1689M</td>
433
- <td align="center">COCO2017</td>
434
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
435
- </tr>
436
- </tbody>
437
- </table>
438
-
439
-
440
- ```python
441
- detector = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_de', source="local", weights=<DETECTOR/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
442
- ```
443
-
444
- ### Pretrained heads - Segmentor trained on ADE20K dataset
445
-
446
- <table style="margin: auto">
447
- <thead>
448
- <tr>
449
- <th>Backbone</th>
450
- <th>Pretraining<br/>Dataset</th>
451
- <th>Head<br/>Dataset</th>
452
- <th>Download</th>
453
- </tr>
454
- </thead>
455
- <tbody>
456
- <tr>
457
- <td>ViT-7B/16</td>
458
- <td align="center">LVD-1689M</td>
459
- <td align="center">ADE20K</td>
460
- <td align="center"><a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a></td>
461
- </tr>
462
- </tbody>
463
- </table>
464
-
465
- ```python
466
- segmentor = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_ms', source="local", weights=<SEGMENTOR/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
467
- ```
468
-
469
- Example command to run a full inference on ADE20K with the provided segmentor (ViT-7B + M2F):
470
-
471
- ```shell
472
- PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \
473
- config=dinov3/eval/segmentation/configs/config-ade20k-m2f-inference.yaml \
474
- datasets.root=<PATH/TO/DATASET> \
475
- load_from=dinov3_vit7b16_ms \
476
- --output-dir <PATH/TO/OUTPUT/DIR>
477
- ```
478
-
479
- Full example code of segmentator on an image
480
-
481
- ```python
482
- import sys
483
- sys.path.append(REPO_DIR)
484
-
485
- from PIL import Image
486
- import torch
487
- from torchvision import transforms
488
- import matplotlib.pyplot as plt
489
- from matplotlib import colormaps
490
- from functools import partial
491
- from dinov3.eval.segmentation.inference import make_inference
492
-
493
-
494
- def get_img():
495
- import requests
496
- url = "http://images.cocodataset.org/val2017/000000039769.jpg"
497
- image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
498
- return image
499
-
500
- def make_transform(resize_size: int | list[int] = 768):
501
- to_tensor = v2.ToImage()
502
- resize = v2.Resize((resize_size, resize_size), antialias=True)
503
- to_float = v2.ToDtype(torch.float32, scale=True)
504
- normalize = v2.Normalize(
505
- mean=(0.485, 0.456, 0.406),
506
- std=(0.229, 0.224, 0.225),
507
- )
508
- return v2.Compose([to_tensor, resize, to_float, normalize])
509
-
510
- segmentor = torch.hub.load(REPO_DIR, 'dinov3_vit7b16_ms', source="local", weights=<SEGMENTOR/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
511
-
512
- img_size = 896
513
- img = get_img()
514
- transform = make_transform(img_size)
515
- with torch.inference_mode():
516
- with torch.autocast('cuda', dtype=torch.bfloat16):
517
- batch_img = transform(img)[None]
518
- pred_vit7b = segmentor(batch_img) # raw predictions
519
- # actual segmentation map
520
- segmentation_map_vit7b = make_inference(
521
- batch_img,
522
- segmentor,
523
- inference_mode="slide",
524
- decoder_head_type="m2f",
525
- rescale_to=(img.size[-1], img.size[-2]),
526
- n_output_channels=150,
527
- crop_size=(img_size, img_size),
528
- stride=(img_size, img_size),
529
- output_activation=partial(torch.nn.functional.softmax, dim=1),
530
- ).argmax(dim=1, keepdim=True)
531
- plt.figure(figsize=(12, 6))
532
- plt.subplot(121)
533
- plt.imshow(img)
534
- plt.axis("off")
535
- plt.subplot(122)
536
- plt.imshow(segmentation_map_vit7b[0,0].cpu(), cmap=colormaps["Spectral"])
537
- plt.axis("off")
538
- ```
539
-
540
-
541
-
542
-
543
- ### Pretrained heads - Zero-shot tasks with `dino.txt`
544
-
545
- <table style="margin: auto">
546
- <thead>
547
- <tr>
548
- <th rowspan="2">Backbone</th>
549
- <th>Download</th>
550
- </tr>
551
- </thead>
552
- <tbody>
553
- <tr>
554
- <td>ViT-L/16 distilled</td>
555
- <td align="center">
556
- <a href="https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/">[link]</a>,
557
- <a href="https://dl.fbaipublicfiles.com/dinov3/thirdparty/bpe_simple_vocab_16e6.txt.gz">vocabulary</a>,
558
- <a href="https://dl.fbaipublicfiles.com/dinov2/thirdparty/LICENSE">vocabulary license</a>
559
- </td>
560
- </tr>
561
- </tbody>
562
- </table>
563
-
564
- The (full) dino.txt model can be loaded via PyTorch Hub:
565
-
566
- ```python
567
- import torch
568
- # DINOv3
569
- dinov3_vitl16_dinotxt_tet1280d20h24l, tokenizer = torch.hub.load(REPO_DIR, 'dinov3_vitl16_dinotxt_tet1280d20h24l', weights=<SEGMENTOR/CHECKPOINT/URL/OR/PATH>, backbone_weights=<BACKBONE/CHECKPOINT/URL/OR/PATH>)
570
- ```
571
-
572
-
573
- ## Installation
574
-
575
- The training and evaluation code requires PyTorch version >= 2.7.1 as well as a few other 3rd party packages. Note that the code has only been tested with the specified versions and also expects a Linux environment. To setup all the required dependencies for training and evaluation, please follow the instructions below:
576
-
577
- *[micromamba](https://mamba.readthedocs.io/en/latest/user_guide/micromamba.html)* **(Recommended)** - Clone the repository and then create and activate a `dinov3` conda environment using the provided environment definition:
578
-
579
- ```shell
580
- micromamba env create -f conda.yaml
581
- micromamba activate dinov3
582
- ```
583
-
584
- ## Getting started
585
-
586
- Several notebooks are provided to get started applying DINOv3:
587
- - [PCA of patch features](notebooks/pca.ipynb): display the PCA of DINOv3 patch features on a foreground object (rainbow visualizations from the paper) [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/pca.ipynb)
588
- - [Foreground segmentation](notebooks/foreground_segmentation.ipynb): train a linear foreground segmentation model based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/foreground_segmentation.ipynb)
589
- - [Dense and sparse matching](notebooks/dense_sparse_matching.ipynb): match patches from objects on two different images based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/dense_sparse_matching.ipynb)
590
- - [Segmentation tracking](notebooks/segmentation_tracking.ipynb): video segmentation tracking using a non-parametric method based on DINOv3 features [[Run in Google Colab]](https://colab.research.google.com/github/facebookresearch/dinov3/blob/main/notebooks/segmentation_tracking.ipynb)
591
- - [Zero-shot segmentation with DINOv3-based dino.txt](notebooks/dinotxt_segmentation_inference.ipynb): compute the open-vocabulary segmentation results with dino.txt strategy.
592
-
593
- ## Data preparation
594
-
595
- ### ImageNet-1k
596
-
597
- The root directory of the dataset should hold the following contents:
598
-
599
- - `<ROOT>/test/ILSVRC2012_test_00000001.JPEG`
600
- - `<ROOT>/test/[..]`
601
- - `<ROOT>/test/ILSVRC2012_test_00100000.JPEG`
602
- - `<ROOT>/train/n01440764/n01440764_10026.JPEG`
603
- - `<ROOT>/train/[...]`
604
- - `<ROOT>/train/n15075141/n15075141_9993.JPEG`
605
- - `<ROOT>/val/n01440764/ILSVRC2012_val_00000293.JPEG`
606
- - `<ROOT>/val/[...]`
607
- - `<ROOT>/val/n15075141/ILSVRC2012_val_00049174.JPEG`
608
- - `<ROOT>/labels.txt`
609
-
610
- The provided dataset implementation expects a few additional metadata files to be present under the extra directory:
611
-
612
- - `<EXTRA>/class-ids-TRAIN.npy`
613
- - `<EXTRA>/class-ids-VAL.npy`
614
- - `<EXTRA>/class-names-TRAIN.npy`
615
- - `<EXTRA>/class-names-VAL.npy`
616
- - `<EXTRA>/entries-TEST.npy`
617
- - `<EXTRA>/entries-TRAIN.npy`
618
- - `<EXTRA>/entries-VAL.npy`
619
-
620
- These metadata files can be generated (once) with the following lines of Python code:
621
-
622
- ```python
623
- from dinov3.data.datasets import ImageNet
624
-
625
- for split in ImageNet.Split:
626
- dataset = ImageNet(split=split, root="<ROOT>", extra="<EXTRA>")
627
- dataset.dump_extra()
628
- ```
629
-
630
- Note that the root and extra directories do not have to be distinct directories.
631
-
632
- ### ImageNet-22k
633
-
634
- Please adapt the [dataset class](dinov3/data/datasets/image_net_22k.py) to match your local setup.
635
-
636
- <br />
637
-
638
- :warning: To execute the commands provided in the next sections for training and evaluation, the `dinov3` package should be included in the Python module search path, i.e. simply prefix the command to run with `PYTHONPATH=.`.
639
-
640
- ## Training
641
-
642
- ### Fast setup: training DINOv3 ViT-L/16 on ImageNet-1k
643
-
644
- Run DINOv3 pre-training on 4 H100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit:
645
-
646
- ```shell
647
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
648
- --nodes 4 \
649
- --config-file dinov3/configs/train/vitl_im1k_lin834.yaml \
650
- --output-dir <PATH/TO/OUTPUT/DIR> \
651
- train.dataset_path=ImageNet22k:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
652
- ```
653
- Training time is approximately 14 hours and the resulting checkpoint should reach 82.0% on k-NN eval and 83.5% on linear eval.
654
-
655
- The training code saves the weights of the teacher in the eval folder every 12500 iterations for evaluation.
656
-
657
- ### Exact DINOv3 setup: training DINOv3 ViT-7B/16
658
-
659
- DINOv3 ViT-7B/16 is trained on a private dataset. The training involves 3 stages:
660
- - Pretraining
661
- - Gram anchoring
662
- - High resolution adaptation
663
-
664
- #### Pretraining
665
-
666
- Launch DINOV3 ViT-7B/16 pretraining on 32 nodes (256 GPUs) in a SLURM cluster environment with submitit.
667
-
668
- ```shell
669
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
670
- --nodes 32 \
671
- --config-file dinov3/configs/train/dinov3_vit7b16_pretrain.yaml \
672
- --output-dir <PATH/TO/OUTPUT/DIR> \
673
- train.dataset_path=<DATASET>:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
674
- ```
675
-
676
- #### Gram anchoring
677
-
678
- ```shell
679
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
680
- --nodes 32 \
681
- --config-file dinov3/configs/train/dinov3_vit7b16_gram_anchor.yaml \
682
- --output-dir <PATH/TO/OUTPUT/DIR> \
683
- train.dataset_path=<DATASET>:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
684
- gram.ckpt=<PATH/TO/GRAM_TEACHER_FROM_PREVIOUS_STEP>
685
- ```
686
-
687
- #### High-resolution adaptation
688
-
689
-
690
- ```shell
691
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
692
- --nodes 32 \
693
- --config-file dinov3/configs/train/dinov3_vit7b16_high_res_adapt.yaml \
694
- --output-dir <PATH/TO/OUTPUT/DIR> \
695
- train.dataset_path=<DATASET>:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
696
- gram.ckpt=<PATH/TO/TEACHER_FROM_GRAM> \
697
- student.resume_from_teacher_chkpt=<PATH/TO/TEACHER_FROM_GRAM>
698
- ```
699
-
700
- ## Multi-distillation
701
-
702
- ### Test setup:
703
-
704
- ```shell
705
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/train/train.py \
706
- --nodes 1 \
707
- --config-file dinov3/configs/train/multi_distillation_test.yaml \
708
- --output-dir <PATH/TO/OUTPUT/DIR> \
709
- --multi-distillation \
710
- train.dataset_path=<DATASET>:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
711
- ```
712
-
713
- ## Evaluation
714
-
715
- The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node:
716
-
717
-
718
- ### Logistic regression classification on ImageNet-1k
719
-
720
- ```shell
721
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/log_regression.py \
722
- model.config_file=<PATH/TO/OUTPUT/DIR>/config.yaml \
723
- model.pretrained_weights=<PATH/TO/OUTPUT/DIR>/teacher_checkpoint.pth \
724
- output_dir=<PATH/TO/OUTPUT/DIR> \
725
- train.dataset=ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
726
- eval.test_dataset=ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
727
- ```
728
-
729
- ### k-NN classification on ImageNet-1k
730
-
731
- ```shell
732
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/knn.py \
733
- model.config_file=<PATH/TO/OUTPUT/DIR>/config.yaml \
734
- model.pretrained_weights=<PATH/TO/OUTPUT/DIR>/teacher_checkpoint.pth \
735
- output_dir=<PATH/TO/OUTPUT/DIR> \
736
- train.dataset=ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
737
- eval.test_dataset=ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
738
- ```
739
-
740
- ### Linear classification with data augmentation on ImageNet-1k
741
-
742
- ```shell
743
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/linear.py \
744
- model.config_file=<PATH/TO/OUTPUT/DIR>/config.yaml \
745
- model.pretrained_weights=<PATH/TO/OUTPUT/DIR>/teacher_checkpoint.pth \
746
- output_dir=<PATH/TO/OUTPUT/DIR> \
747
- train.dataset=ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \
748
- train.val_dataset=ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>
749
- ```
750
-
751
- ### Linear segmentation with data augmentation on ADE20K
752
-
753
- ```shell
754
- PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/segmentation/run.py \
755
- model.dino_hub=dinov3_vit7b16 \
756
- config=dinov3/eval/segmentation/configs/config-ade20k-linear-training.yaml \
757
- datasets.root=<PATH/TO/DATASET> \
758
- --output-dir <PATH/TO/OUTPUT/DIR>
759
- ```
760
-
761
- After the job completes, you will find in the output path directory you specified
762
- - `segmentation_config.yaml` that contains the config you trained the model with;
763
- - `model_final.pth`, the final linear head checkpoint at the end of training; and
764
- - `results-semantic-segmentation.csv` with the final metrics.
765
-
766
-
767
- #### Linear depth estimation on NYUv2 Depth
768
- ```shell
769
- PYTHONPATH=. python -m dinov3.run.submit dinov3/eval/depth/run.py \
770
- model.dino_hub=dinov3_vit7b16 \
771
- config=dinov3/eval/depth/configs/config-nyu.yaml \
772
- datasets.root=<PATH/TO/DATASET> \
773
- --output-dir <PATH/TO/OUTPUT/DIR>
774
- ```
775
-
776
- After the job completes, you will find in the output path directory you specified
777
- - `depth_config.yaml` that contains the config you trained the model with;
778
- - `model_final.pth`, the final linear head checkpoint at the end of training; and
779
- - `results-depth.csv` with the final metrics.
780
-
781
- ### Text alignment on DINOv3 using dino.txt
782
-
783
- Text alignment can be done following the method from `dino.txt` aka [DINOv2 Meets Text](https://arxiv.org/abs/2412.16334).
784
-
785
- ```shell
786
- PYTHONPATH=${PWD} python -m dinov3.run.submit dinov3/eval/text/train_dinotxt.py \
787
- --nodes 4 \
788
- # An example config for text alignment is here: dinov3/eval/text/configs/dinov3_vitl_text.yaml \
789
- trainer_config_file="<PATH/TO/DINOv3/TEXT/CONFIG>" \
790
- output-dir=<PATH/TO/OUTPUT/DIR>
791
- ```
792
- Launching the above trains text alignment on 4 nodes with 8 gpus each (32 gpus in total).
793
- Please note that the text alignment model in the DINOv3 paper was trained on a private dataset and here we have given an example config in ```dinov3/eval/text/configs/dinov3_vitl_text.yaml``` using ```CocoCaptions``` dataset for illustration purposes.
794
- Please adapt the provided ```CocoCaptions``` dataset class, the dataset can be found [here](https://www.kaggle.com/datasets/nikhil7280/coco-image-caption)
795
-
796
-
797
- ## Canopy Height Maps v2 (CHMv2)
798
-
799
- John Brandt, Seungeun Yi, Jamie Tolan, Xinyuan Li, Peter Potapov, <br/>
800
- Jessica Ertel, Justine Spore, Huy V. Vo, Michaël Ramamonjisoa, Patrick Labatut, <br/>
801
- Piotr Bojanowski, Camille Couprie
802
-
803
- [ :scroll: [`Paper`](https://arxiv.org/abs/2603.06382)] [ :newspaper: [`Blog`](http://ai.meta.com/blog/world-resources-institute-dino-canopy-height-maps-v2)]
804
-
805
- ### CHMv2 model loading (via PyTorch [Hub](https://docs.pytorch.org/docs/stable/hub.html))
806
-
807
- :information_source: Please follow the link provided below to get access to the CHMv2 model weights: once accepted, an e-mail will be sent with the URL pointing to the available model weights. The URL can then be used to either:
808
- - download the model weights to a local filesystem and point `torch.hub.load()` to these local weights via the `weights` parameters, or
809
- - directly invoke `torch.hub.load()` to download and load a backbone from its URL.
810
-
811
- CHMv2 uses the DINOv3 ViT-L/16 satellite as the backbone, available after requesting access [here](https://ai.meta.com/resources/models-and-libraries/dinov3-downloads/).
812
-
813
- :warning: Please use `wget` instead of a web browser to download the weights.
814
-
815
- Download link: https://ai.meta.com/resources/models-and-libraries/chmv2-downloads/
816
-
817
- ```python
818
- import torch
819
- from dinov3.hub.backbones import Weights
820
-
821
- REPO_DIR = <PATH/TO/A/LOCAL/DIRECTORY/WHERE/THE/DINOv3/REPO/WAS/CLONED>
822
-
823
- chmv2_model = torch.hub.load(
824
- REPO_DIR,
825
- 'dinov3_vitl16_chmv2',
826
- source="local",
827
- weights="<CHMV2_MODEL/CHECKPOINT/URL/OR/PATH>",
828
- backbone_weights=Weights.SAT493M, # or <DINOV3_VITL_SAT/CHECKPOINT/URL/OR/PATH>
829
- )
830
- ```
831
-
832
- Refer to this [notebook](notebooks/chmv2_inference.ipynb) for an example of how to use the DINOv3 + CHMv2 model.
833
-
834
- This [notebook](notebooks/chmv2_dataset_exploration.ipynb) can be used to download inference data from the existing global dataset stored on aws.
835
-
836
- ### CHMv2 model loading (via Hugging Face [Transformers](https://huggingface.co/docs/transformers/))
837
-
838
- The CHMv2 model is also available on [Hugging Face Hub](https://huggingface.co/facebook/dinov3-vitl16-chmv2-dpt-head) and supported via the Hugging Face [Transformers](https://huggingface.co/docs/transformers/index) library. Please refer to the corresponding documentation for usage, but below is a short example that demonstrates how to obtain canopy height predictions on a sample image.
839
-
840
- ```python
841
- from PIL import Image
842
- import torch
843
-
844
- from transformers import AutoModelForDepthEstimation, AutoImageProcessor
845
-
846
- processor = AutoImageProcessor.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")
847
- model = AutoModelForDepthEstimation.from_pretrained("facebook/dinov3-vitl16-chmv2-dpt-head")
848
-
849
- image = Image.open("image.tif")
850
- inputs = processor(images=image, return_tensors="pt")
851
-
852
- with torch.no_grad():
853
- outputs = model(**inputs)
854
-
855
- depth = processor.post_process_depth_estimation(
856
- outputs, target_sizes=[(image.height, image.width)]
857
- )[0]["predicted_depth"]
858
- ```
859
-
860
- ## License
861
-
862
- DINOv3 code and model weights are released under the DINOv3 License. See [LICENSE.md](LICENSE.md) for additional details.
863
-
864
- ## Contributing
865
-
866
- See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
867
-
868
- ## Citing DINOv3
869
-
870
- If you find this repository useful, please consider giving a star :star: and citation :t-rex::
871
-
872
- ```
873
- @misc{simeoni2025dinov3,
874
- title={{DINOv3}},
875
- author={Sim{\'e}oni, Oriane and Vo, Huy V. and Seitzer, Maximilian and Baldassarre, Federico and Oquab, Maxime and Jose, Cijo and Khalidov, Vasil and Szafraniec, Marc and Yi, Seungeun and Ramamonjisoa, Micha{\"e}l and Massa, Francisco and Haziza, Daniel and Wehrstedt, Luca and Wang, Jianyuan and Darcet, Timoth{\'e}e and Moutakanni, Th{\'e}o and Sentana, Leonel and Roberts, Claire and Vedaldi, Andrea and Tolan, Jamie and Brandt, John and Couprie, Camille and Mairal, Julien and J{\'e}gou, Herv{\'e} and Labatut, Patrick and Bojanowski, Piotr},
876
- year={2025},
877
- eprint={2508.10104},
878
- archivePrefix={arXiv},
879
- primaryClass={cs.CV},
880
- url={https://arxiv.org/abs/2508.10104},
881
- }
882
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README_starVLA.md DELETED
@@ -1,446 +0,0 @@
1
- # StarVLA: A Lego-like Codebase for Vision-Language-Action Model Developing
2
-
3
- <!-- [![Update](https://img.shields.io/badge/UPDATE-Scripts%20fixed%20%7C%20Packaging%20smoother-red?style=for-the-badge)](https://github.com/starVLA/starVLA) -->
4
- [![Model & Data on Hugging Face](https://img.shields.io/badge/HuggingFace-Model%20%26%20Data-orange?style=for-the-badge&logo=huggingface)](https://huggingface.co/StarVLA) [![WeChat](https://img.shields.io/badge/WeChat-加入讨论群-brightgreen?style=for-the-badge&logo=wechat)](assets/starVLA_wechat.jpg)
5
-
6
- **[205/12/25]** We've simultaneously established pipelines for [Behavior-1K](examples/Behavior), [RoboTwin 2.0](examples/Robotwin), and CALVIN. We'd love to collaborate and share baseline results for more benchs with the community!
7
-
8
- **[205/12/25]** We've released RoboCasa evaluation support, which trained **without pretraining and reach SOTA performance**. Check out more details in [examples/Robocasa_tabletop](examples/Robocasa_tabletop).
9
-
10
- **[2025/12/15]** Completed a release regression check to ensure the public code runs smoothly. Routine updates—including recent support for the LeRobot dataset v3.0 and DeepSpeed ZeRO-3—will continue to appear in the [🚧 Daily Development Log](https://github.com/starVLA/starVLA/issues/64#issue-3727060165).
11
-
12
- **[2025/12/09]** Be the first open-source repository that can train with [train your vlm](starVLA/training/train_starvlm.py), [train your vla](starVLA/training/train_starvla.py), and [train your vla with vlm](starVLA/training/train_starvla_cotrain.py). Check out how to co-train your VLA with multimodal data in [examples/CoTrainVLM](examples/CoTrainVLM/README.md).
13
-
14
- <details close>
15
- <summary><b> Historical Milestones </b></summary>
16
-
17
- **[2025/11/12]** We now support [Florence-2](https://github.com/anyantudre/Florence-2-Vision-Language-Model) as a smaller VLM for resource-constrained development. StarVLA can now run on a single A100 GPU. See the [🚀Train with a smaller VLM](#train-smaller-vlm) section for more details.
18
-
19
-
20
- **[2025/10/30]:** We released the LIBERO Training & Evaluation README. Results are very promising. More detail are in [examples/LIBERO](examples/LIBERO).
21
-
22
- **[2025/10/25]:** We fixed several script links and so everything is smoother now. Thanks to the community for the feedback.
23
-
24
- </details>
25
-
26
- ---
27
-
28
- StarVLA is a modular and flexible codebase for developing Vision-Language Model (VLM) to Vision-Language-Action (VLA) models.
29
- In StarVLA (also a pun on “start VLA” ), each functional component (model, data, trainer, config, evaluation, etc.) follows a top-down, intuitive separation and high cohesion and low coupling principle, which enabling plug-and-play design, rapid prototyping, and independent debugging.
30
-
31
-
32
-
33
- ![](assets/Framworks.png)
34
- *Modules with solid borders are supported; borderless ones are coming soon.
35
-
36
- ## Projects Based on StarVLA
37
-
38
- **NeuroVLA**: [*A Brain-like Embodied Intelligence for Fluid and Fast Reflexive Robotics Control*](https://github.com/guoweiyu/NeuroVLA)
39
-
40
- **PhysBrain**: [*Human Egocentric Data as a Bridge from Vision Language Models to Physical Intelligence*](https://zgc-embodyai.github.io/PhysBrain)
41
-
42
-
43
- ## 🔥 Key Features
44
-
45
-
46
-
47
- <details open>
48
- <summary><b>Various VLA Frameworks </b></summary>
49
-
50
- - [x] **Qwen-FAST**: Utilizes Qwen2.5-VL-3B with a fast tokenizer to autoregressively generate discrete action tokens conditioned on visual and linguistic inputs (in line with π₀-fast).
51
- - [x] **Qwen-OFT**: Combines Qwen2.5-VL-3B with an MLP action head to perform parallel decoding of continuous actions, regressed from the hidden states of predefined special action tokens (in line with OpenVLA-OFT/EO).
52
- - [x] **Qwen-PI**: Integrates the Flow-Matching (FM) action expert with Qwen2.5-VL-3B, adopting a diffusion-based approach for continuous action prediction (in line with π₀).
53
- - [x] **Qwen-GR00T**: Implements a dual-system VLA architecture, where Qwen2.5-VL-3B serves as System2 for high-level vision-language reasoning, while the Flow-Matching module acts as System1 for rapid action prediction (in line with GR00T).
54
-
55
- <details open>
56
- <summary><b> Results on SimplerEnv </b></summary>
57
-
58
- <p align="center">
59
- <img src="assets/starvla_simpleEnv.png" alt="SimplerEnv modules" width="95%">
60
- </p>
61
-
62
- </details>
63
-
64
-
65
- <details open>
66
- <summary><b> Results on RoboCasa GR1 </b></summary>
67
-
68
- <p align="center">
69
- <img src="assets/stavla_RoboCasa.png" alt="RoboCasa modules" width="94%">
70
- </p>
71
-
72
- </details>
73
-
74
- <details close>
75
- <summary><b> Results on LIBERO </b></summary>
76
-
77
- <p align="center">
78
- <img src="assets/starvla_LIBERO.png" alt="LIBERO modules" width="84%">
79
- </p>
80
-
81
- </details>
82
-
83
-
84
-
85
-
86
- We have more results for RoboCasa, RoboTwin 2.0, Behavior-1k, Calvin. See our [🍀 Overleaf](https://www.overleaf.com/read/qqtwrnprctkf#d5bdce), which continuously presents our real-time experimental results.
87
-
88
-
89
-
90
-
91
-
92
- ### 📈 Model Zoo
93
- We release a series of modified models and finetuning checkpoints to facilitate reproduction and downstream use.
94
-
95
- #### ✅ Available Modified Models
96
-
97
- | Model | Description | Link |
98
- |-------|-------------|------|
99
- | **Qwen2.5-VL-3B-Action** | Extend Qwen2.5-VL's vocabulary with Fast Tokens | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen2.5-VL-3B-Instruct-Action) |
100
- | **Qwen3-VL-4B-Action** | Extend Qwen3-VL's vocabulary with Fast Tokens | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen3-VL-4B-Instruct-Action) |
101
-
102
- #### ✅ Available Finetuning Checkpoints
103
- | Model | Description | WidowX | Link |
104
- |-------|-------------|------|------|
105
- | **QWen2.5-FAST-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 58.6 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-FAST-Bridge-RT-1) |
106
- | **QWen2.5-OFT-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 41.8 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-OFT-Bridge-RT-1) |
107
- | **QWen2.5-PI-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 62.5 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-FM-Bridge-RT-1) |
108
- | **QWen2.5-GR00T-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 63.6 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-PI-Bridge-RT-1) |
109
- | **QWen-GR00T-Bridge** | Training only on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) | 71.4 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen-GR00T-Bridge) |
110
- | **QWen3VL-OFT-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 42.7 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen3VL-OFT-Bridge-RT-1) |
111
- | **QWen3VL-GR00T-Bridge-RT-1** | Training on [Bridge](https://huggingface.co/datasets/IPEC-COMMUNITY/bridge_orig_lerobot) and [Fractal](https://huggingface.co/datasets/IPEC-COMMUNITY/fractal20220817_data_lerobot) | 65.3 | [🤗 Hugging Face](https://huggingface.co/StarVLA/Qwen3VL-GR00T-Bridge-RT-1) |
112
-
113
- ---
114
- </details>
115
-
116
- <details open>
117
- <summary><b>Various Simulation Benchmarks </b></summary>
118
-
119
-
120
- - [x] **SimplerEnV**
121
- - [x] **LIBERO**
122
- - [x] **Robocasa**
123
- - [x] **RoboTwin**
124
- - [x] **BEHAVIOR**
125
- - [ ] **SO101**
126
- - [ ] **Calvin**
127
- - [ ] **RLBench**
128
-
129
- </details>
130
-
131
-
132
- <details close>
133
- <summary><b> Various Training Strategies </b></summary>
134
-
135
- * [x] Single Imitation Learning
136
- * [x] Multimodal Multitasks Co-training
137
- * [ ] Reinforcement Learning Adaption
138
-
139
- </details>
140
-
141
- ---
142
-
143
- ## 🚀 Quick Start
144
-
145
- <details close>
146
- <summary><b>🛠 Environment Setup
147
- </b></summary>
148
-
149
-
150
-
151
- ```bash
152
- # Clone the repo
153
- git clone https://github.com/starVLA/starVLA
154
-
155
- # Create conda environment
156
- conda create -n starVLA python=3.10 -y
157
- conda activate starVLA
158
-
159
- # Install requirements
160
- pip install -r requirements.txt
161
-
162
- # Install FlashAttention2
163
- pip install flash-attn --no-build-isolation
164
-
165
- # Install starVLA
166
- pip install -e .
167
- ```
168
-
169
-
170
- ⚠️ **Common Issues**
171
- flash-attn can be tricky to install because it must match your system’s CUDA toolkit (nvcc) and PyTorch versions. The `--no-build-isolation` flag resolves most issues, but on newer systems you may need to manually choose a compatible flash-attn version. Ensure your CUDA driver/toolkit and torch versions are aligned. Check your environment:
172
-
173
- ```bash
174
- nvcc -V
175
- pip list | grep -E 'torch|transformers|flash-attn'
176
- ```
177
-
178
- If issues persist, pick a flash-attn release that matches your versions (CUDA and torch) or ask chatGPT with searching function for help with the outputs above.
179
-
180
- We have verified that `flash-attn==2.7.4.post1` works well with nvcc versions `12.0` and `12.4`.
181
-
182
- </details>
183
-
184
- <details close>
185
- <summary><b>👀 Quick Check StarVLA
186
- </b></summary>
187
-
188
-
189
-
190
- ```bash
191
- # check framework with fake examples
192
- python starVLA/model/framework/QwenGR00T.py
193
- ```
194
-
195
-
196
- You should download [Qwen3-VL-4B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-4B-Instruct) and put it as `./playground/Pretrained_models/Qwen3-VL-4B-Instruct`. It should build successfully and `print(model)`. You can also call `model.forward(fake_data)` and obtain unnormalized actions via `model.predict_action(fake_data)`.
197
-
198
- </details>
199
-
200
- <details close>
201
- <summary><b>🧪 Evaluate Existing Models</b></summary>
202
-
203
- We publish benchmark-specific evaluation guides inside each folder under [examples](examples).
204
-
205
- **Recommended quick start: LIBERO simulator**
206
-
207
- 1. Download [Qwen2.5-VL-GR00T-LIBERO-4in1](https://huggingface.co/StarVLA/Qwen2.5-VL-GR00T-LIBERO-4in1).
208
- 2. Follow the [LIBERO Eval](https://github.com/starVLA/starVLA/tree/starVLA/examples/LIBERO#-1-environment-setup) instructions to prepare the Python environment.
209
- 3. Set the environment variables at the top of [`eval_libero.sh`](examples/LIBERO/eval_files/eval_libero.sh) and [`run_policy_server.sh`](examples/LIBERO/eval_files/run_policy_server.sh).
210
- 4. Run:
211
-
212
- ```bash
213
- bash examples/LIBERO/eval_files/run_policy_server.sh &
214
- bash examples/LIBERO/eval_files/eval_libero.sh
215
- ```
216
-
217
- ⚠️ **Common issue**
218
- If `NotImplementedError: Framework QwenGR00T is not implemented` appears, run `python starVLA/model/framework/QwenGR00T.py` to verify your environment.
219
-
220
- </details>
221
-
222
- <details open>
223
- <summary><b>🚀 Train Your Own Model</b></summary>
224
-
225
- We ship benchmark-specific training scripts under [examples](examples). We recommend starting with the [LIBERO suite](examples/LIBERO/train_files):
226
-
227
- 1. Edit `run_libero_train.sh` to point to your checkpoint, dataset root, and desired output directory.
228
- 2. Launch training:
229
-
230
- ```bash
231
- bash examples/LIBERO/train_files/run_libero_train.sh
232
- ```
233
-
234
- ⚠️ **Note:** Ensure all absolute paths inside `run_libero_train.sh` match your local environment before launching.
235
-
236
- </details>
237
-
238
-
239
-
240
- ## 🌟 How does starVLA make model development Lego-like again?
241
- 👇 StarVLA achieves “Lego-like” development via the following designs:
242
- <a id="model"></a>
243
- <details close>
244
- <summary><b>1. Smoke test any submodule </b></summary>
245
-
246
- StarVLA emphasizes a modular model design. Each major framework file can be run standalone for rapid debugging and smoke test your code. For example:
247
-
248
- ```bash
249
- # model
250
- python starVLA/model/framework/QwenOFT.py --config_yaml starvla_cotrain_oxe.yaml
251
- # dataloader
252
- python starVLA/dataloader/lerobot_datasets.py --config_yaml starvla_cotrain_oxe.yaml
253
-
254
- ```
255
- Note: `starVLA/model/framework/yourframework.py` is the single external API surface of the model; it should mirror (be structurally isomorphic to) the framework diagram in your paper.
256
- </details>
257
- <a id="data"></a>
258
- <details close>
259
- <summary><b>2. Explicit model boundaries</b></summary>
260
-
261
- StarVLA follows top‑down decomposition and the principle of high cohesion & low coupling.
262
-
263
- For example:
264
- - Dataloader
265
- - Returns a raw, model‑agnostic dict only; no model‑specific preprocessing (e.g., tokenizer, image encoding).
266
- - A single sample should include (add/remove as needed):
267
- - image: list[PIL.Image] | np.ndarray
268
- - lang: str
269
- - action: np.ndarray[T, action_dim]
270
- - state: Optional[np.ndarray[..., state_dim]]
271
-
272
- Both `framework.forward()` and `framework.predict_action()` operate directly on raw inputs, keeping train/test boundaries explicit and easy to hack.
273
- </details>
274
- <a id="config"></a>
275
- <details close>
276
- <summary><b>3. Flexible configuration system</b></summary>
277
-
278
- StarVLA uses a single global configuration object
279
- Parameters are passed primarily via extensible dicts, allowing overrides and controlled redundancy.
280
-
281
- </details>
282
-
283
-
284
- 🧪 *To self‑test and iterate on StarVLA’s usability, we re‑implemented several representative VLA frameworks. Our have done a beta test: an internal developer can stand up a new VLA framework in under half a day (leat then 3 hours), and an new user can build their first custom VLA framework within a single day. More design insights for each item can be found in [assets/intro_v1.md](assets/intro_v1.md).*
285
-
286
-
287
- ---
288
-
289
-
290
- ## 📖 FAQ
291
-
292
- <details close>
293
- <summary><b>Q: Why not put preprocessing in the dataloader?</b></summary>
294
-
295
- A: We profiled it: data preprocessing takes <1% time. Keeping it inside the Framework is acceptable and allows model‑specific flexible handling.
296
-
297
- </details>
298
-
299
- <details close>
300
- <summary><b>Q: Can I use a backbone other than Qwen2.5-VL?</b></summary>
301
-
302
- A: Yes. Implement new vision + language modules and compose them inside a Framework; any other existing models can be swapped in. Yet, due to the framework processing raw action data, it is very easy to swap in.
303
- </details>
304
-
305
- <details close> <summary><b>Q: Why isn't there an abstract interface for the vision tower?</b></summary>
306
-
307
- A: We believe that VLM will become the base model and will inherently possess its own native vision tower.
308
-
309
- </details>
310
-
311
-
312
- <details close>
313
- <summary><b>Q: Can I override or add parameters via the terminal?</b></summary>
314
-
315
- A: Yes. We use OmegaConf.load(args.config_yaml) as the single configuration entry; standalone debugging also uses args.config_yaml. Parameters may be intentionally redundant; you can freely add or override them via the CLI.
316
-
317
- Examples:
318
- ```bash
319
- accelerate launch \
320
- --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
321
- --num_processes 8 \
322
- starVLA/training/train_internvla.py \
323
- --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
324
- --framework.qwenvl.base_vlm Qwen/Qwen2.5-VL-7B-Instruct \ # override framework choice
325
- --framework.qwenvl.base_vlm Qwen/Qwen2.5-VL-7B-Instruct \ # override framework choice
326
- --framework.action_model.new_module ${module_name} \ # plug-in a new module to action model
327
- ```
328
-
329
- ⚠️: `framework.action_model.new_module` only adds to the global config; its behavior is on your framework.
330
-
331
-
332
- </details>
333
-
334
- <details close>
335
- <summary><b>Q: Can I freeze the VLM via parameters?</b></summary>
336
-
337
- A: Yes. StarVLA uses a regex / name list to control freezing. Example:
338
- ```
339
- --trainer.freeze_modules "qwen_vl_interface.model.model.visual,dino_encoder" \
340
- ```
341
- Tips: You can ``print(your_model)`` first to check the relative paths of your modules and list them as comma-separated values.
342
- (implementation in `TrainerUtils.freeze_backbones`.)
343
-
344
- </details>
345
-
346
- <details close>
347
- <summary><b>Q: Can I set different learning rates for different modules?</b></summary>
348
-
349
- A: Yes, starVLA also uses name: value dict to control learning group. Config example:
350
- ```yaml
351
- trainer:
352
- learning_rate:
353
- base: 1e-05 # other modules
354
- qwen_vl_interface: 1.0e-05
355
- action_model: 1.0e-04
356
- ```
357
- (Also referenced in `trainer_tools.build_param_lr_groups`.)
358
- </details>
359
-
360
- <details close>
361
- <summary><b>Q: Can I resume training from a checkpoint?</b></summary>
362
-
363
- A: Yes, somehow can. Specify the latest checkpoint path in `config.yaml`, e.g.:
364
- ```yaml
365
- trainer:
366
- pretrained_checkpoint: path_to_steps_10000.pt
367
- reload_modules: "action_model"
368
- ```
369
- Empty `reload_modules` means full load all model. However, starVLA does not save `optimizer state`. It requires a lot of memory/disk and bring limited benefit.
370
- </details>
371
-
372
-
373
- <details id="train-smaller-vlm" close>
374
- <summary><b>🚀 Train with a smaller VLM</b></summary>
375
-
376
- ```bash
377
- accelerate launch \
378
- --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
379
- --main_process_ip $MASTER_ADDR \
380
- --main_process_port $MASTER_PORT \
381
- --machine_rank $SLURM_PROCID \
382
- --num_machines $SLURM_NNODES \
383
- --num_processes=${TOTAL_GPUS} \
384
- starVLA/training/train_starvla.py \
385
- --config_yaml ./starVLA/config/training/starvla_cotrain_oxe.yaml \
386
- --framework.framework_py QwenGR00T \
387
- --framework.qwenvl.base_vlm microsoft/Florence-2-large \
388
- --run_root_dir ${run_root_dir} \
389
- --run_id ${run_id} \
390
- --wandb_project your_project \
391
- --wandb_entity your_name
392
- ```
393
-
394
- Note: To ensure better compatibility with already released checkpoints, we are continuing to use `--framework.qwenvl`. This parameter will be unified in the next release.
395
-
396
- </details>
397
-
398
-
399
-
400
- ## ✍️ Citation & Copyright
401
-
402
-
403
- StarVLA is released under the MIT License, which permits commercial use, modification, distribution, and private use. Rebases are allowed for forks and feature branches; when rebasing from upstream StarVLA, use descriptive commit messages (e.g., "chore: rebase from StarVLA") and keep at least the two latest upstream commits as separate. See [License](LICENSE) for details.
404
-
405
-
406
- ```
407
- @misc{starvla2025,
408
- title = {StarVLA: A Lego-like Codebase for Vision-Language-Action Model Developing},
409
- author = {starVLA Community},
410
- url = {https://github.com/starVLA/starVLA}
411
- year = {2025}
412
- }
413
- ```
414
-
415
-
416
- ## 🤝 Contributing
417
-
418
-
419
- 1) If you find an issue, please open an Issue first. If it persists or needs clarification, start a Discussion and we’ll follow up.
420
-
421
- 2) If you have ideas to improve StarVLA, feel free to open a PR. To make sure we will accept your effect, please align scope and design first via an Issue or by booking a short sync with this [Cooperation Form](https://forms.gle/R4VvgiVveULibTCCA).
422
-
423
- 3) If you’re blocked or want to brainstorm, please fill out the [Cooperation Form](https://forms.gle/R4VvgiVveULibTCCA). We host office hours every Friday afternoon for live discussion.
424
-
425
- Tip: Before submitting a PR, run make check locally to pass formatting and lint.
426
-
427
-
428
- ## 🙏 Acknowledgements
429
- This project draws inspiration and references from several notable open-source initiatives, including:
430
- - [LeRobot](https://github.com/huggingface/lerobot)
431
- - [GR00T](https://github.com/NVIDIA/Isaac-GR00T/tree/main)
432
- - [DeepSpeed](https://github.com/deepspeedai/DeepSpeed)
433
- - [Qwen-VL](https://github.com/QwenLM/Qwen3-VL/tree/main)
434
- - [InternVL](https://github.com/OpenGVLab/InternVL)
435
-
436
- The codebase was originally forked from [InternVLA-M1](https://github.com/InternRobotics/InternVLA-M1).
437
-
438
-
439
-
440
- # Star History
441
- Here's how our community has grown over time:
442
-
443
- [![Star History Chart](https://api.star-history.com/svg?repos=starVLA/starVLA&type=date&legend=bottom-right)](https://www.star-history.com/#starVLA/starVLA&type=date&legend=bottom-right)
444
-
445
-
446
- <!-- *Chart updates automatically. Click to interact with the full timeline.* -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
THIRD_PARTY_NOTICES.md CHANGED
@@ -1,25 +1,55 @@
1
- # Third-Party Sources
2
-
3
- This directory is a private reproducibility archive, not a declaration that
4
- all upstream code, weights, and assets have one common license.
5
-
6
- - RoboCasa: original license is retained at `third_party/robocasa/LICENSE`.
7
- - RoboSuite: upstream license is retained at `third_party/robosuite/LICENSE`.
8
- Its collection source is recorded in
9
- `provenance/runtime_versions_and_licenses.json`.
10
- - pykdl_utils and hrl_geom: original `package.xml` and source copyright
11
- headers are retained; both package manifests declare BSD. No standalone
12
- LICENSE file was found in the copied upstream roots. Resolve the complete
13
- applicable license text before public redistribution.
14
- - Orocos KDL / PyKDL 1.5.4: the recovered source and its original notices,
15
- including `orocos_kdl/COPYING`, are vendored. Its pybind11 source/notices
16
- are also retained. See `provenance/kdl_source.json` for the source revision.
17
- - GR1 robot geometry and RoboCasa object assets: preserve all embedded
18
- notices; their redistribution rights must be reviewed separately.
19
- - Original starVLA, NVIDIA simulation wrappers, VJEPA, model metadata, and
20
- other source headers/notices are preserved. Backbone weight licenses must
21
- also be reviewed before distribution; do not relicense them as project code.
22
-
23
- The owner authorized a private Hugging Face archive. This does not authorize
24
- public redistribution. No public-distribution license or permission has been
25
- inferred from local access to these resources.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Third-Party Notices
2
+
3
+ Removing first-party personal paths and optional bylines does not remove
4
+ legally required third-party attribution. Upstream authors are not being
5
+ presented as authors of the anonymous submission.
6
+
7
+ | Component | Retained notice or scope |
8
+ |---|---|
9
+ | StarVLA-derived model/training framework | Existing source headers and `LICENSES/StarVLA-MIT.txt` |
10
+ | OpenVLA-derived logging utilities | `LICENSES/OpenVLA-MIT.txt` |
11
+ | NVIDIA GR00T-derived data and simulation utilities | Existing Apache-2.0 headers |
12
+ | VJEPA2 source | `starVLA/facebookresearch_vjepa2_main/LICENSE` and `APACHE-LICENSE` |
13
+ | NVIDIA Cosmos pretrained components | `NOTICE` and `LICENSES/NVIDIA-Open-Model-License.html`; no relicensing of weights |
14
+ | VJEPA2-AC pretrained components | Original model terms remain applicable; source MIT license is not a blanket weight license |
15
+ | RoboCasa | `third_party/robocasa/LICENSE` |
16
+ | RoboSuite | `third_party/robosuite/LICENSE` |
17
+ | hrl_geom and pykdl_utils | Original source headers and package manifests, including BSD notices |
18
+ | Orocos KDL / PyKDL | `third_party/orocos_kinematics_dynamics/orocos_kdl/COPYING` and source notices |
19
+ | pybind11 | Vendored `LICENSE` within the KDL source tree |
20
+ | GR1 geometry and RoboCasa/RoboSuite objects | Embedded asset notices and applicable original asset terms |
21
+ | Tokenizer/model metadata | Original upstream component terms |
22
+
23
+ The Hugging Face resource repository's existing visibility is preserved.
24
+ Making it public requires confirming the applicable model and asset
25
+ redistribution terms; this package does not infer permission solely from
26
+ files being present on a research server.
27
+
28
+ The model/tokenizer metadata and complete checkpoint are used together;
29
+ downloading an unrelated newer backbone is not an equivalent reconstruction.
30
+ Third-party code is retained only as required by this model's training and
31
+ evaluation stack, including ancestor classes and shared dependency helpers.
32
+
33
+ ## License Sources
34
+
35
+ The standalone texts were retrieved from their upstream publishers on
36
+ September 27, 2026:
37
+
38
+ - [StarVLA MIT license](https://github.com/starVLA/starVLA/blob/starVLA_dev/LICENSE)
39
+ - [OpenVLA MIT license](https://github.com/openvla/openvla/blob/main/LICENSE)
40
+ - [NVIDIA Open Model License](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/)
41
+
42
+ The NVIDIA agreement retained here states a version release date of
43
+ October 24, 2025. The copy preserves the complete agreement text, including
44
+ its separate-component, attribution, guardrail, and trustworthy-AI terms.
45
+ `LICENSES/Apache-2.0.txt` is also retained for Apache-licensed source files.
46
+
47
+ ## Deployment Boundary
48
+
49
+ The inherited Cosmos wrapper uses an optional no-op safety-checker adapter
50
+ for the archived robotics research path. This release does not establish
51
+ that this adapter constitutes a compliant replacement guardrail for any
52
+ particular use or deployment. Review the applicable upstream agreement
53
+ and provide appropriate safeguards before distributing a service or
54
+ using the model outside the controlled simulation benchmark. Do not
55
+ interpret private repository access as a waiver of upstream terms.
TRAINING_PROVENANCE.md DELETED
@@ -1,54 +0,0 @@
1
- # Training Provenance
2
-
3
- ## What Was Recovered
4
-
5
- - Run-saved `provenance/training/run_yzh_cosmos25_perceiver_vjepa2_ac_resume.sh`.
6
- - The run's saved `config.yaml`, `dataset_statistics.json`, and
7
- `summary.jsonl`, under `provenance/training/`.
8
- - Trainer source `starVLA/training/train_starvla.py` and data/model source.
9
- - Per-file source hashes and original modification times in
10
- `provenance/source_snapshot.json`.
11
-
12
- The current project and its `_back` copy were compared during collection;
13
- the selected code contents were identical. A backup directory name is not
14
- evidence of a separate historical version. Original notebook checkpoints,
15
- where present, are retained as evidence, not substituted automatically.
16
-
17
- ## Run Identity
18
-
19
- - Model run: `cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10`.
20
- - Selected released checkpoint step: 280000.
21
- - Dataset mixture: `robocasa_teleop_ee`, original root
22
- `/mnt/workspace/datasets/`.
23
- - Dataset files were NOT migrated. The saved normalization statistics were.
24
- - Final run configuration takes precedence over stale comments or today's
25
- example launch scripts.
26
-
27
- WM4A resumes from
28
- `robocasa_06-26-16-51/checkpoints/steps_180000_pytorch_model.pt`.
29
- The selected 280000-step checkpoint is from the resumed run.
30
-
31
- Initialization resources in the archived script:
32
-
33
- - Cosmos-Predict2.5-2B-Post-Trained, revision
34
- `diffusers/base/post-trained`.
35
- - VJEPA2-AC `vjepa2-ac-vitg.pt` and the vendored VJEPA repository.
36
- - The preceding 180000-step policy checkpoint.
37
-
38
- The archived script's comment says 25000/50000 steps and loss 0.05, but its
39
- actual arguments and saved config specify 180000-step resume, 300000 target
40
- steps, and future-latent loss weight 0.01. Do not use that comment as protocol.
41
- Saved per-device batch size is 14, checkpoint interval 20000, warmup 2000.
42
-
43
- ## Limits And Safe Use
44
-
45
- Exact training reproduction is NOT validated. No training was launched.
46
- The archived scripts contain historical absolute paths and eight-GPU defaults;
47
- they are evidence, not safe one-click commands for a shared host. Update paths,
48
- obtain an explicit allocation, and set `CUDA_VISIBLE_DEVICES` before adapting
49
- them. Required datasets, initialization weights, and any optimizer/resume
50
- states have not been bundled or proven complete.
51
-
52
- The evaluation preparer reconstructs initialization files from the FINAL
53
- policy checkpoint. These files are suitable for loading that policy, not for
54
- reconstructing its original training initialization.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
VALIDATION.md DELETED
@@ -1,222 +0,0 @@
1
- # Validation Status
2
-
3
- Diagnostic date: September 26, 2026 (Asia/Shanghai).
4
-
5
- ## Current Result
6
-
7
- The full migrated RoboCasa benchmark was STOPPED at the user's request at
8
- 2026-09-25T16:21:29Z (September 26, 00:21:29 Asia/Shanghai).
9
- Closed-loop effectiveness has NOT been reproduced. The completed first task,
10
- cup-to-drawer-close, scored 0/50 versus the historical 11/50. The next task
11
- was interrupted and must not be counted as a finished result.
12
- No new complete 24-task mean success rate is available.
13
-
14
- - Host: exact SSH alias `perdon-hou`, verified hostname `nb-5pl2apckdj-0`.
15
- - Checkpoint: step 280000; original pinned SHA-256 verified.
16
- - Strict checkpoint load passed in both the precheck and the full-run process.
17
- - Policy GPU: 0; simulation CUDA/EGL GPU: 1.
18
- - Stopped full-run coordinator PID: 538455; its recorded children also exited.
19
- - Full-run output: `/mnt/workspace/users/maxiangkai/migrations/MaskWAM_WM4A_perdon_hou_20260925T143800Z/WM4A/.runtime/full_01`.
20
- - Historical mean (reference only, NOT a new result): 56.17%.
21
-
22
- ## Open-Loop Diagnostics
23
-
24
- 36 fixed demonstration windows from 9 episodes and 3 tasks were tested with
25
- the original checkpoint normalization statistics and per-window seeds.
26
- The original project/initialization paths and the migrated paths produced
27
- bitwise-identical predictions for both tested input pipelines (72 paired
28
- predictions, maximum absolute difference 0).
29
-
30
- | Input Pipeline | Active-Dimension Action MAE |
31
- | --- | ---: |
32
- | Evaluation client inputs | 0.03853773 |
33
- | Dataset EE state instead of client FK | 0.03853773 |
34
- | Subtask prompt instead of Task prompt | 0.03840540 |
35
- | Dataset EE state, Subtask prompt, PIL resize | 0.03988905 |
36
-
37
- Metrics use the first 12 executed actions, 27 active normalized dimensions.
38
- These are demonstration diagnostics, not held-out success rates.
39
- FK versus preconverted EE states has maximum position discrepancy below
40
- 4e-8 m. Changing only the state to dataset EE values changes predicted
41
- actions by at most 3.19e-6, not exactly zero.
42
-
43
- Ground-truth EE actions passed 864 IK checks with no residual exceeding
44
- 1 mm or 0.01 rad. Predicted actions exceeded that threshold on 12/864
45
- checks (3 cup, 9 potato). Four fixed-seed tests with future-image generation
46
- enabled showed no change to the current or subsequent action prediction.
47
- Three reset-only simulator observations were captured without policy steps;
48
- their images are not blank, and the inspected frame has the expected
49
- orientation and cropped/padded camera layout.
50
-
51
- This does NOT establish the cause of the 0/50 regression or prove July
52
- runtime equivalence. The source-path A/B used today's available original
53
- code and the same current policy environment, not an immutable July runtime.
54
- The 222 vendored RoboSuite source files match the collected
55
- `robocasa_liao` source; differences in another editable RoboSuite checkout
56
- are not evidence that the migrated evaluation used it.
57
-
58
- Detailed evidence and runnable diagnostic scripts:
59
- `provenance/validation/wm4a_openloop_20260925T163212Z/`.
60
- The WM4A full evaluation remains stopped. No model weights, training code,
61
- simulator source, shared environment, or driver were modified by these tests.
62
-
63
- ## Controlled Follow-Up
64
-
65
- Evidence: `provenance/validation/wm4a_followup_20260925T170412Z/REPORT.md`.
66
- The historical effectiveness regression remains unresolved. The full sweep
67
- was not restarted, and no experimental IK change was promoted to default.
68
-
69
- The original cup demonstration (LeRobot episode 0 / HDF5 demo_245) was restored
70
- with bitwise-identical initial simulator state. Recorded joint actions and
71
- recorded EE actions through the actual WM4A client/IK both completed the task
72
- from step 213. Model-driven execution from that same state failed after
73
- 720 steps. This validates that particular demonstration/control path, not
74
- all scenes or historical runtime equivalence.
75
-
76
- In a separate fixed-constructor-seed scene, the baseline, per-chunk IK-cache
77
- reset, and bounded 5 mm approximate IK fallback all failed. Their initial
78
- state, scene XML and first prediction were identical. IK residual misses
79
- at the common 1 mm / 0.01 rad threshold were 429, 317 and 427 out of 1440.
80
- No transient successful substep was omitted by the legacy aggregation in
81
- the five model-driven diagnostic episodes.
82
-
83
- The controlled BF16 implementation matched all 36 prior open-loop outputs
84
- bitwise. Restoring action-head weights in FP32 changed MAE only from
85
- 0.03853773 to 0.03852874. All 901 Diffusers and 2347 Transformers Python
86
- files compared against the June 16 environment archive matched.
87
-
88
- The diagnostic now distinguishes clipped actuator tracking error from raw
89
- hand-command differences, and explicitly seeds RoboSuite's constructor.
90
- Merely calling reset(seed) does not seed its separate RNG. These corrections
91
- are isolated diagnostic changes; the release's general --seed path is not
92
- certified for multi-episode determinism.
93
-
94
- All 1505 sealed source hashes and four release unit tests passed. The
95
- diagnostic server and rollout processes exited; MaskWAM and unrelated jobs
96
- were not signaled. The evidence preserves scripts, predictions, simulator
97
- states, source frames, execution records, and checksums.
98
-
99
- ## Conditioning And Replanning
100
-
101
- Evidence: `provenance/validation/wm4a_conditioning_20260925T175334Z/REPORT.md`.
102
- No repair was promoted and the full benchmark remains stopped.
103
-
104
- The 36 fixed windows were tested with seven paired conditions. Baseline
105
- outputs again match the prior predictions bitwise. Image, language, and state
106
- interventions change internal features and actions; no entire input branch
107
- was found disconnected. Normalized MAE was 0.03854 at baseline, 0.16592 with
108
- black images, 0.16410 with other-task images, 0.05666 with other-task language,
109
- and 0.27769 with other-task states. These interventions are not realistic
110
- evaluation conditions or proof of correct task understanding.
111
-
112
- At the matched demonstration start, replacing the recorded frame with the
113
- reconstructed frame changes target positions by only 3.61/2.89 mm on average
114
- for left/right arms and slightly improves this window's error. This is not
115
- a validation of all subsequent rendered observations.
116
-
117
- Six-step rather than twelve-step execution was tested in two paired scenes,
118
- with initial simulator state, XML, first input and prediction all identical.
119
- Model seeds were aligned at shared physical timesteps. Both episodes failed
120
- after 720 steps. IK misses changed from 386 to 187 in demo_245 and from 429
121
- to zero in the seeded random scene, out of 1440 calls each. Thus IK failure
122
- alone does not explain every unsuccessful episode.
123
-
124
- A further oracle-conditioned replay used the original demonstration images
125
- and states for all 19 model calls. Its predicted actions failed over the
126
- demonstration's 228 transitions, while both recorded-action controls succeeded
127
- from step 213. Mean EE target errors were 4.55/2.78 cm and mean orientation
128
- errors 0.167/0.178 rad. This is not autonomous evaluation, and recorded future
129
- inputs can become inconsistent with the evolving scene. It shows that
130
- correcting the input distribution alone was insufficient in this case.
131
-
132
- The v1 diagnostic's all-dimension `hold_state` metric is invalid because hand
133
- observations and action commands use different conventions. It is preserved
134
- but explicitly excluded in `conditioning/metrics_corrected.json` and
135
- `comparison.json`. Only the direct EE XYZ hold baseline is used.
136
-
137
- All experiments were bounded and their processes exited. The sealed model
138
- and simulator sources, checkpoints, shared environments, and other jobs were
139
- not changed. The historical effectiveness discrepancy remains unresolved.
140
-
141
- ## Action Components And Sampling
142
-
143
- Evidence: `provenance/validation/wm4a_action_components_20260925T184142Z/REPORT.md`.
144
- No repair was promoted; the full benchmark remains stopped.
145
-
146
- Six component replays used the same demonstration, 19 recorded-input model
147
- calls, and 228 executed transitions. Actual restored simulator states match
148
- bitwise, as do all untouched action channels. The unchanged model reproduces
149
- the prior failed replay exactly. Replacing only both arms' Cartesian XYZ with
150
- recorded targets succeeds from step 215. Full recorded actions and recorded
151
- complete EE poses succeed from steps 213 and 216. Replacing only rotations or
152
- hand commands still fails. These are oracle-action interventions on one scene,
153
- not autonomous evaluation or a validated repair.
154
-
155
- The real collected training transforms and mixture sample assembly were
156
- exercised on 55 windows without constructing shared caches. Layout and masks
157
- match the expected 64-state/32-action padded schema; all 36 prior training
158
- images and prompts match exactly. FP16 intermediate casting changes 83/3520
159
- state elements after BF16 conversion. Independently merging the current
160
- 24-dataset min/max statistics exactly reproduces the checkpoint's state and
161
- action bounds. This is not immutable historical training-source validation.
162
-
163
- Nineteen baseline predictions and their isolated head replays match bitwise.
164
- With fixed backbone/VAE features, eight independent head draws have conditional
165
- XYZ spread of 0.945/0.688 cm RMS versus finite-sample mean errors of
166
- 5.424/3.483 cm RMS against the demonstration. This weakens a pure head-noise
167
- explanation on these windows, not every possible source of randomness.
168
-
169
- Four inference variants were replayed without replacing action targets:
170
- eight-draw XYZ averaging, 80 instead of 20 integration steps, training state
171
- casting only, and complete current training inputs. All fail and none brings
172
- the cup into the drawer. XYZ averaging and denser integration reduce maximum
173
- cup lift to about 1.21 and 0.71 cm. Small normalized-MAE improvements do not
174
- justify adopting a candidate.
175
-
176
- CPU-only state-encoder comparisons across five checkpoints are consistent
177
- with the current padded input layout, but cannot prove historical semantics.
178
- All diagnostic jobs exited. One failed CPU-only launcher path attempt is
179
- retained alongside its successful retry. All 1505 sealed source hashes and
180
- four release tests passed locally and remotely. No original weights, sealed
181
- sources, dataset metadata, shared environment, or unrelated jobs were changed.
182
-
183
- ## Completed Precheck
184
-
185
- The cutting-board-to-pan task completed one whole episode: 60 finite action
186
- chunks of shape [1, 12, 29], with up to 12 simulator steps per chunk and a
187
- 720-step episode cap.
188
- The task outcome was 0/1; elapsed simulation time was
189
- 130.46 seconds. This single episode is a runtime
190
- check, not an estimate of the 24-task mean.
191
-
192
- The first attempt used GPU 0 for both policy and rendering and aborted in MuJoCo read_pixels after 40 action calls. No new kernel Xid was observed. The successful end-to-end retest kept policy inference on GPU 0 and moved simulation CUDA/EGL to GPU 1 through the archived host-only sim-python-render1 wrapper. The original failed evidence is retained; no model or task source was changed.
193
-
194
- ## Protocol And Environment
195
-
196
- The stopped sweep requested 24 tasks with 50 episodes each, n_envs=1,
197
- 720 maximum simulator steps, action chunks of 12, shift=5.0, and
198
- the historical top-level inference argument of 5. The action head actually
199
- uses its saved `num_inference_timesteps=20`; the top-level argument is not
200
- forwarded to that action branch. As in the original scripts, no seed was
201
- applied. Independent unseeded reruns are not bitwise-identical reproductions.
202
-
203
- Full-run video encoding was disabled. Camera observation rendering and
204
- future-image inference were enabled. Precheck videos remain on the server.
205
-
206
- The repository's sealed sources and the 44,901 simulation asset files were
207
- verified. The pinned policy and simulation environments passed their CPU
208
- doctor checks. Simulation uses the rebuilt KDL/PyKDL 1.5.4 rather than this
209
- host's system KDL 1.5.1. Host-native NVIDIA EGL libraries are used; no driver
210
- reset, replacement, or other user's process management was performed.
211
-
212
- Code was copied from the latest case-safe Mac release. Existing checkpoints,
213
- backbone caches, environments, and simulation assets were reused on the shared
214
- filesystem, with new per-host runtime configs in an isolated directory.
215
-
216
- Initial evidence is in `provenance/validation/perdon_hou_20260925T143800Z/`.
217
- Its original status snapshots predate the user-requested stop; the new
218
- open-loop evidence contains the stop record and updated process snapshot.
219
- Incomplete runs must not be reported as the full benchmark.
220
-
221
- Clean-machine installation remains unvalidated. The owner has now authorized
222
- private publication; upload completion is recorded separately in publication receipts.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archives/simulation_assets.manifest.json DELETED
@@ -1,11 +0,0 @@
1
- {
2
- "format": "simulation-assets-tar-gzip-v1",
3
- "archive": "archives/simulation_assets.tar.gz",
4
- "archive_bytes": 4528296178,
5
- "archive_sha256": "bb84af93bf7fb93afa1068f1532321e473e70bf4dc6e09c8406bff4e8d8f3987",
6
- "asset_manifest": "provenance/simulation_assets.sha256.json",
7
- "asset_manifest_sha256": "2a0486de9d46ba92ebb60313ecca831257945b9b746833f7c32a8893f811cdc0",
8
- "file_count": 44901,
9
- "expanded_bytes": 9569959833,
10
- "source": "Unchanged pinned RoboCasa and RoboSuite assets from the original release."
11
- }
 
 
 
 
 
 
 
 
 
 
 
 
archives/simulation_assets.tar.gz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bb84af93bf7fb93afa1068f1532321e473e70bf4dc6e09c8406bff4e8d8f3987
3
- size 4528296178
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:411c6fcedb435e0b9bbfd2df3ece274a4bdd94838dcd0bed3fb5c4d43ca2a0a7
3
+ size 4526090391
checkpoints/README.md DELETED
@@ -1,9 +0,0 @@
1
- # Selected Checkpoint
2
-
3
- Filename: `steps_280000_pytorch_model.pt`.
4
-
5
- Bytes: 24232783701
6
-
7
- SHA-256: `eeba9505f715b582a054baac1ef5b599f1da225cabcc060631c23f2f47affe6c`
8
-
9
- Included in private repository `mxk1998/WM4A`. Run `hf download mxk1998/WM4A --local-dir WM4A` to download code, metadata, assets, and weights together. Original source provenance is retained in `release_manifest.json`.
 
 
 
 
 
 
 
 
 
 
checkpoints/{steps_280000_pytorch_model.pt → steps_340000_pytorch_model.pt} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:eeba9505f715b582a054baac1ef5b599f1da225cabcc060631c23f2f47affe6c
3
- size 24232783701
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34bf115c1c99a33b12c79e1dca20e596cd510f006060687c2f145fecea58e60e
3
+ size 23913608021
{provenance/training → configs}/dataset_statistics.json RENAMED
@@ -2,62 +2,62 @@
2
  "gr1": {
3
  "action": {
4
  "mean": [
5
- -0.21876343188173847,
6
- 0.2542603764649471,
7
- 0.25735592673342955,
8
- -1.4224419770189038,
9
- 1.4118179686618095,
10
- 0.9677413259014092,
11
- 0.254269787329523,
12
- 0.20157558706046844,
13
- 0.2765700918702938,
14
- -0.9719737473547996,
15
- 1.5285823525405,
16
- 1.1287437600830488,
17
- -0.9470593414215445,
18
- -0.9470593414215445,
19
- -0.9470593414215445,
20
- -0.9470593414215445,
21
- -1.894118682843089,
22
- 2.969905206790079,
23
- -0.38956377270811676,
24
- -0.38956377270811676,
25
- -0.38956377270811676,
26
- -0.38956377270811676,
27
- -0.7791275454162335,
28
- 2.995247075905939,
29
- 0.0167513807637824,
30
- -0.0010199848207943503,
31
- -0.0006947491371756172
32
  ],
33
  "std": [
34
- 0.09531156752147128,
35
- 0.13266087684176503,
36
- 0.11363675897117656,
37
- 0.3764595681762554,
38
- 0.458622587818543,
39
- 0.3358352130914343,
40
- 0.12306605055805975,
41
- 0.1506433183313249,
42
- 0.10305792541838607,
43
- 0.6731021746504093,
44
- 1.0187575673049833,
45
- 0.791204030896671,
46
- 1.1534490210902855,
47
- 1.1534490210902855,
48
- 1.1534490210902855,
49
- 1.1534490210902855,
50
- 2.306898042180571,
51
- 0.29904643682994947,
52
- 1.447285062842051,
53
- 1.447285062842051,
54
- 1.447285062842051,
55
- 1.447285062842051,
56
- 2.894570125684102,
57
- 0.11911505389401549,
58
- 0.10979417240362366,
59
- 0.03266003831450842,
60
- 0.009266060930719335
61
  ],
62
  "max": [
63
  0.18902048468589783,
@@ -207,62 +207,62 @@
207
  },
208
  "state": {
209
  "mean": [
210
- -0.22014223798204993,
211
- 0.25218131588053977,
212
- 0.261454521303592,
213
- -1.4405245319783067,
214
- 1.4169323001695608,
215
- 0.9483970371150393,
216
- 0.25441613800387486,
217
- 0.20238844294536984,
218
- 0.27860676402857903,
219
- -0.9910073117595959,
220
- 1.559255840740919,
221
- 1.1344707605498425,
222
- 0.2429258048016598,
223
- 0.2383670441400774,
224
- 0.2184290082287895,
225
- 0.2369022090512687,
226
- 0.10050031683771325,
227
- 1.6715468975601704,
228
- 0.5027539195977146,
229
- 0.478607841076631,
230
- 0.43599225253180557,
231
- 0.4730392101029478,
232
- 0.10309797051610864,
233
- 1.6500738313137586,
234
- 0.015432866539153255,
235
- -0.002662589718388015,
236
- -0.0012116882831174618
237
  ],
238
  "std": [
239
- 0.09414176222410257,
240
- 0.1304401813324153,
241
- 0.10956786736212597,
242
- 0.3748300872769308,
243
- 0.4599697142377281,
244
- 0.3322703461212594,
245
- 0.12004850920968421,
246
- 0.14708570352189312,
247
- 0.09991826052817084,
248
- 0.6701938243514319,
249
- 0.9861195388106089,
250
- 0.7678446717932913,
251
- 0.5111558802292329,
252
- 0.5016052745985133,
253
- 0.4620317913465825,
254
- 0.4991993195415816,
255
- 0.24986408401194538,
256
- 0.2729500738984188,
257
- 0.6078879940152446,
258
- 0.5730806777610653,
259
- 0.5181166949285014,
260
- 0.5654965025688024,
261
- 0.22330820141030752,
262
- 0.24597395584778262,
263
- 0.10491566880281573,
264
- 0.031360778810970005,
265
- 0.012937526183543083
266
  ],
267
  "max": [
268
  0.18659894168376923,
@@ -381,7 +381,7 @@
381
  0.055504518561065135
382
  ]
383
  },
384
- "num_transitions": 5460277,
385
  "num_trajectories": 24000
386
  }
387
  }
 
2
  "gr1": {
3
  "action": {
4
  "mean": [
5
+ -0.2186863058533082,
6
+ 0.254326967023003,
7
+ 0.25643251372139036,
8
+ -1.4223759199199852,
9
+ 1.4129110507198768,
10
+ 0.9691956281193489,
11
+ 0.2540388119338039,
12
+ 0.20048292611196247,
13
+ 0.2766831046034787,
14
+ -0.9696032089230912,
15
+ 1.5296555022567568,
16
+ 1.1284871991973162,
17
+ -0.953747134339454,
18
+ -0.953747134339454,
19
+ -0.953747134339454,
20
+ -0.953747134339454,
21
+ -1.907494268678908,
22
+ 2.96978184522707,
23
+ -0.3895600661728508,
24
+ -0.3895600661728508,
25
+ -0.3895600661728508,
26
+ -0.3895600661728508,
27
+ -0.7791201323457017,
28
+ 2.995327029583905,
29
+ 0.01670360130267771,
30
+ -0.0010863468610843273,
31
+ -0.0006765031380749326
32
  ],
33
  "std": [
34
+ 0.0948809278566271,
35
+ 0.1322934088064512,
36
+ 0.11340718149210828,
37
+ 0.37299825049661955,
38
+ 0.45464031185546744,
39
+ 0.33339533526234627,
40
+ 0.12309631816074884,
41
+ 0.15014480703681604,
42
+ 0.10260487127477848,
43
+ 0.6737258943941924,
44
+ 1.0213784182611938,
45
+ 0.7926987422318862,
46
+ 1.1478824532975211,
47
+ 1.1478824532975211,
48
+ 1.1478824532975211,
49
+ 1.1478824532975211,
50
+ 2.2957649065950423,
51
+ 0.29965445606144164,
52
+ 1.447301372218271,
53
+ 1.447301372218271,
54
+ 1.447301372218271,
55
+ 1.447301372218271,
56
+ 2.894602744436542,
57
+ 0.11811250504978604,
58
+ 0.10869733418859324,
59
+ 0.03241877397412978,
60
+ 0.009168184673936977
61
  ],
62
  "max": [
63
  0.18902048468589783,
 
207
  },
208
  "state": {
209
  "mean": [
210
+ -0.22008484204668527,
211
+ 0.2522345320331245,
212
+ 0.26058987434499226,
213
+ -1.4404611848677213,
214
+ 1.4180768351988169,
215
+ 0.9496541538897287,
216
+ 0.254181280876807,
217
+ 0.20129263039608483,
218
+ 0.2787317979273453,
219
+ -0.9886652352941244,
220
+ 1.5602585715832913,
221
+ 1.1343410616559106,
222
+ 0.2399731660217601,
223
+ 0.23547857305439018,
224
+ 0.21583271640580945,
225
+ 0.23403389156571958,
226
+ 0.10023723508260121,
227
+ 1.6714891000112997,
228
+ 0.5027580153027023,
229
+ 0.4784723956457148,
230
+ 0.4361090483145588,
231
+ 0.4729139292368944,
232
+ 0.1019933222467882,
233
+ 1.649660824576679,
234
+ 0.015394441213859134,
235
+ -0.0027341533103602267,
236
+ -0.0012192255130304397
237
  ],
238
  "std": [
239
+ 0.09370971541827343,
240
+ 0.13008819170428582,
241
+ 0.10933323401037695,
242
+ 0.37158662873105086,
243
+ 0.4560435987572224,
244
+ 0.3301418880851555,
245
+ 0.1200648501030723,
246
+ 0.14658516607767536,
247
+ 0.09943411032799544,
248
+ 0.6705285733597247,
249
+ 0.9884809053579303,
250
+ 0.769215931642799,
251
+ 0.5088649328819652,
252
+ 0.4994423897195893,
253
+ 0.4601626860421562,
254
+ 0.49701709942144695,
255
+ 0.24986686845927628,
256
+ 0.2734505027908381,
257
+ 0.6072203087893137,
258
+ 0.5721576546232615,
259
+ 0.5174364208411253,
260
+ 0.5645557735507051,
261
+ 0.22201746347928236,
262
+ 0.24612379771611284,
263
+ 0.10387487513090514,
264
+ 0.031136704866345462,
265
+ 0.012857267171092904
266
  ],
267
  "max": [
268
  0.18659894168376923,
 
381
  0.055504518561065135
382
  ]
383
  },
384
+ "num_transitions": 5820277,
385
  "num_trajectories": 24000
386
  }
387
  }
provenance/training/config.yaml → configs/pilot_340000.yaml RENAMED
@@ -1,10 +1,14 @@
1
  datasets:
2
  vla_data:
3
  data_mix: robocasa_teleop_ee
4
- data_root_dir: /mnt/workspace/datasets/
5
  dataset_py: lerobot_datasets
6
  delete_pause_frame: false
7
  per_device_batch_size: 14
 
 
 
 
8
  framework:
9
  action_model:
10
  action_dim: 32
@@ -42,9 +46,9 @@ framework:
42
  max_samples: 1
43
  max_sequence_length: 512
44
  negative_prompt: null
45
- num_frames: 93
46
  num_inference_steps: 20
47
- num_latent_conditional_frames: 2
48
  output_type: pil
49
  return_full_video: false
50
  width: 224
@@ -55,45 +59,45 @@ framework:
55
  train_time_distribution: logitnormal
56
  future_latent_training:
57
  enabled: true
58
- loss_weight: 0.01
59
  shift: 5.0
60
  train_time_distribution: logitnormal
61
  name: CosmoPredict25PerceiverVJEPA2AC
62
  obs_image_size: null
63
  qwenvl:
64
- base_vlm: /mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
65
  vl_hidden_dim: 2048
66
  vjepa2_ac:
67
- pretrained: /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt
68
- repo_dir: /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main
69
  world_model:
70
- base_wm: /mnt/workspace/users/maxiangkai/models/Cosmos-Predict2.5-2B-Post-Trained
71
  conditional_frame_timestep: 0.1
72
  extract_layers:
73
  - -1
74
  height: 224
75
  revision: diffusers/base/post-trained
76
  width: 224
77
- output_dir: /mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-28-13-10
78
- run_id: robocasa_06-28-13-10
79
- run_root_dir: /mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent
80
  seed: 42
81
  trainer:
82
  eval_interval: 500
83
  freeze_modules: null
84
  gradient_accumulation_steps: 1
85
  gradient_clipping: 1.0
86
- is_resume: true
87
  learning_rate:
88
- action_model: 1.5e-05
89
- action_projector: 1.5e-05
90
  base: 1.0e-05
91
  qwen_vl_interface: 1.0e-05
92
- state_projector: 1.5e-05
93
- vjepa_predictor: 1.5e-05
94
  logging_frequency: 500
95
  lr_scheduler_type: cosine_with_min_lr
96
- max_train_steps: 300000
97
  num_warmup_steps: 2000
98
  optimizer:
99
  betas:
@@ -101,10 +105,12 @@ trainer:
101
  - 0.999
102
  eps: 1.0e-08
103
  weight_decay: 0.1
104
- pretrained_checkpoint: /mnt/workspace/users/maxiangkai/projects/WM4A/outputs/cosmopredict25_vjepa_ImageLatent/robocasa_06-26-16-51/checkpoints/steps_180000_pytorch_model.pt
105
  repeated_diffusion_steps: 4
106
- save_interval: 20000
107
  scheduler_specific_kwargs:
108
- min_lr: 1.0e-07
109
- wandb_entity: mxk
110
- wandb_project: joyRA_robocasa_mxk
 
 
 
 
1
  datasets:
2
  vla_data:
3
  data_mix: robocasa_teleop_ee
4
+ data_root_dir: ${oc.env:PILOT_DATA_ROOT}
5
  dataset_py: lerobot_datasets
6
  delete_pause_frame: false
7
  per_device_batch_size: 14
8
+ video_backend: decord
9
+ include_state: true
10
+ num_workers: 0
11
+ persistent_workers: false
12
  framework:
13
  action_model:
14
  action_dim: 32
 
46
  max_samples: 1
47
  max_sequence_length: 512
48
  negative_prompt: null
49
+ num_frames: 5
50
  num_inference_steps: 20
51
+ num_latent_conditional_frames: 1
52
  output_type: pil
53
  return_full_video: false
54
  width: 224
 
59
  train_time_distribution: logitnormal
60
  future_latent_training:
61
  enabled: true
62
+ loss_weight: 0.1
63
  shift: 5.0
64
  train_time_distribution: logitnormal
65
  name: CosmoPredict25PerceiverVJEPA2AC
66
  obs_image_size: null
67
  qwenvl:
68
+ base_vlm: ${oc.env:PILOT_COSMOS_ROOT}
69
  vl_hidden_dim: 2048
70
  vjepa2_ac:
71
+ pretrained: ${oc.env:PILOT_VJEPA_CHECKPOINT}
72
+ repo_dir: ${oc.env:PILOT_ROOT}/starVLA/facebookresearch_vjepa2_main
73
  world_model:
74
+ base_wm: ${oc.env:PILOT_COSMOS_ROOT}
75
  conditional_frame_timestep: 0.1
76
  extract_layers:
77
  - -1
78
  height: 224
79
  revision: diffusers/base/post-trained
80
  width: 224
81
+ latent_normalization: legacy
82
+ run_id: pilot
83
+ run_root_dir: ${oc.env:PILOT_OUTPUT_ROOT}
84
  seed: 42
85
  trainer:
86
  eval_interval: 500
87
  freeze_modules: null
88
  gradient_accumulation_steps: 1
89
  gradient_clipping: 1.0
90
+ is_resume: false
91
  learning_rate:
92
+ action_model: 5.0e-05
93
+ action_projector: 5.0e-05
94
  base: 1.0e-05
95
  qwen_vl_interface: 1.0e-05
96
+ state_projector: 5.0e-05
97
+ vjepa_predictor: 5.0e-05
98
  logging_frequency: 500
99
  lr_scheduler_type: cosine_with_min_lr
100
+ max_train_steps: 400000
101
  num_warmup_steps: 2000
102
  optimizer:
103
  betas:
 
105
  - 0.999
106
  eps: 1.0e-08
107
  weight_decay: 0.1
 
108
  repeated_diffusion_steps: 4
109
+ save_interval: 10000
110
  scheduler_specific_kwargs:
111
+ min_lr: 2.0e-07
112
+ stateful_dataloader: true
113
+ save_training_state: true
114
+ deterministic_algorithms: true
115
+ wandb_entity: null
116
+ wandb_project: pilot
deployment/model_server/README.md DELETED
@@ -1,22 +0,0 @@
1
-
2
- # start policy server
3
-
4
-
5
- ```bash
6
-
7
- your_ckpt=./results/Checkpoints/1003_qwenfast/checkpoints/steps_50000_pytorch_model.pt
8
-
9
- python deployment/model_server/server_policy.py \
10
- --ckpt_path ${your_ckpt} \
11
- --port 10093 \
12
- --use_bf16
13
- ```
14
-
15
-
16
- # connect to policy server for debug
17
-
18
- ```bash
19
- python deployment/model_server/debug_server_policy.py
20
-
21
- # plus server_policy.py into your vla controler by ref to debug_server_policy.py
22
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment/model_server/server_policy.py DELETED
@@ -1,70 +0,0 @@
1
- # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
-
5
- import logging
6
- import socket
7
- import argparse
8
- from deployment.model_server.tools.websocket_policy_server import WebsocketPolicyServer
9
- from starVLA.model.framework.base_framework import baseframework
10
- import torch, os
11
-
12
-
13
- def main(args) -> None:
14
- # Example usage:
15
- # policy = YourPolicyClass() # Replace with your actual policy class
16
- # server = WebsocketPolicyServer(policy, host="localhost", port=10091)
17
- # server.serve_forever()
18
-
19
- vla = baseframework.from_pretrained( # TODO should auto detect framework from model path
20
- args.ckpt_path,
21
- )
22
-
23
- if args.use_bf16: # False
24
- vla = vla.to(torch.bfloat16)
25
- vla = vla.to("cuda").eval()
26
-
27
- hostname = socket.gethostname()
28
- local_ip = socket.gethostbyname(hostname)
29
- logging.info("Creating server (host: %s, ip: %s)", hostname, local_ip)
30
-
31
- # start websocket server
32
- server = WebsocketPolicyServer(
33
- policy=vla,
34
- host="0.0.0.0",
35
- port=args.port,
36
- idle_timeout=args.idle_timeout,
37
- metadata={"env": "simpler_env"},
38
- )
39
- logging.info("server running ...")
40
- server.serve_forever()
41
-
42
-
43
- def build_argparser():
44
- parser = argparse.ArgumentParser()
45
- parser.add_argument("--ckpt_path", type=str, default="Qwen/Qwen2.5-VL-3B-Instruct")
46
- parser.add_argument("--port", type=int, default=10093)
47
- parser.add_argument("--use_bf16", action="store_true")
48
- parser.add_argument("--idle_timeout" , type=int, default=1800, help="Idle timeout in seconds, -1 means never close")
49
- return parser
50
-
51
-
52
- def start_debugpy_once():
53
- """start debugpy once"""
54
- import debugpy
55
- if getattr(start_debugpy_once, "_started", False):
56
- return
57
- debugpy.listen(("0.0.0.0", 10095))
58
- print("🔍 Waiting for VSCode attach on 0.0.0.0:10095 ...")
59
- debugpy.wait_for_client()
60
- start_debugpy_once._started = True
61
-
62
-
63
- if __name__ == "__main__":
64
- logging.basicConfig(level=logging.INFO, force=True)
65
- parser = build_argparser()
66
- args = parser.parse_args()
67
- if os.getenv("DEBUG", False):
68
- print("🔍 DEBUGPY is enabled")
69
- start_debugpy_once()
70
- main(args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment/model_server/tools/debug_server_policy.py CHANGED
@@ -85,7 +85,3 @@ def _main():
85
 
86
  client.close()
87
  logging.info("Smoke test done.")
88
-
89
-
90
- if __name__ == "__main__":
91
- _main()
 
85
 
86
  client.close()
87
  logging.info("Smoke test done.")
 
 
 
 
deployment/model_server/tools/image_tools.py CHANGED
@@ -116,4 +116,4 @@ def to_pil_preserve(images: Any, scale_float: bool = True):
116
 
117
  raise TypeError(f"Unsupported element type: {type(obj)}")
118
 
119
- return _convert(images)
 
116
 
117
  raise TypeError(f"Unsupported element type: {type(obj)}")
118
 
119
+ return _convert(images)
deployment/model_server/tools/websocket_policy_client.py CHANGED
@@ -1,6 +1,6 @@
1
  # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
 
5
  import logging, argparse
6
  import time, os
@@ -33,14 +33,14 @@ class WebsocketClientPolicy:
33
  def _wait_for_server(self, timeout: float = 300) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
34
  logging.info(f"Waiting for server at {self._uri}...")
35
  start_time = time.time()
36
-
37
  for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
38
  os.environ.pop(k, None)
39
-
40
  while True:
41
  if time.time() - start_time > timeout:
42
  raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
43
-
44
  try:
45
  headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
46
  conn = websockets.sync.client.connect(
@@ -63,7 +63,7 @@ class WebsocketClientPolicy:
63
  self._ws.close()
64
  except Exception:
65
  pass
66
-
67
  @override
68
  def predict_action(self, query_info: Dict) -> Dict:
69
  data = self._packer.pack(query_info)
@@ -72,6 +72,3 @@ class WebsocketClientPolicy:
72
  if isinstance(response, str):
73
  raise RuntimeError(f"Error in inference server:\n{response}")
74
  return msgpack_numpy.unpackb(response)
75
-
76
-
77
-
 
1
  # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+
4
 
5
  import logging, argparse
6
  import time, os
 
33
  def _wait_for_server(self, timeout: float = 300) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
34
  logging.info(f"Waiting for server at {self._uri}...")
35
  start_time = time.time()
36
+
37
  for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
38
  os.environ.pop(k, None)
39
+
40
  while True:
41
  if time.time() - start_time > timeout:
42
  raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
43
+
44
  try:
45
  headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
46
  conn = websockets.sync.client.connect(
 
63
  self._ws.close()
64
  except Exception:
65
  pass
66
+
67
  @override
68
  def predict_action(self, query_info: Dict) -> Dict:
69
  data = self._packer.pack(query_info)
 
72
  if isinstance(response, str):
73
  raise RuntimeError(f"Error in inference server:\n{response}")
74
  return msgpack_numpy.unpackb(response)
 
 
 
deployment/model_server/tools/websocket_policy_server.py CHANGED
@@ -1,6 +1,6 @@
1
  # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
 
5
  import asyncio
6
  import logging
@@ -29,7 +29,7 @@ class WebsocketPolicyServer:
29
  port: int = 10093,
30
  idle_timeout: int = -1, # 新增参数,单位秒,-1表示永不关闭
31
  metadata: dict | None = None,
32
-
33
  ) -> None:
34
  self._policy = policy #
35
  self._host = host
@@ -137,7 +137,7 @@ class WebsocketPolicyServer:
137
  except Exception as e:
138
  logging.exception("Policy inference error (request_id=%s)", req_id)
139
  logging.exception(e)
140
-
141
  return {
142
  "status": "error",
143
  "ok": False,
@@ -168,12 +168,5 @@ class WebsocketPolicyServer:
168
  }
169
 
170
 
171
- if __name__ == "__main__":
172
- logging.basicConfig(level=logging.INFO, force=True)
173
- # Example usage:
174
- # policy = YourPolicyClass() # Replace with your actual policy class
175
- # server = WebsocketPolicyServer(policy, host="localhost", port=10091)
176
- # server.serve_forever()
177
- raise NotImplementedError("This module is not intended to be run directly.")
178
  #
179
  # Instead, it should be imported and used in a server context.
 
1
  # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+
4
 
5
  import asyncio
6
  import logging
 
29
  port: int = 10093,
30
  idle_timeout: int = -1, # 新增参数,单位秒,-1表示永不关闭
31
  metadata: dict | None = None,
32
+
33
  ) -> None:
34
  self._policy = policy #
35
  self._host = host
 
137
  except Exception as e:
138
  logging.exception("Policy inference error (request_id=%s)", req_id)
139
  logging.exception(e)
140
+
141
  return {
142
  "status": "error",
143
  "ok": False,
 
168
  }
169
 
170
 
 
 
 
 
 
 
 
171
  #
172
  # Instead, it should be imported and used in a server context.
deployment/readme-deployment.md DELETED
@@ -1,11 +0,0 @@
1
- sudo ip addr add 172.16.0.100/24 dev enx207bd51a3217
2
- sudo ip link set enx207bd51a3217 up
3
- ping 172.16.0.2
4
-
5
-
6
- python -m real_deployment.model_controller_del_ee
7
-
8
-
9
- ## install frankx
10
- conda install frankx
11
- unzip frankx.zip
 
 
 
 
 
 
 
 
 
 
 
 
deployment/real_infer/open_loop_eval.py DELETED
@@ -1,315 +0,0 @@
1
- import os
2
- import sys
3
- import time
4
- from pathlib import Path
5
- from dataclasses import dataclass, field
6
- from typing import Dict, List, Optional
7
-
8
- import numpy as np
9
- import matplotlib.pyplot as plt
10
- import torch
11
- from omegaconf import OmegaConf
12
- import tyro
13
-
14
- # ====== 你项目里的 import(按你现有路径保留)======
15
- from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
16
- from starVLA.model.framework.base_framework import baseframework
17
- from starVLA.model.framework.share_tools import read_mode_config
18
-
19
-
20
- # -----------------------------
21
- # 1) 你已有的归一化/反归一化逻辑(原封不动)
22
- # -----------------------------
23
- def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
24
- lo = np.asarray(stats["min"], dtype=np.float32)
25
- hi = np.asarray(stats["max"], dtype=np.float32)
26
- denom = np.maximum(hi - lo, eps)
27
- x01 = (x - lo) / denom
28
- xn = x01 * 2.0 - 1.0
29
- return xn.astype(np.float32)
30
-
31
-
32
- def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
33
- mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
34
- action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
35
- normalized_actions = np.clip(normalized_actions, -1, 1)
36
- actions = np.where(
37
- mask,
38
- (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
39
- normalized_actions,
40
- )
41
- return actions
42
-
43
-
44
- # -----------------------------
45
- # 2) Args(按你 server 的 Args 简化必要项)
46
- # -----------------------------
47
- @dataclass
48
- class Args:
49
- ckpt_path: str = "outputs/suqian_post_train_w_state/checkpoints/steps_80000_pytorch_model.pt"
50
- unnorm_key: str = "agibot_genie1"
51
- gripper_threshold: float = 0.5
52
-
53
-
54
- def _build_policy(args: Args):
55
- vla = baseframework.from_pretrained(args.ckpt_path)
56
- vla = vla.to("cuda").eval()
57
-
58
- cfg, norm_stats = read_mode_config(Path(args.ckpt_path))
59
- unnorm_key = args.unnorm_key
60
- cfg = OmegaConf.create(cfg)
61
-
62
- vla.action_norm_stats = norm_stats[unnorm_key]["action"]
63
- vla.state_norm_stats = norm_stats[unnorm_key]["state"]
64
- return vla, cfg
65
-
66
-
67
- def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
68
- prompt = obs.get("prompt", "")
69
-
70
- state = np.asarray(obs["observation/state"], dtype=np.float32)
71
- if state.ndim == 1:
72
- state = state[None, :]
73
- elif state.ndim != 2:
74
- raise ValueError(f"Unexpected state shape: {state.shape}")
75
-
76
- state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
77
-
78
- fake_data = {
79
- "image": [
80
- obs["observation/image"],
81
- obs["observation/wrist_left_image"],
82
- obs["observation/wrist_right_image"],
83
- ],
84
- "lang": prompt,
85
- "state": state_norm,
86
- }
87
-
88
- t0 = time.perf_counter()
89
- with torch.inference_mode():
90
- out = policy.predict_action(fake_data)
91
- infer_ms = (time.perf_counter() - t0) * 1000
92
-
93
- na = out["normalized_actions"] # (1, 16, D)
94
- na2 = na[0] # (16, D)
95
-
96
- raw2 = unnormalize_actions(na2, policy.action_norm_stats) # (16, D)
97
- actions = raw2[None, ...] # (1, 16, D)
98
-
99
- return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
100
-
101
-
102
- # -----------------------------
103
- # 3) 从 single_ds.get_step_data 组装 obs / gt_chunk
104
- # -----------------------------
105
- def build_obs_from_step_data(step_data: dict, single_ds) -> dict:
106
- """
107
- step_data: single_ds.get_step_data(traj_id, base_index) 的 RAW 输出
108
- 返回:_infer_single 所需的 obs dict
109
- """
110
- video_keys = single_ds.modality_keys["video"]
111
- if len(video_keys) < 3:
112
- raise ValueError(f"Need 3 cameras, got video_keys={video_keys}")
113
-
114
- head = step_data[video_keys[0]][0]
115
- left = step_data[video_keys[1]][0]
116
- right = step_data[video_keys[2]][0]
117
-
118
- # state concat: (T, D_total) -> 取第 0 帧对应 base step
119
- state_parts = [step_data[k] for k in single_ds.modality_keys["state"]]
120
- state = np.concatenate(state_parts, axis=1)
121
- state0 = state[0]
122
-
123
- # language(通常是 annotation.xxx),get_language 返回 list[str]
124
- lang_key = single_ds.modality_keys["language"][0]
125
- lang = step_data[lang_key][0]
126
- if isinstance(lang, list):
127
- lang = lang[0]
128
-
129
- obs = {
130
- "observation/image": head,
131
- "observation/wrist_left_image": left,
132
- "observation/wrist_right_image": right,
133
- "observation/state": state0,
134
- "prompt": lang,
135
- }
136
- return obs
137
-
138
-
139
- def get_gt_action_chunk(step_data: dict, single_ds) -> np.ndarray:
140
- action_parts = [step_data[k] for k in single_ds.modality_keys["action"]]
141
- gt = np.concatenate(action_parts, axis=1) # (H, D)
142
- return gt
143
-
144
-
145
- # -----------------------------
146
- # 4) rollout:拼整段 pred/gt(像 gr00t open-loop eval)
147
- # -----------------------------
148
- def rollout_open_loop(
149
- single_ds,
150
- pi0_policy,
151
- args: Args,
152
- traj_id: int,
153
- steps: int = 200,
154
- action_horizon: int = 16,
155
- ):
156
- """
157
- 返回:
158
- pred_action_across_time: (actual_steps, D)
159
- gt_action_across_time: (actual_steps, D)
160
- infer_ms_list: 每次推理耗时
161
- """
162
- traj_len = int(single_ds.trajectory_lengths[single_ds.get_trajectory_index(traj_id)])
163
- actual_steps = min(steps, traj_len)
164
-
165
- pred_list = []
166
- gt_list = []
167
- infer_ms_list = []
168
-
169
- # 每 action_horizon 步推理一次,把 chunk 展开 append
170
- for t in range(0, actual_steps, action_horizon):
171
- step_data = single_ds.get_step_data(traj_id, t)
172
-
173
- obs = build_obs_from_step_data(step_data, single_ds)
174
- pred = _infer_single(pi0_policy, obs, args, args.gripper_threshold)
175
-
176
- pred_chunk = pred["actions"][0] # (H, D)
177
- gt_chunk = get_gt_action_chunk(step_data, single_ds) # (H, D)
178
-
179
- # 可能最后一段不足 action_horizon(如果 traj 尾巴短),这里裁一下
180
- remain = actual_steps - t
181
- pred_chunk = pred_chunk[:remain]
182
- gt_chunk = gt_chunk[:remain]
183
-
184
- pred_list.append(pred_chunk)
185
- gt_list.append(gt_chunk)
186
- infer_ms_list.append(pred["policy_timing"]["infer_ms"])
187
-
188
- pred_action_across_time = np.concatenate(pred_list, axis=0)
189
- gt_action_across_time = np.concatenate(gt_list, axis=0)
190
-
191
- assert pred_action_across_time.shape == gt_action_across_time.shape, (
192
- f"pred={pred_action_across_time.shape}, gt={gt_action_across_time.shape}"
193
- )
194
- return pred_action_across_time, gt_action_across_time, infer_ms_list
195
-
196
-
197
- # -----------------------------
198
- # 5) 画图(整段轨迹)
199
- # -----------------------------
200
- def plot_action_curves(
201
- gt: np.ndarray,
202
- pred: np.ndarray,
203
- save_path: str,
204
- dims: Optional[List[int]] = None,
205
- title: str = "",
206
- ):
207
- """
208
- 画每个维度一张子图(很多维会很长,但 debug 很直观)
209
- """
210
- T, D = gt.shape
211
- if dims is None:
212
- dims = list(range(D))
213
-
214
- n = len(dims)
215
- fig, axes = plt.subplots(nrows=n, ncols=1, figsize=(10, 2.2 * n))
216
- if n == 1:
217
- axes = [axes]
218
-
219
- fig.suptitle(title, fontsize=14)
220
-
221
- x = np.arange(T)
222
- for i, d in enumerate(dims):
223
- ax = axes[i]
224
- ax.plot(x, gt[:, d], label="gt")
225
- ax.plot(x, pred[:, d], label="pred")
226
- ax.set_ylabel(f"dim {d}")
227
- ax.legend(loc="upper right")
228
-
229
- axes[-1].set_xlabel("time step")
230
- plt.tight_layout()
231
- Path(save_path).parent.mkdir(parents=True, exist_ok=True)
232
- plt.savefig(save_path, dpi=150)
233
- plt.close(fig)
234
-
235
-
236
- def plot_error_over_time(gt: np.ndarray, pred: np.ndarray, save_path: str, title: str = ""):
237
- """
238
- 画每个时间步的 L2/MSE(按维度平均) 和 MAE(按维度平均)
239
- """
240
- err = pred - gt
241
- mse_t = np.mean(err**2, axis=1)
242
- mae_t = np.mean(np.abs(err), axis=1)
243
-
244
- x = np.arange(len(mse_t))
245
- fig = plt.figure(figsize=(10, 4))
246
- plt.plot(x, mse_t, label="MSE per step")
247
- plt.plot(x, mae_t, label="MAE per step")
248
- plt.title(title)
249
- plt.xlabel("time step")
250
- plt.ylabel("error")
251
- plt.legend()
252
- plt.tight_layout()
253
- Path(save_path).parent.mkdir(parents=True, exist_ok=True)
254
- plt.savefig(save_path, dpi=150)
255
- plt.close(fig)
256
-
257
-
258
- # -----------------------------
259
- # 6) main:把 dataset + policy 接起来
260
- # -----------------------------
261
- def main(args: Args):
262
- # ===== 2) load policy =====
263
- pi0_policy, cfg = _build_policy(args)
264
- print("policy loaded")
265
-
266
- # ===== 1) 载入训练 yaml,复用你的 dataset 配置 =====
267
- vla_dataset_cfg = cfg.datasets.vla_data
268
- vla_dataset_cfg.task_id = "all" # 或者某个 task_id
269
- # vla_dataset_cfg.data_mix = "suqian_test"
270
-
271
- dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
272
-
273
- # get_vla_dataset 可能返回 mixture(里面有 datasets 列表)
274
- single_ds = dataset.datasets[0] if hasattr(dataset, "datasets") else dataset
275
-
276
- # 选一条 traj
277
- traj_id = int(single_ds.trajectory_ids[0])
278
- print("Using traj_id:", traj_id)
279
-
280
- # ===== 3) rollout open-loop =====
281
- pred, gt, infer_ms_list = rollout_open_loop(
282
- single_ds,
283
- pi0_policy,
284
- args,
285
- traj_id=traj_id,
286
- steps=200,
287
- action_horizon=30,
288
- )
289
-
290
- mse = np.mean((pred - gt) ** 2)
291
- mae = np.mean(np.abs(pred - gt))
292
- print(f"Open-loop MSE={mse:.6f}, MAE={mae:.6f}")
293
- print(f"Infer ms: mean={np.mean(infer_ms_list):.2f}, p95={np.percentile(infer_ms_list, 95):.2f}")
294
-
295
- out_dir = Path("outputs/open_loop_eval")
296
- out_dir.mkdir(parents=True, exist_ok=True)
297
-
298
- # ===== 4) 画图 =====
299
- plot_action_curves(
300
- gt, pred,
301
- save_path=str(out_dir / f"traj{traj_id}_action_curves.png"),
302
- # dims=list(range(min(gt.shape[1], 18))), # 你想只看前 18 维就开这行
303
- title=f"traj {traj_id} action curves (T={gt.shape[0]}, D={gt.shape[1]})",
304
- )
305
- plot_error_over_time(
306
- gt, pred,
307
- save_path=str(out_dir / f"traj{traj_id}_error.png"),
308
- title=f"traj {traj_id} error over time",
309
- )
310
-
311
- print("Saved plots to:", out_dir)
312
-
313
-
314
- if __name__ == "__main__":
315
- main(tyro.cli(Args))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment/real_infer/server.py DELETED
@@ -1,332 +0,0 @@
1
- """
2
- Pi0 WebSocket 推理服务端,兼容 openpi-client 客户端协议。
3
-
4
- - 使用 websockets.asyncio.server,客户端用 WebsocketClientPolicy 连接。
5
- - 首次连接发送 metadata(简单字典)。
6
- - 收到 obs 后,调用 Pi0 推理并返回 {"actions": np.ndarray, "policy_timing": {"infer_ms": ...}}。
7
-
8
- 支持 joint_position 和 camera_position(通过 state 维度判断:16 -> joint,14 -> camera)。
9
- """
10
-
11
- import asyncio
12
- import http
13
- import os
14
- import sys
15
- import time
16
- import traceback
17
- from dataclasses import dataclass, field
18
- from pathlib import Path
19
- from typing import Dict, List, Literal, Optional
20
-
21
- import numpy as np
22
- import tyro
23
- import websockets.asyncio.server as ws_server
24
- import websockets.frames
25
-
26
- import torch
27
-
28
- # 兼容 protobuf 版本
29
- os.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")
30
-
31
- # 路径设置
32
- _current_dir = Path(__file__).resolve().parent
33
- _project_root = _current_dir.parent
34
- if str(_project_root) not in sys.path:
35
- sys.path.insert(0, str(_project_root))
36
-
37
- _openpi_client_src = _project_root / "workspace" / "openpi-client" / "src"
38
- if _openpi_client_src.exists() and str(_openpi_client_src) not in sys.path:
39
- sys.path.insert(0, str(_openpi_client_src))
40
-
41
- from starVLA.model.framework.base_framework import baseframework
42
- from starVLA.model.framework.share_tools import read_mode_config
43
- from openpi_client import msgpack_numpy
44
-
45
-
46
- @dataclass
47
- class Args:
48
- host: str = "0.0.0.0"
49
- port: int = 8000
50
-
51
- ckpt_path: str = "/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/suqian_post_train_no_pretrain/checkpoints/steps_15000_pytorch_model.pt"
52
- data_statistics_path: str = "/workspace/niejunnan/VLAPipeline_RL_BY_Niejunnan/output_train/agibot/benchmark_pro_max/ds_stats.json"
53
- language_tokenizer_path: Optional[str] = "/workspace/paligemma-3b-pt-224"
54
- unnorm_key: Optional[str] = "agibot_genie1"
55
- policy_setup: str = "agibot_genie1"
56
- obs_camera_name: List[str] = field(default_factory=lambda: ["head_color", "hand_left", "hand_right"])
57
- action_scale: float = 1.0
58
- use_filter: bool = False
59
- use_multi_action_head: str = "raw"
60
- use_arm_pose_type: str = "euler"
61
- use_paligemma_original_vocab_size: bool = True
62
- n_action_steps: Optional[int] = None
63
- inference_mode: str = "synchronous"
64
- # 兼容 pi0inference 期望的其他开关
65
- use_distillation_distribution: bool = False
66
- use_embodiment_id: bool = False
67
- use_vit_for_action_head: bool = False
68
- use_distillation: bool = False
69
- use_best_of_n: bool = False
70
- best_of_n: int = 32
71
- use_step_action_mask_for_q: bool = False
72
-
73
- gripper_threshold: float = 0.5
74
-
75
-
76
- # def _build_policy(args: Args) -> LerobotPiFastInference:
77
- # if not args.data_statistics_path:
78
- # raise ValueError("需要 --data_statistics_path")
79
-
80
- # return LerobotPiFastInference(
81
- # args=args,
82
- # saved_model_path=args.ckpt_path,
83
- # policy_setup=args.policy_setup,
84
- # action_scale=args.action_scale,
85
- # use_filter=args.use_filter,
86
- # image_name_list=args.obs_camera_name,
87
- # data_statistics_path=args.data_statistics_path,
88
- # language_tokenlizer_path=args.language_tokenizer_path,
89
- # unnorm_key=args.unnorm_key,
90
- # use_multi_action_head=args.use_multi_action_head,
91
- # use_arm_pose_type=args.use_arm_pose_type,
92
- # inference_mode=args.inference_mode,
93
- # )
94
-
95
-
96
- def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
97
- """
98
- x: (..., D)
99
- stats: contains "min" and "max" (D,)
100
- return: (..., D) in [-1, 1]
101
- """
102
- lo = np.asarray(stats["min"], dtype=np.float32)
103
- hi = np.asarray(stats["max"], dtype=np.float32)
104
- denom = np.maximum(hi - lo, eps)
105
- x01 = (x - lo) / denom
106
- xn = x01 * 2.0 - 1.0
107
- return xn.astype(np.float32)
108
-
109
- def _sincos_state(x: np.ndarray) -> np.ndarray:
110
- """
111
- x: (B, D) or (D,)
112
- return: (B, 2D) in [-1, 1]
113
- """
114
- x = np.asarray(x, dtype=np.float32)
115
- if x.ndim == 1:
116
- x = x[None, :] # (1, D)
117
- elif x.ndim != 2:
118
- raise ValueError(f"Unexpected state shape: {x.shape}")
119
-
120
- sin_x = np.sin(x)
121
- cos_x = np.cos(x)
122
- return np.concatenate([sin_x, cos_x], axis=-1).astype(np.float32) # (B, 2D)
123
-
124
-
125
- def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
126
- """
127
- Args:
128
- normalized_actions: shape (B, chunk, D) (chunk, D)
129
- action_norm_stats:
130
- Returns:
131
- actions
132
- """
133
- mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
134
- action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
135
-
136
- normalized_actions = np.clip(normalized_actions, -1, 1)
137
-
138
- actions = np.where(
139
- mask,
140
- (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
141
- normalized_actions,
142
- )
143
-
144
- return actions
145
-
146
-
147
- def _build_policy(args: Args):
148
- vla = baseframework.from_pretrained(args.ckpt_path)
149
- vla = vla.to("cuda").eval()
150
-
151
- _, norm_stats = read_mode_config(Path(args.ckpt_path))
152
- unnorm_key = args.unnorm_key
153
-
154
- # ✅ action stats(你原来就有)
155
- vla.action_norm_stats = norm_stats[unnorm_key]["action"]
156
-
157
- # ✅ state stats(新增:用于输入归一化,训练一致)
158
- vla.state_norm_stats = norm_stats[unnorm_key]["state"]
159
-
160
- return vla
161
-
162
-
163
- def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
164
- prompt = obs.get("prompt", "")
165
- print("prompt", prompt)
166
-
167
- # -------- state: raw -> normalized (min_max to [-1,1]) --------
168
- state = np.asarray(obs["observation/state"], dtype=np.float32)
169
- print('state', state.shape, state)
170
- if state.ndim == 1:
171
- state = state[None, :] # (1, D)
172
- elif state.ndim != 2:
173
- raise ValueError(f"Unexpected state shape: {state.shape}")
174
-
175
- # ✅ 训练一致:min_max 归一化
176
- state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
177
-
178
- fake_data = {
179
- "image": [
180
- obs["observation/image"],
181
- obs["observation/wrist_left_image"],
182
- obs["observation/wrist_right_image"],
183
- ],
184
- "lang": prompt,
185
- "state": state_norm, # ✅ 用归一化后的 state
186
- }
187
-
188
- print('img', obs["observation/image"].shape)
189
- raw = state
190
- sn = state_norm
191
- print("state raw min/max:", raw.min(), raw.max())
192
- print("state_norm min/max:", sn.min(), sn.max(), "clip_ratio:", np.mean((sn <= -0.999) | (sn >= 0.999)))
193
-
194
- t0 = time.perf_counter()
195
- with torch.inference_mode():
196
- out = policy.predict_action(fake_data)
197
- infer_ms = (time.perf_counter() - t0) * 1000
198
-
199
- # out 来自 predict_action
200
- na = out["normalized_actions"] # (1, 16, 18) numpy
201
-
202
- # 1️⃣ 去掉 batch 维
203
- na2 = na[0] # (16, 18)
204
-
205
- # 2️⃣ 用 numpy 版 unnormalize(CPU)
206
- raw2 = unnormalize_actions(
207
- na2,
208
- policy.action_norm_stats,
209
- ) # (16, 18)
210
-
211
- # 3️⃣ 如有需要再加回 batch 维
212
- actions = raw2[None, ...] # (1, 16, 18)
213
- print(actions[0, 0])
214
-
215
- return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
216
-
217
- def _health_check(connection: ws_server.ServerConnection, request: ws_server.Request):
218
- """健康检查端点"""
219
- if request.path == "/healthz":
220
- return connection.respond(http.HTTPStatus.OK, "OK\n")
221
- return None
222
-
223
-
224
- class Pi0PolicyServer:
225
- """Pi0 WebSocket 推理服务端"""
226
-
227
- def __init__(self, pi0_policy, args: Args):
228
- self._policy = pi0_policy
229
- self._args = args
230
- self._metadata = {
231
- "status": "ok",
232
- "policy": "pi0",
233
- "obs_cameras": args.obs_camera_name,
234
- "action_dim": 14,
235
- }
236
- self._packer = msgpack_numpy.Packer()
237
-
238
- def serve_forever(self) -> None:
239
- """阻塞式启动服务"""
240
- asyncio.run(self._run())
241
-
242
- async def _run(self):
243
- """异步运行服务"""
244
- async with ws_server.serve(
245
- self._handler,
246
- self._args.host,
247
- self._args.port,
248
- compression=None,
249
- max_size=None,
250
- process_request=_health_check,
251
- ) as server:
252
- print("✓ 服务已启动,等待客户端连接...")
253
- await server.serve_forever()
254
-
255
- async def _handler(self, websocket: ws_server.ServerConnection):
256
- """处理单个客户端连接"""
257
- print(f"[连接] 客户端 {websocket.remote_address} 已连接")
258
-
259
- # 发送 metadata
260
- await websocket.send(self._packer.pack(self._metadata))
261
-
262
- while True:
263
- try:
264
- data = await websocket.recv()
265
- if isinstance(data, str):
266
- await websocket.send(f"Invalid data type: {type(data)}")
267
- continue
268
-
269
- obs = msgpack_numpy.unpackb(data)
270
- result = _infer_single(self._policy, obs, self._args, self._args.gripper_threshold)
271
- await websocket.send(self._packer.pack(result))
272
-
273
- except websockets.ConnectionClosed:
274
- print(f"[断开] 客户端 {websocket.remote_address} 已断开")
275
- break
276
- except Exception:
277
- error_msg = traceback.format_exc()
278
- print(f"[错误] {error_msg}")
279
- await websocket.send(error_msg)
280
- await websocket.close(
281
- code=websockets.frames.CloseCode.INTERNAL_ERROR,
282
- reason="Internal server error",
283
- )
284
- raise
285
-
286
-
287
- def serve(args: Args):
288
- print("=" * 60)
289
- print("Pi0 WebSocket 推理服务端 (openpi-client 兼容)")
290
- print("=" * 60)
291
- print(f" 监听: ws://{args.host}:{args.port}")
292
- print(f" 权重: {args.ckpt_path}")
293
- print(f" 数据统计: {args.data_statistics_path}")
294
- print(f" 相机键: {args.obs_camera_name}")
295
- print(f" unnorm_key: {args.unnorm_key}")
296
- print(f" tokenizer: {args.language_tokenizer_path}")
297
- print("=" * 60)
298
-
299
- print("[1/2] 初始化模型...")
300
- pi0_policy = _build_policy(args)
301
- print("✓ 模型就绪")
302
-
303
-
304
- # ===== 在这里加 =====
305
- print("Has predict_action:", hasattr(pi0_policy, "predict_action"))
306
- print("Has __call__:", callable(pi0_policy))
307
- print("Action-related methods:",
308
- [m for m in dir(pi0_policy) if "action" in m.lower()])
309
-
310
- am = pi0_policy.action_model
311
- print("past_action_window_size:", getattr(pi0_policy, "past_action_window_size", None))
312
- print("future_action_window_size:", getattr(pi0_policy, "future_action_window_size", None))
313
- print("action_model:", type(am))
314
- print("action_model attrs (state):", [x for x in dir(am) if "state" in x.lower()])
315
-
316
- # ===================
317
-
318
- print("[2/2] 启动 WebSocket 服务...")
319
- server = Pi0PolicyServer(pi0_policy, args)
320
-
321
- try:
322
- server.serve_forever()
323
- except KeyboardInterrupt:
324
- print("\n[退出] 收到中断信号,正在关闭服务...")
325
-
326
-
327
- def main():
328
- serve(tyro.cli(Args))
329
-
330
-
331
- if __name__ == "__main__":
332
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment/upload/push_model_to_hf.py DELETED
@@ -1,12 +0,0 @@
1
- from huggingface_hub import create_repo, HfApi
2
-
3
- # 1. create repository
4
- hf_name = "StarVLA/Qwen3-VL-OFT-LIBERO-4in1"
5
- create_repo(hf_name, repo_type="model", exist_ok=True)
6
-
7
- # 2. initialize API
8
- api = HfApi()
9
-
10
- # 3. upload large folder
11
- folder_path = "/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1_need/Qwen3-VL-OFT-LIBERO-4in1"
12
- api.upload_large_folder(folder_path=folder_path, repo_id=hf_name, repo_type="model")
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/README.md DELETED
@@ -1,22 +0,0 @@
1
-
2
- # start policy server
3
-
4
-
5
- ```bash
6
-
7
- your_ckpt=./results/Checkpoints/1003_qwenfast/checkpoints/steps_50000_pytorch_model.pt
8
-
9
- python deployment/model_server/server_policy.py \
10
- --ckpt_path ${your_ckpt} \
11
- --port 10093 \
12
- --use_bf16
13
- ```
14
-
15
-
16
- # connect to policy server for debug
17
-
18
- ```bash
19
- python deployment/model_server/debug_server_policy.py
20
-
21
- # plus server_policy.py into your vla controler by ref to debug_server_policy.py
22
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/server_policy.py DELETED
@@ -1,91 +0,0 @@
1
- # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
-
5
- import logging
6
- import socket
7
- import argparse
8
- import random
9
- import numpy as np
10
- from deployment_robotwin.model_server.tools.websocket_policy_server import WebsocketPolicyServer
11
- from starVLA.model.framework.base_framework import baseframework
12
- import torch, os
13
-
14
-
15
- def set_seed(seed: int) -> None:
16
- """Fix all possible random seeds for reproducibility.
17
-
18
- Args:
19
- seed: Random seed to use.
20
- """
21
- random.seed(seed)
22
- np.random.seed(seed)
23
- torch.manual_seed(seed)
24
- torch.cuda.manual_seed(seed)
25
- torch.cuda.manual_seed_all(seed)
26
- torch.backends.cudnn.deterministic = True
27
- torch.backends.cudnn.benchmark = False
28
-
29
-
30
- def main(args) -> None:
31
- # Set random seeds for reproducibility
32
- set_seed(args.seed)
33
-
34
- # Example usage:
35
- # policy = YourPolicyClass() # Replace with your actual policy class
36
- # server = WebsocketPolicyServer(policy, host="localhost", port=10091)
37
- # server.serve_forever()
38
-
39
- vla = baseframework.from_pretrained( # TODO should auto detect framework from model path
40
- args.ckpt_path,
41
- )
42
-
43
- if args.use_bf16: # False
44
- vla = vla.to(torch.bfloat16)
45
- vla = vla.to("cuda").eval()
46
-
47
- hostname = socket.gethostname()
48
- local_ip = socket.gethostbyname(hostname)
49
- logging.info("Creating server (host: %s, ip: %s)", hostname, local_ip)
50
-
51
- # start websocket server
52
- server = WebsocketPolicyServer(
53
- policy=vla,
54
- host="0.0.0.0",
55
- port=args.port,
56
- idle_timeout=args.idle_timeout,
57
- metadata={"env": "simpler_env"},
58
- )
59
- logging.info("server running ...")
60
- server.serve_forever()
61
-
62
-
63
- def build_argparser():
64
- parser = argparse.ArgumentParser()
65
- parser.add_argument("--ckpt_path", type=str, default="Qwen/Qwen2.5-VL-3B-Instruct")
66
- parser.add_argument("--port", type=int, default=10093)
67
- parser.add_argument("--use_bf16", action="store_true")
68
- parser.add_argument("--idle_timeout" , type=int, default=1800, help="Idle timeout in seconds, -1 means never close")
69
- parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility")
70
- return parser
71
-
72
-
73
- def start_debugpy_once():
74
- """start debugpy once"""
75
- import debugpy
76
- if getattr(start_debugpy_once, "_started", False):
77
- return
78
- debugpy.listen(("0.0.0.0", 10095))
79
- print("🔍 Waiting for VSCode attach on 0.0.0.0:10095 ...")
80
- debugpy.wait_for_client()
81
- start_debugpy_once._started = True
82
-
83
-
84
- if __name__ == "__main__":
85
- logging.basicConfig(level=logging.INFO, force=True)
86
- parser = build_argparser()
87
- args = parser.parse_args()
88
- if os.getenv("DEBUG", False):
89
- print("🔍 DEBUGPY is enabled")
90
- start_debugpy_once()
91
- main(args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_client-checkpoint.py DELETED
@@ -1,149 +0,0 @@
1
- # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
-
5
- import logging
6
- import os
7
- import time
8
- from typing import Dict, Optional, Tuple, Any
9
-
10
- from typing_extensions import override
11
- import websockets
12
- import websockets.sync.client
13
-
14
- from . import msgpack_numpy
15
-
16
-
17
- class WebsocketClientPolicy:
18
- """Implements the Policy interface by communicating with a server over websocket.
19
-
20
- See WebsocketPolicyServer for a corresponding server implementation.
21
- """
22
-
23
- def __init__(
24
- self,
25
- host: str = "127.0.0.1",
26
- port: Optional[int] = 10093,
27
- api_key: Optional[str] = None,
28
- connect_timeout: float = 300.0,
29
- open_timeout: float = 150.0,
30
- ping_interval: Optional[float] = 30.0,
31
- ping_timeout: Optional[float] = 300.0,
32
- reconnect_max_attempts: int = 5,
33
- ) -> None:
34
- # 0.0.0.0 cannot be used as a connection target, here default 127.0.0.1
35
- self._uri = f"ws://{host}"
36
- if port is not None:
37
- self._uri += f":{port}"
38
-
39
- self._packer = msgpack_numpy.Packer()
40
- self._api_key = api_key
41
-
42
- self._connect_timeout = connect_timeout
43
- self._open_timeout = open_timeout
44
- self._ping_interval = ping_interval
45
- self._ping_timeout = ping_timeout
46
- self._reconnect_max_attempts = reconnect_max_attempts
47
-
48
- self._ws, self._server_metadata = self._wait_for_server(timeout=self._connect_timeout)
49
-
50
- def get_server_metadata(self) -> Dict:
51
- return self._server_metadata
52
-
53
- def close(self) -> None:
54
- try:
55
- if getattr(self, "_ws", None) is not None:
56
- self._ws.close()
57
- except Exception:
58
- pass
59
-
60
- def _drop_proxy_env(self) -> None:
61
- # Some environments set proxies that break ws://127.0.0.1
62
- for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
63
- os.environ.pop(k, None)
64
-
65
- def _connect_once(self) -> Tuple[websockets.sync.client.ClientConnection, Dict[str, Any]]:
66
- headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
67
- conn = websockets.sync.client.connect(
68
- self._uri,
69
- compression=None,
70
- max_size=None,
71
- additional_headers=headers,
72
- open_timeout=self._open_timeout,
73
- ping_interval=self._ping_interval,
74
- ping_timeout=self._ping_timeout,
75
- close_timeout=10,
76
- )
77
- # First frame: metadata
78
- metadata = msgpack_numpy.unpackb(conn.recv())
79
- if not isinstance(metadata, dict):
80
- raise RuntimeError(f"Server metadata must be dict, got: {type(metadata)}")
81
- return conn, metadata
82
-
83
- def _wait_for_server(self, timeout: float = 300.0) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
84
- logging.info(f"Waiting for server at {self._uri}...")
85
- start_time = time.time()
86
-
87
- self._drop_proxy_env()
88
-
89
- backoff = 0.5 # seconds
90
- while True:
91
- if time.time() - start_time > timeout:
92
- raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
93
-
94
- try:
95
- conn, metadata = self._connect_once()
96
- return conn, metadata
97
- except ConnectionRefusedError:
98
- logging.info(f"Still waiting for server {self._uri} ...")
99
- except Exception as e:
100
- logging.warning(f"Connect failed: {repr(e)}")
101
-
102
- time.sleep(backoff)
103
- backoff = min(backoff * 1.5, 5.0)
104
-
105
- def _reconnect(self) -> None:
106
- """Reconnect with limited attempts. Keeps it synchronous and simple."""
107
- self.close()
108
- last_err = None
109
- for attempt in range(1, self._reconnect_max_attempts + 1):
110
- try:
111
- self._ws, self._server_metadata = self._wait_for_server(timeout=60.0)
112
- return
113
- except Exception as e:
114
- last_err = e
115
- logging.warning(f"Reconnect attempt {attempt}/{self._reconnect_max_attempts} failed: {repr(e)}")
116
- raise RuntimeError(f"Failed to reconnect after {self._reconnect_max_attempts} attempts") from last_err
117
-
118
- @override
119
- def predict_action(self, query_info: Dict) -> Dict:
120
- """
121
- Sends a request to server. Supports both:
122
- - legacy payload dict (query_info)
123
- - or query_info already containing {type, request_id, payload}
124
- """
125
- data = self._packer.pack(query_info)
126
-
127
- try:
128
- self._ws.send(data)
129
- response = self._ws.recv()
130
- except websockets.exceptions.ConnectionClosedError as e:
131
- logging.warning(f"WebSocket closed, reconnecting once... ({e})")
132
- self._reconnect()
133
- self._ws.send(data)
134
- response = self._ws.recv()
135
-
136
- if isinstance(response, str):
137
- # server sent traceback text frame
138
- raise RuntimeError(f"Error in inference server:\n{response}")
139
-
140
- ret = msgpack_numpy.unpackb(response)
141
- if not isinstance(ret, dict):
142
- raise RuntimeError(f"Invalid response type: {type(ret)}")
143
-
144
- # Optional: normalize error replies
145
- if ret.get("ok") is False and ret.get("status") == "error":
146
- err = ret.get("error", {})
147
- raise RuntimeError(f"Server error: {err}")
148
-
149
- return ret
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/.ipynb_checkpoints/websocket_policy_server-checkpoint.py DELETED
@@ -1,207 +0,0 @@
1
- # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
-
5
- import asyncio
6
- import logging
7
- import threading
8
- import time
9
- import traceback
10
- from typing import Any, Dict, Optional
11
-
12
- import numpy as np
13
- import websockets
14
- import websockets.asyncio.server
15
- import websockets.frames
16
-
17
- from . import msgpack_numpy
18
-
19
-
20
- def _to_serializable(obj: Any) -> Any:
21
- """Recursively convert non-serializable objects (e.g. PIL Image) into
22
- msgpack-friendly types so the response can be packed by msgpack_numpy.
23
-
24
- PIL Image objects are converted to numpy arrays (which msgpack_numpy
25
- supports) and the downstream client uses ``np.asarray`` on them anyway.
26
- """
27
- # Lazy import to avoid a hard dependency if PIL is unavailable.
28
- try:
29
- from PIL import Image as _PILImage
30
- except Exception: # pragma: no cover - PIL should be available
31
- _PILImage = None
32
-
33
- if _PILImage is not None and isinstance(obj, _PILImage.Image):
34
- return np.asarray(obj)
35
- if isinstance(obj, dict):
36
- return {key: _to_serializable(value) for key, value in obj.items()}
37
- if isinstance(obj, (list, tuple)):
38
- return [_to_serializable(item) for item in obj]
39
- return obj
40
-
41
-
42
- class WebsocketPolicyServer:
43
- """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
44
-
45
- Currently only implements the `load` and `infer` methods.
46
- """
47
-
48
- def __init__(
49
- self,
50
- policy,
51
- host: str = "0.0.0.0",
52
- port: int = 10093,
53
- idle_timeout: int = -1, # seconds; -1 means never shutdown
54
- metadata: Optional[dict] = None,
55
- ping_interval: Optional[float] = 30.0,
56
- ping_timeout: Optional[float] = 300.0,
57
- ) -> None:
58
- self._policy = policy
59
- self._host = host
60
- self._port = port
61
- self._metadata = metadata or {}
62
- self._idle_timeout = idle_timeout
63
- self._last_active = time.time()
64
-
65
- # WebSocket keepalive tuning (server side!)
66
- self._ping_interval = ping_interval
67
- self._ping_timeout = ping_timeout
68
-
69
- # Thread lock for concurrent inference protection
70
- self._inference_lock = threading.Lock()
71
-
72
- logging.getLogger("websockets.server").setLevel(logging.INFO)
73
-
74
- def serve_forever(self) -> None:
75
- asyncio.run(self.run())
76
-
77
- async def run(self) -> None:
78
- async with websockets.asyncio.server.serve(
79
- self._handler,
80
- self._host,
81
- self._port,
82
- compression=None,
83
- max_size=None,
84
- ping_interval=self._ping_interval,
85
- ping_timeout=self._ping_timeout,
86
- close_timeout=10,
87
- ) as server:
88
- if self._idle_timeout > 0:
89
- await self._idle_watchdog(server)
90
- else:
91
- await server.serve_forever()
92
-
93
- async def _idle_watchdog(self, server: websockets.asyncio.server.Server) -> None:
94
- """Monitor server-level idle time; if no requests for idle_timeout seconds, shut down server."""
95
- while True:
96
- await asyncio.sleep(5)
97
- if time.time() - self._last_active > self._idle_timeout:
98
- logging.info(f"Idle timeout ({self._idle_timeout}s) reached, shutting down server.")
99
- server.close()
100
- await server.wait_closed()
101
- break
102
-
103
- async def _handler(self, websocket: websockets.asyncio.server.ServerConnection) -> None:
104
- logging.info(f"Connection from {websocket.remote_address} opened")
105
- packer = msgpack_numpy.Packer()
106
-
107
- # Send metadata as first binary frame
108
- await websocket.send(packer.pack(self._metadata))
109
-
110
- while True:
111
- try:
112
- raw = await websocket.recv()
113
- msg = msgpack_numpy.unpackb(raw)
114
- self._last_active = time.time()
115
-
116
- # ★ CRITICAL: do NOT block event loop with inference
117
- ret = await asyncio.to_thread(self._route_message, msg)
118
-
119
- await websocket.send(packer.pack(ret))
120
- except websockets.ConnectionClosed:
121
- logging.info(f"Connection from {websocket.remote_address} closed")
122
- break
123
- except Exception:
124
- # Send traceback as text, then close with 1011
125
- tb = traceback.format_exc()
126
- try:
127
- await websocket.send(tb)
128
- except Exception:
129
- pass
130
- try:
131
- await websocket.close(
132
- code=websockets.frames.CloseCode.INTERNAL_ERROR,
133
- reason="Internal server error. Traceback included in previous frame.",
134
- )
135
- except Exception:
136
- pass
137
- raise
138
-
139
- def _route_message(self, msg: Any) -> Dict[str, Any]:
140
- """
141
- Fault-tolerant routing:
142
- Accepts either:
143
- 1) protocol envelope:
144
- {"type": "ping|infer|reset|...", "request_id": "...", "payload": {...}}
145
- 2) legacy style:
146
- { ...payload... } (treated as infer)
147
- """
148
- # Normalize
149
- if isinstance(msg, dict):
150
- req_id = msg.get("request_id", "default")
151
- mtype = msg.get("type", "infer")
152
- payload = msg.get("payload", msg) # if no payload wrapper, treat whole dict as payload
153
- else:
154
- req_id = "default"
155
- mtype = "infer"
156
- payload = msg
157
-
158
- # ping
159
- if mtype == "ping":
160
- return {"status": "ok", "ok": True, "type": "ping", "request_id": req_id}
161
-
162
- # infer / predict_action
163
- if mtype in ("infer", "predict_action"):
164
- if not isinstance(payload, dict):
165
- return {
166
- "status": "error",
167
- "ok": False,
168
- "type": "inference_result",
169
- "request_id": req_id,
170
- "error": {"message": "Payload must be a dict", "payload_type": str(type(payload))},
171
- }
172
-
173
- try:
174
- # IMPORTANT: only pass payload into policy, not control fields
175
- # Use lock to ensure thread-safe concurrent inference
176
- with self._inference_lock:
177
- output_dict = self._policy.predict_action(**payload, is_run_parallel_eval_mxk=True)
178
- return {
179
- "status": "ok",
180
- "ok": True,
181
- "type": "inference_result",
182
- "request_id": req_id,
183
- "data": _to_serializable(output_dict),
184
- }
185
- except Exception as e:
186
- logging.exception("Policy inference error (request_id=%s)", req_id)
187
- return {
188
- "status": "error",
189
- "ok": False,
190
- "type": "inference_result",
191
- "request_id": req_id,
192
- "error": {"message": str(e)},
193
- }
194
-
195
- # unknown request type
196
- return {
197
- "status": "error",
198
- "ok": False,
199
- "type": "unknown",
200
- "request_id": req_id,
201
- "error": {"message": f"Unsupported message type '{mtype}'"},
202
- }
203
-
204
-
205
- if __name__ == "__main__":
206
- logging.basicConfig(level=logging.INFO, force=True)
207
- raise NotImplementedError("This module is not intended to be run directly.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/debug_server_policy.py DELETED
@@ -1,91 +0,0 @@
1
- """
2
- Debug / smoke-test client for deployment_robotwin/model_server/server_policy.py.
3
-
4
- Purpose:
5
- - Establish a WebSocket connection to the policy server.
6
- - Initialize device on the server side.
7
- - Optionally run a very simple inference request to verify end-to-end transport
8
- (serialization + server handling).
9
-
10
- Usage example:
11
- python debug_server_policy.py --host 127.0.0.1 --port 10093 --device cuda --test infer
12
-
13
- Notes:
14
- - The random observation is synthetic and only meant to validate the interface.
15
- - Adjust keys (e.g. 'images', 'task_description') to match the server's expected schema.
16
- """
17
-
18
- import argparse
19
- import logging
20
- import numpy as np
21
-
22
-
23
- from tools.websocket_policy_client import WebsocketClientPolicy
24
-
25
-
26
- def _build_argparser() -> argparse.ArgumentParser:
27
- ap = argparse.ArgumentParser(description="WebSocket policy client smoke test (msgpack protocol)")
28
- ap.add_argument("--host", default="127.0.0.1", help="server hostname/IP (do not use 0.0.0.0)")
29
- ap.add_argument("--port", type=int, default=10093, help="server port")
30
- ap.add_argument("--api_key", default="", help="optional: API key for authentication")
31
- ap.add_argument("--device", default="cuda", choices=["cuda", "cpu"], help="initialize device")
32
- ap.add_argument(
33
- "--test", choices=["init", "infer"], default="infer", help="test mode: only initialize, or try simple inference"
34
- )
35
- ap.add_argument("--log_level", default="INFO")
36
- return ap
37
-
38
-
39
- def _main():
40
- args = _build_argparser().parse_args()
41
- logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.INFO), force=True)
42
-
43
- client = WebsocketClientPolicy(host=args.host, port=args.port, api_key=(args.api_key or None))
44
- logging.info("Connected. Server metadata: %s", client.get_server_metadata())
45
-
46
- # 1) device initialization
47
- init_ret = client.init_device(args.device) # here to set some things on the server
48
- logging.info("Init device resp: %s", init_ret)
49
-
50
- # 2) optional: try one simple inference
51
- if args.test == "infer":
52
- try:
53
- # build observation aligned with model API
54
- H, W = 224, 224
55
- img = np.random.randint(0, 256, (H, W, 3), dtype=np.uint8)
56
- wrist_img = np.random.randint(0, 256, (H, W, 3), dtype=np.uint8)
57
- state = np.zeros((7,), dtype=np.float32) # [x,y,z, ax,ay,az, gripper]
58
-
59
- observation = { # key to align with model API
60
- "request_id": "smoke-test",
61
- "observation.primary": np.expand_dims(img, axis=0), # (1,H,W,C), uint8 0-255
62
- "observation.wrist_image": np.expand_dims(wrist_img, axis=0), # (1,H,W,C)
63
- "observation.state": np.expand_dims(state, axis=0), # (1,7), float32
64
- "instruction": ["debug: pick up the red block"], # single element list
65
- }
66
-
67
- image_path = "assets/table.jpeg"
68
- # read image as PIL
69
- from PIL import Image
70
- image_primary = Image.open(image_path).convert("RGB")
71
- # Convert PIL -> numpy uint8 (H,W,3)
72
- image_primary_np = np.asarray(image_primary, dtype=np.uint8)
73
-
74
- instruction_lang="pick up the red block"
75
- obs = {
76
- "request_id": "smoke-test",
77
- "batch_images": [[image_primary_np]],
78
- "instructions": [instruction_lang], # assume batch task description
79
- }
80
-
81
- infer_ret = client.infer(obs)
82
- logging.info("Infer resp: %s", infer_ret)
83
- except Exception as e:
84
- logging.error("Infer error (this still proves transport OK): %s", e)
85
-
86
- client.close()
87
- logging.info("Smoke test done.")
88
-
89
-
90
- if __name__ == "__main__":
91
- _main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/image_tools.py DELETED
@@ -1,119 +0,0 @@
1
- import numpy as np
2
- from PIL import Image
3
-
4
-
5
- def convert_to_uint8(img: np.ndarray) -> np.ndarray:
6
- """Converts an image to uint8 if it is a float image.
7
-
8
- This is important for reducing the size of the image when sending it over the network.
9
- """
10
- if np.issubdtype(img.dtype, np.floating):
11
- img = (255 * img).astype(np.uint8)
12
- return img
13
-
14
-
15
- def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray:
16
- """Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height.
17
-
18
- Args:
19
- images: A batch of images in [..., height, width, channel] format.
20
- height: The target height of the image.
21
- width: The target width of the image.
22
- method: The interpolation method to use. Default is bilinear.
23
-
24
- Returns:
25
- The resized images in [..., height, width, channel].
26
- """
27
- # If the images are already the correct size, return them as is.
28
- if images.shape[-3:-1] == (height, width):
29
- return images
30
-
31
- original_shape = images.shape
32
-
33
- images = images.reshape(-1, *original_shape[-3:])
34
- resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images])
35
- return resized.reshape(*original_shape[:-3], *resized.shape[-3:])
36
-
37
-
38
- def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image:
39
- """Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and
40
- width without distortion by padding with zeros.
41
-
42
- Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c].
43
- """
44
- cur_width, cur_height = image.size
45
- if cur_width == width and cur_height == height:
46
- return image # No need to resize if the image is already the correct size.
47
-
48
- ratio = max(cur_width / width, cur_height / height)
49
- resized_height = int(cur_height / ratio)
50
- resized_width = int(cur_width / ratio)
51
- resized_image = image.resize((resized_width, resized_height), resample=method)
52
-
53
- zero_image = Image.new(resized_image.mode, (width, height), 0)
54
- pad_height = max(0, int((height - resized_height) / 2))
55
- pad_width = max(0, int((width - resized_width) / 2))
56
- zero_image.paste(resized_image, (pad_width, pad_height))
57
- assert zero_image.size == (width, height)
58
- return zero_image
59
-
60
- from typing import Sequence, Union, List, Tuple, Any
61
- def to_pil_preserve(images: Any, scale_float: bool = True):
62
- """
63
- Convert (possibly nested) numpy image arrays back to PIL.Image WITHOUT changing spatial shape
64
- or nesting structure.
65
-
66
- Accepts:
67
- - np.ndarray with shape (H, W, C), C in {1,3,4}, dtype uint8 or float
68
- - PIL.Image.Image (returned as-is)
69
- - Nested list / tuple structures containing the above
70
-
71
- Guarantees:
72
- - No resize / pad / crop performed
73
- - Returns an object with the SAME nesting layout (list -> list, tuple -> tuple)
74
- - Only dtype (float -> uint8) and channel-mode adaptation may happen
75
- * float arrays assumed in [0,1] if scale_float=True (scaled *255 + clip)
76
- Args:
77
- images: input object / sequence
78
- scale_float: whether to scale float images in [0,1] to uint8
79
- Returns:
80
- Mirrored structure with all leaf nodes as PIL.Image.Image
81
- """
82
- def _convert(obj):
83
- # Nested containers
84
- if isinstance(obj, list):
85
- return [ _convert(x) for x in obj ]
86
- if isinstance(obj, tuple):
87
- return tuple(_convert(x) for x in obj)
88
-
89
- # PIL stays
90
- if isinstance(obj, Image.Image):
91
- return obj
92
-
93
- # numpy -> PIL
94
- if isinstance(obj, np.ndarray):
95
- arr = obj
96
- if arr.ndim != 3:
97
- raise ValueError(f"Expected 3D array (H,W,C), got shape={arr.shape}")
98
- if arr.shape[2] not in (1,3,4):
99
- raise ValueError(f"Channel count must be 1/3/4, got {arr.shape[2]}")
100
- if np.issubdtype(arr.dtype, np.floating):
101
- if scale_float:
102
- arr = np.clip(arr, 0.0, 1.0)
103
- arr = (arr * 255.0 + 0.5).astype(np.uint8)
104
- else:
105
- raise TypeError("Float array provided but scale_float=False")
106
- elif arr.dtype != np.uint8:
107
- arr = arr.astype(np.uint8)
108
-
109
- # Single channel -> 'L'
110
- if arr.shape[2] == 1:
111
- arr = arr[:, :, 0]
112
- return Image.fromarray(arr, mode="L")
113
- # 3 channels -> RGB, 4 -> RGBA
114
- mode = "RGB" if arr.shape[2] == 3 else "RGBA"
115
- return Image.fromarray(arr, mode=mode)
116
-
117
- raise TypeError(f"Unsupported element type: {type(obj)}")
118
-
119
- return _convert(images)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/msgpack_numpy.py DELETED
@@ -1,57 +0,0 @@
1
- """Adds NumPy array support to msgpack.
2
-
3
- msgpack is good for (de)serializing data over a network for multiple reasons:
4
- - msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution)
5
- - msgpack is widely used and has good cross-language support
6
- - msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed
7
- languages like Python and JavaScript
8
- - msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster
9
- than pickle for serializing large arrays using the below strategy
10
-
11
- The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is
12
- that it falls back to pickle for object arrays.
13
- """
14
-
15
- import functools
16
-
17
- import msgpack
18
- import numpy as np
19
-
20
-
21
- def pack_array(obj):
22
- if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
23
- raise ValueError(f"Unsupported dtype: {obj.dtype}")
24
-
25
- if isinstance(obj, np.ndarray):
26
- return {
27
- b"__ndarray__": True,
28
- b"data": obj.tobytes(),
29
- b"dtype": obj.dtype.str,
30
- b"shape": obj.shape,
31
- }
32
-
33
- if isinstance(obj, np.generic):
34
- return {
35
- b"__npgeneric__": True,
36
- b"data": obj.item(),
37
- b"dtype": obj.dtype.str,
38
- }
39
-
40
- return obj
41
-
42
-
43
- def unpack_array(obj):
44
- if b"__ndarray__" in obj:
45
- return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
46
-
47
- if b"__npgeneric__" in obj:
48
- return np.dtype(obj[b"dtype"]).type(obj[b"data"])
49
-
50
- return obj
51
-
52
-
53
- Packer = functools.partial(msgpack.Packer, default=pack_array)
54
- packb = functools.partial(msgpack.packb, default=pack_array)
55
-
56
- Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
57
- unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/websocket_policy_client.py DELETED
@@ -1,149 +0,0 @@
1
- # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
-
5
- import logging
6
- import os
7
- import time
8
- from typing import Dict, Optional, Tuple, Any
9
-
10
- from typing_extensions import override
11
- import websockets
12
- import websockets.sync.client
13
-
14
- from . import msgpack_numpy
15
-
16
-
17
- class WebsocketClientPolicy:
18
- """Implements the Policy interface by communicating with a server over websocket.
19
-
20
- See WebsocketPolicyServer for a corresponding server implementation.
21
- """
22
-
23
- def __init__(
24
- self,
25
- host: str = "127.0.0.1",
26
- port: Optional[int] = 10093,
27
- api_key: Optional[str] = None,
28
- connect_timeout: float = 300.0,
29
- open_timeout: float = 150.0,
30
- ping_interval: Optional[float] = 30.0,
31
- ping_timeout: Optional[float] = 300.0,
32
- reconnect_max_attempts: int = 5,
33
- ) -> None:
34
- # 0.0.0.0 cannot be used as a connection target, here default 127.0.0.1
35
- self._uri = f"ws://{host}"
36
- if port is not None:
37
- self._uri += f":{port}"
38
-
39
- self._packer = msgpack_numpy.Packer()
40
- self._api_key = api_key
41
-
42
- self._connect_timeout = connect_timeout
43
- self._open_timeout = open_timeout
44
- self._ping_interval = ping_interval
45
- self._ping_timeout = ping_timeout
46
- self._reconnect_max_attempts = reconnect_max_attempts
47
-
48
- self._ws, self._server_metadata = self._wait_for_server(timeout=self._connect_timeout)
49
-
50
- def get_server_metadata(self) -> Dict:
51
- return self._server_metadata
52
-
53
- def close(self) -> None:
54
- try:
55
- if getattr(self, "_ws", None) is not None:
56
- self._ws.close()
57
- except Exception:
58
- pass
59
-
60
- def _drop_proxy_env(self) -> None:
61
- # Some environments set proxies that break ws://127.0.0.1
62
- for k in ("HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"):
63
- os.environ.pop(k, None)
64
-
65
- def _connect_once(self) -> Tuple[websockets.sync.client.ClientConnection, Dict[str, Any]]:
66
- headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
67
- conn = websockets.sync.client.connect(
68
- self._uri,
69
- compression=None,
70
- max_size=None,
71
- additional_headers=headers,
72
- open_timeout=self._open_timeout,
73
- ping_interval=self._ping_interval,
74
- ping_timeout=self._ping_timeout,
75
- close_timeout=10,
76
- )
77
- # First frame: metadata
78
- metadata = msgpack_numpy.unpackb(conn.recv())
79
- if not isinstance(metadata, dict):
80
- raise RuntimeError(f"Server metadata must be dict, got: {type(metadata)}")
81
- return conn, metadata
82
-
83
- def _wait_for_server(self, timeout: float = 300.0) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
84
- logging.info(f"Waiting for server at {self._uri}...")
85
- start_time = time.time()
86
-
87
- self._drop_proxy_env()
88
-
89
- backoff = 0.5 # seconds
90
- while True:
91
- if time.time() - start_time > timeout:
92
- raise TimeoutError(f"Failed to connect to server within {timeout} seconds")
93
-
94
- try:
95
- conn, metadata = self._connect_once()
96
- return conn, metadata
97
- except ConnectionRefusedError:
98
- logging.info(f"Still waiting for server {self._uri} ...")
99
- except Exception as e:
100
- logging.warning(f"Connect failed: {repr(e)}")
101
-
102
- time.sleep(backoff)
103
- backoff = min(backoff * 1.5, 5.0)
104
-
105
- def _reconnect(self) -> None:
106
- """Reconnect with limited attempts. Keeps it synchronous and simple."""
107
- self.close()
108
- last_err = None
109
- for attempt in range(1, self._reconnect_max_attempts + 1):
110
- try:
111
- self._ws, self._server_metadata = self._wait_for_server(timeout=60.0)
112
- return
113
- except Exception as e:
114
- last_err = e
115
- logging.warning(f"Reconnect attempt {attempt}/{self._reconnect_max_attempts} failed: {repr(e)}")
116
- raise RuntimeError(f"Failed to reconnect after {self._reconnect_max_attempts} attempts") from last_err
117
-
118
- @override
119
- def predict_action(self, query_info: Dict) -> Dict:
120
- """
121
- Sends a request to server. Supports both:
122
- - legacy payload dict (query_info)
123
- - or query_info already containing {type, request_id, payload}
124
- """
125
- data = self._packer.pack(query_info)
126
-
127
- try:
128
- self._ws.send(data)
129
- response = self._ws.recv()
130
- except websockets.exceptions.ConnectionClosedError as e:
131
- logging.warning(f"WebSocket closed, reconnecting once... ({e})")
132
- self._reconnect()
133
- self._ws.send(data)
134
- response = self._ws.recv()
135
-
136
- if isinstance(response, str):
137
- # server sent traceback text frame
138
- raise RuntimeError(f"Error in inference server:\n{response}")
139
-
140
- ret = msgpack_numpy.unpackb(response)
141
- if not isinstance(ret, dict):
142
- raise RuntimeError(f"Invalid response type: {type(ret)}")
143
-
144
- # Optional: normalize error replies
145
- if ret.get("ok") is False and ret.get("status") == "error":
146
- err = ret.get("error", {})
147
- raise RuntimeError(f"Server error: {err}")
148
-
149
- return ret
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/model_server/tools/websocket_policy_server.py DELETED
@@ -1,207 +0,0 @@
1
- # Copyright 2025 starVLA community. All rights reserved.
2
- # Licensed under the MIT License, Version 1.0 (the "License");
3
- # Implemented by [Jinhui YE / HKUST University] in [2025].
4
-
5
- import asyncio
6
- import logging
7
- import threading
8
- import time
9
- import traceback
10
- from typing import Any, Dict, Optional
11
-
12
- import numpy as np
13
- import websockets
14
- import websockets.asyncio.server
15
- import websockets.frames
16
-
17
- from . import msgpack_numpy
18
-
19
-
20
- def _to_serializable(obj: Any) -> Any:
21
- """Recursively convert non-serializable objects (e.g. PIL Image) into
22
- msgpack-friendly types so the response can be packed by msgpack_numpy.
23
-
24
- PIL Image objects are converted to numpy arrays (which msgpack_numpy
25
- supports) and the downstream client uses ``np.asarray`` on them anyway.
26
- """
27
- # Lazy import to avoid a hard dependency if PIL is unavailable.
28
- try:
29
- from PIL import Image as _PILImage
30
- except Exception: # pragma: no cover - PIL should be available
31
- _PILImage = None
32
-
33
- if _PILImage is not None and isinstance(obj, _PILImage.Image):
34
- return np.asarray(obj)
35
- if isinstance(obj, dict):
36
- return {key: _to_serializable(value) for key, value in obj.items()}
37
- if isinstance(obj, (list, tuple)):
38
- return [_to_serializable(item) for item in obj]
39
- return obj
40
-
41
-
42
- class WebsocketPolicyServer:
43
- """Serves a policy using the websocket protocol. See websocket_client_policy.py for a client implementation.
44
-
45
- Currently only implements the `load` and `infer` methods.
46
- """
47
-
48
- def __init__(
49
- self,
50
- policy,
51
- host: str = "0.0.0.0",
52
- port: int = 10093,
53
- idle_timeout: int = -1, # seconds; -1 means never shutdown
54
- metadata: Optional[dict] = None,
55
- ping_interval: Optional[float] = 30.0,
56
- ping_timeout: Optional[float] = 300.0,
57
- ) -> None:
58
- self._policy = policy
59
- self._host = host
60
- self._port = port
61
- self._metadata = metadata or {}
62
- self._idle_timeout = idle_timeout
63
- self._last_active = time.time()
64
-
65
- # WebSocket keepalive tuning (server side!)
66
- self._ping_interval = ping_interval
67
- self._ping_timeout = ping_timeout
68
-
69
- # Thread lock for concurrent inference protection
70
- self._inference_lock = threading.Lock()
71
-
72
- logging.getLogger("websockets.server").setLevel(logging.INFO)
73
-
74
- def serve_forever(self) -> None:
75
- asyncio.run(self.run())
76
-
77
- async def run(self) -> None:
78
- async with websockets.asyncio.server.serve(
79
- self._handler,
80
- self._host,
81
- self._port,
82
- compression=None,
83
- max_size=None,
84
- ping_interval=self._ping_interval,
85
- ping_timeout=self._ping_timeout,
86
- close_timeout=10,
87
- ) as server:
88
- if self._idle_timeout > 0:
89
- await self._idle_watchdog(server)
90
- else:
91
- await server.serve_forever()
92
-
93
- async def _idle_watchdog(self, server: websockets.asyncio.server.Server) -> None:
94
- """Monitor server-level idle time; if no requests for idle_timeout seconds, shut down server."""
95
- while True:
96
- await asyncio.sleep(5)
97
- if time.time() - self._last_active > self._idle_timeout:
98
- logging.info(f"Idle timeout ({self._idle_timeout}s) reached, shutting down server.")
99
- server.close()
100
- await server.wait_closed()
101
- break
102
-
103
- async def _handler(self, websocket: websockets.asyncio.server.ServerConnection) -> None:
104
- logging.info(f"Connection from {websocket.remote_address} opened")
105
- packer = msgpack_numpy.Packer()
106
-
107
- # Send metadata as first binary frame
108
- await websocket.send(packer.pack(self._metadata))
109
-
110
- while True:
111
- try:
112
- raw = await websocket.recv()
113
- msg = msgpack_numpy.unpackb(raw)
114
- self._last_active = time.time()
115
-
116
- # ★ CRITICAL: do NOT block event loop with inference
117
- ret = await asyncio.to_thread(self._route_message, msg)
118
-
119
- await websocket.send(packer.pack(ret))
120
- except websockets.ConnectionClosed:
121
- logging.info(f"Connection from {websocket.remote_address} closed")
122
- break
123
- except Exception:
124
- # Send traceback as text, then close with 1011
125
- tb = traceback.format_exc()
126
- try:
127
- await websocket.send(tb)
128
- except Exception:
129
- pass
130
- try:
131
- await websocket.close(
132
- code=websockets.frames.CloseCode.INTERNAL_ERROR,
133
- reason="Internal server error. Traceback included in previous frame.",
134
- )
135
- except Exception:
136
- pass
137
- raise
138
-
139
- def _route_message(self, msg: Any) -> Dict[str, Any]:
140
- """
141
- Fault-tolerant routing:
142
- Accepts either:
143
- 1) protocol envelope:
144
- {"type": "ping|infer|reset|...", "request_id": "...", "payload": {...}}
145
- 2) legacy style:
146
- { ...payload... } (treated as infer)
147
- """
148
- # Normalize
149
- if isinstance(msg, dict):
150
- req_id = msg.get("request_id", "default")
151
- mtype = msg.get("type", "infer")
152
- payload = msg.get("payload", msg) # if no payload wrapper, treat whole dict as payload
153
- else:
154
- req_id = "default"
155
- mtype = "infer"
156
- payload = msg
157
-
158
- # ping
159
- if mtype == "ping":
160
- return {"status": "ok", "ok": True, "type": "ping", "request_id": req_id}
161
-
162
- # infer / predict_action
163
- if mtype in ("infer", "predict_action"):
164
- if not isinstance(payload, dict):
165
- return {
166
- "status": "error",
167
- "ok": False,
168
- "type": "inference_result",
169
- "request_id": req_id,
170
- "error": {"message": "Payload must be a dict", "payload_type": str(type(payload))},
171
- }
172
-
173
- try:
174
- # IMPORTANT: only pass payload into policy, not control fields
175
- # Use lock to ensure thread-safe concurrent inference
176
- with self._inference_lock:
177
- output_dict = self._policy.predict_action(**payload, is_run_parallel_eval_mxk=True)
178
- return {
179
- "status": "ok",
180
- "ok": True,
181
- "type": "inference_result",
182
- "request_id": req_id,
183
- "data": _to_serializable(output_dict),
184
- }
185
- except Exception as e:
186
- logging.exception("Policy inference error (request_id=%s)", req_id)
187
- return {
188
- "status": "error",
189
- "ok": False,
190
- "type": "inference_result",
191
- "request_id": req_id,
192
- "error": {"message": str(e)},
193
- }
194
-
195
- # unknown request type
196
- return {
197
- "status": "error",
198
- "ok": False,
199
- "type": "unknown",
200
- "request_id": req_id,
201
- "error": {"message": f"Unsupported message type '{mtype}'"},
202
- }
203
-
204
-
205
- if __name__ == "__main__":
206
- logging.basicConfig(level=logging.INFO, force=True)
207
- raise NotImplementedError("This module is not intended to be run directly.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/readme-deployment.md DELETED
@@ -1,11 +0,0 @@
1
- sudo ip addr add 172.16.0.100/24 dev enx207bd51a3217
2
- sudo ip link set enx207bd51a3217 up
3
- ping 172.16.0.2
4
-
5
-
6
- python -m real_deployment.model_controller_del_ee
7
-
8
-
9
- ## install frankx
10
- conda install frankx
11
- unzip frankx.zip
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/real_infer/open_loop_eval.py DELETED
@@ -1,418 +0,0 @@
1
- import os
2
- import sys
3
- import time
4
- from pathlib import Path
5
- from dataclasses import dataclass
6
- from typing import Dict, List, Optional
7
-
8
- import numpy as np
9
- import matplotlib.pyplot as plt
10
- import torch
11
- from omegaconf import OmegaConf
12
- import tyro
13
-
14
- # ====== 你项目里的 import(按你现有路径保留)======
15
- from starVLA.dataloader.lerobot_datasets import get_vla_dataset
16
- from starVLA.model.framework.base_framework import baseframework
17
- from starVLA.model.framework.share_tools import read_mode_config
18
-
19
- # ✅ 关键:导入你训练用的 VideoResizePad(按你项目实际路径改这里)
20
- from starVLA.dataloader.gr00t_lerobot.transform.video import VideoResizePad
21
-
22
-
23
- # -----------------------------
24
- # 0) 图像:单张图复用 VideoResizePad(resize longest edge -> pad 到 224)
25
- # -----------------------------
26
- def _img_to_torch_nchw(img) -> torch.Tensor:
27
- """
28
- Convert input image to torch float tensor [1,C,H,W] in [0,1].
29
- Supports: np.ndarray(H,W,C) uint8/float, torch.Tensor, PIL.Image
30
- """
31
- if isinstance(img, torch.Tensor):
32
- x = img
33
- if x.ndim == 3 and x.shape[-1] in (1, 3, 4) and x.shape[0] not in (1, 3, 4):
34
- x = x.permute(2, 0, 1) # HWC -> CHW
35
- if x.ndim == 2:
36
- x = x.unsqueeze(0)
37
- if x.ndim != 3:
38
- raise ValueError(f"Unexpected torch image shape: {x.shape}")
39
- x = x.float()
40
- if x.max() > 1.5:
41
- x = x / 255.0
42
- return x.unsqueeze(0) # [1,C,H,W]
43
-
44
- if isinstance(img, np.ndarray):
45
- x = torch.from_numpy(img)
46
- if x.ndim == 3 and x.shape[-1] in (1, 3, 4): # HWC
47
- x = x.permute(2, 0, 1) # -> CHW
48
- elif x.ndim == 2:
49
- x = x.unsqueeze(0)
50
- if x.ndim != 3:
51
- raise ValueError(f"Unexpected numpy image shape: {img.shape}")
52
- x = x.float()
53
- if x.max() > 1.5:
54
- x = x / 255.0
55
- return x.unsqueeze(0)
56
-
57
- # 避免强依赖 PIL:只有你真的传 PIL.Image 才需要
58
- try:
59
- from PIL import Image
60
- if isinstance(img, Image.Image):
61
- x = torch.from_numpy(np.array(img))
62
- if x.ndim == 2:
63
- x = x.unsqueeze(-1)
64
- x = x.permute(2, 0, 1).float()
65
- if x.max() > 1.5:
66
- x = x / 255.0
67
- return x.unsqueeze(0)
68
- except Exception:
69
- pass
70
-
71
- raise TypeError(f"Unsupported image type: {type(img)}")
72
-
73
-
74
- def _torch_chw_to_uint8_hwc(x: torch.Tensor) -> np.ndarray:
75
- """
76
- x: torch.Tensor [C,H,W] float [0,1]
77
- return: np.uint8 [H,W,C]
78
- """
79
- x = (x.clamp(0, 1) * 255.0).to(torch.uint8)
80
- x = x.permute(1, 2, 0).cpu().numpy()
81
- return x
82
-
83
-
84
- class OpenLoopVideoResizePadWrapper:
85
- """
86
- 复用训练同款 VideoResizePad 的 torchvision resize+pad 逻辑,
87
- 但输入/输出是“单张图”。
88
- """
89
-
90
- def __init__(self, resize_pad_transform: VideoResizePad, return_numpy_uint8_hwc: bool = True):
91
- self.t = resize_pad_transform
92
- self.return_numpy_uint8_hwc = return_numpy_uint8_hwc
93
-
94
- def __call__(self, img):
95
- # 单图 -> [1,C,H,W]
96
- x = _img_to_torch_nchw(img)
97
- # 复用类内部 torchvision resize+pad
98
- y = self.t._torchvision_resize_pad(x) # [1,C,S,S]
99
- y = y.squeeze(0) # [C,S,S]
100
- if self.return_numpy_uint8_hwc:
101
- return _torch_chw_to_uint8_hwc(y) # [S,S,C] uint8,最保险(兼容你现有 predict_action)
102
- return y # torch [C,S,S]
103
-
104
-
105
- # -----------------------------
106
- # 1) 你已有的归一化/反归一化逻辑(原封不动)
107
- # -----------------------------
108
- def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
109
- lo = np.asarray(stats["min"], dtype=np.float32)
110
- hi = np.asarray(stats["max"], dtype=np.float32)
111
- denom = np.maximum(hi - lo, eps)
112
- x01 = (x - lo) / denom
113
- xn = x01 * 2.0 - 1.0
114
- return xn.astype(np.float32)
115
-
116
-
117
- def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
118
- mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
119
- action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
120
- normalized_actions = np.clip(normalized_actions, -1, 1)
121
- actions = np.where(
122
- mask,
123
- (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
124
- normalized_actions,
125
- )
126
- return actions
127
-
128
-
129
- # -----------------------------
130
- # 2) Args(按你 server 的 Args 简化必要项)
131
- # -----------------------------
132
- @dataclass
133
- class Args:
134
- ckpt_path: str = "outputs/suqian_post_train_w_state/checkpoints/steps_80000_pytorch_model.pt"
135
- unnorm_key: str = "agibot_genie1"
136
- gripper_threshold: float = 0.5
137
-
138
- # ✅ 关键:对齐训练图像预处理
139
- image_size: int = 224
140
- image_interpolation: str = "linear"
141
- image_fill_value: float = 0.0
142
-
143
-
144
- def _build_policy(args: Args):
145
- vla = baseframework.from_pretrained(args.ckpt_path)
146
- vla = vla.to("cuda").eval()
147
-
148
- cfg, norm_stats = read_mode_config(Path(args.ckpt_path))
149
- unnorm_key = args.unnorm_key
150
- cfg = OmegaConf.create(cfg)
151
-
152
- vla.action_norm_stats = norm_stats[unnorm_key]["action"]
153
- vla.state_norm_stats = norm_stats[unnorm_key]["state"]
154
- return vla, cfg
155
-
156
-
157
- def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
158
- prompt = obs.get("prompt", "")
159
-
160
- state = np.asarray(obs["observation/state"], dtype=np.float32)
161
- if state.ndim == 1:
162
- state = state[None, :]
163
- elif state.ndim != 2:
164
- raise ValueError(f"Unexpected state shape: {state.shape}")
165
-
166
- state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
167
-
168
- # padding 到 64
169
- cur_dim = state_norm.shape[-1]
170
- if cur_dim < 64:
171
- pad_width = 64 - cur_dim
172
- state_norm = np.pad(
173
- state_norm,
174
- pad_width=((0, 0), (0, pad_width)),
175
- mode="constant",
176
- constant_values=0.0,
177
- )
178
-
179
- fake_data = {
180
- "image": [
181
- obs["observation/image"],
182
- obs["observation/wrist_left_image"],
183
- obs["observation/wrist_right_image"],
184
- ],
185
- "lang": prompt,
186
- "state": state_norm,
187
- }
188
-
189
- t0 = time.perf_counter()
190
- with torch.inference_mode():
191
- out = policy.predict_action(fake_data)
192
- infer_ms = (time.perf_counter() - t0) * 1000
193
-
194
- na = out["normalized_actions"] # (1, H, D)
195
- na2 = na[0, :, :18] # (H, D) 你原逻辑保留
196
-
197
- raw2 = unnormalize_actions(na2, policy.action_norm_stats) # (H, D)
198
- actions = raw2[None, ...] # (1, H, D)
199
-
200
- return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
201
-
202
-
203
- # -----------------------------
204
- # 3) 从 single_ds.get_step_data 组装 obs / gt_chunk
205
- # -----------------------------
206
- def build_obs_from_step_data(step_data: dict, single_ds, img_proc: Optional[callable] = None) -> dict:
207
- """
208
- step_data: single_ds.get_step_data(traj_id, base_index) 的 RAW 输出
209
- 返回:_infer_single 所需的 obs dict
210
- """
211
- video_keys = single_ds.modality_keys["video"]
212
- if len(video_keys) < 3:
213
- raise ValueError(f"Need 3 cameras, got video_keys={video_keys}")
214
-
215
- head = step_data[video_keys[0]][0]
216
- left = step_data[video_keys[1]][0]
217
- right = step_data[video_keys[2]][0]
218
-
219
- # ✅ 对齐训练:resize+pad 到 224(或 args.image_size)
220
- if img_proc is not None:
221
- head = img_proc(head)
222
- left = img_proc(left)
223
- right = img_proc(right)
224
-
225
- # state concat: (T, D_total) -> 取第 0 帧对应 base step
226
- state_parts = [step_data[k] for k in single_ds.modality_keys["state"]]
227
- state = np.concatenate(state_parts, axis=1)
228
- state0 = state[0]
229
-
230
- # language
231
- lang_key = single_ds.modality_keys["language"][0]
232
- lang = step_data[lang_key][0]
233
- if isinstance(lang, list):
234
- lang = lang[0]
235
-
236
- obs = {
237
- "observation/image": head,
238
- "observation/wrist_left_image": left,
239
- "observation/wrist_right_image": right,
240
- "observation/state": state0,
241
- "prompt": lang,
242
- }
243
- return obs
244
-
245
-
246
- def get_gt_action_chunk(step_data: dict, single_ds) -> np.ndarray:
247
- action_parts = [step_data[k] for k in single_ds.modality_keys["action"]]
248
- gt = np.concatenate(action_parts, axis=1) # (H, D)
249
- return gt
250
-
251
-
252
- # -----------------------------
253
- # 4) rollout:拼整段 pred/gt(像 gr00t open-loop eval)
254
- # -----------------------------
255
- def rollout_open_loop(
256
- single_ds,
257
- pi0_policy,
258
- args: Args,
259
- traj_id: int,
260
- steps: int = 200,
261
- action_horizon: int = 16,
262
- img_proc: Optional[callable] = None,
263
- ):
264
- traj_len = int(single_ds.trajectory_lengths[single_ds.get_trajectory_index(traj_id)])
265
- actual_steps = min(steps, traj_len)
266
-
267
- pred_list = []
268
- gt_list = []
269
- infer_ms_list = []
270
-
271
- for t in range(0, actual_steps, action_horizon):
272
- step_data = single_ds.get_step_data(traj_id, t)
273
-
274
- obs = build_obs_from_step_data(step_data, single_ds, img_proc=img_proc)
275
- pred = _infer_single(pi0_policy, obs, args, args.gripper_threshold)
276
-
277
- pred_chunk = pred["actions"][0] # (H, D)
278
- gt_chunk = get_gt_action_chunk(step_data, single_ds) # (H, D)
279
-
280
- remain = actual_steps - t
281
- pred_chunk = pred_chunk[:remain]
282
- gt_chunk = gt_chunk[:remain]
283
-
284
- pred_list.append(pred_chunk)
285
- gt_list.append(gt_chunk)
286
- infer_ms_list.append(pred["policy_timing"]["infer_ms"])
287
-
288
- pred_action_across_time = np.concatenate(pred_list, axis=0)
289
- gt_action_across_time = np.concatenate(gt_list, axis=0)
290
-
291
- assert pred_action_across_time.shape == gt_action_across_time.shape, (
292
- f"pred={pred_action_across_time.shape}, gt={gt_action_across_time.shape}")
293
- return pred_action_across_time, gt_action_across_time, infer_ms_list
294
-
295
-
296
- # -----------------------------
297
- # 5) 画图(整段轨迹)
298
- # -----------------------------
299
- def plot_action_curves(
300
- gt: np.ndarray,
301
- pred: np.ndarray,
302
- save_path: str,
303
- dims: Optional[List[int]] = None,
304
- title: str = "",
305
- ):
306
- T, D = gt.shape
307
- if dims is None:
308
- dims = list(range(D))
309
-
310
- n = len(dims)
311
- fig, axes = plt.subplots(nrows=n, ncols=1, figsize=(10, 2.2 * n))
312
- if n == 1:
313
- axes = [axes]
314
-
315
- fig.suptitle(title, fontsize=14)
316
-
317
- x = np.arange(T)
318
- for i, d in enumerate(dims):
319
- ax = axes[i]
320
- ax.plot(x, gt[:, d], label="gt")
321
- ax.plot(x, pred[:, d], label="pred")
322
- ax.set_ylabel(f"dim {d}")
323
- ax.legend(loc="upper right")
324
-
325
- axes[-1].set_xlabel("time step")
326
- plt.tight_layout()
327
- Path(save_path).parent.mkdir(parents=True, exist_ok=True)
328
- plt.savefig(save_path, dpi=150)
329
- plt.close(fig)
330
-
331
-
332
- def plot_error_over_time(gt: np.ndarray, pred: np.ndarray, save_path: str, title: str = ""):
333
- err = pred - gt
334
- mse_t = np.mean(err**2, axis=1)
335
- mae_t = np.mean(np.abs(err), axis=1)
336
-
337
- x = np.arange(len(mse_t))
338
- fig = plt.figure(figsize=(10, 4))
339
- plt.plot(x, mse_t, label="MSE per step")
340
- plt.plot(x, mae_t, label="MAE per step")
341
- plt.title(title)
342
- plt.xlabel("time step")
343
- plt.ylabel("error")
344
- plt.legend()
345
- plt.tight_layout()
346
- Path(save_path).parent.mkdir(parents=True, exist_ok=True)
347
- plt.savefig(save_path, dpi=150)
348
- plt.close(fig)
349
-
350
-
351
- # -----------------------------
352
- # 6) main:把 dataset + policy 接起来
353
- # -----------------------------
354
- def main(args: Args):
355
- # ===== load policy =====
356
- pi0_policy, cfg = _build_policy(args)
357
- print("policy loaded")
358
-
359
- # ===== 构造与训练一致的 VideoResizePad =====
360
- # 训练时写的是 VideoResizePad(apply_to=[video_key], size=224, interpolation="linear", fill_value=0.0)
361
- # 这里我们直接复用其内部 torchvision resize+pad 实现
362
- resize_pad = VideoResizePad(
363
- apply_to=["video"], # 占位即可
364
- size=args.image_size,
365
- interpolation=args.image_interpolation,
366
- fill_value=args.image_fill_value,
367
- backend="torchvision", # 确保走 torchvision
368
- )
369
- img_proc = OpenLoopVideoResizePadWrapper(resize_pad, return_numpy_uint8_hwc=True)
370
-
371
- # ===== 载入训练 yaml 的 dataset 配置 =====
372
- vla_dataset_cfg = cfg.datasets.vla_data
373
- vla_dataset_cfg.task_id = "all"
374
- dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
375
- single_ds = dataset.datasets[0] if hasattr(dataset, "datasets") else dataset
376
-
377
- # 选一条 traj
378
- traj_id = int(single_ds.trajectory_ids[0])
379
- print("Using traj_id:", traj_id)
380
-
381
- # ===== rollout open-loop =====
382
- pred, gt, infer_ms_list = rollout_open_loop(
383
- single_ds,
384
- pi0_policy,
385
- args,
386
- traj_id=traj_id,
387
- steps=200,
388
- action_horizon=30,
389
- img_proc=img_proc, # ✅ 关键:评测也做 resize+pad
390
- )
391
-
392
- mse = np.mean((pred - gt)**2)
393
- mae = np.mean(np.abs(pred - gt))
394
- print(f"Open-loop MSE={mse:.6f}, MAE={mae:.6f}")
395
- print(f"Infer ms: mean={np.mean(infer_ms_list):.2f}, p95={np.percentile(infer_ms_list, 95):.2f}")
396
-
397
- out_dir = Path("outputs/open_loop_eval")
398
- out_dir.mkdir(parents=True, exist_ok=True)
399
-
400
- plot_action_curves(
401
- gt,
402
- pred,
403
- save_path=str(out_dir / f"traj{traj_id}_action_curves.png"),
404
- # dims=list(range(min(gt.shape[1], 18))), # 只看前 18 维就打开
405
- title=f"traj {traj_id} action curves (T={gt.shape[0]}, D={gt.shape[1]})",
406
- )
407
- plot_error_over_time(
408
- gt,
409
- pred,
410
- save_path=str(out_dir / f"traj{traj_id}_error.png"),
411
- title=f"traj {traj_id} error over time",
412
- )
413
-
414
- print("Saved plots to:", out_dir)
415
-
416
-
417
- if __name__ == "__main__":
418
- main(tyro.cli(Args))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/real_infer/server.py DELETED
@@ -1,375 +0,0 @@
1
- """
2
- Pi0 WebSocket 推理服务端,兼容 openpi-client 客户端协议。
3
-
4
- - 使用 websockets.asyncio.server,客户端用 WebsocketClientPolicy 连接。
5
- - 首次连接发送 metadata(简单字典)。
6
- - 收到 obs 后,调用 Pi0 推理并返回 {"actions": np.ndarray, "policy_timing": {"infer_ms": ...}}。
7
-
8
- 支持 joint_position 和 camera_position(通过 state 维度判断:16 -> joint,14 -> camera)。
9
- """
10
-
11
- import asyncio
12
- import http
13
- import os
14
- import sys
15
- import time
16
- import traceback
17
- from dataclasses import dataclass, field
18
- from pathlib import Path
19
- from typing import Dict, List, Literal, Optional
20
-
21
- import numpy as np
22
- import tyro
23
- import websockets.asyncio.server as ws_server
24
- import websockets.frames
25
-
26
- import torch
27
- import cv2 as cv
28
-
29
- # 兼容 protobuf 版本
30
- os.environ.setdefault("PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "python")
31
-
32
- # 路径设置
33
- _current_dir = Path(__file__).resolve().parent
34
- _project_root = _current_dir.parent
35
- if str(_project_root) not in sys.path:
36
- sys.path.insert(0, str(_project_root))
37
-
38
- # openpi-client 在当前目录下
39
- _openpi_client_src = _current_dir / "openpi-client" / "src"
40
- if _openpi_client_src.exists() and str(_openpi_client_src) not in sys.path:
41
- sys.path.insert(0, str(_openpi_client_src))
42
-
43
- from starVLA.model.framework.base_framework import baseframework
44
- from starVLA.model.framework.share_tools import read_mode_config
45
- from openpi_client import msgpack_numpy
46
-
47
-
48
- @dataclass
49
- class Args:
50
- host: str = "0.0.0.0"
51
- port: int = 8000
52
- ckpt_path: str = "/mnt/workspace/users/yuanzhihao/code/starVLA/outputs/suqian_post_train_no_pretrain/checkpoints/steps_15000_pytorch_model.pt"
53
- data_statistics_path: str = "/workspace/niejunnan/VLAPipeline_RL_BY_Niejunnan/output_train/agibot/benchmark_pro_max/ds_stats.json"
54
- language_tokenizer_path: Optional[str] = "/workspace/paligemma-3b-pt-224"
55
- unnorm_key: Optional[str] = "agibot_genie1"
56
- policy_setup: str = "agibot_genie1"
57
- obs_camera_name: List[str] = field(default_factory=lambda: ["head_color", "hand_left", "hand_right"])
58
- action_scale: float = 1.0
59
- use_filter: bool = False
60
- use_multi_action_head: str = "raw"
61
- use_arm_pose_type: str = "euler"
62
- use_paligemma_original_vocab_size: bool = True
63
- n_action_steps: Optional[int] = None
64
- inference_mode: str = "synchronous"
65
- # 兼容 pi0inference 期望的其他开关
66
- use_distillation_distribution: bool = False
67
- use_embodiment_id: bool = False
68
- use_vit_for_action_head: bool = False
69
- use_distillation: bool = False
70
- use_best_of_n: bool = False
71
- best_of_n: int = 32
72
- use_step_action_mask_for_q: bool = False
73
- image_size: int = 224
74
- gripper_threshold: float = 0.5
75
-
76
-
77
- def resizepad_longest_edge_cv2(
78
- image: np.ndarray,
79
- target_size: int = 224,
80
- fill_value: int = 0,
81
- ) -> np.ndarray:
82
- """
83
- Resize longest edge to target_size, keep aspect ratio, then center-pad to (target_size, target_size).
84
- Input: image HWC (H,W,C) or HW (H,W)
85
- Output: uint8 HWC (target_size,target_size,C) or (target_size,target_size) for grayscale
86
- """
87
- if not isinstance(image, np.ndarray):
88
- image = np.asarray(image)
89
-
90
- if image.ndim == 2:
91
- H, W = image.shape
92
- C = None
93
- elif image.ndim == 3:
94
- H, W, C = image.shape
95
- else:
96
- raise ValueError(f"Unexpected image shape: {image.shape}")
97
-
98
- # Avoid degenerate
99
- if H <= 0 or W <= 0:
100
- raise ValueError(f"Invalid image size: H={H}, W={W}")
101
-
102
- # scale longest edge -> target_size
103
- scale = target_size / float(max(H, W))
104
- new_h = max(1, int(round(H * scale)))
105
- new_w = max(1, int(round(W * scale)))
106
-
107
- # choose interpolation
108
- interp = cv.INTER_AREA if scale < 1.0 else cv.INTER_LINEAR
109
-
110
- resized = cv.resize(image, (new_w, new_h), interpolation=interp)
111
-
112
- pad_h = target_size - new_h
113
- pad_w = target_size - new_w
114
- pad_top = pad_h // 2
115
- pad_bottom = pad_h - pad_top
116
- pad_left = pad_w // 2
117
- pad_right = pad_w - pad_left
118
-
119
- # padding value
120
- if resized.ndim == 2:
121
- border_value = fill_value
122
- else:
123
- # OpenCV expects scalar or tuple; tuple is safer for multi-channel
124
- border_value = (fill_value,) * resized.shape[2]
125
-
126
- padded = cv.copyMakeBorder(
127
- resized,
128
- pad_top,
129
- pad_bottom,
130
- pad_left,
131
- pad_right,
132
- borderType=cv.BORDER_CONSTANT,
133
- value=border_value,
134
- )
135
-
136
- # safety: enforce exact target size
137
- if padded.shape[0] != target_size or padded.shape[1] != target_size:
138
- padded = padded[:target_size, :target_size]
139
-
140
- return padded
141
-
142
-
143
- def _minmax_to_minus1_1(x: np.ndarray, stats: dict, eps: float = 1e-6) -> np.ndarray:
144
- """
145
- x: (..., D)
146
- stats: contains "min" and "max" (D,)
147
- return: (..., D) in [-1, 1]
148
- """
149
- lo = np.asarray(stats["min"], dtype=np.float32)
150
- hi = np.asarray(stats["max"], dtype=np.float32)
151
- denom = np.maximum(hi - lo, eps)
152
- x01 = (x - lo) / denom
153
- xn = x01 * 2.0 - 1.0
154
- return xn.astype(np.float32)
155
-
156
-
157
- def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
158
- """
159
- Args:
160
- normalized_actions: shape (B, chunk, D) (chunk, D)
161
- action_norm_stats:
162
- Returns:
163
- actions
164
- """
165
- mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
166
- action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
167
-
168
- normalized_actions = np.clip(normalized_actions, -1, 1)
169
-
170
- actions = np.where(
171
- mask,
172
- (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
173
- normalized_actions,
174
- )
175
-
176
- return actions
177
-
178
-
179
- def _build_policy(args: Args):
180
- vla = baseframework.from_pretrained(args.ckpt_path)
181
- vla = vla.to("cuda").eval()
182
-
183
- _, norm_stats = read_mode_config(Path(args.ckpt_path))
184
- unnorm_key = args.unnorm_key
185
-
186
- # ✅ action stats(你原来就有)
187
- vla.action_norm_stats = norm_stats[unnorm_key]["action"]
188
-
189
- # ✅ state stats(新增:用于输入归一化,训练一致)
190
- vla.state_norm_stats = norm_stats[unnorm_key]["state"]
191
-
192
- return vla
193
-
194
-
195
- def _infer_single(policy, obs: Dict, args: Args, gripper_th: float) -> Dict:
196
- prompt = obs.get("prompt", "")
197
- print("prompt", prompt)
198
-
199
- # -------- state: raw -> normalized (min_max to [-1,1]) --------
200
- state = np.asarray(obs["observation/state"], dtype=np.float32)
201
- # print('state', state.shape, state)
202
- if state.ndim == 1:
203
- state = state[None, :] # (1, D)
204
- elif state.ndim != 2:
205
- raise ValueError(f"Unexpected state shape: {state.shape}")
206
-
207
- # ✅ 训练一致:min_max 归一化
208
- state_norm = _minmax_to_minus1_1(state, policy.state_norm_stats)
209
-
210
- # padding 到 58
211
- cur_dim = state_norm.shape[-1]
212
- if cur_dim < 64:
213
- pad_width = 64 - cur_dim
214
- state_norm = np.pad(
215
- state_norm,
216
- pad_width=((0, 0), (0, pad_width)),
217
- mode="constant",
218
- constant_values=0.0,
219
- )
220
-
221
- head = resizepad_longest_edge_cv2(obs["observation/image"], target_size=args.image_size, fill_value=0)
222
- left = resizepad_longest_edge_cv2(obs["observation/wrist_left_image"], target_size=args.image_size, fill_value=0)
223
- right = resizepad_longest_edge_cv2(obs["observation/wrist_right_image"], target_size=args.image_size, fill_value=0)
224
-
225
- fake_data = {
226
- "image": [head, left, right],
227
- "lang": prompt,
228
- "state": state_norm,
229
- }
230
-
231
- print('img', obs["observation/image"].shape)
232
- # raw = state
233
- # sn = state_norm
234
- # print("state raw min/max:", raw.min(), raw.max())
235
- # print("state_norm min/max:", sn.min(), sn.max(), "clip_ratio:", np.mean((sn <= -0.999) | (sn >= 0.999)))
236
-
237
- t0 = time.perf_counter()
238
- with torch.inference_mode():
239
- out = policy.predict_action(fake_data)
240
- infer_ms = (time.perf_counter() - t0) * 1000
241
-
242
- # out 来自 predict_action
243
- na = out["normalized_actions"] # (1, 16, 18) numpy
244
-
245
- # 1️⃣ 去掉 batch 维
246
- na2 = na[0, :, :18] # (H, D) 你原逻辑保留
247
-
248
- # 2️⃣ 用 numpy 版 unnormalize(CPU)
249
- raw2 = unnormalize_actions(
250
- na2,
251
- policy.action_norm_stats,
252
- ) # (16, 18)
253
-
254
- # 3️⃣ 如有需要再加回 batch 维
255
- actions = raw2[None, ...] # (1, 16, 18)
256
- actions = raw2
257
- print(actions[0, 0])
258
-
259
- return {"actions": actions, "policy_timing": {"infer_ms": infer_ms}}
260
-
261
-
262
- def _health_check(connection: ws_server.ServerConnection, request: ws_server.Request):
263
- """健康检查端点"""
264
- if request.path == "/healthz":
265
- return connection.respond(http.HTTPStatus.OK, "OK\n")
266
- return None
267
-
268
-
269
- class Pi0PolicyServer:
270
- """Pi0 WebSocket 推理服务端"""
271
-
272
- def __init__(self, pi0_policy, args: Args):
273
- self._policy = pi0_policy
274
- self._args = args
275
- self._metadata = {
276
- "status": "ok",
277
- "policy": "pi0",
278
- "obs_cameras": args.obs_camera_name,
279
- "action_dim": 14,
280
- }
281
- self._packer = msgpack_numpy.Packer()
282
-
283
- def serve_forever(self) -> None:
284
- """阻塞式启动服务"""
285
- asyncio.run(self._run())
286
-
287
- async def _run(self):
288
- """异步运行服务"""
289
- async with ws_server.serve(
290
- self._handler,
291
- self._args.host,
292
- self._args.port,
293
- compression=None,
294
- max_size=None,
295
- process_request=_health_check,
296
- ) as server:
297
- print("✓ 服务已启动,等待客户端连接...")
298
- await server.serve_forever()
299
-
300
- async def _handler(self, websocket: ws_server.ServerConnection):
301
- """处理单个客户端连接"""
302
- print(f"[连接] 客户端 {websocket.remote_address} 已连接")
303
-
304
- # 发送 metadata
305
- await websocket.send(self._packer.pack(self._metadata))
306
-
307
- while True:
308
- try:
309
- data = await websocket.recv()
310
- if isinstance(data, str):
311
- await websocket.send(f"Invalid data type: {type(data)}")
312
- continue
313
-
314
- obs = msgpack_numpy.unpackb(data)
315
- result = _infer_single(self._policy, obs, self._args, self._args.gripper_threshold)
316
- await websocket.send(self._packer.pack(result))
317
-
318
- except websockets.ConnectionClosed:
319
- print(f"[断开] 客户端 {websocket.remote_address} 已断开")
320
- break
321
- except Exception:
322
- error_msg = traceback.format_exc()
323
- print(f"[错误] {error_msg}")
324
- await websocket.send(error_msg)
325
- await websocket.close(
326
- code=websockets.frames.CloseCode.INTERNAL_ERROR,
327
- reason="Internal server error",
328
- )
329
- raise
330
-
331
-
332
- def serve(args: Args):
333
- print("=" * 60)
334
- print("Pi0 WebSocket 推理服务端 (openpi-client 兼容)")
335
- print("=" * 60)
336
- print(f" 监听: ws://{args.host}:{args.port}")
337
- print(f" 权重: {args.ckpt_path}")
338
- print(f" 数据统计: {args.data_statistics_path}")
339
- print(f" 相机键: {args.obs_camera_name}")
340
- print(f" unnorm_key: {args.unnorm_key}")
341
- print(f" tokenizer: {args.language_tokenizer_path}")
342
- print("=" * 60)
343
-
344
- print("[1/2] 初始化模型...")
345
- pi0_policy = _build_policy(args)
346
- print("✓ 模型就绪")
347
-
348
- # ===== 在这里加 =====
349
- print("Has predict_action:", hasattr(pi0_policy, "predict_action"))
350
- print("Has __call__:", callable(pi0_policy))
351
- print("Action-related methods:", [m for m in dir(pi0_policy) if "action" in m.lower()])
352
-
353
- am = pi0_policy.action_model
354
- print("past_action_window_size:", getattr(pi0_policy, "past_action_window_size", None))
355
- print("future_action_window_size:", getattr(pi0_policy, "future_action_window_size", None))
356
- print("action_model:", type(am))
357
- print("action_model attrs (state):", [x for x in dir(am) if "state" in x.lower()])
358
-
359
- # ===================
360
-
361
- print("[2/2] 启动 WebSocket 服务...")
362
- server = Pi0PolicyServer(pi0_policy, args)
363
-
364
- try:
365
- server.serve_forever()
366
- except KeyboardInterrupt:
367
- print("\n[退出] 收到中断信号,正在关闭服务...")
368
-
369
-
370
- def main():
371
- serve(tyro.cli(Args))
372
-
373
-
374
- if __name__ == "__main__":
375
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deployment_robotwin/upload/push_model_to_hf.py DELETED
@@ -1,12 +0,0 @@
1
- from huggingface_hub import create_repo, HfApi
2
-
3
- # 1. create repository
4
- hf_name = "StarVLA/Qwen3-VL-OFT-LIBERO-4in1"
5
- create_repo(hf_name, repo_type="model", exist_ok=True)
6
-
7
- # 2. initialize API
8
- api = HfApi()
9
-
10
- # 3. upload large folder
11
- folder_path = "/mnt/petrelfs/yejinhui/Projects/starVLA/results/Checkpoints/1_need/Qwen3-VL-OFT-LIBERO-4in1"
12
- api.upload_large_folder(folder_path=folder_path, repo_id=hf_name, repo_type="model")
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/EVALUATION.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RoboCasa-GR1 Evaluation
2
+
3
+ ## Fixed Contract
4
+
5
+ | Setting | Value |
6
+ |---|---|
7
+ | Checkpoint | Original 340000-step export |
8
+ | Contract identifier | `wm4a_contract_v2_any_physical_step` |
9
+ | Latent coordinates | `legacy` |
10
+ | Instruction format | `Task: <instruction>.` |
11
+ | Tasks | Ordered 24-task list in `release_manifest.json` |
12
+ | Full-run episodes | 50 per task |
13
+ | Scene seeds | 9000 through 9049 within every task |
14
+ | Policy randomness | Seeded per episode and action chunk |
15
+ | Action-sampling steps | 20 |
16
+ | Predicted horizon / executed chunk | 16 / 12 |
17
+ | Maximum physical steps | 720 |
18
+ | Environment process | One independent simulator environment per process |
19
+ | Parallelism | Four clients per policy server; one or two policy GPUs |
20
+ | Rendering | Explicit physical EGL GPU index |
21
+ | Success | Native predicate at any executed physical step |
22
+ | Stop on success | No |
23
+ | IK state | Cleared per environment at episode boundaries |
24
+ | Future-image generation | Off by default |
25
+
26
+ The wrapper evaluates success within each executed action chunk. Testing
27
+ only its last step misses transient success. An initially successful reset
28
+ is not a substitute for an executed successful transition.
29
+
30
+ ## Setup
31
+
32
+ Follow the root README to download resources, create the two environments,
33
+ run `release.doctor`, verify the checkpoint/assets, and run `release.prepare`.
34
+ Preserve the directory layout: the IK wrapper resolves the GR1 URDF relative
35
+ to the release root.
36
+
37
+ Services bind to `127.0.0.1`. Simulation and policy processes therefore run
38
+ on the same machine; no public unauthenticated policy endpoint is exposed.
39
+
40
+ ```bash
41
+ nvidia-smi
42
+ "$POLICY_PYTHON" -m release.evaluate \
43
+ --gpus 0,1 --render-gpu 1 \
44
+ --policy-python "$POLICY_PYTHON" --sim-python "$SIM_PYTHON" \
45
+ --episodes 50 --seed 9000 --workers-per-policy 4 \
46
+ --output /absolute/new/pilot-evaluation
47
+ ```
48
+
49
+ The launcher uses round-robin task assignment across policy GPUs, matching
50
+ the source evaluation when two GPUs are supplied. It records GPU headroom
51
+ and pre-existing process information before launch, checks inherited
52
+ allocations, and does not signal any process it did not start.
53
+
54
+ The default policy cap is 40 GiB. Admission additionally requires 8 GiB
55
+ headroom on policy-only GPUs and 16 GiB on the rendering GPU. These checks
56
+ are not reservations and cannot guarantee that another process will not
57
+ grow later. Reduce concurrency or use another allocated device if needed.
58
+
59
+ For a smoke test, use `--episodes 1` and one `--task` from the manifest.
60
+ Smoke tests are not full benchmark measurements.
61
+
62
+ ## Outputs
63
+
64
+ ```text
65
+ gpu_admission.json
66
+ server_gpu<N>.log
67
+ load_gpu<N>.json
68
+ <task_slug>/simulation.log
69
+ <task_slug>/rollouts/result.json
70
+ <task_slug>/rollouts/episodes.jsonl
71
+ <task_slug>/rollouts/action_requests.jsonl
72
+ <task_slug>/rollouts/physical_steps/
73
+ <task_slug>/rollouts/videos/
74
+ summary.json
75
+ ```
76
+
77
+ `summary.json` must contain `complete: true` and the expected total episode
78
+ count before reporting a full success rate. Failed, interrupted, and
79
+ missing tasks are not silently counted as completed failures or successes.
80
+ Action records include normalized float32 values, request seeds, and
81
+ SHA-256 hashes for replay checks.
82
+
83
+ Raw runtime logs may contain local paths and process information. Review
84
+ them before public redistribution. The bundled `results/` directory
85
+ contains only sanitized aggregate numerical evidence.
86
+
87
+ ## Optional Future Visualization
88
+
89
+ Add `--visualize-every 10` to generate a diagnostic prediction every ten
90
+ action chunks. This invokes additional video-model denoising and decoding.
91
+ It is off in the full action-only benchmark commands.
92
+
93
+ The model uses a five-frame construction for a future observation at
94
+ offset 16, not a demonstrated continuous long-video rollout. Do not
95
+ restore the historical 93-frame visualization setting. Visualization
96
+ randomness is isolated from action sampling.
97
+
98
+ ## Interpreting Results
99
+
100
+ The completed source-snapshot benchmark produced 717/1200 successes
101
+ (59.75%). On those same trajectories, block-end-only scoring gives
102
+ 712/1200, and final-step-only scoring gives 637/1200.
103
+ Those latter values are rescoring results, not additional model runs.
104
+
105
+ The paper's 58.3% is a separately reported experiment. No matched-protocol
106
+ proof equating it with this audit is claimed. The source score is also not
107
+ a guarantee of bitwise identical trajectories across different GPUs,
108
+ CUDA kernels, simulator builds, or a new installation.
109
+
110
+ ## Troubleshooting
111
+
112
+ **Noise-like predicted images or unexpected action behavior**
113
+
114
+ Verify the checkpoint hash, `legacy` coordinates, pinned dependencies,
115
+ normalization statistics, and five-frame temporal setting first. Do not
116
+ change min/max statistics, IK conventions, or prompts as an undocumented fix.
117
+
118
+ **Missing GR1 assets or PyKDL**
119
+
120
+ Run `release.unpack_assets` if needed, source
121
+ `environment/activate_paths.sh`, and run the simulation preflight.
122
+ Use `environment/build_kdl.sh` in a new simulation environment. Do not
123
+ fall back silently from end-effector retargeting to joint-space actions.
124
+
125
+ **EGL initialization failure**
126
+
127
+ Check the host's NVIDIA EGL installation, `MUJOCO_GL`,
128
+ `PYOPENGL_PLATFORM`, and the physical `--render-gpu` index. Use
129
+ `EGL_LIBRARY_PATH` only for a verified directory on that machine.
130
+ CUDA-visible numbering and EGL physical indexing are not interchangeable.
131
+
132
+ **Out of memory**
133
+
134
+ Check existing jobs before starting. Lower `--workers-per-policy`, use a
135
+ single allocated GPU where safe, or choose a larger allocation. Never kill
136
+ other users' processes or use artificial workloads to reserve memory.
137
+
138
+ **Resume/configuration mismatch**
139
+
140
+ `release.prepare` expects this release's exact checkpoint. An old 280000
141
+ cache or another run's statistics must not be reused. Use a new `--cache`
142
+ directory and explicitly pass its prepared checkpoint to evaluation.
docs/TRAINING.md ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Training And Resume
2
+
3
+ ## Scope
4
+
5
+ This release retains the model and data path for the selected
6
+ `CosmoPredict25PerceiverVJEPA2AC` RoboCasa-GR1 artifact. Two ancestor classes
7
+ remain as implementation helpers, but the public factory rejects other
8
+ architectures. Unrelated benchmark launchers and models are excluded.
9
+
10
+ `configs/pilot_340000.yaml` is derived from the selected run's saved
11
+ configuration, with private paths parameterized and explicit latent/temporal
12
+ contracts added. It is not a claim that all paper experiments use this
13
+ one configuration.
14
+
15
+ ## Data
16
+
17
+ Training demonstrations are not bundled. Supply a legally obtained,
18
+ converted LeRobot-format 24-task RoboCasa-GR1 mixture. The ordered paths
19
+ are defined in `starVLA/dataloader/gr00t_lerobot/mixtures.py`.
20
+
21
+ The interface uses the ego-view RGB stream, current robot state,
22
+ `annotation.human.coarse_action`, 16 future action steps, and a future
23
+ observation at offset 16. The GR1 modality configuration and transforms
24
+ are retained with min/max normalization, padded 64-D state and 32-D
25
+ action tensors.
26
+
27
+ Do not substitute a merged dataset with different episode order,
28
+ normalization statistics, image decoding, or EE/joint conventions and
29
+ call it an exact resume. The release includes the selected checkpoint's
30
+ `configs/dataset_statistics.json` for evaluation, not a substitute for
31
+ training data.
32
+
33
+ ## Artifact Configuration
34
+
35
+ | Parameter | Archived selected-run value |
36
+ |---|---|
37
+ | Seed | 42 |
38
+ | Planned training budget | 400000 updates; this release selects update 340000 |
39
+ | Per-device batch | 14 in the archived run configuration |
40
+ | Action steps / horizon | 20 / 16 |
41
+ | Motion query count | 64 |
42
+ | Base learning rate | `1e-5` |
43
+ | Action/CDE/projector learning rates | `5e-5` |
44
+ | Optimizer | AdamW, betas `(0.9, 0.999)`, epsilon `1e-8`, weight decay `0.1` |
45
+ | Warmup | 2000 updates |
46
+ | LR schedule | Cosine with minimum LR `2e-7` |
47
+ | Action-loss weight | 1 |
48
+ | Future-frame-loss weight | 1 |
49
+ | RD/future-representation-loss weight | **0.1** |
50
+ | Gradient accumulation / clipping | 1 / 1.0 |
51
+
52
+ The supplied manuscript appendix states RD weight `0.01`. The actual
53
+ archived configuration for the selected checkpoint says `0.1`; the
54
+ release does not silently replace one with the other.
55
+
56
+ The historical visualization requested 93 frames. The repaired artifact
57
+ uses **5 frames and one conditioning latent frame**, matching its
58
+ supervised temporal construction. The `legacy` coordinate system is
59
+ mandatory for the released weights.
60
+
61
+ ## Conservative Fine-Tuning
62
+
63
+ The launcher defaults to one rank, batch 1, zero workers, accumulation 1,
64
+ native ZeRO-2, deterministic mode, and disabled external W&B reporting.
65
+ These are safety/replay-validation settings, **not the historical batch-14
66
+ training run**.
67
+
68
+ ```bash
69
+ export POLICY_PYTHON=/absolute/path/to/policy/bin/python
70
+ "$POLICY_PYTHON" -m pip install -r environment/training.requirements.txt
71
+ "$POLICY_PYTHON" -m release.prepare
72
+ export CUDA_VISIBLE_DEVICES=0
73
+ export PILOT_DATA_ROOT=/absolute/path/to/converted-datasets
74
+ export PILOT_OUTPUT_ROOT=/absolute/new/pilot-training
75
+ bash run_training.sh --trainer.max_train_steps 1000
76
+ ```
77
+
78
+ The original 340000 checkpoint initializes the full model, while the
79
+ optimizer and update counter start a **new experiment**. A `.pt` file
80
+ contains weights, not a historical optimizer/RNG/data cursor.
81
+
82
+ For initialization from the original pretrained backbones instead,
83
+ provide their locally available, licensed initialization files:
84
+
85
+ ```bash
86
+ export PILOT_FROM_PRETRAINED=1
87
+ export PILOT_COSMOS_ROOT=/absolute/path/to/original/Cosmos-Predict2.5-2B-Post-Trained
88
+ export PILOT_VJEPA_CHECKPOINT=/absolute/path/to/original/vjepa2-ac-vitg.pt
89
+ bash run_training.sh
90
+ ```
91
+
92
+ Do not point these variables at the components materialized from 340000
93
+ and describe that as training from the original pretrained initialization.
94
+ No unattended long-running training job is started by downloading the release.
95
+
96
+ ## Full-State Resume
97
+
98
+ The repaired trainer writes separate `steps_*_training_state` directories
99
+ containing model/optimizer/scheduler/RNG state, data progress, configuration,
100
+ and a completion manifest.
101
+
102
+ ```bash
103
+ export PILOT_RESUME_STATE=/absolute/path/to/previous-run/checkpoints/steps_500_training_state
104
+ export PILOT_OUTPUT_ROOT=/absolute/new/resumed-run-root
105
+ bash run_training.sh
106
+ ```
107
+
108
+ The launcher uses the saved full configuration. Do not pass a weight-only
109
+ initialization at the same time. Incomplete saves, changed training semantics,
110
+ and changed dependency versions are rejected. Exact data replay is supported
111
+ only by the validated single-rank/stateful-loader configuration; unsupported
112
+ worker and multi-rank settings must not be described as exact continuation.
113
+
114
+ ## Validation Limits
115
+
116
+ The source environment completed 1000 unique updates of the full model,
117
+ with 2,525,075,872 trainable parameters, using the real 24-task data mixture.
118
+ Fresh-process resume reproduced updates 501-505 exactly across 2596 model
119
+ entries, optimizer, scheduler, RNG, sampled data, and metrics.
120
+
121
+ That test used batch 1, workers 0, accumulation 1, and bounded 256-update
122
+ epoch windows. It did not traverse the entire corpus, restore the original
123
+ historical optimizer, prove multi-rank behavior, or validate hundreds of
124
+ thousands of updates. Its new export is not the model with the 59.75%
125
+ benchmark score and is not included in this release.
docs/VALIDATION.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Release Validation
2
+
3
+ ## Checked On September 27, 2026
4
+
5
+ The local portable source passed 19 CPU tests using Python 3.10.21 and
6
+ PyTorch 2.8.0 on macOS. The tests cover:
7
+
8
+ - The two native Diffusers latent conventions and explicit checkpoint coordinates.
9
+ - Conflicting checkpoint/configuration metadata and unknown coordinate rejection.
10
+ - The five-frame supervised horizon and explicit temporal-extrapolation opt-in.
11
+ - Per-request seeded sampling without changing the surrounding Torch RNG.
12
+ - Evaluation-mode and Python/NumPy/Torch RNG restoration, including exceptions.
13
+ - The selected checkpoint metadata, 24-task list, and published numerical counts.
14
+ - GPU allocation/headroom admission and owned-process cleanup.
15
+ - Complete task-result protocol validation, including seed and request count.
16
+ - Rejection of same-size corruption in materialized component caches.
17
+ - Safe archive paths, parent symlinks, overwrite refusal, and executable modes.
18
+ - Python source syntax and the absence of private machine bindings in launchers.
19
+ - Separate Hub ignore rules that retain model weights and simulator archives.
20
+
21
+ The selected framework, policy transport, resume validator, and
22
+ `Cosmos2_5_PredictBasePipeline` also imported successfully in the local CPU
23
+ environment. No complete model was constructed by that check.
24
+
25
+ The full 23,913,608,021-byte checkpoint passed SHA-256 verification against
26
+ the source file. All 45,853 simulator/robot resource files matched the
27
+ source hashes before the two documented local path relocations.
28
+ `release.prepare` then completed on the local CPU and reconstructed the
29
+ four constructor component files directly from the selected checkpoint.
30
+ These checks do not constitute a GPU model forward pass.
31
+
32
+ The policy, simulation, and training requirement sets resolved against
33
+ PyPI metadata for a Linux x86_64 / Python 3.10 target. Resolving the
34
+ CUDA-specific wheel indexes was blocked by a local network timeout.
35
+ Dependency resolution is not installation or runtime verification.
36
+
37
+ Whitespace cleanup was checked against each file's Python AST. It did
38
+ not change the parsed computation.
39
+
40
+ ## Not Established By These Checks
41
+
42
+ - A fresh Linux/CUDA installation reproducing policy inference and EGL rendering.
43
+ - The portable bundle reproducing the source-environment 1200-episode score.
44
+ - A full-model forward/backward pass on macOS, MPS, or smaller GPUs.
45
+ - Multi-rank exact resume or hundreds-of-thousands-update training convergence.
46
+ - General-purpose video generation or superiority to a copy-current-frame baseline.
47
+ - Unrestricted redistribution rights or production safety certification for every asset.
48
+
49
+ The completed source-environment benchmark and bounded training checks
50
+ are described separately in the evaluation/training guides. They must
51
+ not be relabeled as fresh-install validation of this portable package.
52
+
53
+ ## Rerun
54
+
55
+ After installing the policy environment, from the repository root:
56
+
57
+ ```bash
58
+ CUDA_VISIBLE_DEVICES=-1 "$POLICY_PYTHON" -m unittest discover -s tests -v
59
+ ```
60
+
61
+ Without Torch, six tensor tests are explicitly skipped rather than
62
+ reported as passed. Resource and checkpoint hashes must also be checked
63
+ using `python -m release.verify --assets` after the bundle is downloaded.
docs/WM4A.md DELETED
@@ -1,154 +0,0 @@
1
- # WM4A: World Model for Action
2
-
3
- WM4A repurposes **pretrained video-generation world models** as visual encoders for
4
- robot action prediction. Instead of using a Vision-Language Model (VLM) backbone,
5
- WM4A feeds images through a **Diffusion Transformer (DiT)** — the same architecture
6
- used for video prediction — and attaches a lightweight action head on top of its
7
- intermediate representations.
8
-
9
- ## Motivation
10
-
11
- Video prediction models learn rich spatiotemporal representations of physics,
12
- object permanence, and dynamics. WM4A exploits these representations directly:
13
-
14
- ```
15
- VLM approach: Image → VLM encoder → language-aligned features → Action Head
16
- WM4A approach: Image → Video DiT encoder → physics-aligned features → Action Head
17
- ```
18
-
19
- ## Supported Backbones
20
-
21
- | Backbone | Params | Layers | Hidden Dim | Source |
22
- |----------|--------|--------|------------|--------|
23
- | **Cosmos-Predict2-2B** | 2B | 28 | 2048 | NVIDIA Cosmos |
24
- | **Wan2.2-T2V** | 5B | 30 | 3072 | Alibaba Wan |
25
-
26
- ## Architecture
27
-
28
- ```
29
- Input: {images: [PIL], instruction: str, actions: [T, action_dim]}
30
- │
31
- ├─ Text Encoder (T5 / UMT5)
32
- │ instruction → [B, L_text, text_hidden]
33
- │
34
- ├─ VAE Encoder
35
- │ images → latents [B, 16, T_latent, H/8, W/8]
36
- │
37
- └─ DiT Transformer (frozen or fine-tuned)
38
- latents + text_embeds → hidden_states [B, N_tokens, hidden_dim]
39
- │
40
- └─ Action Head (one of three variants below)
41
- → predicted actions [B, chunk_len, action_dim]
42
- ```
43
-
44
- ## Action Head Variants
45
-
46
- Each backbone can be paired with three action head types:
47
-
48
- | Variant | Action Head | What it uses | Speed | Frameworks |
49
- |---------|------------|--------------|-------|------------|
50
- | **OFT** | MLP regression | Last layer only | Fastest | `CosmoPredict2OFT`, `WanOFT` |
51
- | **GR00T** | Flow-matching diffusion (single-layer) | Last layer only | Medium | `CosmoPredict2GR00T`, `WanGR00T` |
52
- | **PI** | Layer-wise cross-attention DiT | All transformer layers | Slowest | `CosmoPredict2PI`, `WanPI` |
53
-
54
- This gives **7 framework combinations** (including a generic `WM4A_OFT`).
55
-
56
- ## Quick Start: Inspect the Data Flow
57
-
58
- Run the built-in demo to see the full forward pass (training + inference):
59
-
60
- ```bash
61
- python starVLA/model/framework/WM4A/CosmoPredict2GR00T.py
62
- ```
63
-
64
- This script:
65
- 1. Loads a config and instantiates the `CosmoPredict2_GR00T` model
66
- 2. Creates a synthetic batch with multi-view images and random actions
67
- 3. Runs the **training forward** and prints the action loss
68
- 4. Runs the **inference forward** and prints the predicted actions
69
-
70
- > **Note:** You need the Cosmos-Predict2-2B weights downloaded locally.
71
- > Set the path in the script or download via:
72
- > ```bash
73
- > huggingface-cli download nvidia/Cosmos-Predict2-2B-Video2World \
74
- > --local-dir ./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World
75
- > ```
76
-
77
- ## Training
78
-
79
- ### Recommended: LIBERO with CosmoPredict2OFT
80
-
81
- The simplest way to train a WM4A model is with the OFT (MLP) action head on
82
- the LIBERO benchmark:
83
-
84
- ```bash
85
- # From the starVLA project root
86
- bash examples/LIBERO/train_files/run_libero_train.sh
87
- ```
88
-
89
- Before running, edit the script to set your local paths:
90
-
91
- ```bash
92
- Framework_name=CosmoPredict2OFT # or CosmoPredict2GR00T, WanOFT, etc.
93
- base_wm=nvidia/Cosmos-Predict2-2B-Video2World> # still needed for tokenizer/processor
94
- config_yaml=./examples/LIBERO/train_files/starvla_cotrain_libero.yaml
95
- libero_data_root=<path_to_LIBERO_dataset>
96
- data_mix=libero_all # or libero_goal
97
- ```
98
-
99
- Key training arguments:
100
-
101
- | Argument | Description | Recommended |
102
- |----------|-------------|-------------|
103
- | `--framework.name` | Framework class name | `CosmoPredict2OFT` |
104
- | `--framework.action_model.future_action_window_size` | Action prediction horizon | 7 |
105
- | `--datasets.vla_data.per_device_batch_size` | Per-GPU batch size | 16 (OFT) / 8 (GR00T) |
106
- | `--trainer.max_train_steps` | Total training steps | 80000 |
107
- | `--trainer.save_interval` | Checkpoint save frequency | 10000 |
108
-
109
- ### Switching Backbones
110
-
111
- To use Wan instead of Cosmos, simply change the framework name:
112
-
113
- ```bash
114
- Framework_name=WanOFT # or WanGR00T, WanPI
115
- ```
116
-
117
- The config YAML remains the same — the framework class handles backbone loading
118
- automatically based on its registered name.
119
-
120
- ## Code Structure
121
-
122
- ```
123
- starVLA/model/
124
- ├── framework/
125
- │ └── WM4A/
126
- │ ├── CosmoPredict2GR00T.py # Cosmos + flow-matching head
127
- │ ├── CosmoPredict2OFT.py # Cosmos + MLP head
128
- │ ├── CosmoPredict2PI.py # Cosmos + layer-wise cross-DiT head
129
- │ ├── WanGR00T.py # Wan + flow-matching head
130
- │ ├── WanOFT.py # Wan + MLP head
131
- │ ├── WanPI.py # Wan + layer-wise cross-DiT head
132
- │ └── WM4A_OFT.py # Generic WM backend + MLP head
133
- └── modules/
134
- ├── world_model/
135
- │ └── CosmoPredict2.py # Cosmos backbone wrapper (VAE + T5 + DiT)
136
- └── action_model/
137
- ├── MLP_ActionHeader.py # OFT action head
138
- ├── flow_matching_head/ # GR00T action head (single-layer FM)
139
- └── LayerwiseFM_ActionHeader.py # PI action head (layer-wise FM)
140
- ```
141
-
142
- ## Key Implementation Details
143
-
144
- - **Precision**: DiT forward runs in `bfloat16` for speed; action head runs in
145
- `float32` for numerical stability.
146
- - **Feature extraction**: Uses PyTorch hooks on selected DiT blocks to capture
147
- intermediate hidden states without modifying the backbone code.
148
- - **Timestep trick**: Sets `timestep=0` during feature extraction — this extracts
149
- representations at the near-clean noise level rather than denoising.
150
- - **Shape reshaping**: DiT outputs `[B, C, T, H, W]` video tensors, which are
151
- reshaped to `[B, T*H*W, C]` token sequences for the action head.
152
- - **Framework registry**: All WM4A classes register themselves via
153
- `@FRAMEWORK_REGISTRY.register("FrameworkName")` and are auto-discovered at
154
- import time — no manual imports needed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
docs/assets/method.svg ADDED