mxk1998 commited on
Commit
d1cc8f4
·
verified ·
1 Parent(s): c946ddf

Publish sealed evaluation sources, batch 2

Browse files
Files changed (28) hide show
  1. examples/Suqian_agibot/eval_files/model2robocasa_interface.py +274 -0
  2. examples/Suqian_agibot/eval_files/simulation_env.py +320 -0
  3. examples/Suqian_agibot/eval_files/wrappers/multistep_wrapper.py +296 -0
  4. examples/Suqian_agibot/eval_files/wrappers/obs_index_selection_wrapper.py +114 -0
  5. examples/Suqian_agibot/eval_files/wrappers/video_recording_wrapper.py +238 -0
  6. examples/Suqian_agibot/train_files/download_gr00t_ft_data.py +124 -0
  7. examples/Suqian_agibot/train_files/joyra05acot.sh +140 -0
  8. examples/Suqian_agibot/train_files/run_cotrain_uni.sh +105 -0
  9. examples/Suqian_agibot/train_files/run_post_train.sh +111 -0
  10. examples/Suqian_agibot/train_files/run_pretrain.sh +107 -0
  11. examples/Suqian_agibot/train_files/run_pretrain_debug.sh +104 -0
  12. examples/Suqian_agibot/train_files/run_pretrain_uni.sh +104 -0
  13. examples/Suqian_agibot/train_files/run_pretrain_uni_nw.sh +104 -0
  14. examples/Suqian_agibot/train_files/run_real.sh +107 -0
  15. examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml +116 -0
  16. examples/Suqian_agibot/train_files/submit_robocasa_training.sh +104 -0
  17. examples/ego_sq/train_files/README.md +11 -0
  18. examples/ego_sq/train_files/run_ego_sq.sh +104 -0
  19. examples/ego_sq/train_files/starvla_cotrain_ego_sq.yaml +113 -0
  20. examples/eval_protocol.md +75 -0
  21. model_metadata/cosmos/model_index.json +28 -0
  22. model_metadata/cosmos/scheduler/scheduler_config.json +32 -0
  23. model_metadata/cosmos/text_encoder/config.json +131 -0
  24. model_metadata/cosmos/text_encoder/generation_config.json +12 -0
  25. model_metadata/cosmos/tokenizer/added_tokens.json +24 -0
  26. model_metadata/cosmos/tokenizer/chat_template.jinja +7 -0
  27. model_metadata/cosmos/tokenizer/merges.txt +0 -0
  28. model_metadata/cosmos/tokenizer/special_tokens_map.json +31 -0
