Joshua69 commited on
Commit
cd8bcdc
·
verified ·
1 Parent(s): d4e2525

Add insert_tube weighted policy retrain setup 20260729

Browse files
Files changed (12) hide show
  1. experiments/h100/real150_insert_tube_weighted_policy_20260729/README.md +20 -0
  2. experiments/h100/real150_insert_tube_weighted_policy_20260729/code/act_policy.py +339 -0
  3. experiments/h100/real150_insert_tube_weighted_policy_20260729/code/imitate_episodes.py +514 -0
  4. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl10_lr3e-5_s12000_gw8_late3.yml +53 -0
  5. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl2p5_lr3e-5_s12000_gw8_late3.yml +53 -0
  6. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr2e-5_s12000_gw8_late3.yml +53 -0
  7. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr3e-5_s12000_gw8_late3.yml +53 -0
  8. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr3e-5_s16000_gw8_late3.yml +53 -0
  9. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr3e-5_s8000_gw8_late3.yml +53 -0
  10. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr5e-5_s12000_gw8_late3.yml +53 -0
  11. experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl7p5_lr3e-5_s12000_gw8_late3.yml +53 -0
  12. experiments/h100/real150_insert_tube_weighted_policy_20260729/scripts/run_insert_tube_weighted_policy_8gpu_20260729.sh +27 -0
experiments/h100/real150_insert_tube_weighted_policy_20260729/README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # real150_insert_tube_weighted_policy_20260729
2
+
3
+ Insert-tube focused ViTacDreamer+ACT policy retraining setup.
4
+
5
+ Changes:
6
+ - adds optional weighted gripper action loss (`gripper_loss_weight`, dim=7 when state_dim=8)
7
+ - adds optional late/chunk action weighting (`late_action_loss_weight`, `late_action_loss_start_ratio`)
8
+ - saves intermediate policy checkpoints when `save_step_ckpts: true`
9
+
10
+ Configs:
11
+ - 8 variants: kl={2.5,5,7.5,10}, lr={2e-5,3e-5,5e-5}, steps={8000,12000,16000} around the selected insert_tube grid.
12
+ - All use history_len=5, sample_stride=5, state_dim=8, gripper_loss_weight=8, late_action_loss_weight=3, late start ratio=0.65.
13
+
14
+ Original H100 local dependency paths before cleanup:
15
+ - code root: /dev/shm/muse/src/ViTacDreamer_policy
16
+ - ACT data: /dev/shm/muse/src/ViTacDreamer_policy/UniVTAC/policy/ACT/data/sim-insert_tube
17
+ - real raw data: /dev/shm/muse/data/real_data_encoder_muse150_20260723/insert_tube
18
+ - encoder: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
19
+
20
+ Note: The H100 run was intentionally stopped after only a few minutes; no usable new policy checkpoint is included here.
experiments/h100/real150_insert_tube_weighted_policy_20260729/code/act_policy.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import os
3
+ import torch
4
+ import numpy as np
5
+ import pickle
6
+ from torch.nn import functional as F
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ sys.path.append(str(Path(__file__).resolve().parents[3]))
11
+ from vitacdreamer.policy_wrapper import ViTacDreamerFeatureExtractor
12
+
13
+ try:
14
+ from detr.main import (
15
+ build_ACT_model_and_optimizer,
16
+ build_CNNMLP_model_and_optimizer,
17
+ )
18
+ except:
19
+ from .detr.main import (
20
+ build_ACT_model_and_optimizer,
21
+ build_CNNMLP_model_and_optimizer,
22
+ )
23
+ import IPython
24
+
25
+ e = IPython.embed
26
+
27
+
28
+ class ACTPolicy(nn.Module):
29
+
30
+ def __init__(self, args_override, RoboTwin_Config=None):
31
+ super().__init__()
32
+ model, optimizer = build_ACT_model_and_optimizer(args_override, RoboTwin_Config)
33
+ self.model = model # CVAE decoder
34
+ self.optimizer = optimizer
35
+ self.kl_weight = args_override["kl_weight"]
36
+ self.gripper_loss_weight = float(args_override.get("gripper_loss_weight", 1.0))
37
+ self.late_action_loss_weight = float(args_override.get("late_action_loss_weight", 1.0))
38
+ self.late_action_loss_start_ratio = float(args_override.get("late_action_loss_start_ratio", 1.0))
39
+ self.use_vitacdreamer_feature = args_override.get("use_vitacdreamer_feature", False)
40
+ self.use_cached_vitacdreamer_feature = bool(args_override.get("vitacdreamer_feature_cache_dir"))
41
+ self.finetune_vitacdreamer_encoder = bool(args_override.get("finetune_vitacdreamer_encoder", False))
42
+ self.feature_extractor = None
43
+ if self.finetune_vitacdreamer_encoder and self.use_cached_vitacdreamer_feature:
44
+ raise ValueError(
45
+ "finetune_vitacdreamer_encoder=True requires online ViTacDreamer inputs; "
46
+ "remove vitacdreamer_feature_cache_dir so encoder remains in the computation graph."
47
+ )
48
+ if self.use_vitacdreamer_feature and not self.use_cached_vitacdreamer_feature:
49
+ self.feature_extractor = ViTacDreamerFeatureExtractor(
50
+ checkpoint_path=args_override["vitacdreamer_checkpoint"],
51
+ freeze_encoder=not self.finetune_vitacdreamer_encoder,
52
+ device=args_override.get("device", "cuda:0")
53
+ )
54
+ if self.finetune_vitacdreamer_encoder:
55
+ encoder_lr = args_override.get("vitacdreamer_encoder_lr", args_override.get("lr", 1e-5))
56
+ encoder_params = [
57
+ param for param in self.feature_extractor.parameters()
58
+ if param.requires_grad
59
+ ]
60
+ if encoder_params:
61
+ self.optimizer.add_param_group({"params": encoder_params, "lr": encoder_lr})
62
+ print(f"KL Weight {self.kl_weight}")
63
+
64
+ def forward(self, qpos, cam_image, tac_image, actions=None, is_pad=None, vitac_inputs=None, vitac_feature=None):
65
+ env_state = None
66
+ if self.use_vitacdreamer_feature:
67
+ if vitac_feature is None:
68
+ if vitac_inputs is None:
69
+ raise ValueError("vitac_inputs or vitac_feature are required when use_vitacdreamer_feature=True")
70
+ if self.feature_extractor is None:
71
+ raise ValueError(
72
+ "Cached ViTacDreamer training expects vitac_feature tensors from the dataset. "
73
+ "Check vitacdreamer_feature_cache_dir and cached feature files."
74
+ )
75
+ vitac_feature = self.feature_extractor.extract_features_from_history(
76
+ current_tactile=vitac_inputs["current_tactile"],
77
+ visual_history=vitac_inputs["visual_history"],
78
+ tactile_history=vitac_inputs["tactile_history"],
79
+ action_history=vitac_inputs["action_history"],
80
+ task_id=vitac_inputs.get("task_id"),
81
+ )
82
+ if actions is not None: # training time
83
+ actions = actions[:, :self.model.num_queries]
84
+ is_pad = is_pad[:, :self.model.num_queries]
85
+
86
+ a_hat, is_pad_hat, (mu, logvar) = self.model(
87
+ qpos, cam_image, tac_image, env_state, actions, is_pad, vitac_feature=vitac_feature
88
+ )
89
+ total_kld, dim_wise_kld, mean_kld = kl_divergence(mu, logvar)
90
+ loss_dict = dict()
91
+ all_l1 = F.l1_loss(actions, a_hat, reduction="none")
92
+ valid = (~is_pad).unsqueeze(-1).to(dtype=all_l1.dtype)
93
+ weights = torch.ones_like(all_l1)
94
+ if self.gripper_loss_weight != 1.0 and all_l1.shape[-1] >= 8:
95
+ weights[..., 7] = self.gripper_loss_weight
96
+ if self.late_action_loss_weight != 1.0 and self.late_action_loss_start_ratio < 1.0:
97
+ t0 = int(round(all_l1.shape[1] * self.late_action_loss_start_ratio))
98
+ t0 = max(0, min(t0, all_l1.shape[1]))
99
+ weights[:, t0:, :] *= self.late_action_loss_weight
100
+ weighted_l1 = all_l1 * weights * valid
101
+ denom = (weights * valid).sum().clamp_min(1.0)
102
+ l1 = weighted_l1.sum() / denom
103
+ unweighted_l1 = (all_l1 * valid).sum() / valid.expand_as(all_l1).sum().clamp_min(1.0)
104
+ if all_l1.shape[-1] >= 8:
105
+ gripper_l1 = (all_l1[..., 7:8] * valid).sum() / valid.sum().clamp_min(1.0)
106
+ arm_valid = valid.expand(-1, -1, min(7, all_l1.shape[-1]))
107
+ arm_l1 = (all_l1[..., :7] * arm_valid).sum() / arm_valid.sum().clamp_min(1.0)
108
+ else:
109
+ gripper_l1 = torch.zeros((), device=all_l1.device, dtype=all_l1.dtype)
110
+ arm_l1 = unweighted_l1
111
+ loss_dict["l1"] = l1
112
+ loss_dict["l1_unweighted"] = unweighted_l1
113
+ loss_dict["arm_l1"] = arm_l1
114
+ loss_dict["gripper_l1"] = gripper_l1
115
+ loss_dict["kl"] = total_kld[0]
116
+ loss_dict["loss"] = loss_dict["l1"] + loss_dict["kl"] * self.kl_weight
117
+ return loss_dict
118
+ else: # inference time
119
+ a_hat, _, (_, _) = self.model(
120
+ qpos, cam_image, tac_image, env_state, vitac_feature=vitac_feature
121
+ ) # no action, sample from prior
122
+ return a_hat
123
+
124
+ def configure_optimizers(self):
125
+ return self.optimizer
126
+
127
+
128
+ class CNNMLPPolicy(nn.Module):
129
+
130
+ def __init__(self, args_override):
131
+ super().__init__()
132
+ model, optimizer = build_CNNMLP_model_and_optimizer(args_override)
133
+ self.model = model # decoder
134
+ self.optimizer = optimizer
135
+
136
+ def __call__(self, qpos, image, actions=None, is_pad=None):
137
+ env_state = None # TODO
138
+ if actions is not None: # training time
139
+ actions = actions[:, 0]
140
+ a_hat = self.model(qpos, image, env_state, actions)
141
+ mse = F.mse_loss(actions, a_hat)
142
+ loss_dict = dict()
143
+ loss_dict["mse"] = mse
144
+ loss_dict["loss"] = loss_dict["mse"]
145
+ return loss_dict
146
+ else: # inference time
147
+ a_hat = self.model(qpos, image, env_state) # no action, sample from prior
148
+ return a_hat
149
+
150
+ def configure_optimizers(self):
151
+ return self.optimizer
152
+
153
+
154
+ def kl_divergence(mu, logvar):
155
+ batch_size = mu.size(0)
156
+ assert batch_size != 0
157
+ if mu.data.ndimension() == 4:
158
+ mu = mu.view(mu.size(0), mu.size(1))
159
+ if logvar.data.ndimension() == 4:
160
+ logvar = logvar.view(logvar.size(0), logvar.size(1))
161
+
162
+ klds = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp())
163
+ total_kld = klds.sum(1).mean(0, True)
164
+ dimension_wise_kld = klds.mean(0)
165
+ mean_kld = klds.mean(1).mean(0, True)
166
+
167
+ return total_kld, dimension_wise_kld, mean_kld
168
+
169
+
170
+ class ACT:
171
+
172
+ def __init__(self, args_override=None, RoboTwin_Config=None):
173
+ if args_override is None:
174
+ args_override = {
175
+ "kl_weight": 0.1, # Default value, can be overridden
176
+ "device": "cuda:0",
177
+ }
178
+ self.policy = ACTPolicy(args_override, RoboTwin_Config)
179
+ self.device = torch.device(args_override["device"])
180
+ self.policy.to(self.device)
181
+ self.policy.eval()
182
+
183
+ # Temporal aggregation settings
184
+ self.temporal_agg = args_override.get("temporal_agg", False)
185
+ self.num_queries = args_override["chunk_size"]
186
+ self.state_dim = args_override.get("state_dim", 14) # TacArena: read from args
187
+ self.max_timesteps = 3000 # Large enough for deployment
188
+ self.camera_names = args_override.get("camera_names", ["cam_high"]) # TacArena: read from args
189
+ self.tactile_names = args_override.get("tactile_names", ["tac_left", "tac_right"]) # TacArena: read from args
190
+ self.use_vitacdreamer_feature = args_override.get("use_vitacdreamer_feature", False)
191
+
192
+ # Set query frequency based on temporal_agg - matching imitate_episodes.py logic
193
+ self.query_frequency = self.num_queries
194
+ if self.temporal_agg:
195
+ self.query_frequency = 1
196
+ # Initialize with zeros matching imitate_episodes.py format
197
+ self.all_time_actions = torch.zeros([
198
+ self.max_timesteps,
199
+ self.max_timesteps + self.num_queries,
200
+ self.state_dim,
201
+ ]).to(self.device)
202
+ print(f"Temporal aggregation enabled with {self.num_queries} queries")
203
+
204
+ self.t = 0 # Current timestep
205
+
206
+ # Load statistics for normalization
207
+ ckpt_dir = args_override.get("ckpt_dir", "")
208
+ explicit_stats_path = args_override.get("stats_path")
209
+ explicit_ckpt_path = args_override.get("policy_checkpoint")
210
+ if ckpt_dir:
211
+ # Load dataset stats for normalization
212
+ stats_path = explicit_stats_path or os.path.join(ckpt_dir, "dataset_stats.pkl")
213
+ if os.path.exists(stats_path):
214
+ with open(stats_path, "rb") as f:
215
+ self.stats = pickle.load(f)
216
+ print(f"Loaded normalization stats from {stats_path}")
217
+ else:
218
+ print(f"Warning: Could not find stats file at {stats_path}")
219
+ self.stats = None
220
+
221
+ # Load policy weights
222
+ ckpt_path = explicit_ckpt_path or os.path.join(ckpt_dir, "policy_best.ckpt")
223
+ if not os.path.exists(ckpt_path):
224
+ ckpt_path = os.path.join(ckpt_dir, "policy_last.ckpt")
225
+ print("current pwd:", os.getcwd())
226
+ if os.path.exists(ckpt_path):
227
+ checkpoint_state = torch.load(ckpt_path)
228
+ loading_status = self.policy.load_state_dict(checkpoint_state, strict=False)
229
+ unexpected = list(loading_status.unexpected_keys)
230
+ missing = list(loading_status.missing_keys)
231
+ non_extractor_missing = [
232
+ key for key in missing
233
+ if not key.startswith("feature_extractor.")
234
+ ]
235
+ if unexpected or non_extractor_missing:
236
+ raise RuntimeError(
237
+ "Unexpected policy checkpoint mismatch. "
238
+ f"missing(non-extractor)={non_extractor_missing[:20]}, "
239
+ f"unexpected={unexpected[:20]}"
240
+ )
241
+ print(f"Loaded policy weights from {ckpt_path}")
242
+ if missing and all(key.startswith("feature_extractor.") for key in missing):
243
+ print(
244
+ "Policy checkpoint was trained with cached ViTacDreamer features; "
245
+ "online eval loads feature_extractor weights from vitacdreamer_checkpoint."
246
+ )
247
+ print(f"Loading status: {loading_status}")
248
+ else:
249
+ print(f"Warning: Could not find policy checkpoint at {ckpt_path}")
250
+ else:
251
+ self.stats = None
252
+
253
+ def pre_process(self, qpos):
254
+ """Normalize input joint positions"""
255
+ if self.stats is not None:
256
+ return (qpos - self.stats["qpos_mean"]) / self.stats["qpos_std"]
257
+ return qpos
258
+
259
+ def post_process(self, action):
260
+ """Denormalize model outputs"""
261
+ if self.stats is not None:
262
+ return action * self.stats["action_std"] + self.stats["action_mean"]
263
+ return action
264
+
265
+ def get_action(self, obs=None):
266
+ if obs is None:
267
+ return None
268
+
269
+ # Convert observations to tensors and normalize qpos - matching imitate_episodes.py
270
+ qpos_numpy = np.array(obs["qpos"])
271
+ qpos_normalized = self.pre_process(qpos_numpy)
272
+ qpos = torch.from_numpy(qpos_normalized).float().to(self.device).unsqueeze(0)
273
+
274
+ # Prepare images following imitate_episodes.py pattern
275
+ # Stack images from all cameras
276
+ if len(self.camera_names) > 0:
277
+ cam_image = []
278
+ for cam_name in self.camera_names:
279
+ cam_image.append(obs[cam_name])
280
+ cam_image = torch.stack(cam_image, dim=0).to(self.device).unsqueeze(0)
281
+ else:
282
+ cam_image = torch.tensor([]).to(self.device)
283
+
284
+ if len(self.tactile_names) > 0:
285
+ tac_image = []
286
+ for tac_name in self.tactile_names:
287
+ tac_image.append(obs[tac_name])
288
+ tac_image = torch.stack(tac_image, dim=0).to(self.device).unsqueeze(0)
289
+ else:
290
+ tac_image = torch.tensor([]).to(self.device)
291
+
292
+ with torch.no_grad():
293
+ # Only query the policy at specified intervals - exactly like imitate_episodes.py
294
+ if self.t % self.query_frequency == 0:
295
+ vitac_inputs = obs.get("vitac_inputs") if self.use_vitacdreamer_feature else None
296
+ vitac_feature = obs.get("vitac_feature") if self.use_vitacdreamer_feature else None
297
+ if vitac_feature is not None:
298
+ vitac_feature = vitac_feature.to(self.device).unsqueeze(0)
299
+ self.all_actions = self.policy(
300
+ qpos, cam_image, tac_image, vitac_inputs=vitac_inputs, vitac_feature=vitac_feature
301
+ )
302
+
303
+ if self.temporal_agg:
304
+ # Match temporal aggregation exactly from imitate_episodes.py
305
+ self.all_time_actions[[self.t], self.t:self.t + self.num_queries] = (self.all_actions)
306
+ actions_for_curr_step = self.all_time_actions[:, self.t]
307
+ actions_populated = torch.all(actions_for_curr_step != 0, axis=1)
308
+ actions_for_curr_step = actions_for_curr_step[actions_populated]
309
+
310
+ # Use same weighting factor as in imitate_episodes.py
311
+ k = 0.01
312
+ exp_weights = np.exp(-k * np.arange(len(actions_for_curr_step)))
313
+ exp_weights = exp_weights / exp_weights.sum()
314
+ exp_weights = (torch.from_numpy(exp_weights).to(self.device).unsqueeze(dim=1))
315
+
316
+ raw_action = (actions_for_curr_step * exp_weights).sum(dim=0, keepdim=True)
317
+ else:
318
+ # Direct action selection, same as imitate_episodes.py
319
+ raw_action = self.all_actions[:, self.t % self.query_frequency]
320
+
321
+ # Denormalize action
322
+ raw_action = raw_action.cpu().numpy()
323
+ action = self.post_process(raw_action)
324
+
325
+ self.t += 1
326
+ return action
327
+
328
+ def reset(self):
329
+ """Reset temporal aggregation state and timestep counter"""
330
+ self.t = 0
331
+ feature_extractor = getattr(self.policy, "feature_extractor", None)
332
+ if feature_extractor is not None:
333
+ feature_extractor.reset()
334
+ if self.temporal_agg:
335
+ self.all_time_actions = torch.zeros([
336
+ self.max_timesteps,
337
+ self.max_timesteps + self.num_queries,
338
+ self.state_dim,
339
+ ]).to(self.device)
experiments/h100/real150_insert_tube_weighted_policy_20260729/code/imitate_episodes.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import torch.distributed as dist
4
+ import numpy as np
5
+ import pickle
6
+ import argparse
7
+ import json
8
+ import yaml
9
+
10
+ import matplotlib
11
+ matplotlib.use("Agg")
12
+ import matplotlib.pyplot as plt
13
+
14
+ from copy import deepcopy
15
+ from tqdm import tqdm
16
+ from torch.nn.parallel import DistributedDataParallel as DDP
17
+ from torch.utils.data.distributed import DistributedSampler
18
+
19
+ from utils import load_data # data functions
20
+ from utils import compute_dict_mean, set_seed, detach_dict # helper functions
21
+ from act_policy import ACTPolicy, CNNMLPPolicy
22
+
23
+ import IPython
24
+ e = IPython.embed
25
+ _METRIC_PROCESS_GROUP = None
26
+
27
+
28
+ def is_dist_enabled():
29
+ return dist.is_available() and dist.is_initialized()
30
+
31
+
32
+ def is_main_process():
33
+ return not is_dist_enabled() or dist.get_rank() == 0
34
+
35
+
36
+ def unwrap_model(model):
37
+ return model.module if isinstance(model, DDP) else model
38
+
39
+
40
+ def setup_distributed(args):
41
+ global _METRIC_PROCESS_GROUP
42
+ world_size = int(os.environ.get("WORLD_SIZE", "1"))
43
+ if world_size <= 1:
44
+ args["distributed"] = False
45
+ args["rank"] = 0
46
+ args["local_rank"] = 0
47
+ return
48
+
49
+ args["distributed"] = True
50
+ args["rank"] = int(os.environ["RANK"])
51
+ args["local_rank"] = int(os.environ["LOCAL_RANK"])
52
+ torch.cuda.set_device(args["local_rank"])
53
+ dist.init_process_group(backend="nccl")
54
+ _METRIC_PROCESS_GROUP = dist.new_group(backend="gloo")
55
+ args["device"] = f"cuda:{args['local_rank']}"
56
+
57
+
58
+ def cleanup_distributed():
59
+ if is_dist_enabled():
60
+ dist.destroy_process_group()
61
+
62
+
63
+ def reduce_loss_dict(loss_dict, device):
64
+ if not is_dist_enabled():
65
+ return loss_dict
66
+ keys = sorted(loss_dict.keys())
67
+ values = torch.stack([loss_dict[key].detach().cpu().to(dtype=torch.float64) for key in keys])
68
+ dist.all_reduce(values, op=dist.ReduceOp.SUM, group=_METRIC_PROCESS_GROUP)
69
+ values /= dist.get_world_size()
70
+ return {key: value.to(device) for key, value in zip(keys, values)}
71
+
72
+
73
+ def reduce_weighted_loss_dict(loss_sum_dict, count, device):
74
+ if not is_dist_enabled():
75
+ return {
76
+ key: value / max(count, 1)
77
+ for key, value in loss_sum_dict.items()
78
+ }
79
+
80
+ keys = sorted(loss_sum_dict.keys())
81
+ values = torch.stack([loss_sum_dict[key].detach().cpu().to(dtype=torch.float64) for key in keys])
82
+ count_tensor = torch.tensor(float(count), dtype=torch.float64)
83
+ dist.all_reduce(values, op=dist.ReduceOp.SUM, group=_METRIC_PROCESS_GROUP)
84
+ dist.all_reduce(count_tensor, op=dist.ReduceOp.SUM, group=_METRIC_PROCESS_GROUP)
85
+ count_tensor = count_tensor.clamp_min(1.0)
86
+ return {key: (value / count_tensor).to(device) for key, value in zip(keys, values)}
87
+
88
+
89
+ def policy_state_dict_for_save(policy):
90
+ state_dict = policy.state_dict()
91
+ cleaned = {}
92
+ for key, value in state_dict.items():
93
+ key = key.replace("module.", "", 1)
94
+ key = key.replace("model.module.", "model.", 1)
95
+ cleaned[key] = value
96
+ return cleaned
97
+
98
+
99
+ def _task_template_vars(task_name):
100
+ if not task_name.startswith("sim-"):
101
+ return {
102
+ "task_name_full": task_name,
103
+ "task_stem": task_name,
104
+ "task_config": "",
105
+ "expert_data_num": "",
106
+ "task_config_ep": "",
107
+ }
108
+ core = task_name[4:]
109
+
110
+ # Task names are sim-{task_stem}-{task_config}-{num_episodes}. Parse the
111
+ # episode count independently so path templates work for both 50 and 100
112
+ # demo policies without splitting default-balanced into default/balanced.
113
+ parts = core.rsplit("-", 1)
114
+ if len(parts) == 2 and parts[1].isdigit():
115
+ config_core, expert_data_num = parts
116
+ for suffix in ("-default-ee-balanced", "-default-balanced", "-default-ee", "-default"):
117
+ if config_core.endswith(suffix):
118
+ task_config = suffix[1:]
119
+ return {
120
+ "task_name_full": task_name,
121
+ "task_stem": config_core[: -len(suffix)],
122
+ "task_config": task_config,
123
+ "expert_data_num": expert_data_num,
124
+ "task_config_ep": f"{task_config}-{expert_data_num}",
125
+ }
126
+
127
+ # Backward compatibility for legacy hard-coded 50-demo task names.
128
+ for suffix in ("-default-ee-balanced-50", "-default-balanced-50", "-default-ee-50", "-default-50"):
129
+ if core.endswith(suffix):
130
+ expert_data_num = suffix.rsplit("-", 1)[-1]
131
+ task_config_ep = suffix[1:]
132
+ task_config = task_config_ep[: -(len(expert_data_num) + 1)]
133
+ return {
134
+ "task_name_full": task_name,
135
+ "task_stem": core[: -len(suffix)],
136
+ "task_config": task_config,
137
+ "expert_data_num": expert_data_num,
138
+ "task_config_ep": task_config_ep,
139
+ }
140
+ parts = core.rsplit("-", 2)
141
+ if len(parts) < 3:
142
+ return {
143
+ "task_name_full": task_name,
144
+ "task_stem": core,
145
+ "task_config": "",
146
+ "expert_data_num": "",
147
+ "task_config_ep": "",
148
+ }
149
+ task_stem, task_config, expert_data_num = parts
150
+ return {
151
+ "task_name_full": task_name,
152
+ "task_stem": task_stem,
153
+ "task_config": task_config,
154
+ "expert_data_num": expert_data_num,
155
+ "task_config_ep": f"{task_config}-{expert_data_num}",
156
+ }
157
+
158
+
159
+ def _resolve_path_template(path_value, task_name):
160
+ if not path_value:
161
+ return path_value
162
+ return path_value.format(**_task_template_vars(task_name))
163
+
164
+
165
+ def _resolve_vitacdreamer_task_id(args, task_name):
166
+ task_order = args.get("vitacdreamer_task_order", None)
167
+ if task_order is None:
168
+ return None
169
+ task_stem = _task_template_vars(task_name)["task_stem"]
170
+ if task_stem not in task_order:
171
+ raise ValueError(f"Task {task_stem!r} is not in vitacdreamer_task_order={task_order}")
172
+ return task_order.index(task_stem)
173
+
174
+
175
+ def main(args):
176
+ setup_distributed(args)
177
+ set_seed(1 + int(args.get("rank", 0)))
178
+ # command line parameters
179
+ is_eval = args["eval"]
180
+ ckpt_dir = args["ckpt_dir"]
181
+ policy_class = args["policy_class"]
182
+ onscreen_render = args["onscreen_render"]
183
+ task_name = args["task_name"]
184
+ batch_size_train = args["batch_size"]
185
+ batch_size_val = args["batch_size"]
186
+
187
+ # get task parameters
188
+ is_sim = task_name[:4] == "sim-"
189
+ if is_sim:
190
+ # TacArena: load from JSON file generated by process_data.py
191
+ SIM_TASK_CONFIGS_PATH = "./SIM_TASK_CONFIGS.json"
192
+ with open(SIM_TASK_CONFIGS_PATH, "r") as f:
193
+ SIM_TASK_CONFIGS = json.load(f)
194
+ task_config = SIM_TASK_CONFIGS[task_name]
195
+ else:
196
+ from aloha_scripts.constants import TASK_CONFIGS
197
+ task_config = TASK_CONFIGS[task_name]
198
+
199
+ dataset_dir = task_config["dataset_dir"]
200
+ num_episodes = task_config["num_episodes"]
201
+ episode_len = task_config["episode_len"]
202
+ camera_names = args["camera_names"]
203
+
204
+ # fixed parameters
205
+ if policy_class == "CNNMLP":
206
+ policy_config = {
207
+ "lr": args["lr"],
208
+ "lr_backbone": args["lr_backbone"],
209
+ "backbone": args["backbone"],
210
+ "num_queries": 1,
211
+ "camera_names": camera_names,
212
+ }
213
+ elif policy_class != "ACT":
214
+ raise NotImplementedError
215
+
216
+ state_dim = args["state_dim"]
217
+ tactile_names = args["tactile_names"]
218
+ chunk_size = args["chunk_size"]
219
+ config = {
220
+ "num_epochs": 6000,
221
+ "ckpt_dir": ckpt_dir,
222
+ "episode_len": episode_len,
223
+ "state_dim": state_dim,
224
+ "lr": args["lr"],
225
+ "policy_class": policy_class,
226
+ "onscreen_render": onscreen_render,
227
+ "policy_config": args,
228
+ "task_name": task_name,
229
+ "seed": args["seed"],
230
+ "temporal_agg": args["temporal_agg"],
231
+ "camera_names": camera_names,
232
+ "real_robot": not is_sim,
233
+ "save_freq": args['save_freq'],
234
+ "num_steps": args['num_steps'],
235
+ "save_step_ckpts": args.get("save_step_ckpts", True),
236
+ }
237
+
238
+ if is_eval:
239
+ print("=" * 60)
240
+ print("TacArena ACT Policy Evaluation")
241
+ print("=" * 60)
242
+ print("Please use the unified evaluation script:")
243
+ print(" python scripts/eval_policy.py policy/ACT/deploy_policy_{task_name}.yml")
244
+ print("")
245
+ print("Note: TacArena uses IsaacLab simulation environment for evaluation.")
246
+ print(" The eval_bc() function is for RoboTwin's MuJoCo environment.")
247
+ print("=" * 60)
248
+ exit()
249
+
250
+ train_dataloader, val_dataloader, stats, _, train_sampler, _ = load_data(
251
+ dataset_dir, num_episodes, camera_names, tactile_names, batch_size_train, batch_size_val, chunk_size,
252
+ num_workers=args.get("num_workers", 0),
253
+ use_vitacdreamer_feature=args.get("use_vitacdreamer_feature", False),
254
+ vitacdreamer_history_len=args.get("vitacdreamer_history_len", 5),
255
+ vitacdreamer_feature_cache_dir=_resolve_path_template(
256
+ args.get("vitacdreamer_feature_cache_dir", None),
257
+ task_name,
258
+ ),
259
+ vitacdreamer_task_id=_resolve_vitacdreamer_task_id(args, task_name),
260
+ distributed=args.get("distributed", False),
261
+ )
262
+
263
+ # save dataset stats
264
+ if is_main_process() and not os.path.isdir(ckpt_dir):
265
+ os.makedirs(ckpt_dir)
266
+ stats_path = os.path.join(ckpt_dir, f"dataset_stats.pkl")
267
+ if is_main_process():
268
+ with open(stats_path, "wb") as f:
269
+ pickle.dump(stats, f)
270
+ config["train_sampler"] = train_sampler
271
+ best_ckpt_info = train_bc(train_dataloader, val_dataloader, config)
272
+ if is_main_process():
273
+ best_epoch, min_val_loss, best_state_dict = best_ckpt_info
274
+ ckpt_path = os.path.join(ckpt_dir, f"policy_best.ckpt")
275
+ torch.save(best_state_dict, ckpt_path)
276
+ print(f"Best ckpt, val loss {min_val_loss:.6f} @ epoch{best_epoch}")
277
+ cleanup_distributed()
278
+
279
+
280
+ def make_policy(policy_class, policy_config):
281
+ if policy_class == "ACT":
282
+ policy = ACTPolicy(policy_config)
283
+ elif policy_class == "CNNMLP":
284
+ policy = CNNMLPPolicy(policy_config)
285
+ else:
286
+ raise NotImplementedError
287
+ return policy
288
+
289
+
290
+ def make_optimizer(policy_class, policy):
291
+ if policy_class == "ACT":
292
+ optimizer = policy.configure_optimizers()
293
+ elif policy_class == "CNNMLP":
294
+ optimizer = policy.configure_optimizers()
295
+ else:
296
+ raise NotImplementedError
297
+ return optimizer
298
+
299
+
300
+ def forward_pass(data, policy):
301
+ if len(data) == 6:
302
+ cam_data, tac_data, qpos_data, action_data, is_pad, vitac_data = data
303
+ else:
304
+ cam_data, tac_data, qpos_data, action_data, is_pad = data
305
+ vitac_data = None
306
+ device = next(policy.parameters()).device
307
+ cam_data, tac_data, qpos_data, action_data, is_pad = (
308
+ cam_data.to(device),
309
+ tac_data.to(device),
310
+ qpos_data.to(device),
311
+ action_data.to(device),
312
+ is_pad.to(device),
313
+ )
314
+ vitac_inputs = None
315
+ vitac_feature = None
316
+ if vitac_data is not None:
317
+ if isinstance(vitac_data, dict):
318
+ vitac_inputs = {
319
+ key: value.to(device)
320
+ for key, value in vitac_data.items()
321
+ }
322
+ else:
323
+ vitac_feature = vitac_data.to(device)
324
+ return policy(
325
+ qpos_data,
326
+ cam_data,
327
+ tac_data,
328
+ action_data,
329
+ is_pad,
330
+ vitac_inputs=vitac_inputs,
331
+ vitac_feature=vitac_feature,
332
+ )
333
+
334
+
335
+ def train_bc(train_dataloader, val_dataloader, config):
336
+ ckpt_dir = config["ckpt_dir"]
337
+ seed = config["seed"]
338
+ policy_class = config["policy_class"]
339
+ policy_config = config["policy_config"]
340
+
341
+ set_seed(seed)
342
+
343
+ policy = make_policy(policy_class, policy_config)
344
+ policy.cuda()
345
+ local_rank = int(config.get("local_rank", 0))
346
+ if config.get("distributed", False):
347
+ if getattr(policy, "finetune_vitacdreamer_encoder", False):
348
+ policy = DDP(
349
+ policy,
350
+ device_ids=[local_rank],
351
+ output_device=local_rank,
352
+ find_unused_parameters=True,
353
+ )
354
+ else:
355
+ policy.model = DDP(
356
+ policy.model,
357
+ device_ids=[local_rank],
358
+ output_device=local_rank,
359
+ find_unused_parameters=False,
360
+ )
361
+ optimizer = make_optimizer(policy_class, unwrap_model(policy))
362
+
363
+ train_history = []
364
+ validation_history = []
365
+ min_val_loss = np.inf
366
+ best_ckpt_info = None
367
+
368
+ step_count = 0
369
+ num_steps = config['num_steps']
370
+ epoch = 0
371
+
372
+ pbar = tqdm(range(num_steps), total=num_steps, leave=False, disable=not is_main_process())
373
+ while step_count < num_steps:
374
+ policy.train()
375
+ optimizer.zero_grad()
376
+ if isinstance(train_dataloader.sampler, DistributedSampler):
377
+ train_dataloader.sampler.set_epoch(epoch)
378
+ for batch_idx, data in enumerate(train_dataloader):
379
+ forward_dict = forward_pass(data, policy)
380
+ # backward
381
+ loss = forward_dict["loss"]
382
+ loss.backward()
383
+ optimizer.step()
384
+ optimizer.zero_grad()
385
+ if is_main_process():
386
+ train_history.append(detach_dict(forward_dict))
387
+
388
+ if is_main_process():
389
+ pbar.set_postfix({'epoch': epoch, 'loss': loss.item()})
390
+ pbar.update(1)
391
+
392
+ step_count += 1
393
+ if is_main_process() and step_count % config['save_freq'] == 0:
394
+ state_to_save = policy_state_dict_for_save(policy)
395
+ ckpt_path = os.path.join(ckpt_dir, f"policy_epoch_{epoch + 1}_seed_{seed}.ckpt")
396
+ torch.save(state_to_save, ckpt_path)
397
+ if config.get("save_step_ckpts", True):
398
+ step_ckpt_path = os.path.join(ckpt_dir, f"policy_step_{step_count}_seed_{seed}.ckpt")
399
+ torch.save(state_to_save, step_ckpt_path)
400
+ plot_history(train_history, validation_history, epoch, ckpt_dir, seed)
401
+
402
+ if step_count >= num_steps:
403
+ break
404
+
405
+ stop_after_train = step_count >= num_steps
406
+ if is_dist_enabled():
407
+ stop_tensor = torch.tensor(float(stop_after_train), dtype=torch.float64)
408
+ dist.all_reduce(stop_tensor, op=dist.ReduceOp.MAX, group=_METRIC_PROCESS_GROUP)
409
+ stop_after_train = bool(stop_tensor.item())
410
+
411
+ if stop_after_train:
412
+ break
413
+
414
+ if is_main_process():
415
+ epoch_train_start = epoch * len(train_dataloader)
416
+ epoch_train_dicts = train_history[epoch_train_start:]
417
+ epoch_summary = compute_dict_mean(epoch_train_dicts) if epoch_train_dicts else {}
418
+ train_summary_string = ""
419
+ for k, v in epoch_summary.items():
420
+ train_summary_string += f"{k}: {v.item():.3f} "
421
+ else:
422
+ epoch_summary = {}
423
+ train_summary_string = ""
424
+
425
+ with torch.inference_mode():
426
+ policy.eval()
427
+ epoch_loss_sums = None
428
+ epoch_count = 0
429
+ for batch_idx, data in enumerate(val_dataloader):
430
+ forward_dict = forward_pass(data, policy)
431
+ batch_size = int(data[2].shape[0])
432
+ batch_loss_sums = {
433
+ key: value.detach().to(next(policy.parameters()).device, dtype=torch.float64) * batch_size
434
+ for key, value in forward_dict.items()
435
+ }
436
+ if epoch_loss_sums is None:
437
+ epoch_loss_sums = batch_loss_sums
438
+ else:
439
+ for key in epoch_loss_sums:
440
+ epoch_loss_sums[key] += batch_loss_sums[key]
441
+ epoch_count += batch_size
442
+
443
+ epoch_summary = reduce_weighted_loss_dict(epoch_loss_sums, epoch_count, next(policy.parameters()).device)
444
+ if is_main_process():
445
+ validation_history.append(epoch_summary)
446
+
447
+ epoch_val_loss = epoch_summary["loss"]
448
+ if is_main_process() and epoch_val_loss < min_val_loss:
449
+ min_val_loss = epoch_val_loss
450
+ best_ckpt_info = (epoch, min_val_loss, deepcopy(policy_state_dict_for_save(policy)))
451
+
452
+ eval_summary_string = ""
453
+ for k, v in epoch_summary.items():
454
+ eval_summary_string += f"{k}: {v.item():.3f} "
455
+
456
+ epoch += 1
457
+
458
+ if is_main_process():
459
+ ckpt_path = os.path.join(ckpt_dir, f"policy_last.ckpt")
460
+ torch.save(policy_state_dict_for_save(policy), ckpt_path)
461
+
462
+ if best_ckpt_info is None:
463
+ best_ckpt_info = (epoch, float("nan"), deepcopy(policy_state_dict_for_save(policy)))
464
+
465
+ best_epoch, min_val_loss, best_state_dict = best_ckpt_info
466
+ ckpt_path = os.path.join(ckpt_dir, f"policy_epoch_{best_epoch}_seed_{seed}.ckpt")
467
+ torch.save(best_state_dict, ckpt_path)
468
+ print(f"Training finished:\nSeed {seed}, val loss {min_val_loss:.6f} at epoch {best_epoch}")
469
+
470
+ # save training curves
471
+ plot_history(train_history, validation_history, epoch, ckpt_dir, seed)
472
+
473
+ return best_ckpt_info
474
+
475
+
476
+ def plot_history(train_history, validation_history, num_epochs, ckpt_dir, seed):
477
+ # save training curves
478
+ for key in train_history[0]:
479
+ plot_path = os.path.join(ckpt_dir, f"train_val_{key}_seed_{seed}.png")
480
+ plt.figure()
481
+ train_values = [summary[key].item() for summary in train_history]
482
+ val_values = [summary[key].item() for summary in validation_history]
483
+ plt.plot(
484
+ np.linspace(0, num_epochs - 1, len(train_history)),
485
+ train_values,
486
+ label="train",
487
+ )
488
+ plt.plot(
489
+ np.linspace(0, num_epochs - 1, len(validation_history)),
490
+ val_values,
491
+ label="validation",
492
+ )
493
+ # plt.ylim([-0.1, 1])
494
+ plt.tight_layout()
495
+ plt.legend()
496
+ plt.title(key)
497
+ plt.savefig(plot_path)
498
+ print(f"Saved plots to {ckpt_dir}")
499
+
500
+
501
+ if __name__ == "__main__":
502
+ parser = argparse.ArgumentParser()
503
+ parser.add_argument("--eval", action="store_true")
504
+ parser.add_argument("--onscreen_render", action="store_true")
505
+ parser.add_argument("--ckpt_dir", action="store", type=str, help="ckpt_dir", required=True)
506
+ parser.add_argument("--task_name", action="store", type=str, help="task_name", required=True)
507
+ parser.add_argument("--config_path", action="store", type=str, help="config_path", required=True)
508
+ parser.add_argument("--seed", action="store", type=int, help="seed", required=True)
509
+
510
+ args = parser.parse_args()
511
+ with open(args.config_path, 'r') as f:
512
+ config_args = yaml.load(f, Loader=yaml.FullLoader)
513
+ config_args.update(vars(args))
514
+ main(config_args)
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl10_lr3e-5_s12000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 10.0
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 12000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 3.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl2p5_lr3e-5_s12000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 2.5
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 12000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 3.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr2e-5_s12000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 5.0
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 12000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 2.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr3e-5_s12000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 5.0
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 12000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 3.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr3e-5_s16000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 5.0
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 16000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 3.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr3e-5_s8000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 5.0
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 8000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 3.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl5_lr5e-5_s12000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 5.0
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 12000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 5.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/configs/train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_kl7p5_lr3e-5_s12000_gw8_late3.yml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insert-tube focused retrain with weighted gripper and chunk-late action loss.
2
+ state_dim: 8
3
+ kl_weight: 7.5
4
+ chunk_size: 15
5
+ hidden_dim: 512
6
+ dim_feedforward: 3200
7
+ temporal_agg: true
8
+ device: cuda:0
9
+ ckpt_dir: null
10
+ policy_class: ACT
11
+ num_steps: 12000
12
+ batch_size: 32
13
+ num_workers: 4
14
+ save_freq: 1000
15
+ position_embedding: sine
16
+ lr_vision_backbone: 1.0e-05
17
+ weight_decay: 0.0001
18
+ lr: 3.0e-05
19
+ vitacdreamer_adapter_lr: 5.0e-05
20
+ masks: false
21
+ dilation: false
22
+ backbone: resnet18
23
+ nheads: 8
24
+ enc_layers: 4
25
+ dec_layers: 7
26
+ pre_norm: false
27
+ dropout: 0.025
28
+ camera_names:
29
+ - cam_high
30
+ tactile_names:
31
+ - tac_left
32
+ - tac_right
33
+ lr_tactile_backbone: 1.0e-05
34
+ tactile_masks: false
35
+ tactile_backbone: resnet18
36
+ tactile_ckpt: null
37
+ tactile_dilation: false
38
+ use_vitacdreamer_feature: true
39
+ vitacdreamer_history_len: 5
40
+ vitacdreamer_sample_stride: 5
41
+ vitacdreamer_feature_dim: 512
42
+ vitacdreamer_fusion_mode: feature_query_policy_kv
43
+ vitacdreamer_cross_attn_layers: none
44
+ finetune_vitacdreamer_encoder: false
45
+ vitacdreamer_checkpoint: /dev/shm/muse/checkpoints/real_insert_tube_wipe_board_150_h32_20260725/stage2_prior512_hlen5_depthdelta_120train30val_b192_from_stage1_prior512_hlen5_120train30val_b192/stage2_v2_encoder_only.pth
46
+ vitacdreamer_feature_cache_dir: ./data/sim-{task_stem}/real-150/vitacdreamer_features_real150_stage2_depthdelta_20260727
47
+ vitacdreamer_task_order:
48
+ - insert_tube
49
+ - wipe_board
50
+ save_step_ckpts: true
51
+ gripper_loss_weight: 8.0
52
+ late_action_loss_weight: 3.0
53
+ late_action_loss_start_ratio: 0.65
experiments/h100/real150_insert_tube_weighted_policy_20260729/scripts/run_insert_tube_weighted_policy_8gpu_20260729.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ ROOT=/dev/shm/muse/src/ViTacDreamer_policy
4
+ ACT=$ROOT/UniVTAC/policy/ACT
5
+ ENV=/dev/shm/muse/envs/vitacdreamer_prior512
6
+ RUN=real150_insert_tube_weighted_policy_20260729
7
+ cd "$ACT"
8
+ mkdir -p "logs/$RUN" "scripts/$RUN"
9
+ cp "$0" "scripts/$RUN/launch_8gpu.sh" 2>/dev/null || true
10
+ run_one() {
11
+ local tag="$1" gpu="$2"
12
+ local cfg="train_config_vitacdreamer_real150_stage2_depthdelta_insert_tube_${tag}"
13
+ local log="logs/$RUN/insert_tube_${tag}_gpu${gpu}.log"
14
+ echo "START $(date '+%F %T') tag=$tag gpu=$gpu cfg=$cfg" | tee -a "$log"
15
+ CUDA_VISIBLE_DEVICES="$gpu" PATH="$ENV/bin:$PATH" TORCH_HOME="$ROOT/.torch_cache" bash train.sh insert_tube real 150 0 0 "$cfg" 2>&1 | tee -a "$log"
16
+ echo "END $(date '+%F %T') tag=$tag gpu=$gpu cfg=$cfg" | tee -a "$log"
17
+ }
18
+ run_one kl2p5_lr3e-5_s12000_gw8_late3 0 &
19
+ run_one kl5_lr2e-5_s12000_gw8_late3 1 &
20
+ run_one kl5_lr3e-5_s8000_gw8_late3 2 &
21
+ run_one kl5_lr3e-5_s12000_gw8_late3 3 &
22
+ run_one kl5_lr3e-5_s16000_gw8_late3 4 &
23
+ run_one kl7p5_lr3e-5_s12000_gw8_late3 5 &
24
+ run_one kl10_lr3e-5_s12000_gw8_late3 6 &
25
+ run_one kl5_lr5e-5_s12000_gw8_late3 7 &
26
+ wait
27
+ echo DONE_ALL