examples/Suqian_agibot/eval_files/model2robocasa_interface.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from typing import Optional, Sequence
3
+ import os
4
+ import cv2 as cv
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+
8
+ from deployment.model_server.tools.websocket_policy_client import WebsocketClientPolicy
9
+
10
+ from examples.Robocasa_tabletop.eval_files.adaptive_ensemble import AdaptiveEnsembler
11
+ from typing import Dict
12
+ import numpy as np
13
+ from pathlib import Path
14
+
15
+
16
+
17
+ from starVLA.model.framework.share_tools import read_mode_config
18
+
19
+
20
+
21
+ class PolicyWarper:
22
+ def __init__(
23
+ self,
24
+ policy_ckpt_path,
25
+ unnorm_key: Optional[str] = None,
26
+ policy_setup: str = "franka",
27
+ horizon: int = 0,
28
+ action_ensemble = False, # @Jinhui
29
+ action_ensemble_horizon: Optional[int] = 3, # different cross sim
30
+ image_size: list[int] = [224, 224],
31
+ use_ddim: bool = True,
32
+ num_ddim_steps: int = 10,
33
+ adaptive_ensemble_alpha = 0.1,
34
+ host="0.0.0.0",
35
+ port=10095,
36
+ n_action_steps=2,
37
+ ) -> None:
38
+
39
+ # build client to connect server policy
40
+ self.client = WebsocketClientPolicy(host, port)
41
+ self.policy_setup = policy_setup
42
+ self.unnorm_key = unnorm_key
43
+
44
+ print(f"*** policy_setup: {policy_setup}, unnorm_key: {unnorm_key} ***")
45
+ self.use_ddim = use_ddim
46
+ self.num_ddim_steps = num_ddim_steps
47
+ self.image_size = image_size
48
+ self.horizon = horizon #0
49
+ self.action_ensemble = action_ensemble
50
+ self.adaptive_ensemble_alpha = adaptive_ensemble_alpha
51
+ self.action_ensemble_horizon = action_ensemble_horizon
52
+ self.sticky_action_is_on = False
53
+ self.gripper_action_repeat = 0
54
+ self.sticky_gripper_action = 0.0
55
+ self.previous_gripper_action = None
56
+ self.n_action_steps = n_action_steps
57
+
58
+ self.task_description = None
59
+ self.image_history = deque(maxlen=self.horizon)
60
+ if self.action_ensemble:
61
+ self.action_ensembler = AdaptiveEnsembler(self.action_ensemble_horizon, self.adaptive_ensemble_alpha)
62
+ else:
63
+ self.action_ensembler = None
64
+ self.num_image_history = 0
65
+
66
+ self.action_norm_stats = self.get_action_stats(self.unnorm_key, policy_ckpt_path=policy_ckpt_path)
67
+
68
+
69
+ def _add_image_to_history(self, image: np.ndarray) -> None:
70
+ self.image_history.append(image)
71
+ self.num_image_history = min(self.num_image_history + 1, self.horizon)
72
+
73
+ def reset(self, task_description: str or tuple) -> None:
74
+
75
+ self.task_description = task_description
76
+ self.image_history.clear()
77
+ if self.action_ensemble:
78
+ self.action_ensembler.reset()
79
+ self.num_image_history = 0
80
+
81
+ self.sticky_action_is_on = False
82
+ self.gripper_action_repeat = 0
83
+ self.sticky_gripper_action = 0.0
84
+ self.previous_gripper_action = None
85
+
86
+
87
+ def step(
88
+ self,
89
+ observations,
90
+ **kwargs
91
+ ) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]:
92
+ """
93
+ 执行一步推理
94
+ :param image: 输入图像 (H, W, 3) uint8格式
95
+ :param task_description: 任务描述文本
96
+ :return: (原始动作, 处理后的动作)
97
+ """
98
+
99
+ task_description = observations['annotation.human.coarse_action'][0] # tuple
100
+ ego_view = observations['video.ego_view'] # (N, 1, H, W, 3)
101
+ images = ego_view
102
+ state = {}
103
+ state['left_arm'] = observations['state.left_arm']
104
+ state['right_arm'] = observations['state.right_arm'] # (N, 1, 7)
105
+ state['left_hand'] = observations['state.left_hand'] # (N, 1, 6)
106
+ state['right_hand'] = observations['state.right_hand'] # (N, 1, 6)
107
+ state['waist'] = observations['state.waist'] # (N, 1, 3)
108
+
109
+
110
+ state = self.normalize_state(state)
111
+ input_state = []
112
+ for key in state.keys():
113
+ input_state.append(state[key])
114
+ input_state = np.concatenate(input_state, axis=-1)
115
+
116
+ if task_description is not None:
117
+ if task_description != self.task_description:
118
+ self.reset(task_description)
119
+
120
+ # image: Image.Image = Image.fromarray(image)
121
+
122
+ images = [[self._resize_image(img) for img in sample] for sample in images] # (B, N_view, H, W, 3)
123
+ input_state = [input_s for input_s in input_state] # B, state_dim*(sin, cos)
124
+
125
+ # prepare vla input
126
+ examples = []
127
+ batch_size = len(images)
128
+ instructions = [self.task_description] if isinstance(self.task_description, str) else self.task_description
129
+ for b in range(batch_size):
130
+ example = {
131
+ "image": images[b], # A list of multi-view images for a single sample
132
+ "lang": instructions[b] if isinstance(instructions, list) else instructions,
133
+ "state": input_state[b], # N_history, 58 #Hack BUG
134
+ }
135
+ examples.append(example)
136
+
137
+ vla_input = {
138
+ "examples": examples,
139
+ "do_sample": False,
140
+ "use_ddim": self.use_ddim,
141
+ "num_ddim_steps": self.num_ddim_steps,
142
+ }
143
+
144
+ response = self.client.predict_action(vla_input)
145
+
146
+
147
+ # unnormalize the action
148
+ normalized_actions = response["data"]["normalized_actions"] # B, chunk, D
149
+
150
+ # unnormalize actions in batch form
151
+ raw_actions = self.unnormalize_actions(normalized_actions=normalized_actions, action_norm_stats=self.action_norm_stats)
152
+
153
+ # raw_actions shape: (B, chunk, D)
154
+ if self.action_ensemble:
155
+ # 对batch中的每个样本进行ensemble
156
+ batch_size = raw_actions.shape[0]
157
+ ensembled_actions = []
158
+ for b in range(batch_size):
159
+ ensembled = self.action_ensembler.ensemble_action(raw_actions[b])[None] # (1, D)
160
+ ensembled_actions.append(ensembled)
161
+ raw_actions = np.stack(ensembled_actions, axis=0) # (B, 1, D)
162
+
163
+ raw_action = {
164
+ "action.left_arm": raw_actions[:, :self.n_action_steps, :7], # (B, n_action_steps, 7)
165
+ "action.right_arm": raw_actions[:, :self.n_action_steps, 7:14], # (B, n_action_steps, 7)
166
+ "action.left_hand": raw_actions[:, :self.n_action_steps, 14:20], # (B, n_action_steps, 6)
167
+ "action.right_hand": raw_actions[:, :self.n_action_steps, 20:26], # (B, n_action_steps, 6)
168
+ "action.waist": raw_actions[:, :self.n_action_steps, 26:29], # (B, n_action_steps, 3)
169
+ }
170
+
171
+ return {"actions": raw_action}
172
+
173
+ @staticmethod
174
+ def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray:
175
+ """
176
+ Args:
177
+ normalized_actions: shape (B, chunk, D) (chunk, D)
178
+ action_norm_stats:
179
+ Returns:
180
+ actions
181
+ """
182
+ mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
183
+ action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
184
+
185
+ normalized_actions = np.clip(normalized_actions, -1, 1)
186
+
187
+ actions = np.where(
188
+ mask,
189
+ (normalized_actions + 1) / 2 * (action_high - action_low) + action_low,
190
+ normalized_actions,
191
+ )
192
+
193
+ return actions
194
+
195
+ @staticmethod
196
+ def get_action_stats(unnorm_key: str, policy_ckpt_path) -> dict:
197
+ """
198
+ Duplicate stats accessor (retained for backward compatibility).
199
+ """
200
+ policy_ckpt_path = Path(policy_ckpt_path)
201
+ model_config, norm_stats = read_mode_config(policy_ckpt_path) # read config and norm_stats
202
+
203
+ unnorm_key = PolicyWarper._check_unnorm_key(norm_stats, unnorm_key)
204
+ return norm_stats[unnorm_key]["action"]
205
+
206
+
207
+
208
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
209
+ image = cv.resize(image, tuple(self.image_size), interpolation=cv.INTER_AREA)
210
+ return image
211
+
212
+ def visualize_epoch(
213
+ self, predicted_raw_actions: Sequence[np.ndarray], images: Sequence[np.ndarray], save_path: str
214
+ ) -> None:
215
+ images = [self._resize_image(image) for image in images]
216
+ ACTION_DIM_LABELS = ["x", "y", "z", "roll", "pitch", "yaw", "grasp"]
217
+
218
+ img_strip = np.concatenate(np.array(images[::3]), axis=1)
219
+
220
+ # set up plt figure
221
+ figure_layout = [["image"] * len(ACTION_DIM_LABELS), ACTION_DIM_LABELS]
222
+ plt.rcParams.update({"font.size": 12})
223
+ fig, axs = plt.subplot_mosaic(figure_layout)
224
+ fig.set_size_inches([45, 10])
225
+
226
+ # plot actions
227
+ pred_actions = np.array(
228
+ [
229
+ np.concatenate([a["world_vector"], a["rotation_delta"], a["open_gripper"]], axis=-1)
230
+ for a in predicted_raw_actions
231
+ ]
232
+ )
233
+ for action_dim, action_label in enumerate(ACTION_DIM_LABELS):
234
+ # actions have batch, horizon, dim, in this example we just take the first action for simplicity
235
+ axs[action_label].plot(pred_actions[:, action_dim], label="predicted action")
236
+ axs[action_label].set_title(action_label)
237
+ axs[action_label].set_xlabel("Time in one episode")
238
+
239
+ axs["image"].imshow(img_strip)
240
+ axs["image"].set_xlabel("Time in one episode (subsampled)")
241
+ plt.legend()
242
+ plt.savefig(save_path)
243
+
244
+ @staticmethod
245
+ def _check_unnorm_key(norm_stats, unnorm_key):
246
+ """
247
+ Duplicate helper (retained for backward compatibility).
248
+ See primary _check_unnorm_key above.
249
+ """
250
+ if unnorm_key is None:
251
+ assert len(norm_stats) == 1, (
252
+ f"Your model was trained on more than one dataset, "
253
+ f"please pass a `unnorm_key` from the following options to choose the statistics "
254
+ f"used for un-normalizing actions: {norm_stats.keys()}"
255
+ )
256
+ unnorm_key = next(iter(norm_stats.keys()))
257
+
258
+ assert unnorm_key in norm_stats, (
259
+ f"The `unnorm_key` you chose is not in the set of available dataset statistics, "
260
+ f"please choose from: {norm_stats.keys()}"
261
+ )
262
+ return unnorm_key
263
+
264
+ def normalize_state(self, state: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
265
+ """
266
+ Normalize the state
267
+ """
268
+ for key in state.keys():
269
+ sin_state = np.sin(state[key])
270
+ cos_state = np.cos(state[key])
271
+ state[key] = np.concatenate([sin_state, cos_state], axis=-1)
272
+ return state
273
+
274
+
examples/Suqian_agibot/eval_files/simulation_env.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import time
16
+ from dataclasses import dataclass, field
17
+ from functools import partial
18
+ from pathlib import Path
19
+ from typing import Any, Dict, List, Optional, Tuple
20
+
21
+ import gymnasium as gym
22
+ import numpy as np
23
+ import tyro
24
+ import dataclasses
25
+ import json
26
+ import logging
27
+ import os
28
+
29
+ # Required for robocasa environments
30
+ import robocasa # noqa: F401
31
+ import robosuite # noqa: F401
32
+ from robocasa.utils.gym_utils import GrootRoboCasaEnv # noqa: F401
33
+ from examples.Robocasa_tabletop.eval_files.base_config import ModalityConfig
34
+ from examples.Robocasa_tabletop.eval_files.base_config import BasePolicy
35
+ from examples.Robocasa_tabletop.eval_files.wrappers.multistep_wrapper import MultiStepWrapper
36
+ from examples.Robocasa_tabletop.eval_files.wrappers.video_recording_wrapper import (
37
+ VideoRecorder,
38
+ VideoRecordingWrapper,
39
+ )
40
+
41
+ from examples.Robocasa_tabletop.eval_files.model2robocasa_interface import PolicyWarper
42
+
43
+
44
+ @dataclass
45
+ class VideoConfig:
46
+ """Configuration for video recording settings."""
47
+
48
+ video_dir: Optional[str] = None
49
+ steps_per_render: int = 2 # 和10 是什么关系
50
+ fps: int = 10 # BUG 数据集中应该是 20?
51
+ codec: str = "h264"
52
+ input_pix_fmt: str = "rgb24"
53
+ crf: int = 22
54
+ thread_type: str = "FRAME"
55
+ thread_count: int = 1
56
+
57
+
58
+ @dataclass
59
+ class MultiStepConfig:
60
+ """Configuration for multi-step environment settings."""
61
+
62
+ video_delta_indices: np.ndarray = field(default=np.array([0]))
63
+ state_delta_indices: np.ndarray = field(default=np.array([0]))
64
+ n_action_steps: int = 16
65
+ max_episode_steps: int = 1440
66
+
67
+
68
+ @dataclass
69
+ class SimulationConfig:
70
+ """Main configuration for simulation environment."""
71
+
72
+ env_name: str
73
+ n_episodes: int = 2
74
+ n_envs: int = 1
75
+ video: VideoConfig = field(default_factory=VideoConfig)
76
+ multistep: MultiStepConfig = field(default_factory=MultiStepConfig)
77
+
78
+
79
+ class SimulationInferenceEnv:
80
+ """Client for running simulations with a model."""
81
+
82
+ def __init__(self, model: Optional[BasePolicy] = None):
83
+ """Initialize the simulation client with a model."""
84
+ self.model = model
85
+ self.env = None
86
+
87
+ def get_action(self, observations: Dict[str, Any]) -> Dict[str, Any]:
88
+ """Get action from the model based on observations."""
89
+ # NOTE(YL)!
90
+ # hot fix to change the video.ego_view_bg_crop_pad_res256_freq20 to video.ego_view
91
+ if "video.ego_view_bg_crop_pad_res256_freq20" in observations: # BUG @JinhuiYE here only one viwes
92
+ observations["video.ego_view"] = observations.pop(
93
+ "video.ego_view_bg_crop_pad_res256_freq20"
94
+ )
95
+ return self.model.step(observations)
96
+
97
+ def get_modality_config(self) -> Dict[str, ModalityConfig]:
98
+ """Get modality configuration from the model."""
99
+ return self.model.get_modality_config()
100
+
101
+ def setup_environment(self, config: SimulationConfig) -> gym.vector.VectorEnv:
102
+ """Set up the simulation environment based on the provided configuration."""
103
+ # Create environment functions for each parallel environment
104
+ env_fns = [partial(_create_single_env, config=config, idx=i) for i in range(config.n_envs)]
105
+ # Create vector environment (sync for single env, async for multiple)
106
+ if config.n_envs == 1:
107
+ return gym.vector.SyncVectorEnv(env_fns)
108
+ else:
109
+ return gym.vector.AsyncVectorEnv(
110
+ env_fns,
111
+ shared_memory=False,
112
+ context="spawn",
113
+ )
114
+
115
+ def run_simulation(self, config: SimulationConfig, model: Optional[BasePolicy] = None) -> Tuple[str, List[bool]]:
116
+ """Run the simulation for the specified number of episodes.
117
+
118
+ Args:
119
+ config: Configuration for the simulation
120
+ model: The model to use for inference. If None, uses the model from __init__
121
+ """
122
+ # Use the provided model or fall back to the instance model
123
+ if model is not None:
124
+ self.model = model
125
+
126
+ if self.model is None:
127
+ raise ValueError("No model provided. Please provide a model either in __init__ or run_simulation")
128
+
129
+ start_time = time.time()
130
+ print(
131
+ f"Running {config.n_episodes} episodes for {config.env_name} with {config.n_envs} environments"
132
+ )
133
+ # Set up the environment
134
+ self.env = self.setup_environment(config)
135
+ # Initialize tracking variables
136
+ episode_lengths = []
137
+ current_rewards = [0] * config.n_envs
138
+ current_lengths = [0] * config.n_envs
139
+ completed_episodes = 0
140
+ current_successes = [False] * config.n_envs
141
+ episode_successes = []
142
+ # Initial environment reset
143
+ obs, _ = self.env.reset()
144
+ # Main simulation loop
145
+ while completed_episodes < config.n_episodes:
146
+ # Process observations and get actions from the model
147
+ actions = self._get_actions_from_model(obs)
148
+ # Step the environment
149
+ next_obs, rewards, terminations, truncations, env_infos = self.env.step(actions)
150
+ # Update episode tracking
151
+ for env_idx in range(config.n_envs):
152
+ current_successes[env_idx] |= bool(env_infos["success"][env_idx][0])
153
+ current_rewards[env_idx] += rewards[env_idx]
154
+ current_lengths[env_idx] += 1
155
+ # If episode ended, store results
156
+ if terminations[env_idx] or truncations[env_idx]:
157
+ episode_lengths.append(current_lengths[env_idx])
158
+ episode_successes.append(current_successes[env_idx])
159
+ current_successes[env_idx] = False
160
+ completed_episodes += 1
161
+ # Reset trackers for this environment
162
+ current_rewards[env_idx] = 0
163
+ current_lengths[env_idx] = 0
164
+ obs = next_obs
165
+ # Clean up
166
+ self.env.reset()
167
+ self.env.close()
168
+ self.env = None
169
+ print(
170
+ f"Collecting {config.n_episodes} episodes took {time.time() - start_time:.2f} seconds"
171
+ )
172
+ assert (
173
+ len(episode_successes) >= config.n_episodes
174
+ ), f"Expected at least {config.n_episodes} episodes, got {len(episode_successes)}"
175
+ return config.env_name, episode_successes
176
+
177
+ def _get_actions_from_model(self, observations: Dict[str, Any]) -> Dict[str, Any]:
178
+ """Process observations and get actions from the model."""
179
+ # Get actions from the model
180
+ action_dict = self.get_action(observations)
181
+ # Extract actions from the response
182
+ if "actions" in action_dict:
183
+ actions = action_dict["actions"]
184
+ else:
185
+ actions = action_dict
186
+ # Add batch dimension to actions
187
+ return actions
188
+
189
+
190
+ def _create_single_env(config: SimulationConfig, idx: int) -> gym.Env:
191
+ """Create a single environment with appropriate wrappers."""
192
+ # Create base environment
193
+ env = gym.make(config.env_name, enable_render=True)
194
+ # Add video recording wrapper if needed (only for the first environment)
195
+ if config.video.video_dir is not None:
196
+ video_recorder = VideoRecorder.create_h264(
197
+ fps=config.video.fps,
198
+ codec=config.video.codec,
199
+ input_pix_fmt=config.video.input_pix_fmt,
200
+ crf=config.video.crf,
201
+ thread_type=config.video.thread_type,
202
+ thread_count=config.video.thread_count,
203
+ )
204
+ env = VideoRecordingWrapper(
205
+ env,
206
+ video_recorder,
207
+ video_dir=Path(config.video.video_dir),
208
+ steps_per_render=config.video.steps_per_render,
209
+ )
210
+ # Add multi-step wrapper
211
+ env = MultiStepWrapper(
212
+ env,
213
+ video_delta_indices=config.multistep.video_delta_indices,
214
+ state_delta_indices=config.multistep.state_delta_indices,
215
+ n_action_steps=config.multistep.n_action_steps,
216
+ max_episode_steps=config.multistep.max_episode_steps,
217
+ )
218
+ return env
219
+
220
+
221
+ def run_evaluation(
222
+ env_name: str,
223
+ model: BasePolicy,
224
+ video_dir: Optional[str] = None,
225
+ n_episodes: int = 2,
226
+ n_envs: int = 1,
227
+ n_action_steps: int = 2,
228
+ max_episode_steps: int = 100,
229
+ ) -> Tuple[str, List[bool]]:
230
+ """
231
+ Simple entry point to run a simulation evaluation.
232
+ Args:
233
+ env_name: Name of the environment to run
234
+ model: The model to use for inference
235
+ video_dir: Directory to save videos (None for no videos)
236
+ n_episodes: Number of episodes to run
237
+ n_envs: Number of parallel environments
238
+ n_action_steps: Number of action steps per environment step
239
+ max_episode_steps: Maximum number of steps per episode
240
+ Returns:
241
+ Tuple of environment name and list of episode success flags
242
+ """
243
+ # Create configuration
244
+ config = SimulationConfig(
245
+ env_name=env_name,
246
+ n_episodes=n_episodes,
247
+ n_envs=n_envs,
248
+ video=VideoConfig(video_dir=video_dir),
249
+ multistep=MultiStepConfig(
250
+ n_action_steps=n_action_steps, max_episode_steps=max_episode_steps
251
+ ),
252
+ )
253
+ # Create client and run simulation
254
+ client = SimulationInferenceEnv(model=model)
255
+ results = client.run_simulation(config)
256
+ # Print results
257
+ print(f"Results for {env_name}:")
258
+ print(f"Success rate: {np.mean(results[1]):.2f}")
259
+ return results
260
+
261
+
262
+ @dataclasses.dataclass
263
+ class Args:
264
+ host: str = "127.0.0.1"
265
+ port: int = 5678
266
+ resize_size = [224,224]
267
+
268
+ #################################################################################################################
269
+ # LIBERO environment-specific parameters
270
+ #################################################################################################################
271
+ env_name: str = "gr1_unified/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env" # Task suite. Options: libero_spatial, libero_object, libero_goal, libero_10, libero_90
272
+ n_episodes: int = 50 # Number of steps to wait for objects to stabilize i n sim
273
+ n_envs: int = 1 # Number of rollouts per task
274
+ max_episode_steps: int = 360 #
275
+ n_action_steps: int = 3
276
+
277
+ #################################################################################################################
278
+ # Utils
279
+ #################################################################################################################
280
+ video_out_path: str = "experiments/1029_qwenGR00T_fourier_gr1_unified_1000_PnPMilkToMicrowaveClose_gpus_woPretrain_wState/checkpoints/steps_20000_pytorch_model.pt.log/gr1_unified/logs/PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_Env" # Path to save videos
281
+
282
+ seed: int = 7 # Random Seed (for reproducibility)
283
+
284
+ pretrained_path: str = "results/Checkpoints/1029_qwenGR00T_fourier_gr1_unified_1000_PnPMilkToMicrowaveClose_gpus_woPretrain_wState/checkpoints/steps_20000_pytorch_model.pt"
285
+
286
+
287
+
288
+ def eval_gr1_unified(args: Args) -> None:
289
+ logging.info(f"Arguments: {json.dumps(dataclasses.asdict(args), indent=4)}")
290
+ if os.getenv("DEBUG", False):
291
+ start_debugpy_once()
292
+
293
+ model = PolicyWarper(
294
+ policy_ckpt_path=args.pretrained_path, # to get unnormalization stats
295
+ host=args.host,
296
+ port=args.port,
297
+ image_size=args.resize_size,
298
+ n_action_steps=args.n_action_steps,
299
+ )
300
+ run_evaluation(
301
+ env_name=args.env_name,
302
+ model=model,
303
+ video_dir=args.video_out_path,
304
+ n_episodes=args.n_episodes,
305
+ n_envs=args.n_envs,
306
+ n_action_steps=args.n_action_steps,
307
+ max_episode_steps=args.max_episode_steps,
308
+ )
309
+
310
+ def start_debugpy_once():
311
+ import debugpy
312
+ if getattr(start_debugpy_once, "_started", False):
313
+ return
314
+ debugpy.listen(("0.0.0.0", 10092))
315
+ print("🔍 Waiting for VSCode attach on 0.0.0.0:10092 ...")
316
+ debugpy.wait_for_client()
317
+ start_debugpy_once._started = True
318
+
319
+ if __name__ == "__main__":
320
+ tyro.cli(eval_gr1_unified)
examples/Suqian_agibot/eval_files/wrappers/multistep_wrapper.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from collections import defaultdict, deque
17
+
18
+ import gymnasium as gym
19
+ import numpy as np
20
+ from gymnasium import spaces
21
+
22
+
23
+ def stack_repeated(x, n, loc):
24
+ return np.repeat(np.expand_dims(x, axis=loc), n, axis=loc)
25
+
26
+
27
+ def repeated_box(box_space, n, loc):
28
+ return spaces.Box(
29
+ low=stack_repeated(box_space.low, n, loc),
30
+ high=stack_repeated(box_space.high, n, loc),
31
+ shape=box_space.shape[:loc] + (n,) + box_space.shape[loc:],
32
+ dtype=box_space.dtype,
33
+ )
34
+
35
+
36
+ def repeated_space(space, n, loc=0):
37
+ if isinstance(space, spaces.Box):
38
+ return repeated_box(space, n, loc)
39
+ elif isinstance(space, spaces.Dict):
40
+ result_space = spaces.Dict()
41
+ for key, value in space.items():
42
+ result_space[key] = repeated_space(value, n, loc)
43
+ return result_space
44
+ elif isinstance(space, spaces.Discrete):
45
+ return spaces.MultiDiscrete([[space.n] for _ in range(n)])
46
+ elif isinstance(space, spaces.Text): # For language, we don't repeat and only keep the last one
47
+ return space
48
+ else:
49
+ raise RuntimeError(f"Unsupported space type {type(space)}")
50
+
51
+
52
+ def take_last_n(x, n):
53
+ x = list(x)
54
+ n = min(len(x), n)
55
+ return np.array(x[-n:])
56
+
57
+
58
+ def dict_take_last_n(x, n):
59
+ result = dict()
60
+ for key, value in x.items():
61
+ result[key] = take_last_n(value, n)
62
+ return result
63
+
64
+
65
+ def aggregate(data, method="max"):
66
+ if method == "max":
67
+ # equivalent to any
68
+ return np.max(data)
69
+ elif method == "min":
70
+ # equivalent to all
71
+ return np.min(data)
72
+ elif method == "mean":
73
+ return np.mean(data)
74
+ elif method == "sum":
75
+ return np.sum(data)
76
+ else:
77
+ raise NotImplementedError()
78
+
79
+
80
+ class MultiStepWrapper(gym.Wrapper):
81
+ def __init__(
82
+ self,
83
+ env,
84
+ video_delta_indices,
85
+ state_delta_indices,
86
+ n_action_steps,
87
+ max_episode_steps=None,
88
+ reward_agg_method="max",
89
+ ):
90
+ """
91
+ video_delta_indices: np.ndarray[int], please check `assert_delta_indices` to see the requirements
92
+ state_delta_indices: np.ndarray[int] | None, please check `assert_delta_indices` to see the requirements
93
+ if None, it means the model is vision-only
94
+ """
95
+ super().__init__(env)
96
+ # Assign action space
97
+ self._action_space = repeated_space(env.action_space, n_action_steps)
98
+
99
+ # Assign delta indices and horizons
100
+ self.video_delta_indices = video_delta_indices
101
+ self.video_horizon = len(video_delta_indices)
102
+ self.assert_delta_indices(self.video_delta_indices, self.video_horizon)
103
+ if state_delta_indices is not None:
104
+ self.state_delta_indices = state_delta_indices
105
+ self.state_horizon = len(state_delta_indices)
106
+ self.assert_delta_indices(self.state_delta_indices, self.state_horizon)
107
+ else:
108
+ self.state_horizon = None
109
+ self.state_delta_indices = None
110
+
111
+ # Assign observation space
112
+ self._observation_space = self.convert_observation_space(
113
+ self.observation_space,
114
+ self.video_horizon,
115
+ self.state_horizon,
116
+ )
117
+
118
+ # Assign other attributes
119
+ self.max_episode_steps = max_episode_steps
120
+ self.n_action_steps = n_action_steps
121
+ self.reward_agg_method = reward_agg_method
122
+ self.max_steps_needed = self.get_max_steps_needed()
123
+
124
+ self.obs = deque(maxlen=self.max_steps_needed + 1)
125
+ self.reward = list()
126
+ self.done = list()
127
+ self.info = defaultdict(lambda: deque(maxlen=self.max_steps_needed + 1))
128
+
129
+ def convert_observation_space(self, observation_space, video_horizon, state_horizon):
130
+ """
131
+ For video, the observation space will be (video_horizon,) + original shape
132
+ For state (if not None), the observation space will be (state_horizon,) + original shape
133
+ """
134
+ new_observation_space = {}
135
+ for k in observation_space.keys():
136
+ if k.startswith("video"):
137
+ box = observation_space[k]
138
+ horizon = video_horizon
139
+ new_observation_space[k] = repeated_space(box, horizon)
140
+ elif k.startswith("state"):
141
+ box = observation_space[k]
142
+ if state_horizon is not None:
143
+ horizon = state_horizon
144
+ else:
145
+ # Don't include the state in the observation space
146
+ continue
147
+ new_observation_space[k] = repeated_space(box, horizon)
148
+ elif k.startswith("annotation"):
149
+ text = observation_space[k]
150
+ new_observation_space[k] = text
151
+ else:
152
+ raise ValueError(f"Unknown key: {k}") # NOTE: We might add "language" in the future
153
+
154
+ return spaces.Dict(new_observation_space)
155
+
156
+ def get_max_steps_needed(self):
157
+ """
158
+ Get the maximum number of steps that we need to cache.
159
+ """
160
+ video_max_steps_needed = (
161
+ np.max(self.video_delta_indices) - np.min(self.video_delta_indices) + 1
162
+ )
163
+ if self.state_delta_indices is not None:
164
+ state_max_steps_needed = (
165
+ np.max(self.state_delta_indices) - np.min(self.state_delta_indices) + 1
166
+ )
167
+ else:
168
+ state_max_steps_needed = 0
169
+ return int(max(video_max_steps_needed, state_max_steps_needed))
170
+
171
+ def assert_delta_indices(self, delta_indices: np.ndarray, horizon: int):
172
+ # Check the length
173
+ # (In this wrapper, this seems redundant because we get the horizon from the delta indices. But in the policy, the horizon is not derived from the delta indices but we need to make it consistent. To make the function consistent, we keep the check here.)
174
+ assert len(delta_indices) == horizon, f"{delta_indices=}, {horizon=}"
175
+ # All delta indices should be non-positive because there's no way to get the future observations
176
+ assert np.all(delta_indices <= 0), f"{delta_indices=}"
177
+ # The last delta index should be 0 because it doesn't make sense to not use the latest observation
178
+ assert delta_indices[-1] == 0, f"{delta_indices=}"
179
+ if len(delta_indices) > 1:
180
+ # The step is consistent (because in real robot experiments, we actually use the dt to get the observations, which requires the step to be consistent)
181
+ assert np.all(
182
+ np.diff(delta_indices) == delta_indices[1] - delta_indices[0]
183
+ ), f"{delta_indices=}"
184
+ # And the step is positive
185
+ assert (delta_indices[1] - delta_indices[0]) > 0, f"{delta_indices=}"
186
+
187
+ def reset(self, seed=None, options=None):
188
+ """Resets the environment using kwargs."""
189
+ obs, info = super().reset(seed=seed, options=options)
190
+
191
+ self.obs = deque([obs] * (self.max_steps_needed + 1), maxlen=self.max_steps_needed + 1)
192
+ self.reward = list()
193
+ self.done = list()
194
+ self.info = defaultdict(lambda: deque(maxlen=self.max_steps_needed + 1))
195
+
196
+ obs = self._get_obs(self.video_delta_indices, self.state_delta_indices)
197
+ info = {k: [v] for k, v in info.items()}
198
+ return obs, info
199
+
200
+ def step(self, action):
201
+ """
202
+ action: dict: key-value pairs where the values are of shape (n_action_steps,) + action_shape
203
+ """
204
+ states = []
205
+ rewards = []
206
+ dones = []
207
+ for step in range(self.n_action_steps):
208
+ act = {}
209
+ for key, value in action.items():
210
+ act[key] = value[step, :]
211
+ if len(self.done) > 0 and self.done[-1]:
212
+ # termination
213
+ break
214
+ observation, reward, done, truncated, info = super().step(act)
215
+ env_state = {"states": [], "model": []}
216
+ states.append(env_state["states"])
217
+ rewards.append(reward)
218
+ dones.append(done)
219
+ self.obs.append(observation)
220
+ self.reward.append(reward)
221
+ if (self.max_episode_steps is not None) and (
222
+ len(self.reward) >= self.max_episode_steps
223
+ ):
224
+ # truncation
225
+ done = True
226
+ self.done.append(done)
227
+ self._add_info(info)
228
+
229
+ observation = self._get_obs(self.video_delta_indices, self.state_delta_indices)
230
+ reward = aggregate(self.reward, self.reward_agg_method)
231
+ done = aggregate(self.done, "max")
232
+ info = dict_take_last_n(self.info, self.max_steps_needed)
233
+ states = np.array(states)
234
+ rewards = np.array(rewards)
235
+ dones = np.array(dones)
236
+ info["states"] = states
237
+ info["rewards"] = rewards
238
+ info["model"] = env_state["model"]
239
+ info["actions"] = action
240
+ info["dones"] = dones
241
+ return observation, reward, done, truncated, info
242
+
243
+ def _get_obs(self, video_delta_indices, state_delta_indices):
244
+ """
245
+ Output:
246
+ For video: (video_horizon,) + obs_shape
247
+ For state (if not None): (state_horizon,) + obs_shape
248
+ """
249
+ assert len(self.obs) > 0
250
+ if isinstance(self.observation_space, spaces.Dict):
251
+ result = dict()
252
+ for key in self.observation_space.keys():
253
+ if key.startswith("video"):
254
+ """
255
+ NOTE:
256
+ We need to subtract 1 because video_delta_indices is 0-indexed.
257
+ E.g., video_delta_indices = np.array([-4, -3, -2, -1, 0])
258
+ Then when we select the observation,
259
+ it should be [obs[-5], obs[-4], obs[-3], obs[-2], obs[-1]]
260
+ (i.e., the latest observation is at the last index)
261
+ """
262
+ delta_indices = video_delta_indices - 1
263
+ this_obs = [self.obs[i][key] for i in delta_indices]
264
+ result[key] = np.stack(this_obs, axis=0)
265
+ elif key.startswith("state"):
266
+ if state_delta_indices is not None:
267
+ delta_indices = state_delta_indices - 1
268
+ else:
269
+ raise ValueError(
270
+ f"state_delta_indices is None but `state` is still in the {self.observation_space=}"
271
+ )
272
+ this_obs = [self.obs[i][key] for i in delta_indices]
273
+ result[key] = np.stack(this_obs, axis=0)
274
+ elif key.startswith("annotation"):
275
+ result[key] = self.obs[-1][key]
276
+ else:
277
+ raise ValueError(f"Unknown key: {key}")
278
+ return result
279
+ else:
280
+ raise RuntimeError(f"Unsupported space type: {type(self.observation_space)=}")
281
+
282
+ def _add_info(self, info):
283
+ for key, value in info.items():
284
+ self.info[key].append(value)
285
+
286
+ def get_rewards(self):
287
+ return self.reward
288
+
289
+ def get_attr(self, name):
290
+ return getattr(self, name)
291
+
292
+ def get_infos(self):
293
+ result = dict()
294
+ for k, v in self.info.items():
295
+ result[k] = list(v)
296
+ return result
examples/Suqian_agibot/eval_files/wrappers/obs_index_selection_wrapper.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import gymnasium as gym
17
+ import numpy as np
18
+
19
+
20
+ class ObsIndexSelectionWrapper(gym.Wrapper):
21
+ def __init__(self, env, video_delta_indices, state_delta_indices):
22
+ super().__init__(env)
23
+ self.video_delta_indices = video_delta_indices
24
+ self.video_horizon = len(video_delta_indices)
25
+ self.assert_delta_indices(self.video_delta_indices, self.video_horizon)
26
+
27
+ if state_delta_indices is not None:
28
+ self.state_delta_indices = state_delta_indices
29
+ self.state_horizon = len(state_delta_indices)
30
+ self.assert_delta_indices(self.state_delta_indices, self.state_horizon)
31
+ else:
32
+ self.state_horizon = None
33
+ self.state_delta_indices = None
34
+
35
+ self._observation_space = self.convert_observation_space(
36
+ self.observation_space,
37
+ self.video_horizon,
38
+ self.state_horizon,
39
+ )
40
+
41
+ def assert_delta_indices(self, delta_indices: np.ndarray, horizon: int):
42
+ # Check the length
43
+ # (In this wrapper, this seems redundant because we get the horizon from the delta indices. But in the policy, the horizon is not derived from the delta indices but we need to make it consistent. To make the function consistent, we keep the check here.)
44
+ assert len(delta_indices) == horizon, f"{delta_indices=}, {horizon=}"
45
+ # All delta indices should be non-positive because there's no way to get the future observations
46
+ assert np.all(delta_indices <= 0), f"{delta_indices=}"
47
+ # The last delta index should be 0 because it doesn't make sense to not use the latest observation
48
+ assert delta_indices[-1] == 0, f"{delta_indices=}"
49
+ if len(delta_indices) > 1:
50
+ # The step is consistent (because in real robot experiments, we actually use the dt to get the observations, which requires the step to be consistent)
51
+ assert np.all(
52
+ np.diff(delta_indices) == delta_indices[1] - delta_indices[0]
53
+ ), f"{delta_indices=}"
54
+ # And the step is positive
55
+ assert (delta_indices[1] - delta_indices[0]) > 0, f"{delta_indices=}"
56
+
57
+ def select_steps_for_values(self, data_value, delta_indices):
58
+ """
59
+ data_value: [L, ...]
60
+ delta_indices: np.ndarray[int], please check `assert_delta_indices` to see the requirements
61
+ """
62
+ L = data_value.shape[0]
63
+ assert L >= len(delta_indices), f"{L=}, {len(delta_indices)=}"
64
+ selected_indices = (L - 1) + delta_indices
65
+ assert selected_indices[0] >= 0, f"{L=}, {selected_indices=}"
66
+ return data_value[selected_indices]
67
+
68
+ def select_steps_for_obs(self, obs):
69
+ new_obs = {}
70
+ for k in obs.keys():
71
+ if k.startswith("video"):
72
+ new_obs[k] = self.select_steps_for_values(obs[k], self.video_delta_indices)
73
+ elif k.startswith("state"):
74
+ if self.state_delta_indices is not None:
75
+ new_obs[k] = self.select_steps_for_values(obs[k], self.state_delta_indices)
76
+ else:
77
+ # Don't include the state in the observation
78
+ continue
79
+ else:
80
+ raise ValueError(f"Unknown key: {k}")
81
+ return new_obs
82
+
83
+ def convert_observation_space(self, observation_space, video_horizon, state_horizon):
84
+ new_observation_space = {}
85
+ for k in observation_space.keys():
86
+ box = observation_space[k]
87
+ if k.startswith("video"):
88
+ horizon = video_horizon
89
+ elif k.startswith("state"):
90
+ if state_horizon is not None:
91
+ horizon = state_horizon
92
+ else:
93
+ # Don't include the state in the observation space
94
+ continue
95
+ else:
96
+ raise ValueError(f"Unknown key: {k}")
97
+
98
+ new_observation_space[k] = gym.spaces.Box(
99
+ low=box.low[:horizon],
100
+ high=box.high[:horizon],
101
+ shape=(horizon, *box.shape[1:]),
102
+ dtype=box.dtype,
103
+ )
104
+ return gym.spaces.Dict(new_observation_space)
105
+
106
+ def reset(self, seed=None, options=None):
107
+ obs, info = super().reset(seed=seed, options=options)
108
+ obs = self.select_steps_for_obs(obs)
109
+ return obs, info
110
+
111
+ def step(self, action):
112
+ obs, reward, terminated, truncated, info = super().step(action)
113
+ obs = self.select_steps_for_obs(obs)
114
+ return obs, reward, terminated, truncated, info
examples/Suqian_agibot/eval_files/wrappers/video_recording_wrapper.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ import uuid
18
+ from pathlib import Path
19
+
20
+ import av
21
+ import gymnasium as gym
22
+ import numpy as np
23
+
24
+
25
+ def get_accumulate_timestamp_idxs(
26
+ timestamps: list[float],
27
+ start_time: float,
28
+ dt: float,
29
+ eps: float = 1e-5,
30
+ next_global_idx: int | None = 0,
31
+ allow_negative: bool = False,
32
+ ) -> tuple[list[int], list[int], int]:
33
+ """
34
+ For each dt window, choose the first timestamp in the window.
35
+ Assumes timestamps sorted. One timestamp might be chosen multiple times due to dropped frames.
36
+ next_global_idx should start at 0 normally, and then use the returned next_global_idx.
37
+ However, when overwiting previous values are desired, set last_global_idx to None.
38
+
39
+ Returns:
40
+ local_idxs: which index in the given timestamps array to chose from
41
+ global_idxs: the global index of each chosen timestamp
42
+ next_global_idx: used for next call.
43
+ """
44
+ local_idxs = list()
45
+ global_idxs = list()
46
+ for local_idx, ts in enumerate(timestamps):
47
+ # add eps * dt to timestamps so that when ts == start_time + k * dt
48
+ # is always recorded as kth element (avoiding floating point errors)
49
+ global_idx = np.floor((ts - start_time) / dt + eps)
50
+ if (not allow_negative) and (global_idx < 0):
51
+ continue
52
+ if next_global_idx is None:
53
+ next_global_idx = global_idx
54
+
55
+ n_repeats = max(0, global_idx - next_global_idx + 1)
56
+ for i in range(n_repeats):
57
+ local_idxs.append(local_idx)
58
+ global_idxs.append(next_global_idx + i)
59
+ next_global_idx += n_repeats
60
+ return local_idxs, global_idxs, next_global_idx
61
+
62
+
63
+ class VideoRecorder:
64
+ def __init__(
65
+ self,
66
+ fps,
67
+ codec,
68
+ input_pix_fmt,
69
+ # options for codec
70
+ **kwargs,
71
+ ):
72
+ """
73
+ input_pix_fmt: rgb24, bgr24 see https://github.com/PyAV-Org/PyAV/blob/bc4eedd5fc474e0f25b22102b2771fe5a42bb1c7/av/video/frame.pyx#L352
74
+ """
75
+
76
+ self.fps = fps
77
+ self.codec = codec
78
+ self.input_pix_fmt = input_pix_fmt
79
+ self.kwargs = kwargs
80
+ # runtime set
81
+ self._reset_state()
82
+
83
+ def _reset_state(self):
84
+ self.container = None
85
+ self.stream = None
86
+ self.shape = None
87
+ self.dtype = None
88
+ self.start_time = None
89
+ self.next_global_idx = 0
90
+
91
+ @classmethod
92
+ def create_h264(
93
+ cls,
94
+ fps,
95
+ codec="h264",
96
+ input_pix_fmt="rgb24",
97
+ output_pix_fmt="yuv420p",
98
+ crf=18,
99
+ profile="high",
100
+ **kwargs,
101
+ ):
102
+ obj = cls(
103
+ fps=fps,
104
+ codec=codec,
105
+ input_pix_fmt=input_pix_fmt,
106
+ pix_fmt=output_pix_fmt,
107
+ options={"crf": str(crf), "profile:v": "high"},
108
+ **kwargs,
109
+ )
110
+ return obj
111
+
112
+ def __del__(self):
113
+ self.stop()
114
+
115
+ def is_ready(self):
116
+ return self.stream is not None
117
+
118
+ def start(self, file_path, start_time=None):
119
+ if self.is_ready():
120
+ # if still recording, stop first and start anew.
121
+ self.stop()
122
+
123
+ self.container = av.open(file_path, mode="w")
124
+ self.stream = self.container.add_stream(self.codec, rate=self.fps)
125
+ codec_context = self.stream.codec_context
126
+ for k, v in self.kwargs.items():
127
+ setattr(codec_context, k, v)
128
+ self.start_time = start_time
129
+
130
+ def write_frame(self, img: np.ndarray, frame_time=None):
131
+ if not self.is_ready():
132
+ raise RuntimeError("Must run start() before writing!")
133
+
134
+ n_repeats = 1
135
+ if self.start_time is not None:
136
+ local_idxs, global_idxs, self.next_global_idx = get_accumulate_timestamp_idxs(
137
+ # only one timestamp
138
+ timestamps=[frame_time],
139
+ start_time=self.start_time,
140
+ dt=1 / self.fps,
141
+ next_global_idx=self.next_global_idx,
142
+ )
143
+ # number of appearance means repeats
144
+ n_repeats = len(local_idxs)
145
+
146
+ if self.shape is None:
147
+ self.shape = img.shape
148
+ self.dtype = img.dtype
149
+ h, w, c = img.shape
150
+ self.stream.width = w
151
+ self.stream.height = h
152
+ assert img.shape == self.shape
153
+ assert img.dtype == self.dtype
154
+
155
+ frame = av.VideoFrame.from_ndarray(img, format=self.input_pix_fmt)
156
+ for i in range(n_repeats):
157
+ for packet in self.stream.encode(frame):
158
+ self.container.mux(packet)
159
+
160
+ def stop(self):
161
+ if not self.is_ready():
162
+ return
163
+
164
+ # Flush stream
165
+ for packet in self.stream.encode():
166
+ self.container.mux(packet)
167
+
168
+ # Close the file
169
+ self.container.close()
170
+
171
+ # reset runtime parameters
172
+ self._reset_state()
173
+
174
+
175
+ class VideoRecordingWrapper(gym.Wrapper):
176
+ def __init__(
177
+ self,
178
+ env,
179
+ video_recorder: VideoRecorder,
180
+ mode="rgb_array",
181
+ video_dir: Path | None = None,
182
+ steps_per_render=1,
183
+ **kwargs,
184
+ ):
185
+ """
186
+ When file_path is None, don't record.
187
+ """
188
+ super().__init__(env)
189
+
190
+ if video_dir is not None:
191
+ video_dir.mkdir(parents=True, exist_ok=True)
192
+
193
+ self.mode = mode
194
+ self.render_kwargs = kwargs
195
+ self.steps_per_render = steps_per_render
196
+ self.video_dir = video_dir
197
+ self.video_recorder = video_recorder
198
+ self.file_path = None
199
+
200
+ self.step_count = 0
201
+
202
+ self.is_success = False
203
+
204
+ def reset(self, **kwargs):
205
+ result = super().reset(**kwargs)
206
+ self.frames = list()
207
+ self.step_count = 1
208
+ self.video_recorder.stop()
209
+
210
+ if self.video_dir is not None and self.file_path is not None:
211
+ # rename the file to indicate success or failure
212
+ original_filestem = self.file_path.stem
213
+ new_filestem = f"{original_filestem}_success{int(self.is_success)}"
214
+ new_file_path = self.video_dir / f"{new_filestem}.mp4"
215
+ os.rename(self.file_path, new_file_path)
216
+
217
+ self.is_success = False
218
+ if self.video_dir is not None:
219
+ self.file_path = self.video_dir / f"{uuid.uuid4()}.mp4"
220
+ return result
221
+
222
+ def step(self, action):
223
+ result = super().step(action)
224
+ self.step_count += 1
225
+ if self.file_path is not None and ((self.step_count % self.steps_per_render) == 0):
226
+ if not self.video_recorder.is_ready():
227
+ self.video_recorder.start(self.file_path)
228
+
229
+ frame = self.env.render()
230
+ assert frame.dtype == np.uint8
231
+ self.video_recorder.write_frame(frame)
232
+ self.is_success = result[-1]["success"]
233
+ return result
234
+
235
+ def render(self, mode="rgb_array", **kwargs):
236
+ if self.video_recorder.is_ready():
237
+ self.video_recorder.stop()
238
+ return self.file_path
examples/Suqian_agibot/train_files/download_gr00t_ft_data.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import list_repo_files, hf_hub_download
2
+ from concurrent.futures import ThreadPoolExecutor, as_completed
3
+ import os
4
+ import time
5
+ import random
6
+
7
+
8
+ REPO_ID = "nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim"
9
+ REPO_TYPE = "dataset"
10
+
11
+ LOCAL_DIR = "./playground/Datasets/nvidia/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim"
12
+
13
+ FOLDERS = [
14
+ "gr1_unified.PnPBottleToCabinetClose_GR1ArmsAndWaistFourierHands_1000",
15
+ "gr1_unified.PnPCanToDrawerClose_GR1ArmsAndWaistFourierHands_1000",
16
+ "gr1_unified.PnPCupToDrawerClose_GR1ArmsAndWaistFourierHands_1000",
17
+ "gr1_unified.PnPMilkToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000",
18
+ "gr1_unified.PnPPotatoToMicrowaveClose_GR1ArmsAndWaistFourierHands_1000",
19
+ "gr1_unified.PnPWineToCabinetClose_GR1ArmsAndWaistFourierHands_1000",
20
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToBasketSplitA_GR1ArmsAndWaistFourierHands_1000",
21
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000",
22
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToPanSplitA_GR1ArmsAndWaistFourierHands_1000",
23
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToPotSplitA_GR1ArmsAndWaistFourierHands_1000",
24
+ "gr1_unified.PosttrainPnPNovelFromCuttingboardToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000",
25
+ "gr1_unified.PosttrainPnPNovelFromPlacematToBasketSplitA_GR1ArmsAndWaistFourierHands_1000",
26
+ "gr1_unified.PosttrainPnPNovelFromPlacematToBowlSplitA_GR1ArmsAndWaistFourierHands_1000",
27
+ "gr1_unified.PosttrainPnPNovelFromPlacematToPlateSplitA_GR1ArmsAndWaistFourierHands_1000",
28
+ "gr1_unified.PosttrainPnPNovelFromPlacematToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000",
29
+ "gr1_unified.PosttrainPnPNovelFromPlateToBowlSplitA_GR1ArmsAndWaistFourierHands_1000",
30
+ "gr1_unified.PosttrainPnPNovelFromPlateToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000",
31
+ "gr1_unified.PosttrainPnPNovelFromPlateToPanSplitA_GR1ArmsAndWaistFourierHands_1000",
32
+ "gr1_unified.PosttrainPnPNovelFromPlateToPlateSplitA_GR1ArmsAndWaistFourierHands_1000",
33
+ "gr1_unified.PosttrainPnPNovelFromTrayToCardboardboxSplitA_GR1ArmsAndWaistFourierHands_1000",
34
+ "gr1_unified.PosttrainPnPNovelFromTrayToPlateSplitA_GR1ArmsAndWaistFourierHands_1000",
35
+ "gr1_unified.PosttrainPnPNovelFromTrayToPotSplitA_GR1ArmsAndWaistFourierHands_1000",
36
+ "gr1_unified.PosttrainPnPNovelFromTrayToTieredbasketSplitA_GR1ArmsAndWaistFourierHands_1000",
37
+ "gr1_unified.PosttrainPnPNovelFromTrayToTieredshelfSplitA_GR1ArmsAndWaistFourierHands_1000",
38
+ ]
39
+
40
+
41
+ def download_with_retry(
42
+ filename: str,
43
+ max_retries: int = 50,
44
+ ) -> bool:
45
+ """
46
+ Download a single file from Hugging Face Hub with retry logic.
47
+
48
+ Args:
49
+ filename: Path of the file in the repository.
50
+ max_retries: Maximum number of retry attempts.
51
+
52
+ Returns:
53
+ True if download succeeds, False otherwise.
54
+ """
55
+ for attempt in range(1, max_retries + 1):
56
+ try:
57
+ hf_hub_download(
58
+ repo_id=REPO_ID,
59
+ repo_type=REPO_TYPE,
60
+ filename=filename,
61
+ local_dir=LOCAL_DIR,
62
+ local_dir_use_symlinks=False,
63
+ )
64
+ return True
65
+ except Exception as exc:
66
+ wait_time = random.uniform(1.0, 5.0) * attempt / 10.0
67
+ print(
68
+ f"[{attempt}/{max_retries}] "
69
+ f"Download failed: {filename} ({exc}); "
70
+ f"retrying in {wait_time:.1f}s"
71
+ )
72
+ time.sleep(wait_time)
73
+
74
+ print(f"Giving up after {max_retries} retries: {filename}")
75
+ return False
76
+
77
+
78
+ def main() -> None:
79
+ print("Listing all files in the repository...")
80
+ all_files = list_repo_files(repo_id=REPO_ID, repo_type=REPO_TYPE)
81
+
82
+ target_files = [
83
+ f
84
+ for f in all_files
85
+ if any(f.startswith(folder + "/") for folder in FOLDERS)
86
+ ]
87
+
88
+ print(f"Found {len(target_files)} matching files to download.\n")
89
+
90
+ max_workers = 32
91
+ print(f"Starting parallel download with {max_workers} workers...\n")
92
+
93
+ failed_files: list[str] = []
94
+
95
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
96
+ futures = {
97
+ executor.submit(download_with_retry, filename): filename
98
+ for filename in target_files
99
+ }
100
+
101
+ for idx, future in enumerate(as_completed(futures), start=1):
102
+ filename = futures[future]
103
+ try:
104
+ success = future.result()
105
+ if success:
106
+ print(f"[{idx}/{len(target_files)}] Downloaded: {filename}")
107
+ else:
108
+ failed_files.append(filename)
109
+ except Exception as exc:
110
+ print(f"Unexpected error for {filename}: {exc}")
111
+ failed_files.append(filename)
112
+
113
+ print("\nAll download attempts finished.")
114
+
115
+ if failed_files:
116
+ print(f"{len(failed_files)} files failed to download:")
117
+ for filename in failed_files:
118
+ print(f" - {filename}")
119
+ else:
120
+ print("All files downloaded successfully.")
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
examples/Suqian_agibot/train_files/joyra05acot.sh ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env zsh
2
+ set -euo pipefail
3
+
4
+ # Cosmos-Predict2.5 Perceiver training with eval-time future-image visualization.
5
+ # Action training uses Cosmos hidden states + Perceiver; eval additionally runs
6
+ # the Cosmos2.5 decoder/generation path and saves pred future images.
7
+
8
+ if [ -d /sys/class/infiniband ]; then
9
+ RDMA_DEVICES=$(ls /sys/class/infiniband 2>/dev/null || true)
10
+ else
11
+ RDMA_DEVICES=""
12
+ fi
13
+
14
+ if [ -n "${RDMA_DEVICES}" ]; then
15
+ NCCL_IB_HCA=$(echo "${RDMA_DEVICES}" | tr '\n' ',' | sed 's/,$//')
16
+ export NCCL_IB_HCA
17
+ echo "Detected RDMA devices: ${NCCL_IB_HCA}"
18
+ export NCCL_IB_DISABLE=0
19
+ export NCCL_NET_GDR_LEVEL=2
20
+ else
21
+ echo "No RDMA devices detected; using TCP/NCCL fallback."
22
+ export NCCL_IB_DISABLE=1
23
+ fi
24
+
25
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME:-eth0}
26
+ export NCCL_DEBUG=WARN
27
+ unset NCCL_DEBUG_SUBSYS || true
28
+ export NCCL_BLOCKING_WAIT=1
29
+ export NCCL_ASYNC_ERROR_HANDLING=1
30
+ export NCCL_TIMEOUT=1000
31
+ export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
32
+
33
+ cd /mnt/workspace/users/maxiangkai/projects/WM4A
34
+ if [ -f /mnt/workspace/envs/conda3/bin/activate ]; then
35
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
36
+ fi
37
+
38
+ NUM_GPUS_PER_NODE=${1:-2} # mytest
39
+
40
+ Framework_name=QwenWanPerceiverACoT
41
+ base_vlm=/mnt/workspace/users/maxiangkai/models/Qwen3-VL-4B-Instruct
42
+ base_wm=/mnt/workspace/users/maxiangkai/models/Wan2.2-TI2V-5B-Diffusers
43
+ transformer_path=/mnt/workspace/users/maxiangkai/models/Motus_Wan2_2_5B_pretrain
44
+ pretrained_checkpoint=/mnt/workspace/users/chidafeng/main_results/joyra05/pretrain/0529_joyra05_data_0530_QwenWanPerceiver_15wsteps_bs16/final_model/pytorch_model.pt
45
+ config_yaml=/mnt/workspace/users/maxiangkai/projects/WM4A/examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
46
+ DIT_TYPE="DiT-B"
47
+ data_root_dir=/mnt/workspace/datasets/
48
+ data_mix=robocasa_teleop_ee
49
+
50
+ action_dim=32
51
+ state_dim=64
52
+ action_hidden_dim=1024
53
+ cross_attention_dim=2048
54
+
55
+ run_root_dir=/mnt/workspace/users/maxiangkai/projects/WM4A/outputs/joyra05acot
56
+ run_id=robocasa
57
+
58
+ export PYTHONPATH="${PYTHONPATH}:/mnt/workspace/users/maxiangkai/projects/WM4A"
59
+
60
+ output_dir=${run_root_dir}/${run_id}
61
+ mkdir -p "${output_dir}"
62
+ export WANDB_MODE=offline
63
+ export WANDB_DIR="${output_dir}/wandb"
64
+ mkdir -p "${WANDB_DIR}"
65
+ cp "$0" "${output_dir}/"
66
+ cp ${config_yaml} ${output_dir}
67
+
68
+ env IS_TORCHRUN=1 torchrun \
69
+ --nnodes=${PET_NNODES:-1} \
70
+ --node_rank=${PET_NODE_RANK:-0} \
71
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
72
+ --master_port=${PET_MASTER_PORT:-29500} \
73
+ --nproc_per_node=${NUM_GPUS_PER_NODE} \
74
+ starVLA/training/train_starvla.py \
75
+ --config_yaml ${config_yaml} \
76
+ --framework.name ${Framework_name} \
77
+ --framework.world_model.base_wm "${base_wm}" \
78
+ --framework.world_model.transformer_path ${transformer_path} \
79
+ --framework.world_model.extract_layers "[-1]" \
80
+ --framework.world_model.height 224 \
81
+ --framework.world_model.width 224 \
82
+ --framework.world_model.conditional_frame_timestep 0.1 \
83
+ --framework.qwenvl.base_vlm "${base_vlm}" \
84
+ --framework.qwenvl.vl_hidden_dim 2048 \
85
+ --framework.action_model.action_model_type ${DIT_TYPE} \
86
+ --framework.action_model.action_dim ${action_dim} \
87
+ --framework.action_model.state_dim ${state_dim} \
88
+ --framework.action_model.action_hidden_dim ${action_hidden_dim} \
89
+ --framework.action_model.hidden_size ${action_hidden_dim} \
90
+ --framework.action_model.diffusion_model_cfg.cross_attention_dim ${cross_attention_dim} \
91
+ --framework.action_model.diffusion_model_cfg.output_dim ${action_hidden_dim} \
92
+ --framework.action_model.num_target_vision_tokens 64 \
93
+ --framework.vjepa2_ac.repo_dir /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main \
94
+ --framework.vjepa2_ac.pretrained /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt \
95
+ --framework.future_latent_training.enabled true \
96
+ --framework.future_latent_training.loss_weight 0.02 \
97
+ --framework.future_latent_training.train_time_distribution logitnormal \
98
+ --framework.future_latent_training.shift 5.0 \
99
+ --framework.future_image_training.enabled true \
100
+ --framework.future_image_training.loss_weight 1.0 \
101
+ --framework.future_image_training.train_time_distribution logitnormal \
102
+ --framework.future_image_training.shift 5.0 \
103
+ --framework.future_image_generation.enabled true \
104
+ --framework.future_image_generation.conditioning_mode auto \
105
+ --framework.future_image_generation.max_samples 1 \
106
+ --framework.future_image_generation.height 224 \
107
+ --framework.future_image_generation.width 224 \
108
+ --framework.future_image_generation.num_frames 93 \
109
+ --framework.future_image_generation.num_inference_steps 20 \
110
+ --framework.future_image_generation.guidance_scale 7.0 \
111
+ --framework.future_image_generation.output_type pil \
112
+ --framework.future_image_generation.future_frame_index -1 \
113
+ --framework.future_image_generation.return_full_video false \
114
+ --datasets.vla_data.data_root_dir "${data_root_dir}" \
115
+ --datasets.vla_data.data_mix "${data_mix}" \
116
+ --datasets.vla_data.include_state true \
117
+ --datasets.vla_data.per_device_batch_size 4 \
118
+ --datasets.vla_data.num_workers 8 \
119
+ --datasets.vla_data.prefetch_factor 2 \
120
+ --datasets.vla_data.pin_memory true \
121
+ --datasets.vla_data.persistent_workers true \
122
+ --trainer.pretrained_checkpoint ${pretrained_checkpoint} \
123
+ --trainer.max_train_steps 300000 \
124
+ --trainer.save_interval 50000 \
125
+ --trainer.logging_frequency 10 \
126
+ --trainer.eval_interval 10 \
127
+ --trainer.num_warmup_steps 1000 \
128
+ --trainer.learning_rate.base 1e-5 \
129
+ --trainer.learning_rate.action_model 5e-5 \
130
+ --trainer.learning_rate.vjepa_predictor 5e-5 \
131
+ --trainer.learning_rate.state_projector 5e-5 \
132
+ --trainer.learning_rate.action_projector 5e-5 \
133
+ --trainer.scheduler_specific_kwargs.min_lr 2e-7 \
134
+ --trainer.optimizer.betas "[0.9,0.999]" \
135
+ --trainer.optimizer.weight_decay 0.1 \
136
+ --run_root_dir ${run_root_dir} \
137
+ --run_id ${run_id} \
138
+ --wandb_project joyRA_robocasa_mxk \
139
+ --wandb_entity mxk \
140
+ 2>&1 | tee -a "${output_dir}/train.log"
examples/Suqian_agibot/train_files/run_cotrain_uni.sh ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=8
54
+
55
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
56
+
57
+ Framework_name=QwenPerceiver
58
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
59
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
60
+ DIT_TYPE="DiT-B"
61
+ data_root_dir=/mnt/workspace/datasets/
62
+ data_mix="sq_agi-beta_egodex-f"
63
+
64
+
65
+ run_root_dir=./outputs
66
+ run_id=cotrain_sq_agi-beta_egodex-f
67
+
68
+ export WANDB_MODE=offline
69
+ export WANDB_DIR=../../
70
+
71
+ output_dir=${run_root_dir}/${run_id}
72
+ mkdir -p ${output_dir}
73
+ # mv this script to the output dir
74
+ cp $0 ${output_dir}/
75
+
76
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
77
+
78
+
79
+ env IS_TORCHRUN=1 torchrun \
80
+ --nnodes=${PET_NNODES:-1} \
81
+ --node_rank=${PET_NODE_RANK:-0} \
82
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
83
+ --master_port=${PET_MASTER_PORT:-26500} \
84
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
85
+ starVLA/training/train_starvla_cotrain.py \
86
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
87
+ --framework.name ${Framework_name} \
88
+ --framework.qwenvl.base_vlm ${base_vlm} \
89
+ --framework.action_model.action_model_type ${DIT_TYPE} \
90
+ --datasets.vlm_data.per_device_batch_size 2 \
91
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
92
+ --datasets.vla_data.data_mix ${data_mix} \
93
+ --datasets.vla_data.per_device_batch_size 32 \
94
+ --trainer.freeze_modules ${freeze_module_list} \
95
+ --trainer.max_train_steps 200000 \
96
+ --trainer.save_interval 50000 \
97
+ --trainer.logging_frequency 100 \
98
+ --trainer.eval_interval 100 \
99
+ --trainer.learning_rate.base 3e-5 \
100
+ --run_root_dir ${run_root_dir} \
101
+ --run_id ${run_id} \
102
+ --wandb_project starVLA_robocasa \
103
+ --wandb_entity curryyuan \
104
+ 2>&1 | tee -a "${output_dir}/train.log"
105
+ # --is_debug True
examples/Suqian_agibot/train_files/run_post_train.sh ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=8
54
+
55
+ cd /mnt/workspace/users/yuanzhihao/code/starVLA
56
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
57
+
58
+ Framework_name=QwenGR00T
59
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
60
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
61
+ DIT_TYPE="DiT-B"
62
+ data_root_dir=/mnt/workspace/datasets/suqian_agibot_lerobot_data/
63
+ data_mix=suqian_test
64
+
65
+
66
+ run_root_dir=./outputs
67
+ run_id=suqian_post_train_pre_10w
68
+
69
+ export WANDB_MODE=offline
70
+ export WANDB_DIR=/mnt/workspace/users/yuanzhihao/
71
+
72
+ output_dir=${run_root_dir}/${run_id}
73
+ mkdir -p ${output_dir}
74
+ # mv this script to the output dir
75
+ cp $0 ${output_dir}/
76
+
77
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
78
+
79
+
80
+ env IS_TORCHRUN=1 torchrun \
81
+ --nnodes=${PET_NNODES:-1} \
82
+ --node_rank=${PET_NODE_RANK:-0} \
83
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
84
+ --master_port=${PET_MASTER_PORT:-29500} \
85
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
86
+ starVLA/training/train_starvla.py \
87
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
88
+ --framework.name ${Framework_name} \
89
+ --framework.qwenvl.base_vlm ${base_vlm} \
90
+ --framework.action_model.action_model_type ${DIT_TYPE} \
91
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
92
+ --datasets.vla_data.data_mix ${data_mix} \
93
+ --datasets.vla_data.per_device_batch_size 8 \
94
+ --trainer.freeze_modules ${freeze_module_list} \
95
+ --trainer.max_train_steps 30000 \
96
+ --trainer.save_interval 10000 \
97
+ --trainer.logging_frequency 20 \
98
+ --trainer.eval_interval 100 \
99
+ --trainer.learning_rate.base 3e-5 \
100
+ --trainer.pretrained_checkpoint /mnt/workspace/users/chenzengjue/starVLA2/res/ego_suqian_pretrain_lr1e5_freeze_llm_bs256/final_model/pytorch_model.pt \
101
+ --run_root_dir ${run_root_dir} \
102
+ --run_id ${run_id} \
103
+ --wandb_project starVLA_robocasa \
104
+ --wandb_entity curryyuan \
105
+ 2>&1 | tee -a "${output_dir}/train.log"
106
+ # --is_debug True
107
+ #
108
+
109
+
110
+
111
+
examples/Suqian_agibot/train_files/run_pretrain.sh ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=1
54
+
55
+ cd /mnt/workspace/users/yuanzhihao/code/starVLA
56
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
57
+
58
+ Framework_name=QwenGR00T
59
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
60
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
61
+ DIT_TYPE="DiT-B"
62
+ data_root_dir=/mnt/workspace/datasets/
63
+ data_mix=suqian_egodex_train
64
+
65
+
66
+ run_root_dir=./outputs
67
+ run_id=suqian_egodex_pretrain
68
+
69
+ export WANDB_MODE=disabled
70
+ export WANDB_DIR=/mnt/workspace/users/yuanzhihao/
71
+
72
+ output_dir=${run_root_dir}/${run_id}
73
+ mkdir -p ${output_dir}
74
+ # mv this script to the output dir
75
+ cp $0 ${output_dir}/
76
+
77
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
78
+
79
+
80
+ env IS_TORCHRUN=1 torchrun \
81
+ --nnodes=${PET_NNODES:-1} \
82
+ --node_rank=${PET_NODE_RANK:-0} \
83
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
84
+ --master_port=${PET_MASTER_PORT:-29500} \
85
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
86
+ starVLA/training/train_starvla.py \
87
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
88
+ --framework.name ${Framework_name} \
89
+ --framework.qwenvl.base_vlm ${base_vlm} \
90
+ --framework.action_model.action_model_type ${DIT_TYPE} \
91
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
92
+ --datasets.vla_data.data_mix ${data_mix} \
93
+ --datasets.vla_data.per_device_batch_size 8 \
94
+ --trainer.freeze_modules ${freeze_module_list} \
95
+ --trainer.max_train_steps 100000 \
96
+ --trainer.save_interval 50000 \
97
+ --trainer.logging_frequency 100 \
98
+ --trainer.eval_interval 100 \
99
+ --trainer.learning_rate.base 3e-5 \
100
+ --run_root_dir ${run_root_dir} \
101
+ --run_id ${run_id} \
102
+ --wandb_project starVLA_robocasa \
103
+ --wandb_entity curryyuan \
104
+ 2>&1 | tee -a "${output_dir}/train.log"
105
+ # --is_debug True
106
+
107
+
examples/Suqian_agibot/train_files/run_pretrain_debug.sh ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=2
54
+
55
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
56
+
57
+ Framework_name=QwenPerceiver
58
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
59
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
60
+ DIT_TYPE="DiT-B"
61
+ data_root_dir=/mnt/workspace/datasets/
62
+ data_mix=sq_egodex-f_nvwa-f_robotwin_robocasa
63
+
64
+
65
+ run_root_dir=./outputs
66
+ run_id=pretrain_sq_egodex-f_nvwa-f_robotwin_robocasa
67
+
68
+ export WANDB_MODE=offline
69
+ export WANDB_DIR=../../
70
+
71
+ output_dir=${run_root_dir}/${run_id}
72
+ mkdir -p ${output_dir}
73
+ # mv this script to the output dir
74
+ cp $0 ${output_dir}/
75
+
76
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
77
+
78
+
79
+ env IS_TORCHRUN=1 torchrun \
80
+ --nnodes=${PET_NNODES:-1} \
81
+ --node_rank=${PET_NODE_RANK:-0} \
82
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
83
+ --master_port=${PET_MASTER_PORT:-26500} \
84
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
85
+ starVLA/training/train_starvla.py \
86
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
87
+ --framework.name ${Framework_name} \
88
+ --framework.qwenvl.base_vlm ${base_vlm} \
89
+ --framework.action_model.action_model_type ${DIT_TYPE} \
90
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
91
+ --datasets.vla_data.data_mix ${data_mix} \
92
+ --datasets.vla_data.per_device_batch_size 32 \
93
+ --trainer.freeze_modules ${freeze_module_list} \
94
+ --trainer.max_train_steps 300000 \
95
+ --trainer.save_interval 10000 \
96
+ --trainer.logging_frequency 100 \
97
+ --trainer.eval_interval 100 \
98
+ --trainer.learning_rate.base 3e-5 \
99
+ --run_root_dir ${run_root_dir} \
100
+ --run_id ${run_id} \
101
+ --wandb_project starVLA_robocasa \
102
+ --wandb_entity curryyuan \
103
+ 2>&1 | tee -a "${output_dir}/train.log"
104
+ # --is_debug True
examples/Suqian_agibot/train_files/run_pretrain_uni.sh ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=8
54
+
55
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
56
+
57
+ Framework_name=QwenPerceiver
58
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
59
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
60
+ DIT_TYPE="DiT-B"
61
+ data_root_dir=/mnt/workspace/datasets/
62
+ data_mix=sq_egodex-f_robotwin_robocasa
63
+
64
+
65
+ run_root_dir=./outputs
66
+ run_id=pretrain_sq_egodex-f_robotwin_robocasa
67
+
68
+ export WANDB_MODE=offline
69
+ export WANDB_DIR=../../
70
+
71
+ output_dir=${run_root_dir}/${run_id}
72
+ mkdir -p ${output_dir}
73
+ # mv this script to the output dir
74
+ cp $0 ${output_dir}/
75
+
76
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
77
+
78
+
79
+ env IS_TORCHRUN=1 torchrun \
80
+ --nnodes=${PET_NNODES:-1} \
81
+ --node_rank=${PET_NODE_RANK:-0} \
82
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
83
+ --master_port=${PET_MASTER_PORT:-26500} \
84
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
85
+ starVLA/training/train_starvla.py \
86
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
87
+ --framework.name ${Framework_name} \
88
+ --framework.qwenvl.base_vlm ${base_vlm} \
89
+ --framework.action_model.action_model_type ${DIT_TYPE} \
90
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
91
+ --datasets.vla_data.data_mix ${data_mix} \
92
+ --datasets.vla_data.per_device_batch_size 32 \
93
+ --trainer.freeze_modules ${freeze_module_list} \
94
+ --trainer.max_train_steps 300000 \
95
+ --trainer.save_interval 10000 \
96
+ --trainer.logging_frequency 100 \
97
+ --trainer.eval_interval 100 \
98
+ --trainer.learning_rate.base 3e-5 \
99
+ --run_root_dir ${run_root_dir} \
100
+ --run_id ${run_id} \
101
+ --wandb_project starVLA_robocasa \
102
+ --wandb_entity curryyuan \
103
+ 2>&1 | tee -a "${output_dir}/train.log"
104
+ # --is_debug True
examples/Suqian_agibot/train_files/run_pretrain_uni_nw.sh ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=8
54
+
55
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
56
+
57
+ Framework_name=QwenPerceiver
58
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
59
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
60
+ DIT_TYPE="DiT-B"
61
+ data_root_dir=/mnt/workspace/datasets/
62
+ data_mix=sq_egodex-f_nvwa-f_robotwin_robocasa
63
+
64
+
65
+ run_root_dir=./outputs
66
+ run_id=pretrain_sq_egodex-f_nvwa-f_robotwin_robocasa
67
+
68
+ export WANDB_MODE=offline
69
+ export WANDB_DIR=../../
70
+
71
+ output_dir=${run_root_dir}/${run_id}
72
+ mkdir -p ${output_dir}
73
+ # mv this script to the output dir
74
+ cp $0 ${output_dir}/
75
+
76
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
77
+
78
+
79
+ env IS_TORCHRUN=1 torchrun \
80
+ --nnodes=${PET_NNODES:-1} \
81
+ --node_rank=${PET_NODE_RANK:-0} \
82
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
83
+ --master_port=${PET_MASTER_PORT:-26500} \
84
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
85
+ starVLA/training/train_starvla.py \
86
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
87
+ --framework.name ${Framework_name} \
88
+ --framework.qwenvl.base_vlm ${base_vlm} \
89
+ --framework.action_model.action_model_type ${DIT_TYPE} \
90
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
91
+ --datasets.vla_data.data_mix ${data_mix} \
92
+ --datasets.vla_data.per_device_batch_size 32 \
93
+ --trainer.freeze_modules ${freeze_module_list} \
94
+ --trainer.max_train_steps 300000 \
95
+ --trainer.save_interval 50000 \
96
+ --trainer.logging_frequency 100 \
97
+ --trainer.eval_interval 100 \
98
+ --trainer.learning_rate.base 3e-5 \
99
+ --run_root_dir ${run_root_dir} \
100
+ --run_id ${run_id} \
101
+ --wandb_project starVLA_robocasa \
102
+ --wandb_entity curryyuan \
103
+ 2>&1 | tee -a "${output_dir}/train.log"
104
+ # --is_debug True
examples/Suqian_agibot/train_files/run_real.sh ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=8
54
+
55
+ cd /mnt/workspace/users/yuanzhihao/code/starVLA
56
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
57
+
58
+ Framework_name=QwenGR00T
59
+ base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct
60
+ freeze_module_list='' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
61
+ DIT_TYPE="DiT-B"
62
+ data_root_dir=/mnt/workspace/datasets/suqian_agibot_lerobot_data/
63
+ data_mix=suqian_train
64
+
65
+
66
+ run_root_dir=./outputs
67
+ run_id=suqian_pretrain_0107
68
+
69
+ export WANDB_MODE=offline
70
+ export WANDB_DIR=/mnt/workspace/users/yuanzhihao/
71
+
72
+ output_dir=${run_root_dir}/${run_id}
73
+ mkdir -p ${output_dir}
74
+ # mv this script to the output dir
75
+ cp $0 ${output_dir}/
76
+
77
+ LOGFILE=${output_dir}/train_$(date +%Y%m%d_%H%M%S).log
78
+
79
+
80
+ env IS_TORCHRUN=1 torchrun \
81
+ --nnodes=${PET_NNODES:-1} \
82
+ --node_rank=${PET_NODE_RANK:-0} \
83
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
84
+ --master_port=${PET_MASTER_PORT:-29500} \
85
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
86
+ starVLA/training/train_starvla.py \
87
+ --config_yaml examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml \
88
+ --framework.name ${Framework_name} \
89
+ --framework.qwenvl.base_vlm ${base_vlm} \
90
+ --framework.action_model.action_model_type ${DIT_TYPE} \
91
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
92
+ --datasets.vla_data.data_mix ${data_mix} \
93
+ --datasets.vla_data.per_device_batch_size 8 \
94
+ --trainer.freeze_modules ${freeze_module_list} \
95
+ --trainer.max_train_steps 300000 \
96
+ --trainer.save_interval 50000 \
97
+ --trainer.logging_frequency 100 \
98
+ --trainer.eval_interval 100 \
99
+ --trainer.learning_rate.base 3e-5 \
100
+ --run_root_dir ${run_root_dir} \
101
+ --run_id ${run_id} \
102
+ --wandb_project starVLA_robocasa \
103
+ --wandb_entity curryyuan \
104
+ 2>&1 | tee -a "${output_dir}/train.log"
105
+ # --is_debug True
106
+
107
+
examples/Suqian_agibot/train_files/starvla_cotrain_robocasa_gr1.yaml ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ run_id: qwenact
2
+ run_root_dir: results/Checkpoints
3
+ seed: 42
4
+ trackers: [jsonl, wandb]
5
+ wandb_entity: your_wandb_entity
6
+ wandb_project: starvla
7
+ is_debug: false
8
+
9
+ framework:
10
+ name: QwenGR00T
11
+ qwenvl:
12
+ base_vlm: ./playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
13
+ attn_implementation: flash_attention_2
14
+ vl_hidden_dim: 2048
15
+ dino:
16
+ dino_backbone: dinov2_vits14
17
+
18
+ action_model:
19
+ action_model_type: DiT-B
20
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
21
+ add_pos_embed: True
22
+ max_seq_len: 1024
23
+ action_dim: 32
24
+ state_dim: 64
25
+ future_action_window_size: 29
26
+ action_horizon: 30
27
+ past_action_window_size: 0
28
+ repeated_diffusion_steps: 8
29
+ noise_beta_alpha: 1.5
30
+ noise_beta_beta: 1.0
31
+ noise_s: 0.999
32
+ num_timestep_buckets: 1000
33
+ num_inference_timesteps: 4
34
+ num_target_vision_tokens: 32
35
+ diffusion_model_cfg: # DiT Transformers 的参数
36
+ cross_attention_dim: 2048 # VLM 的 dim
37
+ dropout: 0.2
38
+ final_dropout: true
39
+ interleave_self_attention: true
40
+ norm_type: "ada_norm"
41
+ num_layers: 16
42
+ output_dim: 2560
43
+ positional_embeddings: null
44
+
45
+
46
+
47
+ datasets:
48
+ vlm_data:
49
+ dataset_py: vlm_datasets
50
+ dataformat: llava_json
51
+ # dataset_use: cambrain_300k_vlapt,refspatial_2d_100k_vlapt,refspatial_3d_150k_vlapt,refspatial_3d_visual_50k_vlapt,robovqa_300k_vlapt,gal_subtask_110k
52
+ dataset_use: agibot_subtask,sq_subtask,cambrain_300k_vlapt,refspatial_2d_100k_vlapt,refspatial_3d_150k_vlapt,refspatial_3d_visual_50k_vlapt # gal_subtask_110k
53
+ eval_dataset: sq_subtask
54
+ data_flatten: false
55
+ base_interval: 2
56
+ max_pixels: 50176
57
+ min_pixels: 784
58
+ model_max_length: 4096
59
+ model_type: qwen2.5vl
60
+ per_device_batch_size: 4
61
+
62
+ vla_data:
63
+ dataset_py: lerobot_datasets
64
+ data_root_dir: /mnt/workspace/datasets/suqian_agibot_lerobot_data/
65
+ data_mix: suqian_test # bridge_rt_1
66
+ action_type: delta_ee
67
+ CoT_prompt: "{instruction}"
68
+ CoT_answer: bbox
69
+ default_image_resolution: [3, 224, 224]
70
+ per_device_batch_size: 16
71
+ load_all_data_for_training: true
72
+ obs: ["image_0"]
73
+ image_size: [224,224]
74
+ delete_pause_frame: false
75
+ include_state: false
76
+ video_backend: torchvision_av
77
+
78
+ trainer:
79
+ epochs: 100
80
+ max_train_steps: 100000
81
+ num_warmup_steps: 5000
82
+ save_interval: 5000
83
+ eval_interval: 100
84
+ learning_rate:
85
+ base: 1e-05
86
+ qwen_vl_interface: 1.0e-05
87
+ action_model: 1.0e-04
88
+ lr_scheduler_type: cosine_with_min_lr
89
+ scheduler_specific_kwargs:
90
+ min_lr: 5.0e-07
91
+ freeze_modules: ''
92
+ loss_scale:
93
+ vla: 1.0
94
+ vlm: 0.05
95
+ # pretrained_checkpoint: outputs/StarVLA_Qwen3_VL_GR00T_Robocasa_gr1/checkpoints/steps_90000_pytorch_model.pt
96
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
97
+ repeated_diffusion_steps: 4
98
+ max_grad_norm: 1.0
99
+ warmup_ratio: 0.1
100
+ weight_decay: 0.0
101
+ logging_frequency: 10
102
+ gradient_clipping: 1.0
103
+ gradient_accumulation_steps: 1
104
+
105
+ optimizer:
106
+ name: AdamW
107
+ betas: [0.9, 0.95]
108
+ eps: 1.0e-08
109
+ weight_decay: 1.0e-08
110
+
111
+ # parameters to be determined
112
+ is_resume: false
113
+ resume_epoch: null
114
+ resume_step: null
115
+ enable_gradient_checkpointing: true
116
+ enable_mixed_precision_training: true
examples/Suqian_agibot/train_files/submit_robocasa_training.sh ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --job-name=test_RoCaPI # name
3
+ #SBATCH -p si
4
+ #SBATCH -N 4 # nodes
5
+ #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
6
+ #SBATCH --cpus-per-task=128 # number of cores per tasks
7
+ #SBATCH --gres=gpu:8 # number of gpus
8
+ #SBATCH --output=/mnt/petrelfs/yejinhui/Projects/starVLA/results/logs/%x-%j.out # output file name
9
+ #SBATCH --error=/mnt/petrelfs/yejinhui/Projects/starVLA/results/logs/%x-%j.err
10
+ #SBATCH --exclude=SH-IDCA1404-10-140-54-13
11
+
12
+ # 6955707 si RoCaPI reserved yejinhui normal R 9:14 4 gpu:32 SH-IDCA1404-10-140-54-[13,88-89,107]
13
+
14
+ # source ~/.bashrc # 确保 conda 命令可用
15
+ # source ~/.zshrc
16
+ # source ~/envs4jinhui.sh
17
+ # proxy_on
18
+
19
+ # conda activate llavavla310 # 替换为你的环境名
20
+
21
+ # export task_id=31_32_33
22
+
23
+ export NCCL_TIMEOUT=10000 # timeout set to 1 hour (unit: seconds)
24
+ export NCCL_SOCKET_TIMEOUT_MS=360000
25
+
26
+
27
+ export NCCL_SOCKET_IFNAME=bond0
28
+ # export NCCL_IB_HCA=mlx5_2,mlx5_3,mlx5_4,mlx5_5
29
+ export NCCL_IB_HCA=mlx5_2,mlx5_3
30
+
31
+ export GPUS_PER_NODE=8
32
+ export MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
33
+ export MASTER_PORT=$((RANDOM % 101 + 20000))
34
+
35
+
36
+ cd /mnt/petrelfs/yejinhui/Projects/starVLA
37
+ export PYTHONPATH="$PWD/starVLA/model/openvla:$PYTHONPATH"
38
+
39
+ # conda activate llavavla310
40
+ proxy_on
41
+
42
+ # <model_id/local_path_to_model,e.g,"CogACT/CogACT-Base">
43
+
44
+ # === Please modify the following paths according to your environment ===
45
+ ###########################################################################################
46
+
47
+ export Framework_name=QwenPI_v2
48
+ export base_vlm=./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct # must be a local path, due to simpler will run in other where
49
+ export base_vlm=./playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action
50
+ export freeze_module_list=""
51
+ export action_input_dim=2560
52
+ export DIT_TYPE="DiT-B"
53
+ export config_yaml=./examples/Robocasa_tabletop/train_files/starvla_cotrain_robocasa_gr1.yaml
54
+ export data_mix=fourier_gr1_unified_1000
55
+ export include_state=True
56
+ export run_root_dir=./results/Checkpoints
57
+ export run_id=debug_1224_${data_mix}_${Framework_name}_nostate_qwen3
58
+ # === End of environment variable configuration ===
59
+ ###########################################################################################
60
+
61
+
62
+ unset DEBUG
63
+
64
+ export TOTAL_GPUS=$((GPUS_PER_NODE * SLURM_NNODES))
65
+ export global_batch_size=$((TOTAL_GPUS * vla_per_device_batch_size)) # 512 is the default global batch size, you can change it if needed
66
+ echo "Total GPUs: $TOTAL_GPUS"
67
+
68
+
69
+ # export WANDB_MODE=disabled
70
+
71
+ export output_dir=${run_root_dir}/${run_id}
72
+ mkdir -p ${output_dir}
73
+ # mv this script to the output dir
74
+ cp $0 ${output_dir}/
75
+
76
+ # --datasets.vla_data.include_state ${include_state} \
77
+
78
+ srun --jobid $SLURM_JOBID bash -c 'accelerate launch \
79
+ --config_file starVLA/config/deepseeds/deepspeed_zero2.yaml \
80
+ --main_process_ip $MASTER_ADDR \
81
+ --main_process_port $MASTER_PORT \
82
+ --machine_rank $SLURM_PROCID \
83
+ --num_machines $SLURM_NNODES \
84
+ --num_processes=${TOTAL_GPUS} \
85
+ starVLA/training/train_starvla.py \
86
+ --config_yaml ${config_yaml} \
87
+ --framework.name ${Framework_name} \
88
+ --framework.action_model.action_model_type ${DIT_TYPE} \
89
+ --framework.qwenvl.base_vlm ${base_vlm} \
90
+ --datasets.vla_data.per_device_batch_size 8 \
91
+ --trainer.freeze_modules ${freeze_module_list} \
92
+ --datasets.vla_data.data_mix ${data_mix} \
93
+ --trainer.max_train_steps 200000 \
94
+ --trainer.save_interval 10000 \
95
+ --trainer.eval_interval 100 \
96
+ --trainer.num_warmup_steps 5000 \
97
+ --trainer.logging_frequency 50 \
98
+ --trainer.learning_rate.base 3e-5 \
99
+ --run_root_dir ${run_root_dir} \
100
+ --run_id ${run_id} \
101
+ --wandb_project StarVLA_Robocasa \
102
+ --wandb_entity jinhuiye \
103
+ --trainer.is_resume True '
104
+
examples/ego_sq/train_files/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 基本使用方法:
2
+ 1.在starvla_cotrain_ego_sq.yaml中设置必要的训练参数,如action_dim、future_action_window_size、action_horizon,分布决定训练时模型的动作维度,和模型预测未来的action chunk长度。
3
+ 2.在run_ego_sq.sh中设置必要的训练参数,如wandb相关,run_root_dir,base_vlm路径,freeze_module_list需要冻结的部分,data_root_dir数据集路径,data_mix数据混训模式。
4
+ 3.bash run_ego_sq.sh启动训练
5
+
6
+
7
+ 注意事项:
8
+ 1.若修改action horizon长度,要starvla_cotrain_ego_sq.yaml中future_action_window_size、action_horizon一起修改,还有starVLA/dataloader/gr00t_lerobot/data_config.py中的目标数据集下的action_indices。
9
+ 2.data_mix可以查看starVLA/dataloader/gr00t_lerobot/mixtures.py中的分类,freeze_module_list可冻结的部分可以为qwen_vl_interface,action_model.model,action_model.state_encoder,action_model.future_tokens,action_model.position_embedding
10
+ 3.batch size=bash文件中的NUM_GPUS_PER_NODE*per_device_batch_size*训练卡数
11
+ 4.目前版本loss中不加入action mask,若想使用action mask,需要手动在starVLA/model/modules/action_model/GR00T_ActionHeader.py中318-338行的代码注释去掉
examples/ego_sq/train_files/run_ego_sq.sh ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RDMA_DEVICES=$(ls /sys/class/infiniband)
2
+ if [ -z "$RDMA_DEVICES" ]; then
3
+ log "ERROR: No active RDMA devices found. Exiting script." >&2
4
+ exit 1
5
+ fi
6
+
7
+ # 设置RDMA设备列表 (逗号分隔)
8
+ NCCL_IB_HCA=$(echo "$RDMA_DEVICES" | tr '\n' ',' | sed 's/,$//')
9
+ export NCCL_IB_HCA
10
+ echo "Detected RDMA devices: $NCCL_IB_HCA"
11
+
12
+ # 获取GID_INDEX
13
+ NCCL_IB_GID_INDEX=""
14
+ output=$(show_gids | grep v2)
15
+ # 遍历每一行
16
+ while IFS= read -r line; do
17
+ ipv4=$(echo "$line" | awk '{print $5}')
18
+ # 检查IPv4地址是否有值(不是空字符串且不是全0地址)
19
+ if [[ -n "$ipv4" && "$ipv4" != "0000:0000:0000:0000:0000:ffff:0000:0000" && "$ipv4" =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]]; then
20
+ NCCL_IB_GID_INDEX=$(echo "$line" | awk '{print $3}')
21
+ # 找到第一个匹配项后立即退出循环
22
+ break
23
+ fi
24
+ done <<<"$output"
25
+
26
+ export NCCL_SOCKET_IFNAME="eth0"
27
+
28
+ # 处理分布式训练需要使用到的相关环境变量
29
+ export NCCL_IB_HCA=${NCCL_IB_HCA}
30
+ export NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX}
31
+ export NCCL_NET_GDR_LEVEL=2
32
+ # export NCCL_DEBUG_SUBSYS=ALL
33
+ # 加速
34
+ export NCCL_DEBUG=WARN
35
+ unset NCCL_DEBUG_SUBSYS
36
+ export NCCL_IB_DISABLE=0
37
+ export NCCL_SOCKET_IFNAME=${NCCL_SOCKET_IFNAME}
38
+
39
+ # used for check save when communication
40
+ export NCCL_BLOCKING_WAIT=1
41
+ export NCCL_ASYNC_ERROR_HANDLING=1
42
+ export NCCL_TIMEOUT=1000 # timeout set to 1 hour (unit: seconds)
43
+
44
+ # ==== 多节点配置 ====
45
+ # 总节点数(根据实际情况修改)
46
+ NUM_NODES=${PET_NNODES}
47
+ # 当前节点索引(0-based,每个节点启动时需指定不同值)
48
+ NODE_RANK=${PET_NODE_RANK}
49
+ # 主节点IP地址(确保所有节点可访问)
50
+ MASTER_ADDR=${PET_MASTER_ADDR} # 替换为实际主节点IP
51
+ # 主节点端口(保持与代码中一致)
52
+ MASTER_PORT=${PET_MASTER_PORT}
53
+ NUM_GPUS_PER_NODE=8
54
+
55
+ cd /mnt/workspace/users/chenzengjue/starVLA2
56
+ source /mnt/workspace/envs/conda3/bin/activate starVLA_1
57
+
58
+ Framework_name=QwenGR00T
59
+ base_vlm=/mnt/workspace/users/yuanzhihao/code/starVLA/playground/Pretrained_models/Qwen3-VL-4B-Instruct
60
+ freeze_module_list='qwen_vl_interface.model.model' # just for fast debug, sota is under fully FT, i.g., freeze_module_list=""
61
+ DIT_TYPE="DiT-B"
62
+ data_root_dir=/mnt/workspace
63
+ data_mix=ego_dex_suqian_agi
64
+
65
+
66
+ run_root_dir=./res
67
+ run_id=test
68
+
69
+ export WANDB_MODE=offline
70
+ export WANDB_DIR= #YOUR_WANDB
71
+
72
+ output_dir=${run_root_dir}/${run_id}
73
+ mkdir -p ${output_dir}
74
+ # mv this script to the output dir
75
+ cp $0 ${output_dir}/
76
+
77
+ env IS_TORCHRUN=1 torchrun \
78
+ --nnodes=${PET_NNODES:-1} \
79
+ --node_rank=${PET_NODE_RANK:-0} \
80
+ --master_addr=${PET_MASTER_ADDR:-127.0.0.1} \
81
+ --master_port=${PET_MASTER_PORT:-29500} \
82
+ --nproc_per_node=${NUM_GPUS_PER_NODE:-8} \
83
+ starVLA/training/train_starvla.py \
84
+ --config_yaml ./examples/ego_sq/train_files/starvla_cotrain_ego_sq.yaml \
85
+ --framework.name ${Framework_name} \
86
+ --framework.qwenvl.base_vlm ${base_vlm} \
87
+ --framework.action_model.action_model_type ${DIT_TYPE} \
88
+ --datasets.vla_data.data_root_dir ${data_root_dir} \
89
+ --datasets.vla_data.data_mix ${data_mix} \
90
+ --datasets.vla_data.per_device_batch_size 8 \
91
+ --trainer.freeze_modules ${freeze_module_list} \
92
+ --trainer.max_train_steps 100000 \
93
+ --trainer.save_interval 10000 \
94
+ --trainer.logging_frequency 50 \
95
+ --trainer.eval_interval 100 \
96
+ --trainer.learning_rate.base 1e-5 \
97
+ --run_root_dir ${run_root_dir} \
98
+ --run_id ${run_id} \
99
+ --wandb_project #YOUR_WANBD \
100
+ --wandb_entity #YOUR_WANBD\
101
+ 2>&1 | tee -a "${output_dir}/train.log"
102
+ # --is_debug True
103
+
104
+
examples/ego_sq/train_files/starvla_cotrain_ego_sq.yaml ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ run_id: qwenact
2
+ run_root_dir: results/Checkpoints
3
+ seed: 42
4
+ trackers: [jsonl, wandb]
5
+ wandb_entity: your_wandb_entity
6
+ wandb_project: starvla
7
+ is_debug: false
8
+
9
+ framework:
10
+ name: QwenGR00T
11
+ qwenvl:
12
+ base_vlm: ./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct
13
+ attn_implementation: flash_attention_2
14
+ vl_hidden_dim: 2048
15
+ dino:
16
+ dino_backbone: dinov2_vits14
17
+
18
+ action_model:
19
+ action_model_type: DiT-B
20
+ hidden_size: 2560 # 和 DiT 最后的 projection 对应,用于 ActionDecoder
21
+ add_pos_embed: True
22
+ max_seq_len: 1024
23
+ action_dim: 32
24
+ state_dim: 58
25
+ future_action_window_size: 15
26
+ action_horizon: 16
27
+ past_action_window_size: 0
28
+ repeated_diffusion_steps: 8
29
+ noise_beta_alpha: 1.5
30
+ noise_beta_beta: 1.0
31
+ noise_s: 0.999
32
+ num_timestep_buckets: 1000
33
+ num_inference_timesteps: 4
34
+ num_target_vision_tokens: 32
35
+ diffusion_model_cfg: # DiT Transformers 的参数
36
+ cross_attention_dim: 2048 # VLM 的 dim
37
+ dropout: 0.2
38
+ final_dropout: true
39
+ interleave_self_attention: true
40
+ norm_type: "ada_norm"
41
+ num_layers: 16
42
+ output_dim: 2560
43
+ positional_embeddings: null
44
+
45
+
46
+
47
+ datasets:
48
+ vlm_data:
49
+ dataset_py: vlm_datasets
50
+ dataformat: llava_json
51
+ dataset_use: asv2_conversation_en,asv2_detailed_description_en,asv2_region_captioning_en,coco_internvl_longcap_en,coco_karpathy_train_567_en,coco_negative_gpt4o_en,coco_poetry_zh,coco_rem_en_zh,cocorem_exist_yorn_en,cocotextv2_en,cocotextv2_gpt4o_en,okvqa_en,refcoco_grounding_aug_en,refcoco_grounding_en,tallyqa_coco_en,toloka_grounding_aug_en,vqav2_en,vsr_en
52
+ eval_dataset: aokvqa_cauldron_llava_format
53
+ data_flatten: false
54
+ base_interval: 2
55
+ max_pixels: 50176
56
+ min_pixels: 784
57
+ model_max_length: 2048
58
+ model_type: qwen2.5vl
59
+ per_device_batch_size: 4
60
+
61
+ vla_data:
62
+ dataset_py: lerobot_datasets
63
+ data_root_dir: playground/Datasets/PhysicalAI-Robotics-GR00T-X-Embodiment-Sim
64
+ data_mix: fourier_gr1_unified_1000 # bridge_rt_1
65
+ action_type: delta_ee
66
+ CoT_prompt: "Your task is {instruction}. To identify the key objects for your task. Locate their bounding boxes in [x1,y1,x2,y2] format."
67
+ CoT_answer: bbox
68
+ default_image_resolution: [3, 224, 224]
69
+ per_device_batch_size: 16
70
+ load_all_data_for_training: true
71
+ obs: ["image_0"]
72
+ image_size: [224,224]
73
+ delete_pause_frame: false
74
+
75
+ trainer:
76
+ epochs: 100
77
+ max_train_steps: 100000
78
+ num_warmup_steps: 5000
79
+ save_interval: 5000
80
+ eval_interval: 100
81
+ learning_rate:
82
+ base: 1e-05
83
+ qwen_vl_interface: 1.0e-05
84
+ action_model: 1.0e-04
85
+ lr_scheduler_type: cosine_with_min_lr
86
+ scheduler_specific_kwargs:
87
+ min_lr: 5.0e-07
88
+ freeze_modules: ''
89
+ loss_scale:
90
+ vla: 1.0
91
+ vlm: 0.1
92
+ # pretrained_checkpoint: ./results/Checkpoints/1_need/0601_qwenact_fixqwen_32gpus_lr_1e-3_qformer_36_37/steps_100000/pytorch_model.pt
93
+ # reload_modules: 'action_model,layer_qformer' # warning: this may cause model to not converge
94
+ repeated_diffusion_steps: 4
95
+ max_grad_norm: 1.0
96
+ warmup_ratio: 0.1
97
+ weight_decay: 0.0
98
+ logging_frequency: 10
99
+ gradient_clipping: 1.0
100
+ gradient_accumulation_steps: 1
101
+
102
+ optimizer:
103
+ name: AdamW
104
+ betas: [0.9, 0.95]
105
+ eps: 1.0e-08
106
+ weight_decay: 1.0e-08
107
+
108
+ # parameters to be determined
109
+ is_resume: false
110
+ resume_epoch: null
111
+ resume_step: null
112
+ enable_gradient_checkpointing: true
113
+ enable_mixed_precision_training: true
examples/eval_protocol.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # StarVLA Evaluation Framework Usage Guide
2
+
3
+ ## 1. Overview
4
+ StarVLA standardizes the inference pipeline for real-robot or simulation evaluations by tunneling data through WebSocket, enabling new models to be integrated into existing evaluation environments with minimal changes.
5
+
6
+
7
+
8
+ ## 2. Architecture Diagram
9
+
10
+
11
+ The StarVLA framework uses a client-server architecture to separate the Evaluation Environment (Client) from the Policy Server (Model).
12
+
13
+ ![](../assets/starVLA_PolicyServer.png)
14
+
15
+
16
+
17
+ <details close>
18
+ <summary><b>Component Description </b></summary>
19
+
20
+ | Component | Color Code | Description |
21
+ |-----------------------|------------|-----------------------------------------------------------------------------|
22
+ | Sim / Real Controller | Grey | External to StarVLA: Contains the core loop of the evaluation environment or robot controller, handling observation collection (`get_obs()`) and action execution (`apply_action()`). |
23
+ | PolicyClient.py & WebSocket & PolicyServer | Blue | Standard Communication Flow: Client-side wrapper responsible for data transmission (tunneling) and interfacing the environment with the server. |
24
+ | Framework.py | Orange | Model Infer Core: Contains the user-defined model inference function (`Framework.predict_action`), which is the main logic for generating actions. |
25
+
26
+ </details>
27
+
28
+
29
+ ## 3. Data Protocol (Example dictionary contract)
30
+
31
+ Minimal pseudo-code example (evaluation-side client):
32
+
33
+ ```python
34
+ import WebsocketClientPolicy
35
+
36
+ client = WebsocketClientPolicy(
37
+ host="127.0.0.1",
38
+ port=10092
39
+ )
40
+
41
+ while True:
42
+ images = capture_multiview() # returns List[np.ndarray]
43
+ lang = get_instruction() # may come from task scripts
44
+ example = {
45
+ "image": images,
46
+ "lang": lang,
47
+ }
48
+
49
+ result = client.predict_action(example) # --> forwarded to framework.predict_action
50
+ action = result["normalized_actions"][0] # take the first item in the batch
51
+ apply_action(action)
52
+ ```
53
+
54
+ ### Notes
55
+ - Ensure every field in `example` is JSON-serializable or convertible (lists, floats, ints, strings); convert custom objects explicitly.
56
+ - Images must be sent as `np.ndarray`. Perform `PIL.Image -> np.ndarray` before transmission and convert back on the server (`to_pil_preserve`) if required.
57
+ - Keep auxiliary metadata (episode IDs, timestamps, etc.) in dedicated keys so the framework can forward or log them without collisions.
58
+
59
+
60
+ ### PolicyClient Interface Design
61
+
62
+ ![](../assets/starVLA_PolicyInterface.png)
63
+
64
+
65
+ The [`*2model_interface.py`](./LIBERO/eval_files/model2libero_client.py) interface is designed to wrap and abstract any variations originating from the simulation or real-world environment. It also supports user-defined controllers, such as converting delta actions to absolute joint positions.
66
+
67
+ ## 7. FAQ
68
+
69
+ Q: Why do examples contain files such as `model2{bench}_client.py`?
70
+ A: They encapsulate benchmark-specific alignment, e.g., action ensembling, converting delta actions to absolute actions, or bridging simulator quirks, so the model server can stay generic.
71
+
72
+ Q: Why does the model expect PIL images while the transport uses `ndarray`?
73
+ A: WebSocket payloads do not serialize PIL objects directly. Convert to `np.ndarray` on the client side and restore to PIL inside the framework if the model requires it.
74
+
75
+ Feedback on environment-specific needs is welcome via issues.
model_metadata/cosmos/model_index.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "Cosmos2_5_PredictBasePipeline",
3
+ "_diffusers_version": "0.37.0.dev0",
4
+ "safety_checker": [
5
+ null,
6
+ null
7
+ ],
8
+ "scheduler": [
9
+ "diffusers",
10
+ "UniPCMultistepScheduler"
11
+ ],
12
+ "text_encoder": [
13
+ "transformers",
14
+ "Qwen2_5_VLForConditionalGeneration"
15
+ ],
16
+ "tokenizer": [
17
+ "transformers",
18
+ "Qwen2TokenizerFast"
19
+ ],
20
+ "transformer": [
21
+ "diffusers",
22
+ "CosmosTransformer3DModel"
23
+ ],
24
+ "vae": [
25
+ "diffusers",
26
+ "AutoencoderKLWan"
27
+ ]
28
+ }
model_metadata/cosmos/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UniPCMultistepScheduler",
3
+ "_diffusers_version": "0.37.0.dev0",
4
+ "beta_end": 0.02,
5
+ "beta_schedule": "linear",
6
+ "beta_start": 0.0001,
7
+ "disable_corrector": [],
8
+ "dynamic_thresholding_ratio": 0.995,
9
+ "final_sigmas_type": "zero",
10
+ "flow_shift": 1.0,
11
+ "lower_order_final": true,
12
+ "num_train_timesteps": 1000,
13
+ "predict_x0": true,
14
+ "prediction_type": "flow_prediction",
15
+ "rescale_betas_zero_snr": false,
16
+ "sample_max_value": 1.0,
17
+ "sigma_max": 200.0,
18
+ "sigma_min": 0.01,
19
+ "solver_order": 2,
20
+ "solver_p": null,
21
+ "solver_type": "bh2",
22
+ "steps_offset": 0,
23
+ "thresholding": false,
24
+ "time_shift_type": "exponential",
25
+ "timestep_spacing": "linspace",
26
+ "trained_betas": null,
27
+ "use_beta_sigmas": false,
28
+ "use_dynamic_shifting": false,
29
+ "use_exponential_sigmas": false,
30
+ "use_flow_sigmas": true,
31
+ "use_karras_sigmas": true
32
+ }
model_metadata/cosmos/text_encoder/config.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2_5_VLForConditionalGeneration"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "dtype": "bfloat16",
8
+ "eos_token_id": 151645,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 3584,
11
+ "image_token_id": 151655,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 18944,
14
+ "max_position_embeddings": 128000,
15
+ "max_window_layers": 28,
16
+ "model_type": "qwen2_5_vl",
17
+ "num_attention_heads": 28,
18
+ "num_hidden_layers": 28,
19
+ "num_key_value_heads": 4,
20
+ "rms_norm_eps": 1e-06,
21
+ "rope_scaling": {
22
+ "mrope_section": [
23
+ 16,
24
+ 24,
25
+ 24
26
+ ],
27
+ "rope_type": "default",
28
+ "type": "default"
29
+ },
30
+ "rope_theta": 1000000.0,
31
+ "sliding_window": 32768,
32
+ "text_config": {
33
+ "_name_or_path": "nvidia/Cosmos-Reason1-7B",
34
+ "architectures": [
35
+ "Qwen2_5_VLForConditionalGeneration"
36
+ ],
37
+ "attention_dropout": 0.0,
38
+ "bos_token_id": 151643,
39
+ "dtype": "bfloat16",
40
+ "eos_token_id": 151645,
41
+ "hidden_act": "silu",
42
+ "hidden_size": 3584,
43
+ "initializer_range": 0.02,
44
+ "intermediate_size": 18944,
45
+ "layer_types": [
46
+ "full_attention",
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention",
52
+ "full_attention",
53
+ "full_attention",
54
+ "full_attention",
55
+ "full_attention",
56
+ "full_attention",
57
+ "full_attention",
58
+ "full_attention",
59
+ "full_attention",
60
+ "full_attention",
61
+ "full_attention",
62
+ "full_attention",
63
+ "full_attention",
64
+ "full_attention",
65
+ "full_attention",
66
+ "full_attention",
67
+ "full_attention",
68
+ "full_attention",
69
+ "full_attention",
70
+ "full_attention",
71
+ "full_attention",
72
+ "full_attention",
73
+ "full_attention"
74
+ ],
75
+ "max_position_embeddings": 128000,
76
+ "max_window_layers": 28,
77
+ "model_type": "qwen2_5_vl_text",
78
+ "num_attention_heads": 28,
79
+ "num_hidden_layers": 28,
80
+ "num_key_value_heads": 4,
81
+ "rms_norm_eps": 1e-06,
82
+ "rope_scaling": {
83
+ "mrope_section": [
84
+ 16,
85
+ 24,
86
+ 24
87
+ ],
88
+ "rope_type": "default",
89
+ "type": "default"
90
+ },
91
+ "rope_theta": 1000000.0,
92
+ "sliding_window": null,
93
+ "use_cache": true,
94
+ "use_sliding_window": false,
95
+ "vision_token_id": 151654,
96
+ "vocab_size": 152064
97
+ },
98
+ "tie_word_embeddings": false,
99
+ "transformers_version": "4.57.1",
100
+ "use_cache": true,
101
+ "use_sliding_window": false,
102
+ "video_token_id": 151656,
103
+ "vision_config": {
104
+ "depth": 32,
105
+ "fullatt_block_indexes": [
106
+ 7,
107
+ 15,
108
+ 23,
109
+ 31
110
+ ],
111
+ "hidden_act": "silu",
112
+ "hidden_size": 1280,
113
+ "in_channels": 3,
114
+ "in_chans": 3,
115
+ "initializer_range": 0.02,
116
+ "intermediate_size": 3420,
117
+ "model_type": "qwen2_5_vl",
118
+ "num_heads": 16,
119
+ "out_hidden_size": 3584,
120
+ "patch_size": 14,
121
+ "spatial_merge_size": 2,
122
+ "spatial_patch_size": 14,
123
+ "temporal_patch_size": 2,
124
+ "tokens_per_second": 2,
125
+ "window_size": 112
126
+ },
127
+ "vision_end_token_id": 151653,
128
+ "vision_start_token_id": 151652,
129
+ "vision_token_id": 151654,
130
+ "vocab_size": 152064
131
+ }
model_metadata/cosmos/text_encoder/generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 1e-06,
11
+ "transformers_version": "4.57.1"
12
+ }
model_metadata/cosmos/tokenizer/added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
model_metadata/cosmos/tokenizer/chat_template.jinja ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system
2
+ You are a helpful assistant.<|im_end|>
3
+ {% endif %}<|im_start|>{{ message['role'] }}
4
+ {% if message['content'] is string %}{{ message['content'] }}<|im_end|>
5
+ {% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|vision_start|><|image_pad|><|vision_end|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|vision_start|><|video_pad|><|vision_end|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>
6
+ {% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant
7
+ {% endif %}
model_metadata/cosmos/tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model_metadata/cosmos/tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }