mxk1998 commited on
Commit
c5a2786
·
verified ·
1 Parent(s): d3db4cb

Publish sealed evaluation sources, batch 21

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py +309 -0
  2. starVLA/facebookresearch_vjepa2_main/src/models/attentive_pooler.py +137 -0
  3. starVLA/facebookresearch_vjepa2_main/src/models/predictor.py +261 -0
  4. starVLA/facebookresearch_vjepa2_main/src/models/utils/__init__.py +0 -0
  5. starVLA/facebookresearch_vjepa2_main/src/models/utils/modules.py +616 -0
  6. starVLA/facebookresearch_vjepa2_main/src/models/utils/patch_embed.py +52 -0
  7. starVLA/facebookresearch_vjepa2_main/src/models/utils/pos_embs.py +93 -0
  8. starVLA/facebookresearch_vjepa2_main/src/models/vision_transformer.py +487 -0
  9. starVLA/facebookresearch_vjepa2_main/src/utils/checkpoint_loader.py +37 -0
  10. starVLA/facebookresearch_vjepa2_main/src/utils/distributed.py +101 -0
  11. starVLA/facebookresearch_vjepa2_main/src/utils/logging.py +108 -0
  12. starVLA/facebookresearch_vjepa2_main/src/utils/monitoring.py +171 -0
  13. starVLA/facebookresearch_vjepa2_main/src/utils/schedulers.py +112 -0
  14. starVLA/facebookresearch_vjepa2_main/src/utils/tensors.py +53 -0
  15. starVLA/facebookresearch_vjepa2_main/src/utils/wrappers.py +44 -0
  16. starVLA/facebookresearch_vjepa2_main/tests/__init__.py +10 -0
  17. starVLA/facebookresearch_vjepa2_main/tests/datasets/__init__.py +10 -0
  18. starVLA/facebookresearch_vjepa2_main/tests/datasets/test_dataloader.py +34 -0
  19. starVLA/facebookresearch_vjepa2_main/tests/datasets/test_memory_efficient_sampler.py +151 -0
  20. starVLA/facebookresearch_vjepa2_main/tests/datasets/test_vjepa_transforms.py +91 -0
  21. starVLA/facebookresearch_vjepa2_main/tests/models/__init__.py +10 -0
  22. starVLA/facebookresearch_vjepa2_main/tests/models/test_models.py +93 -0
  23. starVLA/facebookresearch_vjepa2_main/tests/models/test_predictor.py +58 -0
  24. starVLA/facebookresearch_vjepa2_main/tests/models/test_vision_transformer.py +63 -0
  25. starVLA/model/framework/DreamZero.py +496 -0
  26. starVLA/model/framework/M1.py +421 -0
  27. starVLA/model/framework/QwenAdapter.py +427 -0
  28. starVLA/model/framework/QwenDual.py +288 -0
  29. starVLA/model/framework/QwenFast.py +307 -0
  30. starVLA/model/framework/QwenFastWanPerceiver.py +372 -0
  31. starVLA/model/framework/QwenGR00T.py +276 -0
  32. starVLA/model/framework/QwenOFT.py +338 -0
  33. starVLA/model/framework/QwenPI.py +275 -0
  34. starVLA/model/framework/QwenPerceiver.py +313 -0
  35. starVLA/model/framework/QwenWanPerceiver.py +373 -0
  36. starVLA/model/framework/QwenWanPerceiverACoT.py +595 -0
  37. starVLA/model/framework/QwenWanPerceiverMask.py +703 -0
  38. starVLA/model/framework/WAM_VJEPA/.ipynb_checkpoints/CosmoPredict25PerceiverVJEPA2AC-checkpoint.py +895 -0
  39. starVLA/model/framework/WAM_VJEPA/CosmoPredict25Perceiver.py +92 -0
  40. starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverDINO.py +709 -0
  41. starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverVJEPA2AC.py +893 -0
  42. starVLA/model/framework/WAM_VJEPA/CosmoPredict2Perceiver.py +258 -0
  43. starVLA/model/framework/WAM_VJEPA/__init__.py +1 -0
  44. starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25Perceiver-checkpoint.py +91 -0
  45. starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverFutureImage-checkpoint.py +727 -0
  46. starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverMaskedFutureImage-checkpoint.py +196 -0
  47. starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PolicyNative-checkpoint.py +756 -0
  48. starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict2Perceiver-checkpoint.py +256 -0
  49. starVLA/model/framework/WM4A/.ipynb_checkpoints/JoyRA05MaskFutureImage-checkpoint.py +452 -0
  50. starVLA/model/framework/WM4A/CosmoPredict25Perceiver.py +91 -0
starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from functools import partial
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ from src.models.utils.modules import ACBlock as Block
13
+ from src.models.utils.modules import build_action_block_causal_attention_mask
14
+ from src.utils.tensors import trunc_normal_
15
+
16
+
17
+ class VisionTransformerPredictorAC(nn.Module):
18
+ """Action Conditioned Vision Transformer Predictor"""
19
+
20
+ def __init__(
21
+ self,
22
+ img_size=(224, 224),
23
+ patch_size=16,
24
+ num_frames=1,
25
+ tubelet_size=2,
26
+ embed_dim=768,
27
+ predictor_embed_dim=1024,
28
+ depth=24,
29
+ num_heads=16,
30
+ mlp_ratio=4.0,
31
+ qkv_bias=True,
32
+ qk_scale=None,
33
+ drop_rate=0.0,
34
+ attn_drop_rate=0.0,
35
+ drop_path_rate=0.0,
36
+ norm_layer=nn.LayerNorm,
37
+ init_std=0.02,
38
+ uniform_power=True,
39
+ use_silu=False,
40
+ wide_silu=True,
41
+ is_frame_causal=True,
42
+ use_activation_checkpointing=False,
43
+ use_rope=True,
44
+ action_embed_dim=7,
45
+ use_extrinsics=False,
46
+ **kwargs
47
+ ):
48
+ super().__init__()
49
+ self.is_frame_causal = is_frame_causal
50
+ self.use_extrinsics = use_extrinsics
51
+
52
+ # Map input to predictor dimension
53
+ self.predictor_embed = nn.Linear(embed_dim, predictor_embed_dim, bias=True)
54
+ self.action_encoder = nn.Linear(action_embed_dim, predictor_embed_dim, bias=True)
55
+ self.state_encoder = nn.Linear(action_embed_dim, predictor_embed_dim, bias=True)
56
+ self.extrinsics_encoder = nn.Linear(action_embed_dim - 1, predictor_embed_dim, bias=True)
57
+
58
+ # Determine positional embedding
59
+ if type(img_size) is int:
60
+ img_size = (img_size, img_size)
61
+ self.img_height, self.img_width = img_size
62
+ self.patch_size = patch_size
63
+ # --
64
+ self.num_frames = num_frames
65
+ self.tubelet_size = tubelet_size
66
+ self.is_video = num_frames > 1
67
+
68
+ self.grid_height = img_size[0] // self.patch_size
69
+ self.grid_width = img_size[1] // self.patch_size
70
+ self.use_activation_checkpointing = use_activation_checkpointing
71
+
72
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
73
+
74
+ # Position embedding
75
+ self.uniform_power = uniform_power
76
+
77
+ # Attention Blocks
78
+ self.use_rope = use_rope
79
+ self.predictor_blocks = nn.ModuleList(
80
+ [
81
+ Block(
82
+ use_rope=use_rope,
83
+ grid_size=self.grid_height,
84
+ dim=predictor_embed_dim,
85
+ num_heads=num_heads,
86
+ mlp_ratio=mlp_ratio,
87
+ qkv_bias=qkv_bias,
88
+ qk_scale=qk_scale,
89
+ drop=drop_rate,
90
+ act_layer=nn.SiLU if use_silu else nn.GELU,
91
+ wide_silu=wide_silu,
92
+ attn_drop=attn_drop_rate,
93
+ drop_path=dpr[i],
94
+ norm_layer=norm_layer,
95
+ )
96
+ for i in range(depth)
97
+ ]
98
+ )
99
+
100
+ # Normalize & project back to input dimension
101
+ self.predictor_norm = norm_layer(predictor_embed_dim)
102
+ self.predictor_proj = nn.Linear(predictor_embed_dim, embed_dim, bias=True)
103
+
104
+ # ------ initialize weights
105
+ self.init_std = init_std
106
+ self.apply(self._init_weights)
107
+ self._rescale_blocks()
108
+
109
+ attn_mask = None
110
+ if self.is_frame_causal:
111
+ grid_depth = self.num_frames // self.tubelet_size
112
+ grid_height = self.img_height // self.patch_size
113
+ grid_width = self.img_width // self.patch_size
114
+ attn_mask = build_action_block_causal_attention_mask(
115
+ grid_depth, grid_height, grid_width, add_tokens=3 if use_extrinsics else 2
116
+ )
117
+ self.attn_mask = attn_mask
118
+
119
+ def _init_weights(self, m):
120
+ if isinstance(m, nn.Linear):
121
+ trunc_normal_(m.weight, std=self.init_std)
122
+ if isinstance(m, nn.Linear) and m.bias is not None:
123
+ nn.init.constant_(m.bias, 0)
124
+ elif isinstance(m, nn.LayerNorm):
125
+ nn.init.constant_(m.bias, 0)
126
+ nn.init.constant_(m.weight, 1.0)
127
+
128
+ def _rescale_blocks(self):
129
+ def rescale(param, layer_id):
130
+ param.div_(math.sqrt(2.0 * layer_id))
131
+
132
+ for layer_id, layer in enumerate(self.predictor_blocks):
133
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
134
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
135
+
136
+ def forward_for_WAM_VJEPA2AC(self, x, target_emb, state_emb, extrinsics=None):
137
+ # print('############ VisionTransformerPredictorAC.forward-1')
138
+ # print(x.shape) # torch.Size([8, 256, 1408])
139
+ x = self.predictor_embed(x)
140
+ # print(x.shape) # torch.Size([8, 256, 1024])
141
+
142
+ # 这里T是在计算x是由几张图片经过VJEPA2-AC-Encoder编码得到的表征
143
+ B, N_ctxt, D = x.size()
144
+ T = N_ctxt // (self.grid_height * self.grid_width)
145
+ # print(self.grid_height) # 16
146
+ # print(self.grid_width) # 16
147
+ # print(T) # 1
148
+
149
+ # print(state_emb.shape) # torch.Size([8, 1, 1024])
150
+ s = state_emb.unsqueeze(1)
151
+ # print(s.shape) # torch.Size([8, 1, 1, 1024])
152
+
153
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
154
+ a = target_emb.unsqueeze(1)
155
+ # print(a.shape) # torch.Size([8, 1, 64, 1024])
156
+
157
+ x = x.view(B, T, self.grid_height * self.grid_width, D)
158
+ # print(x.shape) # torch.Size([8, 1, 256, 1024])
159
+
160
+ # print(self.use_extrinsics) # False
161
+ # print(extrinsics) # None
162
+ if self.use_extrinsics:
163
+ e = self.extrinsics_encoder(extrinsics).unsqueeze(2)
164
+ x = torch.cat([a, s, e, x], dim=2).flatten(1, 2) # [B, T*(H*W+3), D]
165
+ else:
166
+ x = torch.cat([a, s, x], dim=2).flatten(1, 2) # [B, T*(H*W+2), D]
167
+ # print(x.shape) # torch.Size([8, 321, 1024])
168
+
169
+ cond_tokens = (a.shape[2]+s.shape[2]+1) if self.use_extrinsics else (a.shape[2]+s.shape[2])
170
+ # print(cond_tokens) # 65
171
+ attn_mask = self.attn_mask[: x.size(1), : x.size(1)].to(x.device, non_blocking=True)
172
+ # print(self.attn_mask.shape) # torch.Size([8256, 8256])
173
+ # print(attn_mask.shape) # torch.Size([321, 312])
174
+
175
+ # print(self.use_activation_checkpointing) # False
176
+ # print(len(self.predictor_blocks)) # 24
177
+ for i, blk in enumerate(self.predictor_blocks):
178
+ # print(type(blk)) # <class 'src.models.utils.modules.ACBlock'>
179
+ # print(x.shape) # torch.Size([8, 321, 1024])
180
+ if self.use_activation_checkpointing:
181
+ x = torch.utils.checkpoint.checkpoint(
182
+ blk,
183
+ x,
184
+ mask=None,
185
+ attn_mask=attn_mask,
186
+ T=T,
187
+ H=self.grid_height,
188
+ W=self.grid_width,
189
+ action_tokens=cond_tokens,
190
+ use_reentrant=False,
191
+ )
192
+ else:
193
+ x = blk(
194
+ x,
195
+ mask=None,
196
+ attn_mask=attn_mask,
197
+ T=T,
198
+ H=self.grid_height,
199
+ W=self.grid_width,
200
+ action_tokens=cond_tokens,
201
+ )
202
+ # print(x.shape) # torch.Size([8, 321, 1024])
203
+
204
+ # Split out action and frame tokens
205
+ # print(x.shape) # torch.Size([8, 321, 1024])
206
+ x = x.view(B, T, cond_tokens + self.grid_height * self.grid_width, D) # [B, T, K+H*W, D]
207
+ # print(x.shape) # torch.Size([8, 1, 321, 1024])
208
+ x = x[:, :, cond_tokens:, :].flatten(1, 2)
209
+ # print(x.shape) # torch.Size([8, 256, 1024])
210
+ x = self.predictor_norm(x)
211
+ # print(x.shape) # torch.Size([8, 256, 1024])
212
+ x = self.predictor_proj(x)
213
+ # print(x.shape) # torch.Size([8, 256, 1408])
214
+
215
+ # print('############ VisionTransformerPredictorAC.forward-2')
216
+ return x
217
+
218
+ def forward(self, x, actions, states, extrinsics=None):
219
+ # print('############ VisionTransformerPredictorAC.forward-1')
220
+ print('Warning: this function should not used in WAM-VJEPA !!!!!! '
221
+ '(in /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py)')
222
+
223
+ # print(x.shape) # torch.Size([125, 256, 1408])
224
+ x = self.predictor_embed(x)
225
+ # print(x.shape) # torch.Size([125, 256, 1024])
226
+
227
+ # 这里T是在计算x是由几张图片经过VJEPA2-AC-Encoder编码得到的表征
228
+ B, N_ctxt, D = x.size()
229
+ T = N_ctxt // (self.grid_height * self.grid_width)
230
+ # print(self.grid_height) # 16
231
+ # print(self.grid_width) # 16
232
+ # print(T) # 1
233
+
234
+ # print(states.shape) # torch.Size([125, 1, 7])
235
+ # print(actions.shape) # torch.Size([125, 1, 7])
236
+ s = self.state_encoder(states).unsqueeze(2)
237
+ a = self.action_encoder(actions).unsqueeze(2)
238
+ # print(s.shape) # torch.Size([125, 1, 1, 1024])
239
+ # print(a.shape) # torch.Size([125, 1, 1, 1024])
240
+
241
+ x = x.view(B, T, self.grid_height * self.grid_width, D)
242
+ # print(x.shape) # torch.Size([125, 1, 256, 1024])
243
+
244
+ # print(self.use_extrinsics) # False
245
+ # print(extrinsics) # None
246
+ if self.use_extrinsics:
247
+ e = self.extrinsics_encoder(extrinsics).unsqueeze(2)
248
+ x = torch.cat([a, s, e, x], dim=2).flatten(1, 2) # [B, T*(H*W+3), D]
249
+ else:
250
+ x = torch.cat([a, s, x], dim=2).flatten(1, 2) # [B, T*(H*W+2), D]
251
+ # print(x.shape) # torch.Size([125, 258, 1024])
252
+
253
+ cond_tokens = 3 if self.use_extrinsics else 2
254
+ # print(cond_tokens) # 2
255
+ attn_mask = self.attn_mask[: x.size(1), : x.size(1)].to(x.device, non_blocking=True)
256
+ # print(self.attn_mask.shape) # torch.Size([8256, 8256])
257
+ # print(attn_mask.shape) # torch.Size([258, 258])
258
+
259
+ # print(self.use_activation_checkpointing) # False
260
+ # print(len(self.predictor_blocks)) # 24
261
+ for i, blk in enumerate(self.predictor_blocks):
262
+ # print(type(blk)) # <class 'src.models.utils.modules.ACBlock'>
263
+ # print(x.shape) # torch.Size([125, 258, 1024])
264
+ if self.use_activation_checkpointing:
265
+ x = torch.utils.checkpoint.checkpoint(
266
+ blk,
267
+ x,
268
+ mask=None,
269
+ attn_mask=attn_mask,
270
+ T=T,
271
+ H=self.grid_height,
272
+ W=self.grid_width,
273
+ action_tokens=cond_tokens,
274
+ use_reentrant=False,
275
+ )
276
+ else:
277
+ x = blk(
278
+ x,
279
+ mask=None,
280
+ attn_mask=attn_mask,
281
+ T=T,
282
+ H=self.grid_height,
283
+ W=self.grid_width,
284
+ action_tokens=cond_tokens,
285
+ )
286
+ # print(x.shape) # torch.Size([125, 258, 1024])
287
+
288
+ # Split out action and frame tokens
289
+ # print(x.shape) # torch.Size([125, 258, 1024])
290
+ x = x.view(B, T, cond_tokens + self.grid_height * self.grid_width, D) # [B, T, K+H*W, D]
291
+ # print(x.shape) # torch.Size([125, 1, 258, 1024])
292
+ x = x[:, :, cond_tokens:, :].flatten(1, 2)
293
+ # print(x.shape) # torch.Size([125, 256, 1024])
294
+ x = self.predictor_norm(x)
295
+ # print(x.shape) # torch.Size([125, 256, 1024])
296
+ x = self.predictor_proj(x)
297
+ # print(x.shape) # torch.Size([125, 256, 1408])
298
+
299
+ # print('############ VisionTransformerPredictorAC.forward-2')
300
+ return x
301
+
302
+ def vit_ac_predictor(**kwargs):
303
+ model = VisionTransformerPredictorAC(
304
+ mlp_ratio=4,
305
+ qkv_bias=True,
306
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
307
+ **kwargs
308
+ )
309
+ return model
starVLA/facebookresearch_vjepa2_main/src/models/attentive_pooler.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ from src.models.utils.modules import Block, CrossAttention, CrossAttentionBlock
13
+ from src.utils.tensors import trunc_normal_
14
+
15
+
16
+ class AttentivePooler(nn.Module):
17
+ """Attentive Pooler"""
18
+
19
+ def __init__(
20
+ self,
21
+ num_queries=1,
22
+ embed_dim=768,
23
+ num_heads=12,
24
+ mlp_ratio=4.0,
25
+ depth=1,
26
+ norm_layer=nn.LayerNorm,
27
+ init_std=0.02,
28
+ qkv_bias=True,
29
+ complete_block=True,
30
+ use_activation_checkpointing=False,
31
+ ):
32
+ super().__init__()
33
+ self.use_activation_checkpointing = use_activation_checkpointing
34
+ self.query_tokens = nn.Parameter(torch.zeros(1, num_queries, embed_dim))
35
+
36
+ self.complete_block = complete_block
37
+ if complete_block:
38
+ self.cross_attention_block = CrossAttentionBlock(
39
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer
40
+ )
41
+ else:
42
+ self.cross_attention_block = CrossAttention(dim=embed_dim, num_heads=num_heads, qkv_bias=qkv_bias)
43
+
44
+ self.blocks = None
45
+ if depth > 1:
46
+ self.blocks = nn.ModuleList(
47
+ [
48
+ Block(
49
+ dim=embed_dim,
50
+ num_heads=num_heads,
51
+ mlp_ratio=mlp_ratio,
52
+ qkv_bias=qkv_bias,
53
+ qk_scale=False,
54
+ norm_layer=norm_layer,
55
+ )
56
+ for i in range(depth - 1)
57
+ ]
58
+ )
59
+
60
+ self.init_std = init_std
61
+ trunc_normal_(self.query_tokens, std=self.init_std)
62
+ self.apply(self._init_weights)
63
+ self._rescale_blocks()
64
+
65
+ def _rescale_blocks(self):
66
+ def rescale(param, layer_id):
67
+ param.div_(math.sqrt(2.0 * layer_id))
68
+
69
+ layer_id = 0
70
+ if self.blocks is not None:
71
+ for layer_id, layer in enumerate(self.blocks):
72
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
73
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
74
+
75
+ if self.complete_block:
76
+ rescale(self.cross_attention_block.mlp.fc2.weight.data, layer_id + 1)
77
+
78
+ def _init_weights(self, m):
79
+ if isinstance(m, nn.Linear):
80
+ trunc_normal_(m.weight, std=self.init_std)
81
+ if isinstance(m, nn.Linear) and m.bias is not None:
82
+ nn.init.constant_(m.bias, 0)
83
+ elif isinstance(m, nn.LayerNorm):
84
+ nn.init.constant_(m.bias, 0)
85
+ nn.init.constant_(m.weight, 1.0)
86
+ elif isinstance(m, nn.Conv2d):
87
+ trunc_normal_(m.weight, std=self.init_std)
88
+ if m.bias is not None:
89
+ nn.init.constant_(m.bias, 0)
90
+
91
+ def forward(self, x):
92
+ if self.blocks is not None:
93
+ for blk in self.blocks:
94
+ if self.use_activation_checkpointing:
95
+ x = torch.utils.checkpoint.checkpoint(blk, x, False, None, use_reentrant=False)
96
+ else:
97
+ x = blk(x)
98
+ q = self.query_tokens.repeat(len(x), 1, 1)
99
+ q = self.cross_attention_block(q, x)
100
+ return q
101
+
102
+
103
+ class AttentiveClassifier(nn.Module):
104
+ """Attentive Classifier"""
105
+
106
+ def __init__(
107
+ self,
108
+ embed_dim=768,
109
+ num_heads=12,
110
+ mlp_ratio=4.0,
111
+ depth=1,
112
+ norm_layer=nn.LayerNorm,
113
+ init_std=0.02,
114
+ qkv_bias=True,
115
+ num_classes=1000,
116
+ complete_block=True,
117
+ use_activation_checkpointing=False,
118
+ ):
119
+ super().__init__()
120
+ self.pooler = AttentivePooler(
121
+ num_queries=1,
122
+ embed_dim=embed_dim,
123
+ num_heads=num_heads,
124
+ mlp_ratio=mlp_ratio,
125
+ depth=depth,
126
+ norm_layer=norm_layer,
127
+ init_std=init_std,
128
+ qkv_bias=qkv_bias,
129
+ complete_block=complete_block,
130
+ use_activation_checkpointing=use_activation_checkpointing,
131
+ )
132
+ self.linear = nn.Linear(embed_dim, num_classes, bias=True)
133
+
134
+ def forward(self, x):
135
+ x = self.pooler(x).squeeze(1)
136
+ x = self.linear(x)
137
+ return x
starVLA/facebookresearch_vjepa2_main/src/models/predictor.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from functools import partial
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ from src.masks.utils import apply_masks
13
+ from src.models.utils.modules import Block
14
+ from src.models.utils.pos_embs import get_2d_sincos_pos_embed, get_3d_sincos_pos_embed
15
+ from src.utils.tensors import repeat_interleave_batch, trunc_normal_
16
+
17
+
18
+ class VisionTransformerPredictor(nn.Module):
19
+ """Vision Transformer"""
20
+
21
+ def __init__(
22
+ self,
23
+ img_size=(224, 224),
24
+ patch_size=16,
25
+ num_frames=1,
26
+ tubelet_size=2,
27
+ embed_dim=768,
28
+ predictor_embed_dim=384,
29
+ out_embed_dim=None,
30
+ depth=6,
31
+ num_heads=12,
32
+ mlp_ratio=4.0,
33
+ qkv_bias=True,
34
+ qk_scale=None,
35
+ drop_rate=0.0,
36
+ attn_drop_rate=0.0,
37
+ drop_path_rate=0.0,
38
+ norm_layer=nn.LayerNorm,
39
+ init_std=0.02,
40
+ uniform_power=False,
41
+ use_mask_tokens=False,
42
+ num_mask_tokens=2,
43
+ zero_init_mask_tokens=True,
44
+ use_silu=False,
45
+ wide_silu=True,
46
+ use_activation_checkpointing=False,
47
+ return_all_tokens=False,
48
+ chop_last_n_tokens=0,
49
+ use_rope=False,
50
+ **kwargs
51
+ ):
52
+ super().__init__()
53
+ self.return_all_tokens = return_all_tokens
54
+ self.chop_last_n_tokens = chop_last_n_tokens
55
+
56
+ # Map input to predictor dimension
57
+ self.predictor_embed = nn.Linear(embed_dim, predictor_embed_dim, bias=True)
58
+
59
+ # Mask tokens
60
+ self.mask_tokens = None
61
+ self.num_mask_tokens = 0
62
+ if use_mask_tokens:
63
+ self.num_mask_tokens = num_mask_tokens
64
+ self.mask_tokens = nn.ParameterList(
65
+ [nn.Parameter(torch.zeros(1, 1, predictor_embed_dim)) for i in range(num_mask_tokens)]
66
+ )
67
+
68
+ # Determine positional embedding
69
+ if type(img_size) is int:
70
+ img_size = (img_size, img_size)
71
+ self.img_height, self.img_width = img_size
72
+ self.patch_size = patch_size
73
+ # --
74
+ self.num_frames = num_frames
75
+ self.tubelet_size = tubelet_size
76
+ self.is_video = num_frames > 1
77
+
78
+ self.grid_height = img_size[0] // self.patch_size
79
+ self.grid_width = img_size[1] // self.patch_size
80
+ self.grid_depth = num_frames // self.tubelet_size
81
+ self.use_activation_checkpointing = use_activation_checkpointing
82
+
83
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
84
+
85
+ if self.is_video:
86
+ self.num_patches = num_patches = (
87
+ (num_frames // tubelet_size) * (img_size[0] // patch_size) * (img_size[1] // patch_size)
88
+ )
89
+ else:
90
+ self.num_patches = num_patches = (img_size[0] // patch_size) * (img_size[1] // patch_size)
91
+ # Position embedding
92
+ self.uniform_power = uniform_power
93
+
94
+ self.predictor_pos_embed = None
95
+ if not use_rope:
96
+ self.predictor_pos_embed = nn.Parameter(
97
+ torch.zeros(1, num_patches, predictor_embed_dim), requires_grad=False
98
+ )
99
+
100
+ # Attention Blocks
101
+ self.use_rope = use_rope
102
+ self.predictor_blocks = nn.ModuleList(
103
+ [
104
+ Block(
105
+ use_rope=use_rope,
106
+ grid_size=self.grid_height,
107
+ grid_depth=self.grid_depth,
108
+ dim=predictor_embed_dim,
109
+ num_heads=num_heads,
110
+ mlp_ratio=mlp_ratio,
111
+ qkv_bias=qkv_bias,
112
+ qk_scale=qk_scale,
113
+ drop=drop_rate,
114
+ act_layer=nn.SiLU if use_silu else nn.GELU,
115
+ wide_silu=wide_silu,
116
+ attn_drop=attn_drop_rate,
117
+ drop_path=dpr[i],
118
+ norm_layer=norm_layer,
119
+ )
120
+ for i in range(depth)
121
+ ]
122
+ )
123
+
124
+ if out_embed_dim is None:
125
+ teacher_embed_dim = kwargs.get("teacher_embed_dim", None)
126
+ if teacher_embed_dim is not None:
127
+ out_embed_dim = teacher_embed_dim
128
+ else:
129
+ out_embed_dim = embed_dim
130
+
131
+ # Normalize & project back to input dimension
132
+ self.predictor_norm = norm_layer(predictor_embed_dim)
133
+ self.predictor_proj = nn.Linear(predictor_embed_dim, out_embed_dim, bias=True)
134
+
135
+ # ------ initialize weights
136
+ if self.predictor_pos_embed is not None:
137
+ self._init_pos_embed(self.predictor_pos_embed.data) # sincos pos-embed
138
+ self.init_std = init_std
139
+ if not zero_init_mask_tokens:
140
+ for mt in self.mask_tokens:
141
+ trunc_normal_(mt, std=init_std)
142
+ self.apply(self._init_weights)
143
+ self._rescale_blocks()
144
+
145
+ def _init_pos_embed(self, pos_embed):
146
+ embed_dim = pos_embed.size(-1)
147
+ grid_size = self.img_height // self.patch_size # TODO: update; currently assumes square input
148
+ if self.is_video:
149
+ grid_depth = self.num_frames // self.tubelet_size
150
+ sincos = get_3d_sincos_pos_embed(
151
+ embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=self.uniform_power
152
+ )
153
+ else:
154
+ sincos = get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False)
155
+ pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0))
156
+
157
+ def _init_weights(self, m):
158
+ if isinstance(m, nn.Linear):
159
+ trunc_normal_(m.weight, std=self.init_std)
160
+ if isinstance(m, nn.Linear) and m.bias is not None:
161
+ nn.init.constant_(m.bias, 0)
162
+ elif isinstance(m, nn.LayerNorm):
163
+ nn.init.constant_(m.bias, 0)
164
+ nn.init.constant_(m.weight, 1.0)
165
+
166
+ def _rescale_blocks(self):
167
+ def rescale(param, layer_id):
168
+ param.div_(math.sqrt(2.0 * layer_id))
169
+
170
+ for layer_id, layer in enumerate(self.predictor_blocks):
171
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
172
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
173
+
174
+ def forward(self, x, masks_x, masks_y, mask_index=1, has_cls=False):
175
+ """
176
+ :param x: context tokens
177
+ :param masks_x: indices of context tokens in input
178
+ :params masks_y: indices of target tokens in input
179
+ """
180
+ assert (masks_x is not None) and (masks_y is not None), "Cannot run predictor without mask indices"
181
+ if not isinstance(masks_x, list):
182
+ masks_x = [masks_x]
183
+ if not isinstance(masks_y, list):
184
+ masks_y = [masks_y]
185
+
186
+ # Batch Size
187
+ B = len(x) // len(masks_x)
188
+
189
+ # Map context tokens to predictor dimensions
190
+ x = self.predictor_embed(x)
191
+ if has_cls:
192
+ x_cls = x[:, :1, :]
193
+ x = x[:, 1:, :]
194
+ _, N_ctxt, D = x.shape
195
+
196
+ # Add positional embedding to ctxt tokens
197
+ if not self.use_rope:
198
+ x_pos_embed = self.predictor_pos_embed.repeat(B, 1, 1)
199
+ x += apply_masks(x_pos_embed, masks_x)
200
+
201
+ # Make target tokens
202
+ mask_index = mask_index % self.num_mask_tokens
203
+ pred_tokens = self.mask_tokens[mask_index]
204
+ pred_tokens = pred_tokens.repeat(B, self.num_patches, 1)
205
+ pred_tokens = apply_masks(pred_tokens, masks_y)
206
+ # -- add pos embed
207
+ if not self.use_rope:
208
+ pos_embs = self.predictor_pos_embed.repeat(B, 1, 1)
209
+ pos_embs = apply_masks(pos_embs, masks_y)
210
+ pos_embs = repeat_interleave_batch(pos_embs, B, repeat=len(masks_x))
211
+ pred_tokens += pos_embs
212
+
213
+ # Concatenate context & target tokens
214
+ x = x.repeat(len(masks_x), 1, 1)
215
+ x = torch.cat([x, pred_tokens], dim=1)
216
+
217
+ # Positions of context & target tokens
218
+ masks_x = torch.cat(masks_x, dim=0)
219
+ masks_y = torch.cat(masks_y, dim=0)
220
+ masks = torch.cat([masks_x, masks_y], dim=1)
221
+
222
+ # Put tokens in sorted order
223
+ argsort = torch.argsort(masks, dim=1) # [B, N]
224
+ masks = torch.stack([masks[i, row] for i, row in enumerate(argsort)], dim=0)
225
+ x = torch.stack([x[i, row, :] for i, row in enumerate(argsort)], dim=0)
226
+
227
+ # Remove the last n tokens of sorted sequence before processing
228
+ if self.chop_last_n_tokens > 0:
229
+ x = x[:, : -self.chop_last_n_tokens]
230
+ masks = masks[:, : -self.chop_last_n_tokens]
231
+
232
+ if has_cls:
233
+ x = torch.cat([x_cls, x], dim=1)
234
+
235
+ # Fwd prop
236
+ for i, blk in enumerate(self.predictor_blocks):
237
+ if self.use_activation_checkpointing:
238
+ x = torch.utils.checkpoint.checkpoint(blk, x, masks, None, use_reentrant=False)
239
+ else:
240
+ x = blk(x, mask=masks, attn_mask=None)
241
+ x = self.predictor_norm(x)
242
+
243
+ if has_cls:
244
+ x = x[:, 1:, :]
245
+
246
+ # Return output corresponding to target tokens
247
+ if not self.return_all_tokens:
248
+ reverse_argsort = torch.argsort(argsort, dim=1) # [B, N]
249
+ x = torch.stack([x[i, row, :] for i, row in enumerate(reverse_argsort)], dim=0)
250
+ x = x[:, N_ctxt:]
251
+
252
+ x = self.predictor_proj(x)
253
+
254
+ return x
255
+
256
+
257
+ def vit_predictor(**kwargs):
258
+ model = VisionTransformerPredictor(
259
+ mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs
260
+ )
261
+ return model
starVLA/facebookresearch_vjepa2_main/src/models/utils/__init__.py ADDED
File without changes
starVLA/facebookresearch_vjepa2_main/src/models/utils/modules.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from timm.models.layers import drop_path
10
+
11
+
12
+ def build_action_block_causal_attention_mask(T, H, W, add_tokens=1):
13
+ N_T = add_tokens + (H * W)
14
+ N = T * N_T
15
+ mask = torch.zeros(N, N).bool()
16
+ mask_block = torch.ones(N_T, N_T).bool()
17
+ local_window_time = T
18
+
19
+ for t1 in range(T):
20
+ for t2 in range(max(0, t1 - local_window_time + 1), t1 + 1):
21
+ mask[t1 * N_T : (t1 + 1) * N_T, t2 * N_T : (t2 + 1) * N_T] = mask_block
22
+
23
+ return mask
24
+
25
+
26
+ def rotate_queries_or_keys(x, pos):
27
+ B, num_heads, N, D = x.size()
28
+ orig_dtype = x.dtype
29
+ assert D % 2 == 0, "Embedding dimension must be a multiple of 2 for block matrix rotation"
30
+
31
+ # -- compute angle for each position
32
+ omega = torch.arange(D // 2, dtype=x.dtype, device=x.device)
33
+ omega /= D / 2.0
34
+ omega = 1.0 / 10000**omega # (D/2,)
35
+ freq = torch.einsum("..., f -> ... f", pos, omega) # (..., N, D/2), outer product
36
+
37
+ # -- build rotation matrix and apply
38
+ emb_sin = freq.sin() # (..., N, D/2)
39
+ emb_cos = freq.cos() # (..., N, D/2)
40
+ # -- NOTE: This expansion has a subtle bug where frequencies are duplicated across the vector pair.
41
+ # -- Fixing the bug would break compatibility with the pretrained model, but the fix can be applied by commenting
42
+ # -- out the two lines below, and uncommenting the following two lines.
43
+ # -- Thanks to @echosprint, original PR: https://github.com/facebookresearch/vjepa2/pull/15
44
+ emb_sin = emb_sin.squeeze(-1).repeat(1, 1, 1, 2)
45
+ emb_cos = emb_cos.squeeze(-1).repeat(1, 1, 1, 2)
46
+ # emb_sin = emb_sin.repeat_interleave(2, dim=-1) # (..., N, D)
47
+ # emb_cos = emb_cos.repeat_interleave(2, dim=-1) # (..., N, D)
48
+
49
+ # --
50
+ y = x.unflatten(-1, (-1, 2))
51
+ y1, y2 = y.unbind(
52
+ dim=-1,
53
+ )
54
+ y = torch.stack((-y2, y1), dim=-1)
55
+ y = y.flatten(-2)
56
+ return ((x * emb_cos) + (y * emb_sin)).to(orig_dtype)
57
+
58
+
59
+ class DropPath(nn.Module):
60
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
61
+
62
+ def __init__(self, drop_prob=None):
63
+ super(DropPath, self).__init__()
64
+ self.drop_prob = drop_prob
65
+
66
+ def forward(self, x):
67
+ return drop_path(x, self.drop_prob, self.training)
68
+
69
+ def extra_repr(self) -> str:
70
+ return "p={}".format(self.drop_prob)
71
+
72
+
73
+ class MLP(nn.Module):
74
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
75
+ super().__init__()
76
+ out_features = out_features or in_features
77
+ hidden_features = hidden_features or in_features
78
+ self.fc1 = nn.Linear(in_features, hidden_features)
79
+ self.act = act_layer()
80
+ self.fc2 = nn.Linear(hidden_features, out_features)
81
+ self.drop = nn.Dropout(drop)
82
+
83
+ def forward(self, x):
84
+ x = self.fc1(x)
85
+ x = self.act(x)
86
+ x = self.drop(x)
87
+ x = self.fc2(x)
88
+ x = self.drop(x)
89
+ return x
90
+
91
+
92
+ class SwiGLUFFN(nn.Module):
93
+ def __init__(
94
+ self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, wide_silu=True
95
+ ):
96
+ super().__init__()
97
+ out_features = out_features or in_features
98
+ swiglu_hidden_features = hidden_features = hidden_features or in_features
99
+ if wide_silu:
100
+ swiglu_hidden_features = int(2 * hidden_features / 3)
101
+ align_as = 8
102
+ swiglu_hidden_features = (swiglu_hidden_features + align_as - 1) // align_as * align_as
103
+ self.fc1 = nn.Linear(in_features, swiglu_hidden_features)
104
+ self.fc2 = nn.Linear(in_features, swiglu_hidden_features)
105
+ self.act = act_layer()
106
+ self.fc3 = nn.Linear(swiglu_hidden_features, out_features)
107
+
108
+ def forward(self, x):
109
+ x1 = self.fc1(x)
110
+ x2 = self.fc2(x)
111
+ hidden = F.silu(x1) * x2
112
+ return self.fc3(hidden)
113
+
114
+
115
+ class ACRoPEAttention(nn.Module):
116
+ def __init__(
117
+ self,
118
+ dim,
119
+ num_heads=8,
120
+ qkv_bias=False,
121
+ qk_scale=None,
122
+ attn_drop=0.0,
123
+ proj_drop=0.0,
124
+ use_sdpa=True,
125
+ is_causal=False,
126
+ grid_size=16,
127
+ ):
128
+ super().__init__()
129
+ self.num_heads = num_heads
130
+ self.head_dim = head_dim = dim // num_heads
131
+ self.scale = qk_scale or head_dim**-0.5
132
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
133
+ self.attn_drop = nn.Dropout(attn_drop)
134
+ self.proj = nn.Linear(dim, dim)
135
+ self.proj_drop_prob = proj_drop
136
+ self.proj_drop = nn.Dropout(proj_drop)
137
+ self.use_sdpa = use_sdpa
138
+ # --
139
+ self.d_dim = int(2 * ((head_dim // 3) // 2))
140
+ self.h_dim = int(2 * ((head_dim // 3) // 2))
141
+ self.w_dim = int(2 * ((head_dim // 3) // 2))
142
+ self.grid_size = grid_size
143
+ self.is_causal = is_causal
144
+
145
+ def _get_frame_pos(self, ids, H_patches, W_patches):
146
+ tokens_per_frame = int(H_patches * W_patches)
147
+ return ids // tokens_per_frame
148
+
149
+ def _get_height_pos(self, ids, H_patches, W_patches):
150
+ # Remove frame component from ids
151
+ tokens_per_frame = int(H_patches * W_patches)
152
+ tokens_per_row = W_patches
153
+ frame_ids = self._get_frame_pos(ids, H_patches, W_patches)
154
+ ids = ids - tokens_per_frame * frame_ids
155
+ # --
156
+ return ids // tokens_per_row
157
+
158
+ def separate_positions(self, ids, H_patches, W_patches):
159
+ tokens_per_frame = int(H_patches * W_patches)
160
+ tokens_per_row = W_patches
161
+ frame_ids = self._get_frame_pos(ids, H_patches, W_patches)
162
+ # --
163
+ height_ids = self._get_height_pos(ids, H_patches, W_patches)
164
+ # --
165
+ # Remove frame component from ids (1st term) and height component (2nd term)
166
+ width_ids = (ids - tokens_per_frame * frame_ids) - tokens_per_row * height_ids
167
+ return 1.0 * frame_ids, 1.0 * height_ids, 1.0 * width_ids
168
+
169
+ def forward(self, x, mask=None, attn_mask=None, T=None, H=None, W=None, action_tokens=0):
170
+ B, N, C = x.size()
171
+
172
+ # -- compute position of each frame token
173
+ if mask is not None:
174
+ mask = mask.unsqueeze(1).repeat(1, self.num_heads, 1)
175
+ d_mask, h_mask, w_mask = self.separate_positions(mask, H, W)
176
+ else:
177
+ mask = torch.arange(int(T * H * W), device=x.device)
178
+ d_mask, h_mask, w_mask = self.separate_positions(mask, H, W)
179
+
180
+ # -- snap spatial positions to grid size
181
+ h_mask *= self.grid_size / H
182
+ w_mask *= self.grid_size / W
183
+
184
+ # -- split out action tokens from sequence
185
+ if action_tokens > 0:
186
+ x = x.view(B, -1, action_tokens + H * W, C) # [B, T, 1+H*W, D]
187
+
188
+ action_q, action_k, action_v = [], [], []
189
+ for i in range(action_tokens):
190
+ a = x[:, :, i : i + 1, :].flatten(1, 2)
191
+ # Note action tokens do not work with masking
192
+ # -- compute qkv for action tokens and rotate
193
+ qkv = self.qkv(a).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4)
194
+ q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D]
195
+ # --
196
+ qd = rotate_queries_or_keys(q[..., : self.d_dim], pos=torch.arange(T, device=x.device))
197
+ kd = rotate_queries_or_keys(k[..., : self.d_dim], pos=torch.arange(T, device=x.device))
198
+ qr = q[..., self.d_dim :]
199
+ kr = k[..., self.d_dim :]
200
+ action_q += [torch.cat([qd, qr], dim=-1).view(B, self.num_heads, T, 1, -1)]
201
+ action_k += [torch.cat([kd, kr], dim=-1).view(B, self.num_heads, T, 1, -1)]
202
+ action_v += [v.view(B, self.num_heads, T, 1, -1)]
203
+
204
+ action_q = torch.cat(action_q, dim=3).flatten(2, 3)
205
+ action_k = torch.cat(action_k, dim=3).flatten(2, 3)
206
+ action_v = torch.cat(action_v, dim=3).flatten(2, 3)
207
+ x = x[:, :, action_tokens:, :].flatten(1, 2)
208
+
209
+ # -- compute qkv for frame tokens and rotate
210
+ qkv = self.qkv(x).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4)
211
+ q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D]
212
+
213
+ s = 0
214
+ # Rotate depth
215
+ qd = rotate_queries_or_keys(q[..., s : s + self.d_dim], pos=d_mask)
216
+ kd = rotate_queries_or_keys(k[..., s : s + self.d_dim], pos=d_mask)
217
+ s += self.d_dim
218
+ # Rotate height dim
219
+ qh = rotate_queries_or_keys(q[..., s : s + self.h_dim], pos=h_mask)
220
+ kh = rotate_queries_or_keys(k[..., s : s + self.h_dim], pos=h_mask)
221
+ s += self.h_dim
222
+ # Rotate width dim
223
+ qw = rotate_queries_or_keys(q[..., s : s + self.w_dim], pos=w_mask)
224
+ kw = rotate_queries_or_keys(k[..., s : s + self.w_dim], pos=w_mask)
225
+ s += self.w_dim
226
+
227
+ # Combine rotated dimension
228
+ if s < self.head_dim:
229
+ qr = q[..., s:]
230
+ kr = k[..., s:]
231
+ q = torch.cat([qd, qh, qw, qr], dim=-1)
232
+ k = torch.cat([kd, kh, kw, kr], dim=-1)
233
+ else:
234
+ q = torch.cat([qd, qh, qw], dim=-1)
235
+ k = torch.cat([kd, kh, kw], dim=-1)
236
+
237
+ if action_tokens > 0:
238
+
239
+ def merge_(tx, ta):
240
+ """tx, tx in [B, num_heads, N, D]"""
241
+ tx = tx.view(B, self.num_heads, T, H * W, -1) # [B, T, H*W, D]
242
+ ta = ta.view(B, self.num_heads, T, action_tokens, -1) # [B, T, A, D]
243
+ return torch.cat([ta, tx], dim=3).flatten(2, 3)
244
+
245
+ q = merge_(q, action_q)
246
+ k = merge_(k, action_k)
247
+ v = merge_(v, action_v)
248
+
249
+ if attn_mask is not None or self.use_sdpa:
250
+ with torch.backends.cuda.sdp_kernel():
251
+ x = F.scaled_dot_product_attention(
252
+ q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal, attn_mask=attn_mask
253
+ )
254
+ attn = None
255
+ else:
256
+ attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, D, D]
257
+ attn = attn.softmax(dim=-1)
258
+ attn = self.attn_drop(attn)
259
+ x = attn @ v
260
+
261
+ x = x.transpose(1, 2).reshape(B, N, C)
262
+ x = self.proj(x)
263
+ x = self.proj_drop(x)
264
+ return x
265
+
266
+
267
+ class RoPEAttention(nn.Module):
268
+ def __init__(
269
+ self,
270
+ dim,
271
+ num_heads=8,
272
+ qkv_bias=False,
273
+ qk_scale=None,
274
+ attn_drop=0.0,
275
+ proj_drop=0.0,
276
+ use_sdpa=True,
277
+ grid_size=14,
278
+ is_causal=False,
279
+ ):
280
+ super().__init__()
281
+ self.num_heads = num_heads
282
+ self.head_dim = head_dim = dim // num_heads
283
+ self.scale = qk_scale or head_dim**-0.5
284
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
285
+ self.attn_drop = nn.Dropout(attn_drop)
286
+ self.proj = nn.Linear(dim, dim)
287
+ self.proj_drop_prob = proj_drop
288
+ self.proj_drop = nn.Dropout(proj_drop)
289
+ self.use_sdpa = use_sdpa
290
+ # --
291
+ self.d_dim = int(2 * ((head_dim // 3) // 2))
292
+ self.h_dim = int(2 * ((head_dim // 3) // 2))
293
+ self.w_dim = int(2 * ((head_dim // 3) // 2))
294
+ self.grid_size = grid_size
295
+ self.is_causal = is_causal
296
+
297
+ def _get_frame_pos(self, ids, H_patches=None, W_patches=None):
298
+ if H_patches is None or W_patches is None:
299
+ tokens_per_frame = int(self.grid_size * self.grid_size)
300
+ else:
301
+ tokens_per_frame = int(H_patches * W_patches)
302
+ return ids // tokens_per_frame
303
+
304
+ def _get_height_pos(self, ids, H_patches=None, W_patches=None):
305
+ # Remove frame component from ids
306
+ if H_patches is None or W_patches is None:
307
+ tokens_per_frame = int(self.grid_size * self.grid_size)
308
+ tokens_per_row = self.grid_size
309
+ else:
310
+ tokens_per_frame = int(H_patches * W_patches)
311
+ tokens_per_row = W_patches
312
+ frame_ids = self._get_frame_pos(ids, H_patches, W_patches)
313
+ ids = ids - tokens_per_frame * frame_ids
314
+ # --
315
+ return ids // tokens_per_row
316
+
317
+ def separate_positions(self, ids, H_patches=None, W_patches=None):
318
+ if H_patches is None or W_patches is None:
319
+ tokens_per_frame = int(self.grid_size * self.grid_size)
320
+ tokens_per_row = self.grid_size
321
+ else:
322
+ tokens_per_frame = int(H_patches * W_patches)
323
+ tokens_per_row = W_patches
324
+ frame_ids = self._get_frame_pos(ids, H_patches, W_patches)
325
+ # --
326
+ height_ids = self._get_height_pos(ids, H_patches, W_patches)
327
+ # --
328
+ # Remove frame component from ids (1st term) and height component (2nd term)
329
+ width_ids = (ids - tokens_per_frame * frame_ids) - tokens_per_row * height_ids
330
+ return frame_ids, height_ids, width_ids
331
+
332
+ def forward(self, x, mask=None, attn_mask=None, T=None, H_patches=None, W_patches=None):
333
+ B, N, C = x.size()
334
+ grid_depth = int(N // (self.grid_size * self.grid_size))
335
+
336
+ qkv = self.qkv(x).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4)
337
+ q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D]
338
+
339
+ if mask is not None:
340
+ mask = mask.unsqueeze(1).repeat(1, self.num_heads, 1)
341
+ d_mask, h_mask, w_mask = self.separate_positions(mask, H_patches, W_patches)
342
+ else:
343
+ if T is None or H_patches is None or W_patches is None:
344
+ mask = torch.arange(int(grid_depth * self.grid_size * self.grid_size), device=x.device)
345
+ else:
346
+ mask = torch.arange(int(T * H_patches * W_patches), device=x.device)
347
+ d_mask, h_mask, w_mask = self.separate_positions(mask, H_patches, W_patches)
348
+
349
+ s = 0
350
+ # Rotate depth
351
+ qd = rotate_queries_or_keys(q[..., s : s + self.d_dim], pos=d_mask)
352
+ kd = rotate_queries_or_keys(k[..., s : s + self.d_dim], pos=d_mask)
353
+ s += self.d_dim
354
+ # Rotate height dim
355
+ qh = rotate_queries_or_keys(q[..., s : s + self.h_dim], pos=h_mask)
356
+ kh = rotate_queries_or_keys(k[..., s : s + self.h_dim], pos=h_mask)
357
+ s += self.h_dim
358
+ # Rotate width dim
359
+ qw = rotate_queries_or_keys(q[..., s : s + self.w_dim], pos=w_mask)
360
+ kw = rotate_queries_or_keys(k[..., s : s + self.w_dim], pos=w_mask)
361
+ s += self.w_dim
362
+
363
+ # Combine rotated dimension
364
+ if s < self.head_dim:
365
+ qr = q[..., s:]
366
+ kr = k[..., s:]
367
+ q = torch.cat([qd, qh, qw, qr], dim=-1)
368
+ k = torch.cat([kd, kh, kw, kr], dim=-1)
369
+ else:
370
+ q = torch.cat([qd, qh, qw], dim=-1)
371
+ k = torch.cat([kd, kh, kw], dim=-1)
372
+
373
+ if attn_mask is not None or self.use_sdpa:
374
+ with torch.backends.cuda.sdp_kernel():
375
+ x = F.scaled_dot_product_attention(
376
+ q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal, attn_mask=attn_mask
377
+ )
378
+ attn = None
379
+ else:
380
+ attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, D, D]
381
+ attn = attn.softmax(dim=-1)
382
+ attn = self.attn_drop(attn)
383
+ x = attn @ v
384
+
385
+ x = x.transpose(1, 2).reshape(B, N, C)
386
+ x = self.proj(x)
387
+ x = self.proj_drop(x)
388
+ return x
389
+
390
+
391
+ class Attention(nn.Module):
392
+ def __init__(
393
+ self,
394
+ dim,
395
+ num_heads=8,
396
+ qkv_bias=False,
397
+ qk_scale=None,
398
+ attn_drop=0.0,
399
+ proj_drop=0.0,
400
+ use_sdpa=True,
401
+ is_causal=False,
402
+ ):
403
+ super().__init__()
404
+ self.num_heads = num_heads
405
+ head_dim = dim // num_heads
406
+ self.scale = qk_scale or head_dim**-0.5
407
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
408
+ self.attn_drop = nn.Dropout(attn_drop)
409
+ self.proj = nn.Linear(dim, dim)
410
+ self.proj_drop_prob = proj_drop
411
+ self.proj_drop = nn.Dropout(proj_drop)
412
+ self.use_sdpa = use_sdpa
413
+ self.is_causal = is_causal
414
+
415
+ def forward(self, x, mask=None, attn_mask=None):
416
+ B, N, C = x.shape
417
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
418
+ q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D]
419
+
420
+ if attn_mask is not None or self.use_sdpa:
421
+ with torch.backends.cuda.sdp_kernel():
422
+ x = F.scaled_dot_product_attention(
423
+ q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal, attn_mask=attn_mask
424
+ )
425
+ attn = None
426
+ else:
427
+ attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, D, D]
428
+ attn = attn.softmax(dim=-1)
429
+ attn = self.attn_drop(attn)
430
+ x = attn @ v
431
+
432
+ x = x.transpose(1, 2).reshape(B, N, C)
433
+ x = self.proj(x)
434
+ x = self.proj_drop(x)
435
+ return x
436
+
437
+
438
+ class ACBlock(nn.Module):
439
+ def __init__(
440
+ self,
441
+ dim,
442
+ num_heads,
443
+ mlp_ratio=4.0,
444
+ qkv_bias=False,
445
+ qk_scale=None,
446
+ drop=0.0,
447
+ attn_drop=0.0,
448
+ drop_path=0.0,
449
+ act_layer=nn.GELU,
450
+ wide_silu=True,
451
+ norm_layer=nn.LayerNorm,
452
+ use_sdpa=True,
453
+ is_causal=False,
454
+ grid_size=16,
455
+ use_rope=False,
456
+ **kwargs,
457
+ ):
458
+ super().__init__()
459
+ self.norm1 = norm_layer(dim)
460
+ if use_rope:
461
+ self.attn = ACRoPEAttention(
462
+ dim,
463
+ num_heads=num_heads,
464
+ qkv_bias=qkv_bias,
465
+ qk_scale=qk_scale,
466
+ attn_drop=attn_drop,
467
+ use_sdpa=use_sdpa,
468
+ is_causal=is_causal,
469
+ grid_size=grid_size,
470
+ proj_drop=drop,
471
+ )
472
+ else:
473
+ self.attn = Attention(
474
+ dim,
475
+ num_heads=num_heads,
476
+ qkv_bias=qkv_bias,
477
+ qk_scale=qk_scale,
478
+ attn_drop=attn_drop,
479
+ use_sdpa=use_sdpa,
480
+ is_causal=is_causal,
481
+ proj_drop=drop,
482
+ )
483
+
484
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
485
+ self.norm2 = norm_layer(dim)
486
+ mlp_hidden_dim = int(dim * mlp_ratio)
487
+ if act_layer is nn.SiLU:
488
+ self.mlp = SwiGLUFFN(
489
+ in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, wide_silu=wide_silu, drop=drop
490
+ )
491
+ else:
492
+ self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
493
+
494
+ def forward(self, x, mask=None, attn_mask=None, T=None, H=None, W=None, action_tokens=0):
495
+ y = self.norm1(x)
496
+ if isinstance(self.attn, ACRoPEAttention):
497
+ y = self.attn(y, mask=mask, attn_mask=attn_mask, T=T, H=H, W=W, action_tokens=action_tokens)
498
+ else:
499
+ y = self.attn(y, mask=mask, attn_mask=attn_mask)
500
+ x = x + self.drop_path(y)
501
+ y = self.norm2(x)
502
+ x = x + self.drop_path(self.mlp(y))
503
+ return x
504
+
505
+
506
+ class Block(nn.Module):
507
+ def __init__(
508
+ self,
509
+ dim,
510
+ num_heads,
511
+ mlp_ratio=4.0,
512
+ qkv_bias=False,
513
+ qk_scale=None,
514
+ drop=0.0,
515
+ attn_drop=0.0,
516
+ drop_path=0.0,
517
+ act_layer=nn.GELU,
518
+ wide_silu=True,
519
+ norm_layer=nn.LayerNorm,
520
+ use_sdpa=True,
521
+ is_causal=False,
522
+ grid_size=16,
523
+ use_rope=False,
524
+ **kwargs,
525
+ ):
526
+ super().__init__()
527
+ self.norm1 = norm_layer(dim)
528
+ if use_rope:
529
+ self.attn = RoPEAttention(
530
+ dim,
531
+ num_heads=num_heads,
532
+ qkv_bias=qkv_bias,
533
+ qk_scale=qk_scale,
534
+ attn_drop=attn_drop,
535
+ use_sdpa=use_sdpa,
536
+ is_causal=is_causal,
537
+ grid_size=grid_size,
538
+ proj_drop=drop,
539
+ )
540
+ else:
541
+ self.attn = Attention(
542
+ dim,
543
+ num_heads=num_heads,
544
+ qkv_bias=qkv_bias,
545
+ qk_scale=qk_scale,
546
+ attn_drop=attn_drop,
547
+ use_sdpa=use_sdpa,
548
+ is_causal=is_causal,
549
+ proj_drop=drop,
550
+ )
551
+
552
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
553
+ self.norm2 = norm_layer(dim)
554
+ mlp_hidden_dim = int(dim * mlp_ratio)
555
+ if act_layer is nn.SiLU:
556
+ self.mlp = SwiGLUFFN(
557
+ in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, wide_silu=wide_silu, drop=drop
558
+ )
559
+ else:
560
+ self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
561
+
562
+ def forward(self, x, mask=None, attn_mask=None, T=None, H_patches=None, W_patches=None):
563
+ if isinstance(self.attn, RoPEAttention):
564
+ y = self.attn(self.norm1(x), mask=mask, attn_mask=attn_mask, T=T, H_patches=H_patches, W_patches=W_patches)
565
+ else:
566
+ y = self.attn(self.norm1(x), mask=mask, attn_mask=attn_mask)
567
+ x = x + self.drop_path(y)
568
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
569
+ return x
570
+
571
+
572
+ class CrossAttention(nn.Module):
573
+ def __init__(self, dim, num_heads=12, qkv_bias=False, use_sdpa=True):
574
+ super().__init__()
575
+ self.num_heads = num_heads
576
+ head_dim = dim // num_heads
577
+ self.scale = head_dim**-0.5
578
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
579
+ self.kv = nn.Linear(dim, int(dim * 2), bias=qkv_bias)
580
+ # self.proj = nn.Linear(dim, dim)
581
+ self.use_sdpa = use_sdpa
582
+
583
+ def forward(self, q, x):
584
+ B, n, C = q.shape
585
+ q = self.q(q).reshape(B, n, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
586
+
587
+ B, N, C = x.shape
588
+ kv = self.kv(x).reshape(B, N, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
589
+ k, v = kv[0], kv[1] # (batch_size, num_heads, seq_len, feature_dim_per_head)
590
+
591
+ if self.use_sdpa:
592
+ with torch.backends.cuda.sdp_kernel():
593
+ q = F.scaled_dot_product_attention(q, k, v)
594
+ else:
595
+ xattn = (q @ k.transpose(-2, -1)) * self.scale
596
+ xattn = xattn.softmax(dim=-1) # (batch_size, num_heads, query_len, seq_len)
597
+ q = xattn @ v
598
+
599
+ q = q.transpose(1, 2).reshape(B, n, C)
600
+ return q
601
+
602
+
603
+ class CrossAttentionBlock(nn.Module):
604
+ def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
605
+ super().__init__()
606
+ self.norm1 = norm_layer(dim)
607
+ self.xattn = CrossAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias)
608
+ self.norm2 = norm_layer(dim)
609
+ mlp_hidden_dim = int(dim * mlp_ratio)
610
+ self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer)
611
+
612
+ def forward(self, q, x):
613
+ y = self.xattn(q, self.norm1(x))
614
+ q = q + y
615
+ q = q + self.mlp(self.norm2(q))
616
+ return q
starVLA/facebookresearch_vjepa2_main/src/models/utils/patch_embed.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+
9
+
10
+ class PatchEmbed(nn.Module):
11
+ """
12
+ Image to Patch Embedding
13
+ """
14
+
15
+ def __init__(self, patch_size=16, in_chans=3, embed_dim=768):
16
+ super().__init__()
17
+ self.patch_size = patch_size
18
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
19
+
20
+ def forward(self, x):
21
+ B, C, H, W = x.shape
22
+ x = self.proj(x).flatten(2).transpose(1, 2)
23
+ return x
24
+
25
+
26
+ class PatchEmbed3D(nn.Module):
27
+ """
28
+ Image to Patch Embedding
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ patch_size=16,
34
+ tubelet_size=2,
35
+ in_chans=3,
36
+ embed_dim=768,
37
+ ):
38
+ super().__init__()
39
+ self.patch_size = patch_size
40
+ self.tubelet_size = tubelet_size
41
+
42
+ self.proj = nn.Conv3d(
43
+ in_channels=in_chans,
44
+ out_channels=embed_dim,
45
+ kernel_size=(tubelet_size, patch_size, patch_size),
46
+ stride=(tubelet_size, patch_size, patch_size),
47
+ )
48
+
49
+ def forward(self, x, **kwargs):
50
+ B, C, T, H, W = x.shape
51
+ x = self.proj(x).flatten(2).transpose(1, 2)
52
+ return x
starVLA/facebookresearch_vjepa2_main/src/models/utils/pos_embs.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import numpy as np
7
+
8
+
9
+ def get_3d_sincos_pos_embed(embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=False):
10
+ """
11
+ grid_size: int of the grid height and width
12
+ grid_depth: int of the grid depth
13
+ returns:
14
+ pos_embed: [grid_depth*grid_size*grid_size, embed_dim] (w/o cls_token)
15
+ or [1+grid_depth*grid_size*grid_size, embed_dim] (w/ cls_token)
16
+ """
17
+ grid_d = np.arange(grid_depth, dtype=float)
18
+ grid_h = np.arange(grid_size, dtype=float)
19
+ grid_w = np.arange(grid_size, dtype=float)
20
+ grid_h, grid_d, grid_w = np.meshgrid(
21
+ grid_h, grid_d, grid_w
22
+ ) # order of meshgrid is very important for indexing as [d,h,w]
23
+
24
+ if not uniform_power:
25
+ h_embed_dim = embed_dim // 4
26
+ w_embed_dim = embed_dim // 4
27
+ d_embed_dim = embed_dim // 2
28
+ else:
29
+ h_embed_dim = w_embed_dim = d_embed_dim = int(np.ceil(embed_dim / 6) * 2)
30
+
31
+ emb_h = get_1d_sincos_pos_embed_from_grid(h_embed_dim, grid_h) # (T*H*W, D1)
32
+ emb_w = get_1d_sincos_pos_embed_from_grid(w_embed_dim, grid_w) # (T*H*W, D2)
33
+ emb_d = get_1d_sincos_pos_embed_from_grid(d_embed_dim, grid_d) # (T*H*W, D3)
34
+ pos_embed = np.concatenate([emb_d, emb_h, emb_w], axis=1)
35
+ pos_embed = pos_embed[:, :embed_dim]
36
+ if cls_token:
37
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
38
+ return pos_embed
39
+
40
+
41
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
42
+ """
43
+ grid_size: int of the grid height and width
44
+ returns:
45
+ pos_embed: [grid_size*grid_size, embed_dim] (w/o cls_token)
46
+ or [1+grid_size*grid_size, embed_dim] (w/ cls_token)
47
+ """
48
+ grid_h = np.arange(grid_size, dtype=float)
49
+ grid_w = np.arange(grid_size, dtype=float)
50
+ grid_w, grid_h = np.meshgrid(grid_w, grid_h) # order of meshgrid is very important for indexing as [h, w]
51
+
52
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid_h) # (H*W, D/2)
53
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid_w) # (H*W, D/2)
54
+ pos_embed = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
55
+ if cls_token:
56
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
57
+ return pos_embed
58
+
59
+
60
+ def get_1d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
61
+ """
62
+ embed_dim: output dimension for each position
63
+ grid_size: int of the grid length
64
+ returns:
65
+ pos_embed: [grid_size, embed_dim] (w/o cls_token)
66
+ or [1+grid_size, embed_dim] (w/ cls_token)
67
+ """
68
+ grid = np.arange(grid_size, dtype=float)
69
+ pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid)
70
+ if cls_token:
71
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
72
+ return pos_embed
73
+
74
+
75
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
76
+ """
77
+ embed_dim: output dimension for each position
78
+ pos: a list of positions to be encoded: size (M,)
79
+ returns: (M, D)
80
+ """
81
+ assert embed_dim % 2 == 0
82
+ omega = np.arange(embed_dim // 2, dtype=float)
83
+ omega /= embed_dim / 2.0
84
+ omega = 1.0 / 10000**omega # (D/2,)
85
+
86
+ pos = pos.reshape(-1) # (M,)
87
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
88
+
89
+ emb_sin = np.sin(out) # (M, D/2)
90
+ emb_cos = np.cos(out) # (M, D/2)
91
+
92
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
93
+ return emb
starVLA/facebookresearch_vjepa2_main/src/models/vision_transformer.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from functools import partial
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ from src.masks.utils import apply_masks
13
+ from src.models.utils.modules import Block
14
+ from src.models.utils.patch_embed import PatchEmbed, PatchEmbed3D
15
+ from src.models.utils.pos_embs import get_2d_sincos_pos_embed, get_3d_sincos_pos_embed
16
+ from src.utils.tensors import trunc_normal_
17
+
18
+
19
+ class VisionTransformer(nn.Module):
20
+ """Vision Transformer"""
21
+
22
+ def __init__(
23
+ self,
24
+ img_size=(224, 224),
25
+ patch_size=16,
26
+ num_frames=1,
27
+ tubelet_size=2,
28
+ in_chans=3,
29
+ embed_dim=768,
30
+ depth=12,
31
+ num_heads=12,
32
+ mlp_ratio=4.0,
33
+ qkv_bias=True,
34
+ qk_scale=None,
35
+ drop_rate=0.0,
36
+ attn_drop_rate=0.0,
37
+ drop_path_rate=0.0,
38
+ norm_layer=nn.LayerNorm,
39
+ init_std=0.02,
40
+ out_layers=None,
41
+ uniform_power=False,
42
+ use_silu=False,
43
+ wide_silu=True,
44
+ use_sdpa=True,
45
+ use_activation_checkpointing=False,
46
+ use_rope=False,
47
+ handle_nonsquare_inputs=True,
48
+ **kwargs
49
+ ):
50
+ super().__init__()
51
+ self.num_features = self.embed_dim = embed_dim
52
+ self.num_heads = num_heads
53
+ self.out_layers = out_layers
54
+ self.handle_nonsquare_inputs = handle_nonsquare_inputs
55
+
56
+ if type(img_size) is int:
57
+ img_size = (img_size, img_size)
58
+ self.img_height, self.img_width = img_size
59
+ self.patch_size = patch_size
60
+ self.num_frames = num_frames
61
+ self.tubelet_size = tubelet_size
62
+ self.is_video = num_frames > 1
63
+
64
+ self.use_activation_checkpointing = use_activation_checkpointing
65
+
66
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
67
+
68
+ # Tokenize pixels with convolution
69
+ if self.is_video:
70
+ self.patch_embed = PatchEmbed3D(
71
+ patch_size=patch_size, tubelet_size=tubelet_size, in_chans=in_chans, embed_dim=embed_dim
72
+ )
73
+ self.num_patches = (num_frames // tubelet_size) * (img_size[0] // patch_size) * (img_size[1] // patch_size)
74
+ else:
75
+ self.patch_embed = PatchEmbed(patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
76
+ self.num_patches = (img_size[0] // patch_size) * (img_size[1] // patch_size)
77
+
78
+ # Position embedding
79
+ self.uniform_power = uniform_power
80
+ self.use_rope = use_rope
81
+ if self.use_rope:
82
+ self.pos_embed = None
83
+ else:
84
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim), requires_grad=False)
85
+
86
+ # Attention Blocks
87
+ self.blocks = nn.ModuleList(
88
+ [
89
+ Block(
90
+ use_rope=use_rope,
91
+ grid_size=img_size[0] // patch_size,
92
+ grid_depth=num_frames // tubelet_size,
93
+ dim=embed_dim,
94
+ num_heads=num_heads,
95
+ mlp_ratio=mlp_ratio,
96
+ use_sdpa=use_sdpa,
97
+ qkv_bias=qkv_bias,
98
+ qk_scale=qk_scale,
99
+ drop=drop_rate,
100
+ act_layer=nn.SiLU if use_silu else nn.GELU,
101
+ wide_silu=wide_silu,
102
+ attn_drop=attn_drop_rate,
103
+ drop_path=dpr[i],
104
+ norm_layer=norm_layer,
105
+ )
106
+ for i in range(depth)
107
+ ]
108
+ )
109
+ self.norm = norm_layer(embed_dim)
110
+
111
+ # ------ initialize weights
112
+ if self.pos_embed is not None:
113
+ self._init_pos_embed(self.pos_embed.data) # sincos pos-embed
114
+ self.init_std = init_std
115
+ self.apply(self._init_weights)
116
+ self._rescale_blocks()
117
+
118
+ def _init_pos_embed(self, pos_embed):
119
+ embed_dim = pos_embed.size(-1)
120
+ grid_size = self.img_height // self.patch_size # TODO: update; currently assumes square input
121
+ if self.is_video:
122
+ grid_depth = self.num_frames // self.tubelet_size
123
+ sincos = get_3d_sincos_pos_embed(
124
+ embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=self.uniform_power
125
+ )
126
+ else:
127
+ sincos = get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False)
128
+ pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0))
129
+
130
+ def _init_weights(self, m):
131
+ if isinstance(m, nn.Linear):
132
+ trunc_normal_(m.weight, std=self.init_std)
133
+ if isinstance(m, nn.Linear) and m.bias is not None:
134
+ nn.init.constant_(m.bias, 0)
135
+ elif isinstance(m, nn.LayerNorm):
136
+ nn.init.constant_(m.bias, 0)
137
+ nn.init.constant_(m.weight, 1.0)
138
+ elif isinstance(m, nn.Conv2d):
139
+ trunc_normal_(m.weight, std=self.init_std)
140
+ if m.bias is not None:
141
+ nn.init.constant_(m.bias, 0)
142
+ elif isinstance(m, nn.Conv3d):
143
+ trunc_normal_(m.weight, std=self.init_std)
144
+ if m.bias is not None:
145
+ nn.init.constant_(m.bias, 0)
146
+
147
+ def _rescale_blocks(self):
148
+ def rescale(param, layer_id):
149
+ param.div_(math.sqrt(2.0 * layer_id))
150
+
151
+ for layer_id, layer in enumerate(self.blocks):
152
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
153
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
154
+
155
+ def get_num_layers(self):
156
+ return len(self.blocks)
157
+
158
+ def no_weight_decay(self):
159
+ return {}
160
+
161
+ def forward(self, x, masks=None):
162
+ """
163
+ :param x: input image/video
164
+ :param masks: indices of patch tokens to mask (remove)
165
+ """
166
+ if masks is not None and not isinstance(masks, list):
167
+ masks = [masks]
168
+
169
+ # Tokenize input
170
+ # Image
171
+ if x.ndim == 4:
172
+ _, _, H, W = x.shape
173
+ T = 1
174
+ # Video
175
+ elif x.ndim == 5:
176
+ _, _, T, H, W = x.shape
177
+ T = T // self.tubelet_size
178
+ H_patches = H // self.patch_size
179
+ W_patches = W // self.patch_size
180
+ if not self.handle_nonsquare_inputs:
181
+ T = H_patches = W_patches = None
182
+
183
+ if not self.use_rope:
184
+ pos_embed = self.interpolate_pos_encoding(x, self.pos_embed)
185
+ x = self.patch_embed(x)
186
+ x += pos_embed
187
+ else:
188
+ x = self.patch_embed(x)
189
+
190
+ # Mask away unwanted tokens (if masks provided)
191
+ if masks is not None:
192
+ x = apply_masks(x, masks)
193
+ masks = torch.cat(masks, dim=0)
194
+
195
+ # Fwd prop
196
+ outs = []
197
+ for i, blk in enumerate(self.blocks):
198
+ if self.use_activation_checkpointing:
199
+ x = torch.utils.checkpoint.checkpoint(
200
+ blk, x, masks, None, T=T, H_patches=H_patches, W_patches=W_patches, use_reentrant=False
201
+ )
202
+ else:
203
+ x = blk(x, mask=masks, attn_mask=None, T=T, H_patches=H_patches, W_patches=W_patches)
204
+ if self.out_layers is not None and i in self.out_layers:
205
+ outs.append(self.norm(x))
206
+
207
+ if self.out_layers is not None:
208
+ return outs
209
+
210
+ if self.norm is not None:
211
+ x = self.norm(x)
212
+
213
+ return x
214
+
215
+ def interpolate_pos_encoding(self, x, pos_embed):
216
+
217
+ _, N, dim = pos_embed.shape
218
+
219
+ if self.is_video:
220
+
221
+ # If pos_embed already correct size, just return
222
+ _, _, T, H, W = x.shape
223
+ if H == self.img_height and W == self.img_width and T == self.num_frames:
224
+ return pos_embed
225
+
226
+ # Just chop off last N tokens of positional embedding
227
+ elif H == self.img_height and W == self.img_width and T < self.num_frames:
228
+ new_N = int((T // self.tubelet_size) * (H // self.patch_size) * (W // self.patch_size))
229
+ return pos_embed[:, :new_N, :]
230
+
231
+ # Convert depth, height, width of input to be measured in patches
232
+ # instead of pixels/frames
233
+ T = T // self.tubelet_size
234
+ H = H // self.patch_size
235
+ W = W // self.patch_size
236
+
237
+ # Compute the initialized shape of the positional embedding measured
238
+ # in patches
239
+ N_t = self.num_frames // self.tubelet_size
240
+ N_h = self.img_height // self.patch_size
241
+ N_w = self.img_width // self.patch_size
242
+ assert N_h * N_w * N_t == N, "Positional embedding initialized incorrectly"
243
+
244
+ # Compute scale factor for spatio-temporal interpolation
245
+ scale_factor = (T / N_t, H / N_h, W / N_w)
246
+
247
+ pos_embed = nn.functional.interpolate(
248
+ pos_embed.reshape(1, N_t, N_h, N_w, dim).permute(0, 4, 1, 2, 3),
249
+ scale_factor=scale_factor,
250
+ mode="trilinear",
251
+ )
252
+ pos_embed = pos_embed.permute(0, 2, 3, 4, 1).view(1, -1, dim)
253
+ return pos_embed
254
+
255
+ else:
256
+
257
+ # If pos_embed already correct size, just return
258
+ _, _, H, W = x.shape
259
+ if H == self.img_height and W == self.img_width:
260
+ return pos_embed
261
+
262
+ # Compute scale factor for spatial interpolation
263
+ npatch = (H // self.patch_size) * (W // self.patch_size)
264
+ scale_factor = math.sqrt(npatch / N)
265
+
266
+ pos_embed = nn.functional.interpolate(
267
+ pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
268
+ scale_factor=scale_factor,
269
+ mode="bicubic",
270
+ )
271
+ pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
272
+ return pos_embed
273
+
274
+
275
+ def vit_large(patch_size=16, **kwargs):
276
+ model = VisionTransformer(
277
+ patch_size=patch_size,
278
+ embed_dim=1024,
279
+ depth=24,
280
+ num_heads=16,
281
+ mlp_ratio=4,
282
+ qkv_bias=True,
283
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
284
+ **kwargs
285
+ )
286
+ return model
287
+
288
+
289
+ def vit_huge(patch_size=16, **kwargs):
290
+ model = VisionTransformer(
291
+ patch_size=patch_size,
292
+ embed_dim=1280,
293
+ depth=32,
294
+ num_heads=16,
295
+ mlp_ratio=4,
296
+ qkv_bias=True,
297
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
298
+ **kwargs
299
+ )
300
+ return model
301
+
302
+
303
+ def vit_giant_xformers(patch_size=16, **kwargs):
304
+ model = VisionTransformer(
305
+ patch_size=patch_size,
306
+ embed_dim=1408,
307
+ depth=40,
308
+ num_heads=22,
309
+ mlp_ratio=48 / 11,
310
+ qkv_bias=True,
311
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
312
+ **kwargs
313
+ )
314
+ return model
315
+
316
+
317
+ # We do not use any of the following ViT definitions in V-JEPA 2, but retain them for
318
+ # compatibility reasons.
319
+ def vit_synthetic(patch_size=16, **kwargs):
320
+ # For performance testing only
321
+ model = VisionTransformer(
322
+ patch_size=patch_size,
323
+ embed_dim=1,
324
+ depth=1,
325
+ num_heads=1,
326
+ mlp_ratio=4,
327
+ qkv_bias=True,
328
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
329
+ **kwargs
330
+ )
331
+ return model
332
+
333
+
334
+ def vit_tiny(patch_size=16, **kwargs):
335
+ model = VisionTransformer(
336
+ patch_size=patch_size,
337
+ embed_dim=192,
338
+ depth=12,
339
+ num_heads=3,
340
+ mlp_ratio=4,
341
+ qkv_bias=True,
342
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
343
+ **kwargs
344
+ )
345
+ return model
346
+
347
+
348
+ def vit_small(patch_size=16, **kwargs):
349
+ model = VisionTransformer(
350
+ patch_size=patch_size,
351
+ embed_dim=384,
352
+ depth=12,
353
+ num_heads=6,
354
+ mlp_ratio=4,
355
+ qkv_bias=True,
356
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
357
+ **kwargs
358
+ )
359
+ return model
360
+
361
+
362
+ def vit_base(patch_size=16, **kwargs):
363
+ model = VisionTransformer(
364
+ patch_size=patch_size,
365
+ embed_dim=768,
366
+ depth=12,
367
+ num_heads=12,
368
+ mlp_ratio=4,
369
+ qkv_bias=True,
370
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
371
+ **kwargs
372
+ )
373
+ return model
374
+
375
+
376
+ def vit_large_rope(patch_size=16, **kwargs):
377
+ model = VisionTransformer(
378
+ patch_size=patch_size,
379
+ embed_dim=1024,
380
+ depth=24,
381
+ num_heads=16,
382
+ mlp_ratio=4,
383
+ qkv_bias=True,
384
+ use_rope=True,
385
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
386
+ **kwargs
387
+ )
388
+ return model
389
+
390
+
391
+ def vit_huge_rope(patch_size=16, **kwargs):
392
+ model = VisionTransformer(
393
+ patch_size=patch_size,
394
+ embed_dim=1280,
395
+ depth=32,
396
+ num_heads=16,
397
+ mlp_ratio=4,
398
+ qkv_bias=True,
399
+ use_rope=True,
400
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
401
+ **kwargs
402
+ )
403
+ return model
404
+
405
+
406
+ def vit_giant(patch_size=16, **kwargs):
407
+ model = VisionTransformer(
408
+ patch_size=patch_size,
409
+ embed_dim=1408,
410
+ depth=40,
411
+ num_heads=16,
412
+ mlp_ratio=48 / 11,
413
+ qkv_bias=True,
414
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
415
+ **kwargs
416
+ )
417
+ return model
418
+
419
+
420
+ def vit_giant_rope(patch_size=16, **kwargs):
421
+ model = VisionTransformer(
422
+ patch_size=patch_size,
423
+ embed_dim=1408,
424
+ depth=40,
425
+ num_heads=16,
426
+ mlp_ratio=48 / 11,
427
+ qkv_bias=True,
428
+ use_rope=True,
429
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
430
+ **kwargs
431
+ )
432
+ return model
433
+
434
+
435
+ def vit_giant_xformers_rope(patch_size=16, **kwargs):
436
+ model = VisionTransformer(
437
+ patch_size=patch_size,
438
+ embed_dim=1408,
439
+ depth=40,
440
+ num_heads=22,
441
+ mlp_ratio=48 / 11,
442
+ qkv_bias=True,
443
+ use_rope=True,
444
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
445
+ **kwargs
446
+ )
447
+ return model
448
+
449
+
450
+ def vit_gigantic(patch_size=16, **kwargs):
451
+ model = VisionTransformer(
452
+ patch_size=patch_size,
453
+ embed_dim=1664,
454
+ depth=48,
455
+ num_heads=16,
456
+ mlp_ratio=64 / 13,
457
+ qkv_bias=True,
458
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
459
+ **kwargs
460
+ )
461
+ return model
462
+
463
+
464
+ def vit_gigantic_xformers(patch_size=16, **kwargs):
465
+ model = VisionTransformer(
466
+ patch_size=patch_size,
467
+ embed_dim=1664,
468
+ depth=48,
469
+ num_heads=26,
470
+ mlp_ratio=64 / 13,
471
+ qkv_bias=True,
472
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
473
+ **kwargs
474
+ )
475
+ return model
476
+
477
+
478
+ VIT_EMBED_DIMS = {
479
+ "vit_synthetic": 1,
480
+ "vit_tiny": 192,
481
+ "vit_small": 384,
482
+ "vit_base": 768,
483
+ "vit_large": 1024,
484
+ "vit_huge": 1280,
485
+ "vit_giant": 1408,
486
+ "vit_gigantic": 1664,
487
+ }
starVLA/facebookresearch_vjepa2_main/src/utils/checkpoint_loader.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ import random
8
+ import time
9
+ from typing import Any
10
+
11
+ import torch
12
+ from torch.serialization import MAP_LOCATION
13
+
14
+ from src.utils.logging import get_logger
15
+
16
+ logger = get_logger(os.path.basename(__file__))
17
+
18
+
19
+ def robust_checkpoint_loader(r_path: str, map_location: MAP_LOCATION = "cpu", max_retries: int = 3) -> Any:
20
+ """
21
+ Loads a checkpoint from a path, retrying up to max_retries times if the checkpoint is not found.
22
+ """
23
+ retries = 0
24
+
25
+ while retries < max_retries:
26
+ try:
27
+ return torch.load(r_path, map_location=map_location)
28
+ except Exception as e:
29
+ logger.warning(f"Encountered exception when loading checkpoint {e}")
30
+ retries += 1
31
+ if retries < max_retries:
32
+ sleep_time_s = (2**retries) * random.uniform(1.0, 1.1)
33
+ logger.warning(f"Sleeping {sleep_time_s}s and trying again, count {retries}/{max_retries}")
34
+ time.sleep(sleep_time_s)
35
+ continue
36
+ else:
37
+ raise e
starVLA/facebookresearch_vjepa2_main/src/utils/distributed.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+
12
+ from src.utils.logging import get_logger
13
+
14
+ logger = get_logger()
15
+
16
+
17
+ def init_distributed(port=37129, rank_and_world_size=(None, None)):
18
+ # try to set all environment variables to avoid triggering a segfault
19
+ # environment variables can be reallocated during the execution of torch.distributed.init_process_group
20
+ # the idea is a race condition may trigger if init_progress_group is modifying an environment variable at
21
+ # the same time as Python, so we try to set all environs before initializing distributed
22
+ if "SLURM_JOB_ID" in os.environ:
23
+ # Use the slurm_tmpdir (if it exists) instead of /tmp
24
+ tmpdir = Path(f"/scratch/slurm_tmpdir/{os.environ['SLURM_JOB_ID']}")
25
+ if tmpdir.exists():
26
+ os.environ["TMPDIR"] = str(tmpdir)
27
+
28
+ if dist.is_available() and dist.is_initialized():
29
+ return dist.get_world_size(), dist.get_rank()
30
+
31
+ rank, world_size = rank_and_world_size
32
+ os.environ["MASTER_ADDR"] = "localhost"
33
+
34
+ if (rank is None) or (world_size is None):
35
+ try:
36
+ world_size = int(os.environ["SLURM_NTASKS"])
37
+ rank = int(os.environ["SLURM_PROCID"])
38
+ os.environ["MASTER_ADDR"] = os.environ["HOSTNAME"]
39
+ except Exception:
40
+ logger.info("SLURM vars not set (distributed training not available)")
41
+ world_size, rank = 1, 0
42
+ return world_size, rank
43
+
44
+ try:
45
+ os.environ["MASTER_PORT"] = str(port)
46
+ torch.distributed.init_process_group(backend="nccl", world_size=world_size, rank=rank)
47
+ except Exception as e:
48
+ world_size, rank = 1, 0
49
+ logger.info(f"Rank: {rank}. Distributed training not available {e}")
50
+
51
+ return world_size, rank
52
+
53
+
54
+ class AllGather(torch.autograd.Function):
55
+
56
+ @staticmethod
57
+ def forward(ctx, x):
58
+ if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1):
59
+ x = x.contiguous()
60
+ outputs = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
61
+ dist.all_gather(outputs, x)
62
+ return torch.cat(outputs, 0)
63
+ return x
64
+
65
+ @staticmethod
66
+ def backward(ctx, grads):
67
+ if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1):
68
+ s = (grads.shape[0] // dist.get_world_size()) * dist.get_rank()
69
+ e = (grads.shape[0] // dist.get_world_size()) * (dist.get_rank() + 1)
70
+ grads = grads.contiguous()
71
+ dist.all_reduce(grads)
72
+ return grads[s:e]
73
+ return grads
74
+
75
+
76
+ class AllReduceSum(torch.autograd.Function):
77
+
78
+ @staticmethod
79
+ def forward(ctx, x):
80
+ if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1):
81
+ x = x.contiguous()
82
+ dist.all_reduce(x)
83
+ return x
84
+
85
+ @staticmethod
86
+ def backward(ctx, grads):
87
+ return grads
88
+
89
+
90
+ class AllReduce(torch.autograd.Function):
91
+
92
+ @staticmethod
93
+ def forward(ctx, x):
94
+ if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1):
95
+ x = x.contiguous() / dist.get_world_size()
96
+ dist.all_reduce(x)
97
+ return x
98
+
99
+ @staticmethod
100
+ def backward(ctx, grads):
101
+ return grads
starVLA/facebookresearch_vjepa2_main/src/utils/logging.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import logging
7
+ import os
8
+ import subprocess
9
+ import sys
10
+
11
+ import torch
12
+
13
+
14
+ def gpu_timer(closure, log_timings=True):
15
+ """Helper to time gpu-time to execute closure()"""
16
+ log_timings = log_timings and torch.cuda.is_available()
17
+
18
+ elapsed_time = -1.0
19
+ if log_timings:
20
+ start = torch.cuda.Event(enable_timing=True)
21
+ end = torch.cuda.Event(enable_timing=True)
22
+ start.record()
23
+
24
+ result = closure()
25
+
26
+ if log_timings:
27
+ end.record()
28
+ torch.cuda.synchronize()
29
+ elapsed_time = start.elapsed_time(end)
30
+
31
+ return result, elapsed_time
32
+
33
+
34
+ LOG_FORMAT = "[%(levelname)-8s][%(asctime)s][%(name)-20s][%(funcName)-25s] %(message)s"
35
+ DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
36
+
37
+
38
+ def get_logger(name=None, force=False):
39
+ logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT, force=force)
40
+ return logging.getLogger(name=name)
41
+
42
+
43
+ class CSVLogger(object):
44
+
45
+ def __init__(self, fname, *argv, **kwargs):
46
+ self.fname = fname
47
+ self.types = []
48
+ mode = kwargs.get("mode", "+a")
49
+ self.delim = kwargs.get("delim", ",")
50
+ # -- print headers
51
+ with open(self.fname, mode) as f:
52
+ for i, v in enumerate(argv, 1):
53
+ self.types.append(v[0])
54
+ if i < len(argv):
55
+ print(v[1], end=self.delim, file=f)
56
+ else:
57
+ print(v[1], end="\n", file=f)
58
+
59
+ def log(self, *argv):
60
+ with open(self.fname, "+a") as f:
61
+ for i, tv in enumerate(zip(self.types, argv), 1):
62
+ end = self.delim if i < len(argv) else "\n"
63
+ print(tv[0] % tv[1], end=end, file=f)
64
+
65
+
66
+ class AverageMeter(object):
67
+ """computes and stores the average and current value"""
68
+
69
+ def __init__(self):
70
+ self.reset()
71
+
72
+ def reset(self):
73
+ self.val = 0
74
+ self.avg = 0
75
+ self.max = float("-inf")
76
+ self.min = float("inf")
77
+ self.sum = 0
78
+ self.count = 0
79
+
80
+ def update(self, val, n=1):
81
+ self.val = val
82
+ try:
83
+ self.max = max(val, self.max)
84
+ self.min = min(val, self.min)
85
+ except Exception:
86
+ pass
87
+ self.sum += val * n
88
+ self.count += n
89
+ self.avg = self.sum / self.count
90
+
91
+
92
+ def jepa_rootpath():
93
+ this_file = os.path.abspath(__file__)
94
+ return "/".join(this_file.split("/")[:-3])
95
+
96
+
97
+ def git_information():
98
+ jepa_root = jepa_rootpath()
99
+ try:
100
+ resp = (
101
+ subprocess.check_output(["git", "-C", jepa_root, "rev-parse", "HEAD", "--abbrev-ref", "HEAD"])
102
+ .decode("ascii")
103
+ .strip()
104
+ )
105
+ commit, branch = resp.split("\n")
106
+ return f"branch: {branch}\ncommit: {commit}\n"
107
+ except Exception:
108
+ return "unknown"
starVLA/facebookresearch_vjepa2_main/src/utils/monitoring.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import dataclasses
7
+ import threading
8
+ import time
9
+ from typing import Dict, Tuple
10
+
11
+ import psutil
12
+
13
+
14
+ @dataclasses.dataclass
15
+ class ResourceStatsSample:
16
+ timestamp: float
17
+ cpu_percent: float
18
+ read_count: int
19
+ write_count: int
20
+ read_bytes: int
21
+ write_bytes: int
22
+ read_chars: int
23
+ write_chars: int
24
+ cpu_times_user: float
25
+ cpu_times_system: float
26
+ cpu_times_children_user: float
27
+ cpu_times_children_system: float
28
+ cpu_times_iowait: float
29
+ cpu_affinity: str
30
+ cpu_num: int
31
+ num_threads: int
32
+ num_voluntary_ctx_switches: int
33
+ num_involuntary_ctx_switches: int
34
+
35
+ def as_tuple(self) -> Dict:
36
+ """Return values mirroring fields."""
37
+ return dataclasses.astuple(self)
38
+
39
+ def fields(self) -> Tuple[dataclasses.Field, ...]:
40
+ """Return fields in this dataclass."""
41
+ return dataclasses.fields(self.__class__)
42
+
43
+
44
+ class ResourceMonitoringThread(threading.Thread):
45
+ def __init__(self, pid=None, refresh_interval=None, stats_callback_fn=None):
46
+ """Starts a thread to monitor pid every refresh_interval seconds.
47
+
48
+ Passes a ResourceStatsSample object to the callback."""
49
+ super(ResourceMonitoringThread, self).__init__()
50
+ if refresh_interval is None:
51
+ refresh_interval = 5
52
+ self.is_running_event = threading.Event()
53
+ self.p = psutil.Process(pid)
54
+ self.refresh_interval = refresh_interval
55
+ if stats_callback_fn is None:
56
+ # Default callback
57
+ def stats_callback_fn(resource_sample: ResourceStatsSample):
58
+ print(f"PID {self.p.pid} Stats: {resource_sample.resource_stats}")
59
+
60
+ elif not callable(stats_callback_fn):
61
+ raise ValueError("Callback needs to be callable, got {}".format(type(stats_callback_fn)))
62
+ self.stats_callback_fn = stats_callback_fn
63
+
64
+ def stop(self) -> None:
65
+ self.is_running_event.set()
66
+
67
+ def run(self) -> None:
68
+ while not self.is_running_event.is_set():
69
+ self.sample_counters()
70
+ self.is_running_event.wait(self.refresh_interval)
71
+
72
+ def log_sample(self, resource_sample: ResourceStatsSample) -> None:
73
+ self.stats_callback_fn(resource_sample)
74
+
75
+ def sample_counters(self) -> None:
76
+ if not self.p.is_running():
77
+ self.stop()
78
+ return
79
+
80
+ with self.p.oneshot():
81
+ cpu_percent = self.p.cpu_percent()
82
+ cpu_times = self.p.cpu_times()
83
+ io_counters = self.p.io_counters()
84
+ cpu_affinity = self.p.cpu_affinity()
85
+ cpu_num = self.p.cpu_num()
86
+ num_threads = self.p.num_threads()
87
+ num_ctx_switches = self.p.num_ctx_switches()
88
+ timestamp = time.time()
89
+
90
+ read_count = io_counters.read_count
91
+ write_count = io_counters.write_count
92
+ read_bytes = io_counters.read_bytes
93
+ write_bytes = io_counters.write_bytes
94
+ read_chars = io_counters.read_chars
95
+ write_chars = io_counters.write_chars
96
+
97
+ def compress_cpu_affinity(cpu_affinity):
98
+ """Change list representation to interval/range representation."""
99
+ if not cpu_affinity:
100
+ return ""
101
+ cpu_affinity_compressed = []
102
+ min_x = None
103
+ max_x = None
104
+ last_x = None
105
+
106
+ # Find contiguous ranges
107
+ for x in cpu_affinity:
108
+ if last_x is None:
109
+ # Start interval
110
+ min_x = x
111
+ max_x = x
112
+ last_x = x
113
+ continue
114
+ elif x == (last_x + 1):
115
+ # Move interval up
116
+ max_x = x
117
+ elif max_x is not None:
118
+ # Interval ended, start again
119
+ if min_x == max_x:
120
+ cpu_affinity_compressed.append("{}".format(min_x))
121
+ else:
122
+ cpu_affinity_compressed.append("{}-{}".format(min_x, max_x))
123
+ min_x = x
124
+ max_x = x
125
+ last_x = x
126
+ # Terminate last range
127
+ if max_x is not None:
128
+ if min_x == max_x:
129
+ cpu_affinity_compressed.append("{}".format(min_x))
130
+ else:
131
+ cpu_affinity_compressed.append("{}-{}".format(min_x, max_x))
132
+
133
+ # Concat
134
+ cpu_affinity_compressed = ",".join(cpu_affinity_compressed)
135
+
136
+ return cpu_affinity_compressed
137
+
138
+ cpu_affinity = compress_cpu_affinity(cpu_affinity)
139
+
140
+ resource_sample = ResourceStatsSample(
141
+ timestamp=timestamp,
142
+ cpu_percent=cpu_percent,
143
+ read_count=read_count,
144
+ write_count=write_count,
145
+ read_bytes=read_bytes,
146
+ write_bytes=write_bytes,
147
+ read_chars=read_chars,
148
+ write_chars=write_chars,
149
+ cpu_times_user=cpu_times.user,
150
+ cpu_times_system=cpu_times.system,
151
+ cpu_times_children_user=cpu_times.children_user,
152
+ cpu_times_children_system=cpu_times.children_system,
153
+ cpu_times_iowait=cpu_times.iowait,
154
+ cpu_affinity=cpu_affinity,
155
+ cpu_num=cpu_num,
156
+ num_threads=num_threads,
157
+ num_voluntary_ctx_switches=num_ctx_switches.voluntary,
158
+ num_involuntary_ctx_switches=num_ctx_switches.involuntary,
159
+ )
160
+ self.log_sample(resource_sample)
161
+
162
+
163
+ if __name__ == "__main__":
164
+ import multiprocessing
165
+
166
+ pid = multiprocessing.current_process().pid
167
+ monitor_thread = ResourceMonitoringThread(pid, 1)
168
+ monitor_thread.start()
169
+ time.sleep(5)
170
+ print("Shutdown")
171
+ monitor_thread.stop()
starVLA/facebookresearch_vjepa2_main/src/utils/schedulers.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+
8
+
9
+ class WSDSchedule(object):
10
+
11
+ def __init__(self, optimizer, warmup_steps, anneal_steps, T_max, start_lr, ref_lr, final_lr=0.0):
12
+ self.optimizer = optimizer
13
+ self.start_lr = start_lr
14
+ self.ref_lr = ref_lr
15
+ self.final_lr = final_lr
16
+ self.anneal_steps = anneal_steps
17
+ self.warmup_steps = warmup_steps
18
+ self.T_max = T_max - warmup_steps - anneal_steps
19
+ self._step = 0.0
20
+
21
+ def step(self):
22
+ self._step += 1
23
+ if self._step < self.warmup_steps:
24
+ progress = float(self._step) / float(max(1, self.warmup_steps))
25
+ new_lr = self.start_lr + progress * (self.ref_lr - self.start_lr)
26
+ elif self._step < self.T_max + self.warmup_steps:
27
+ new_lr = self.ref_lr
28
+ else:
29
+ _step = self._step - (self.T_max + self.warmup_steps)
30
+ progress = float(_step) / float(max(1, self.anneal_steps))
31
+ new_lr = self.ref_lr + progress * (self.final_lr - self.ref_lr)
32
+
33
+ for group in self.optimizer.param_groups:
34
+ group["lr"] = new_lr
35
+ if "lr_scale" in group:
36
+ group["lr"] *= group["lr_scale"]
37
+
38
+ return new_lr
39
+
40
+
41
+ class WarmupCosineSchedule(object):
42
+
43
+ def __init__(self, optimizer, warmup_steps, start_lr, ref_lr, T_max, last_epoch=-1, final_lr=0.0):
44
+ self.optimizer = optimizer
45
+ self.start_lr = start_lr
46
+ self.ref_lr = ref_lr
47
+ self.final_lr = final_lr
48
+ self.warmup_steps = warmup_steps
49
+ self.T_max = T_max - warmup_steps
50
+ self._step = 0.0
51
+
52
+ def step(self):
53
+ self._step += 1
54
+ if self._step < self.warmup_steps:
55
+ progress = float(self._step) / float(max(1, self.warmup_steps))
56
+ new_lr = self.start_lr + progress * (self.ref_lr - self.start_lr)
57
+ else:
58
+ # -- progress after warmup
59
+ progress = float(self._step - self.warmup_steps) / float(max(1, self.T_max))
60
+ new_lr = max(
61
+ self.final_lr,
62
+ self.final_lr + (self.ref_lr - self.final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)),
63
+ )
64
+
65
+ for group in self.optimizer.param_groups:
66
+ group["lr"] = new_lr
67
+
68
+ return new_lr
69
+
70
+
71
+ class CosineWDSchedule(object):
72
+
73
+ def __init__(self, optimizer, ref_wd, T_max, final_wd=0.0):
74
+ self.optimizer = optimizer
75
+ self.ref_wd = ref_wd
76
+ self.final_wd = final_wd
77
+ self.T_max = T_max
78
+ self._step = 0.0
79
+
80
+ def step(self):
81
+ self._step += 1
82
+ progress = self._step / self.T_max
83
+ new_wd = self.final_wd + (self.ref_wd - self.final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress))
84
+
85
+ if self.final_wd <= self.ref_wd:
86
+ new_wd = max(self.final_wd, new_wd)
87
+ else:
88
+ new_wd = min(self.final_wd, new_wd)
89
+
90
+ for group in self.optimizer.param_groups:
91
+ if ("WD_exclude" not in group) or not group["WD_exclude"]:
92
+ group["weight_decay"] = new_wd
93
+ return new_wd
94
+
95
+
96
+ class LinearDecaySchedule(object):
97
+
98
+ def __init__(self, optimizer, ref_lr, T_max, last_epoch=-1, final_lr=0.0):
99
+ self.optimizer = optimizer
100
+ self.ref_lr = ref_lr
101
+ self.final_lr = final_lr
102
+ self.T_max = T_max
103
+ self._step = 0.0
104
+
105
+ def step(self):
106
+ self._step += 1
107
+ progress = float(self._step) / float(max(1, self.T_max))
108
+ new_lr = self.ref_lr + progress * (self.final_lr - self.ref_lr)
109
+ for group in self.optimizer.param_groups:
110
+ group["lr"] = new_lr
111
+
112
+ return new_lr
starVLA/facebookresearch_vjepa2_main/src/utils/tensors.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from logging import getLogger
8
+
9
+ import torch
10
+
11
+ logger = getLogger()
12
+
13
+
14
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
15
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
16
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
17
+ def norm_cdf(x):
18
+ # Computes standard normal cumulative distribution function
19
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
20
+
21
+ with torch.no_grad():
22
+ # Values are generated by using a truncated uniform distribution and
23
+ # then using the inverse CDF for the normal distribution.
24
+ # Get upper and lower cdf values
25
+ lower = norm_cdf((a - mean) / std)
26
+ upper = norm_cdf((b - mean) / std)
27
+
28
+ # Uniformly fill tensor with values from [lower, upper], then translate to
29
+ # [2*lower-1, 2*upper-1].
30
+ tensor.uniform_(2 * lower - 1, 2 * upper - 1)
31
+
32
+ # Use inverse cdf transform for normal distribution to get truncated
33
+ # standard normal
34
+ tensor.erfinv_()
35
+
36
+ # Transform to proper mean, std
37
+ tensor.mul_(std * math.sqrt(2.0))
38
+ tensor.add_(mean)
39
+
40
+ # Clamp to ensure it's in the proper range
41
+ tensor.clamp_(min=a, max=b)
42
+ return tensor
43
+
44
+
45
+ def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
46
+ # type: (Tensor, float, float, float, float) -> Tensor
47
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
48
+
49
+
50
+ def repeat_interleave_batch(x, B, repeat):
51
+ N = len(x) // B
52
+ x = torch.cat([torch.cat([x[i * B : (i + 1) * B] for _ in range(repeat)], dim=0) for i in range(N)], dim=0)
53
+ return x
starVLA/facebookresearch_vjepa2_main/src/utils/wrappers.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import torch.nn as nn
7
+
8
+
9
+ class MultiSeqWrapper(nn.Module):
10
+
11
+ def __init__(self, backbone):
12
+ super().__init__()
13
+ self.backbone = backbone
14
+ self.embed_dim = backbone.embed_dim
15
+
16
+ def forward(self, x, masks=None):
17
+ """
18
+ :param x: [list] List of Tensors of different seq lengths
19
+ :param masks: [list[list]] List of Tensors (out index: masks for given seq length, inner index: multimasks for that seq len)
20
+ """
21
+ if masks is None:
22
+ return [self.backbone(xi) for xi in x]
23
+
24
+ outs = [[] for _ in x]
25
+ for i, (xi, mi) in enumerate(zip(x, masks)):
26
+ for mij in mi:
27
+ outs[i] += [self.backbone(xi, masks=mij)]
28
+ return outs
29
+
30
+
31
+ class PredictorMultiSeqWrapper(nn.Module):
32
+
33
+ def __init__(self, backbone):
34
+ super().__init__()
35
+ self.backbone = backbone
36
+
37
+ def forward(self, x, masks_x, masks_y, has_cls=False):
38
+ n = 0
39
+ outs = [[] for _ in x]
40
+ for i, (xi, mxi, myi) in enumerate(zip(x, masks_x, masks_y)):
41
+ for xij, mxij, myij in zip(xi, mxi, myi):
42
+ outs[i] += [self.backbone(xij, mxij, myij, mask_index=i, has_cls=has_cls)]
43
+ n += 1
44
+ return outs
starVLA/facebookresearch_vjepa2_main/tests/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ import sys
8
+
9
+ JEPA_ROOT = os.path.dirname(os.path.dirname(__file__))
10
+ sys.path.append(JEPA_ROOT)
starVLA/facebookresearch_vjepa2_main/tests/datasets/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ import sys
8
+
9
+ JEPA_ROOT = os.path.dirname(os.path.dirname(__file__))
10
+ sys.path.append(JEPA_ROOT)
starVLA/facebookresearch_vjepa2_main/tests/datasets/test_dataloader.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import unittest
7
+
8
+ from src.datasets.utils.dataloader import ConcatIndices
9
+
10
+
11
+ class TestConcatIndices(unittest.TestCase):
12
+ def test_concat_indices(self):
13
+ sizes = [10, 20, 30, 40]
14
+ total_size = sum(sizes)
15
+ concat_indices = ConcatIndices(sizes)
16
+
17
+ # -1 is outside the total range
18
+ with self.assertRaises(ValueError):
19
+ concat_indices[-1]
20
+ # 0-9 map to dataset 0
21
+ self.assertEqual(concat_indices[0], (0, 0))
22
+ self.assertEqual(concat_indices[9], (0, 9))
23
+ # 10-29 map to dataset 1
24
+ self.assertEqual(concat_indices[10], (1, 0))
25
+ self.assertEqual(concat_indices[29], (1, 19))
26
+ # 30-59 map to dataset 2
27
+ self.assertEqual(concat_indices[30], (2, 0))
28
+ self.assertEqual(concat_indices[59], (2, 29))
29
+ # 60-99 map to dataset 3
30
+ self.assertEqual(concat_indices[60], (3, 0))
31
+ self.assertEqual(concat_indices[99], (3, 39))
32
+ # 100 is outside the total range
33
+ with self.assertRaises(ValueError):
34
+ concat_indices[total_size]
starVLA/facebookresearch_vjepa2_main/tests/datasets/test_memory_efficient_sampler.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import unittest
7
+
8
+ from src.datasets.utils.weighted_sampler import (
9
+ MemoryEfficientDistributedWeightedSampler,
10
+ MemoryEfficientDistributedWeightedSamplerLessRepeat,
11
+ )
12
+
13
+
14
+ class MockDataset:
15
+ def __init__(self, datasets, dataset_weights):
16
+ self.datasets = datasets
17
+ self.dataset_weights = dataset_weights
18
+
19
+ def __len__(self):
20
+ return sum(len(d) for d in self.datasets)
21
+
22
+
23
+ class TestMemoryEfficientSampler(unittest.TestCase):
24
+
25
+ def test_shuffled_sampling_single(self):
26
+ "The specific values returned are a function of the random sampler with the given seed."
27
+ datasets = []
28
+ for i in range(3):
29
+ datasets.append([f"DS{i}"] * 100 * (i + 1))
30
+
31
+ mock_dataset = MockDataset(datasets, [1, 1, 1])
32
+ sampler = MemoryEfficientDistributedWeightedSampler(mock_dataset, num_replicas=1, rank=0, shuffle=True)
33
+
34
+ smplr_it = iter(sampler)
35
+
36
+ ex = next(smplr_it)
37
+ self.assertIsNotNone(ex)
38
+ self.assertEqual(ex, 202) # Based on previous run
39
+
40
+ ex = next(smplr_it)
41
+ self.assertIsNotNone(ex)
42
+ self.assertEqual(ex, 26) # Based on previous run
43
+
44
+ def test_shuffled_sampling(self):
45
+ datasets = []
46
+ for i in range(3):
47
+ datasets.append([f"DS{i}"] * 100 * (i + 1))
48
+
49
+ mock_dataset = MockDataset(datasets, [1, 2000, 1])
50
+ sampler = MemoryEfficientDistributedWeightedSampler(mock_dataset, num_replicas=8, rank=3, shuffle=True)
51
+
52
+ smplr_it = iter(sampler)
53
+
54
+ # Notice how the following samples are drawn from the 2nd dataset, which has a weight of 2000.
55
+ ex = next(smplr_it)
56
+ self.assertIsNotNone(ex)
57
+ self.assertEqual(ex, 135) # Based on previous run
58
+
59
+ ex = next(smplr_it)
60
+ self.assertIsNotNone(ex)
61
+ self.assertEqual(ex, 143) # Based on previous run
62
+
63
+ def test_non_shuffled_sampling(self):
64
+ datasets = []
65
+ for i in range(3):
66
+ datasets.append([f"DS{i}"] * 100 * (i + 1))
67
+
68
+ mock_dataset = MockDataset(datasets, [1, 10, 1])
69
+ sampler = MemoryEfficientDistributedWeightedSampler(mock_dataset, num_replicas=4, rank=2, shuffle=False)
70
+
71
+ smplr_it = iter(sampler)
72
+
73
+ ex = next(smplr_it)
74
+ self.assertIsNotNone(ex)
75
+ self.assertEqual(ex, 102) # Calculated based on the `__next__` function's non shuffled logic.
76
+
77
+ ex = next(smplr_it)
78
+ self.assertIsNotNone(ex)
79
+ self.assertEqual(ex, 106) # Calculated based on the `__next__` function's non shuffled logic.
80
+
81
+
82
+ class TestMemoryEfficientSamplerLessRepeat(unittest.TestCase):
83
+
84
+ def test_shuffled_sampling_single(self):
85
+ """
86
+ Testing all weights are equal to 1.
87
+ The specific values returned are a function of the random sampler with the given seed.
88
+ """
89
+ datasets = []
90
+ for i in range(3):
91
+ datasets.append([f"DS{i}"] * 100 * (i + 1))
92
+
93
+ mock_dataset = MockDataset(datasets, [1, 1, 1])
94
+ sampler = MemoryEfficientDistributedWeightedSamplerLessRepeat(
95
+ mock_dataset, num_replicas=1, rank=0, shuffle=True
96
+ )
97
+
98
+ smplr_it = iter(sampler)
99
+
100
+ ex = next(smplr_it)
101
+ self.assertIsNotNone(ex)
102
+ self.assertEqual(ex, 144) # Based on previous run
103
+
104
+ ex = next(smplr_it)
105
+ self.assertIsNotNone(ex)
106
+ self.assertEqual(ex, 84) # Based on previous run
107
+
108
+ def test_shuffled_sampling(self):
109
+ """
110
+ Testing one dominant dataset.
111
+ The specific values returned are a function of the random sampler with the given seed.
112
+ """
113
+ datasets = []
114
+ for i in range(3):
115
+ datasets.append([f"DS{i}"] * 100 * (i + 1))
116
+
117
+ mock_dataset = MockDataset(datasets, [1, 2000, 1])
118
+ sampler = MemoryEfficientDistributedWeightedSamplerLessRepeat(
119
+ mock_dataset, num_replicas=8, rank=3, shuffle=True
120
+ )
121
+
122
+ smplr_it = iter(sampler)
123
+
124
+ # Notice how the following samples are drawn from the 2nd dataset, which has a weight of 2000.
125
+ ex = next(smplr_it)
126
+ self.assertIsNotNone(ex)
127
+ self.assertEqual(ex, 255) # Based on previous run
128
+
129
+ ex = next(smplr_it)
130
+ self.assertIsNotNone(ex)
131
+ self.assertEqual(ex, 231) # Based on previous run
132
+
133
+ def test_non_shuffled_sampling(self):
134
+ datasets = []
135
+ for i in range(3):
136
+ datasets.append([f"DS{i}"] * 100 * (i + 1))
137
+
138
+ mock_dataset = MockDataset(datasets, [1, 10, 1])
139
+ sampler = MemoryEfficientDistributedWeightedSamplerLessRepeat(
140
+ mock_dataset, num_replicas=4, rank=2, shuffle=False
141
+ )
142
+
143
+ smplr_it = iter(sampler)
144
+
145
+ ex = next(smplr_it)
146
+ self.assertIsNotNone(ex)
147
+ self.assertEqual(ex, 102) # Calculated based on the `__next__` function's non shuffled logic.
148
+
149
+ ex = next(smplr_it)
150
+ self.assertIsNotNone(ex)
151
+ self.assertEqual(ex, 106) # Calculated based on the `__next__` function's non shuffled logic.
starVLA/facebookresearch_vjepa2_main/tests/datasets/test_vjepa_transforms.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import unittest
7
+
8
+ import numpy as np
9
+ import torch
10
+
11
+ from app.vjepa import transforms
12
+ from src.datasets.utils.video import functional
13
+ from src.datasets.utils.video.volume_transforms import ClipToTensor
14
+
15
+
16
+ class TestNormalize(unittest.TestCase):
17
+
18
+ def setUp(self):
19
+ self.g = torch.Generator()
20
+ self.g.manual_seed(42)
21
+
22
+ def test_approximation_equivalence(self):
23
+ T, H, W, C = 16, 224, 224, 3
24
+ shape = (T, H, W, C)
25
+ mean = torch.tensor([0.485, 0.456, 0.406])
26
+ std = torch.tensor([0.229, 0.224, 0.225])
27
+ for i in range(10):
28
+ X = torch.randint(low=0, high=255, size=shape, generator=self.g, dtype=torch.uint8)
29
+ X_clone = X.clone().permute(3, 0, 1, 2) # C, T, H, W
30
+
31
+ X_norm = transforms.tensor_normalize(X, mean, std)
32
+ X_norm_fast = transforms._tensor_normalize_inplace(X_clone, 255.0 * mean, 255.0 * std)
33
+ self.assertTrue(torch.allclose(X_norm, X_norm_fast.permute(1, 2, 3, 0)))
34
+
35
+
36
+ class TestVideoTransformFunctionalCrop(unittest.TestCase):
37
+ def test_tensor_numpy(self):
38
+ T, C, H, W = 16, 3, 280, 320
39
+ shape = (T, C, H, W)
40
+ crop_size = (10, 10, 224, 224)
41
+ video_tensor = torch.randint(low=0, high=255, size=shape, dtype=torch.uint8)
42
+ video_numpy = video_tensor.numpy()
43
+
44
+ cropped_tensor = functional.crop_clip(video_tensor, *crop_size)
45
+ self.assertIsInstance(cropped_tensor[0], torch.Tensor)
46
+
47
+ cropped_np_array = functional.crop_clip(video_numpy, *crop_size)
48
+ self.assertIsInstance(cropped_np_array[0], np.ndarray)
49
+
50
+ for clip_tensor, clip_np in zip(cropped_tensor, cropped_np_array):
51
+ torch.testing.assert_close(clip_tensor, torch.Tensor(clip_np).to(dtype=torch.uint8))
52
+
53
+
54
+ class TestVideoTransformFunctionalResize(unittest.TestCase):
55
+ def test_tensor_numpy(self):
56
+ T, C, H, W = 16, 3, 280, 320
57
+ shape = (T, C, H, W)
58
+ resize_to = 256
59
+
60
+ video_tensor = torch.randint(low=0, high=255, size=shape, dtype=torch.int16)
61
+ # We permute the videos because our underlying numpy.array based transforms are expecting
62
+ # image in (H, W, C) shape whereas our tensor transforms are mostly in (C, H, W)
63
+ video_numpy = video_tensor.permute(0, 2, 3, 1).numpy() # (T, C, H, W) -> (T, H, W, C)
64
+
65
+ resized_tensor = functional.resize_clip(video_tensor, resize_to)
66
+ self.assertIsInstance(resized_tensor[0], torch.Tensor)
67
+
68
+ resized_np_array = functional.resize_clip(video_numpy, resize_to)
69
+ self.assertIsInstance(resized_np_array[0], np.ndarray)
70
+
71
+ for clip_tensor, clip_np in zip(resized_tensor, resized_np_array):
72
+ clip_tensor = clip_tensor.permute(1, 2, 0)
73
+ diff = torch.mean((torch.abs(clip_tensor - torch.Tensor(clip_np).to(torch.int16))) / (clip_tensor + 1))
74
+
75
+ # Transformations can not exactly match because of their interpolation functions coming from
76
+ # two different sources. Here we check for their relative differences.
77
+ # See the discussion here: https://github.com/fairinternal/jepa-internal/pull/65#issuecomment-2101833959
78
+ self.assertLess(diff, 0.05)
79
+
80
+
81
+ class TestVideoTransformClipToTensor(unittest.TestCase):
82
+ def test_tensor_numpy(self):
83
+ T, C, H, W = 16, 3, 280, 320
84
+ shape = (T, C, H, W)
85
+ transform = ClipToTensor()
86
+
87
+ video_tensor = [clip for clip in torch.randint(low=0, high=255, size=shape, dtype=torch.int16)]
88
+ # We permute the videos because our underlying numpy.array based transforms are expecting
89
+ # image in (H, W, C) shape whereas our tensor transforms are mostly in (C, H, W)
90
+ video_numpy = [clip.permute(1, 2, 0).numpy() for clip in video_tensor]
91
+ torch.testing.assert_close(transform(video_tensor), transform(video_numpy))
starVLA/facebookresearch_vjepa2_main/tests/models/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ import sys
8
+
9
+ JEPA_ROOT = os.path.dirname(os.path.dirname(__file__))
10
+ sys.path.append(JEPA_ROOT)
starVLA/facebookresearch_vjepa2_main/tests/models/test_models.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import unittest
7
+
8
+ import torch
9
+
10
+ from src.models.vision_transformer import VIT_EMBED_DIMS, vit_tiny
11
+
12
+
13
+ class TestImageViT(unittest.TestCase):
14
+ def setUp(self) -> None:
15
+ self._vit_tiny = vit_tiny()
16
+ self.height, self.width = 224, 224
17
+ self.num_patches = (self.height // self._vit_tiny.patch_size) * (self.width // self._vit_tiny.patch_size)
18
+
19
+ def test_model_image_nomask_batchsize_4(self):
20
+ BS = 4
21
+ x = torch.rand((BS, 3, self.height, self.width))
22
+ y = self._vit_tiny(x)
23
+ self.assertIsInstance(y, torch.Tensor)
24
+ self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"]))
25
+
26
+ def test_model_image_nomask_batchsize_1(self):
27
+ BS = 1
28
+ x = torch.rand((BS, 3, self.height, self.width))
29
+ y = self._vit_tiny(x)
30
+ self.assertIsInstance(y, torch.Tensor)
31
+ self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"]))
32
+
33
+ def test_model_image_masked_batchsize_4(self):
34
+ BS = 4
35
+ mask_indices = [6, 7, 8]
36
+ masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)]
37
+ x = torch.rand((BS, 3, self.height, self.width))
38
+ y = self._vit_tiny(x, masks=masks)
39
+ self.assertIsInstance(y, torch.Tensor)
40
+ self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"]))
41
+
42
+ def test_model_image_masked_batchsize_1(self):
43
+ BS = 1
44
+ mask_indices = [6, 7, 8]
45
+ masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)]
46
+ x = torch.rand((BS, 3, self.height, self.width))
47
+ y = self._vit_tiny(x, masks=masks)
48
+ self.assertIsInstance(y, torch.Tensor)
49
+ self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"]))
50
+
51
+
52
+ class TestVideoViT(unittest.TestCase):
53
+ def setUp(self) -> None:
54
+ self.num_frames = 8
55
+ self._vit_tiny = vit_tiny(num_frames=8)
56
+ self.height, self.width = 224, 224
57
+ self.num_patches = (
58
+ (self.height // self._vit_tiny.patch_size)
59
+ * (self.width // self._vit_tiny.patch_size)
60
+ * (self.num_frames // self._vit_tiny.tubelet_size)
61
+ )
62
+
63
+ def test_model_video_nomask_batchsize_4(self):
64
+ BS = 4
65
+ x = torch.rand((BS, 3, self.num_frames, self.height, self.width))
66
+ y = self._vit_tiny(x)
67
+ self.assertIsInstance(y, torch.Tensor)
68
+ self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"]))
69
+
70
+ def test_model_video_nomask_batchsize_1(self):
71
+ BS = 1
72
+ x = torch.rand((BS, 3, self.num_frames, self.height, self.width))
73
+ y = self._vit_tiny(x)
74
+ self.assertIsInstance(y, torch.Tensor)
75
+ self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"]))
76
+
77
+ def test_model_video_masked_batchsize_4(self):
78
+ BS = 4
79
+ mask_indices = [6, 7, 8]
80
+ masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)]
81
+ x = torch.rand((BS, 3, self.num_frames, self.height, self.width))
82
+ y = self._vit_tiny(x, masks=masks)
83
+ self.assertIsInstance(y, torch.Tensor)
84
+ self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"]))
85
+
86
+ def test_model_video_masked_batchsize_1(self):
87
+ BS = 1
88
+ mask_indices = [6, 7, 8]
89
+ masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)]
90
+ x = torch.rand((BS, 3, self.num_frames, self.height, self.width))
91
+ y = self._vit_tiny(x, masks=masks)
92
+ self.assertIsInstance(y, torch.Tensor)
93
+ self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"]))
starVLA/facebookresearch_vjepa2_main/tests/models/test_predictor.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import unittest
7
+
8
+ import torch
9
+
10
+ from src.models.predictor import VisionTransformerPredictor
11
+
12
+
13
+ class TestImagePredictorMaskTokens(unittest.TestCase):
14
+ def setUp(self) -> None:
15
+ self._embed_dim = 768
16
+ self._predictor = VisionTransformerPredictor(embed_dim=self._embed_dim, use_mask_tokens=True)
17
+
18
+ def test_image_predictor_batchsize_4(self):
19
+ BS = 4
20
+ enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)]
21
+ target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)]
22
+ enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim))
23
+ y = self._predictor(enc, enc_mask_indices, target_mask_indices)
24
+ self.assertIsInstance(y, torch.Tensor)
25
+ self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim))
26
+
27
+ def test_image_predictor_batchsize_1(self):
28
+ BS = 1
29
+ enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)]
30
+ target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)]
31
+ enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim))
32
+ y = self._predictor(enc, enc_mask_indices, target_mask_indices)
33
+ self.assertIsInstance(y, torch.Tensor)
34
+ self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim))
35
+
36
+
37
+ class TestVideoPredictorMaskTokens(unittest.TestCase):
38
+ def setUp(self) -> None:
39
+ self._embed_dim = 768
40
+ self._predictor = VisionTransformerPredictor(embed_dim=self._embed_dim, use_mask_tokens=True)
41
+
42
+ def test_video_predictor_batchsize_4(self):
43
+ BS = 4
44
+ enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)]
45
+ target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)]
46
+ enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim))
47
+ y = self._predictor(enc, enc_mask_indices, target_mask_indices)
48
+ self.assertIsInstance(y, torch.Tensor)
49
+ self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim))
50
+
51
+ def test_video_predictor_batchsize_1(self):
52
+ BS = 1
53
+ enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)]
54
+ target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)]
55
+ enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim))
56
+ y = self._predictor(enc, enc_mask_indices, target_mask_indices)
57
+ self.assertIsInstance(y, torch.Tensor)
58
+ self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim))
starVLA/facebookresearch_vjepa2_main/tests/models/test_vision_transformer.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import unittest
7
+ from copy import deepcopy
8
+
9
+ import numpy as np
10
+ import pytest
11
+ import torch
12
+
13
+ from src.models.vision_transformer import vit_giant_xformers_rope
14
+
15
+
16
+ # Usage: pytest tests/models/test_vision_transformer.py
17
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="This test requires CUDA")
18
+ class TestViTGiant(unittest.TestCase):
19
+ def setUp(self) -> None:
20
+ self.model_shape_invariant = vit_giant_xformers_rope(
21
+ img_size=256, patch_size=16, num_frames=16, handle_nonsquare_inputs=True
22
+ ).cuda()
23
+ self.model_square = deepcopy(self.model_shape_invariant)
24
+ self.model_square.handle_nonsquare_inputs = False
25
+ torch.manual_seed(42)
26
+ self.total_iters = 10
27
+
28
+ def test_square_inputs(self):
29
+ for i in range(self.total_iters):
30
+ input = torch.rand(1, 3, 16, 256, 256).cuda()
31
+ with torch.cuda.amp.autocast(enabled=True):
32
+ with torch.no_grad():
33
+ out1 = self.model_shape_invariant(input)
34
+ out2 = self.model_square(input)
35
+ torch.testing.assert_close(out1, out2)
36
+
37
+ def test_square_inputs_with_mask(self):
38
+ for i in range(self.total_iters):
39
+ input = torch.rand(1, 3, 16, 256, 256).cuda()
40
+ mask = torch.randint(0, 2, (1, 2048)).cuda()
41
+ with torch.cuda.amp.autocast(enabled=True):
42
+ with torch.no_grad():
43
+ out1 = self.model_shape_invariant(input, masks=mask)
44
+ out2 = self.model_square(input, masks=mask)
45
+ torch.testing.assert_close(out1, out2)
46
+
47
+ def test_nonsquare_inputs(self):
48
+ for i in range(self.total_iters):
49
+ rand_width = np.random.randint(256, 512)
50
+ rand_height = np.random.randint(256, 512)
51
+ input = torch.rand(1, 3, 16, rand_height, rand_width).cuda()
52
+ # Since input is interpolated, output won't be exactly the same
53
+ input_resized_to_square = [
54
+ torch.nn.functional.interpolate(input[:, :, frame_idx], size=256, mode="bicubic")
55
+ for frame_idx in range(input.shape[2])
56
+ ]
57
+ input_resized_to_square = torch.stack(input_resized_to_square, dim=2)
58
+
59
+ with torch.cuda.amp.autocast(enabled=True):
60
+ with torch.no_grad():
61
+ out1 = self.model_shape_invariant(input).mean(dim=1)
62
+ out2 = self.model_square(input_resized_to_square).mean(dim=1)
63
+ self.assertAlmostEqual(torch.nn.functional.cosine_similarity(out2, out1).item(), 1.0, places=3)
starVLA/model/framework/DreamZero.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """DreamZero Wan2.2 policy framework for starVLA.
4
+
5
+ This is a starVLA-native DreamZero model file. It uses the existing
6
+ Wan2.2-TI2V-5B-Diffusers world model in ``starVLA.model.modules.world_model.Wan2``
7
+ and trains joint action/future-image latent flow targets, so it does not depend
8
+ on the official DreamZero training stack, Hydra, GrootSimPolicy, or PEFT.
9
+ """
10
+
11
+ import math
12
+ import os
13
+ from dataclasses import dataclass, field
14
+ from typing import List, Optional
15
+
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn.functional as F
19
+
20
+ from deployment.model_server.tools.image_tools import to_pil_preserve
21
+ from starVLA.model.framework.base_framework import baseframework
22
+ from starVLA.model.framework.share_tools import merge_framework_config
23
+ from starVLA.model.modules.world_model import get_world_model
24
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
25
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
26
+
27
+
28
+ @dataclass
29
+ class DreamZeroDefaultConfig:
30
+ """Wan2.2 DreamZero-style action/video policy defaults."""
31
+
32
+ name: str = "DreamZero"
33
+
34
+ world_model: dict = field(default_factory=lambda: {
35
+ "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers",
36
+ "extract_layers": [-1],
37
+ "height": 224,
38
+ "width": 224,
39
+ })
40
+
41
+ qwenvl: dict = field(default_factory=lambda: {
42
+ "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers",
43
+ "vl_hidden_dim": 3072,
44
+ })
45
+
46
+ action_model: dict = field(default_factory=lambda: {
47
+ "action_dim": 32,
48
+ "state_dim": 64,
49
+ "future_action_window_size": 15,
50
+ "action_horizon": 16,
51
+ "past_action_window_size": 0,
52
+ })
53
+
54
+ policy: dict = field(default_factory=lambda: {
55
+ "train_time_distribution": "logitnormal",
56
+ "shift": 5.0,
57
+ "action_loss_weight": 1.0,
58
+ "future_image_loss_weight": 1.0,
59
+ "num_inference_steps": 5,
60
+ "timestep_scale": 1000.0,
61
+ "decode_future_images": True,
62
+ "autoregressive": True,
63
+ "latent_clip_value": 30.0,
64
+ "prediction_clip_value": 30.0,
65
+ })
66
+
67
+ obs_image_size: Optional[list] = None
68
+
69
+
70
+ @FRAMEWORK_REGISTRY.register("DreamZero")
71
+ class DreamZero(baseframework):
72
+ """Wan2.2 latent action and future-image flow-matching policy."""
73
+
74
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
75
+ super().__init__()
76
+ self.config = merge_framework_config(DreamZeroDefaultConfig, config)
77
+ self.backbone = get_world_model(config=self.config)
78
+ self._disable_backbone_feature_hooks()
79
+
80
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
81
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
82
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
83
+ self.action_dim = self.config.framework.action_model.action_dim
84
+
85
+ policy_cfg = self.config.framework.get("policy", {})
86
+ self.train_time_distribution = policy_cfg.get("train_time_distribution", "logitnormal")
87
+ self.shift = float(policy_cfg.get("shift", 5.0))
88
+ self.action_loss_weight = float(policy_cfg.get("action_loss_weight", 1.0))
89
+ self.future_image_loss_weight = float(policy_cfg.get("future_image_loss_weight", 1.0))
90
+ self.num_inference_steps = int(policy_cfg.get("num_inference_steps", 5))
91
+ self.timestep_scale = float(policy_cfg.get("timestep_scale", 1000.0))
92
+ self.decode_future_images = self._as_bool(policy_cfg.get("decode_future_images", True))
93
+ self.autoregressive = self._as_bool(policy_cfg.get("autoregressive", True))
94
+ self.latent_clip_value = float(policy_cfg.get("latent_clip_value", 30.0))
95
+ self.prediction_clip_value = float(policy_cfg.get("prediction_clip_value", 30.0))
96
+ self._wm_debug_count = 0
97
+
98
+ @staticmethod
99
+ def _as_bool(value) -> bool:
100
+ if isinstance(value, str):
101
+ return value.lower() in {"1", "true", "yes", "on"}
102
+ return bool(value)
103
+
104
+ def _disable_backbone_feature_hooks(self) -> None:
105
+ for hook in getattr(self.backbone, "_hooks", []):
106
+ hook.remove()
107
+ if hasattr(self.backbone, "_hooks"):
108
+ self.backbone._hooks.clear()
109
+ if hasattr(self.backbone, "_intermediate_features"):
110
+ self.backbone._intermediate_features.clear()
111
+
112
+ def _begin_wm_debug_trace(self) -> bool:
113
+ if os.getenv("STARVLA_WM_DEBUG", "0").lower() not in {"1", "true", "yes", "on"}:
114
+ return False
115
+ max_traces = int(os.getenv("STARVLA_WM_DEBUG_MAX", "6"))
116
+ if self._wm_debug_count >= max_traces:
117
+ return False
118
+ self._wm_debug_count += 1
119
+ return True
120
+
121
+ @staticmethod
122
+ def _tensor_stats(name: str, tensor: torch.Tensor) -> str:
123
+ tensor = tensor.detach().float()
124
+ return (
125
+ f"{name}:shape={tuple(tensor.shape)},"
126
+ f"mean={tensor.mean().item():.4g},std={tensor.std(unbiased=False).item():.4g},"
127
+ f"min={tensor.min().item():.4g},max={tensor.max().item():.4g},"
128
+ f"nan={torch.isnan(tensor).any().item()},inf={torch.isinf(tensor).any().item()}"
129
+ )
130
+
131
+ def _log_wm_debug(self, enabled: bool, label: str, **tensors) -> None:
132
+ if not enabled:
133
+ return
134
+ parts = [f"[WM_DEBUG_VERSION=DreamZeroWan2Native] {type(self).__name__} {label}"]
135
+ for name, tensor in tensors.items():
136
+ if tensor is not None:
137
+ parts.append(self._tensor_stats(name, tensor))
138
+ print(" | ".join(parts), flush=True)
139
+
140
+ @staticmethod
141
+ def _sanitize_tensor(tensor: torch.Tensor, clip_value: Optional[float] = None) -> torch.Tensor:
142
+ tensor = torch.nan_to_num(tensor, nan=0.0, posinf=0.0, neginf=0.0)
143
+ if clip_value is not None and clip_value > 0:
144
+ tensor = tensor.clamp(min=-clip_value, max=clip_value)
145
+ return tensor
146
+
147
+ def _select_action_chunk(self, actions) -> torch.Tensor:
148
+ actions = torch.tensor(np.array(actions), dtype=torch.float32)
149
+ return actions[:, -(self.future_action_window_size + 1):, :]
150
+
151
+ @staticmethod
152
+ def _latent_slot_count(latents: torch.Tensor) -> int:
153
+ _, channels, _, height, width = latents.shape
154
+ return channels * height * width
155
+
156
+ def _tensor_to_latent_frame(self, values: torch.Tensor, latents: torch.Tensor) -> torch.Tensor:
157
+ batch_size, channels, _, height, width = latents.shape
158
+ flat_values = values.reshape(batch_size, -1).to(device=latents.device, dtype=latents.dtype)
159
+ slot_count = self._latent_slot_count(latents)
160
+ repeat_factor = math.ceil(slot_count / flat_values.shape[1])
161
+ tiled_values = flat_values.repeat(1, repeat_factor)[:, :slot_count]
162
+ return tiled_values.reshape(batch_size, channels, height, width)
163
+
164
+ def _actions_to_latent_frame(self, actions: torch.Tensor, latents: torch.Tensor) -> torch.Tensor:
165
+ return self._tensor_to_latent_frame(actions, latents)
166
+
167
+ def _latent_frame_to_actions(self, action_frame: torch.Tensor, action_shape) -> torch.Tensor:
168
+ batch_size = action_frame.shape[0]
169
+ flat_dim = int(np.prod(action_shape[1:]))
170
+ flat_frame = action_frame.reshape(batch_size, -1)
171
+ slot_count = flat_frame.shape[1]
172
+ action_indices = torch.arange(slot_count, device=flat_frame.device) % flat_dim
173
+
174
+ action_sum = flat_frame.new_zeros((batch_size, flat_dim))
175
+ action_count = flat_frame.new_zeros((batch_size, flat_dim))
176
+ expanded_indices = action_indices.expand(batch_size, -1)
177
+ action_sum.scatter_add_(1, expanded_indices, flat_frame)
178
+ action_count.scatter_add_(1, expanded_indices, torch.ones_like(flat_frame))
179
+ return (action_sum / action_count.clamp_min(1.0)).reshape(batch_size, *action_shape[1:])
180
+
181
+ def _sample_train_times(self, batch_size: int, device: torch.device) -> torch.Tensor:
182
+ distribution = str(self.train_time_distribution).lower()
183
+ if distribution == "logitnormal":
184
+ return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32))
185
+ if distribution == "uniform":
186
+ return torch.rand(batch_size, device=device, dtype=torch.float32)
187
+ raise ValueError(f"Unsupported train_time_distribution={self.train_time_distribution!r}")
188
+
189
+ def _shift_time(self, time: torch.Tensor, shift: Optional[float] = None) -> torch.Tensor:
190
+ shift = self.shift if shift is None else float(shift)
191
+ return shift * time / (1.0 + (shift - 1.0) * time)
192
+
193
+ def _flow_inference_schedule(self, num_steps: int, device: torch.device, shift: Optional[float] = None):
194
+ base_times = torch.linspace(1.0, 0.0, num_steps + 1, device=device, dtype=torch.float32)
195
+ return self._shift_time(base_times, shift=shift)
196
+
197
+ def _make_wan_timestep(
198
+ self,
199
+ hidden_states: torch.Tensor,
200
+ target_indices: List[int],
201
+ timestep: torch.Tensor,
202
+ ) -> torch.Tensor:
203
+ batch_size, _, num_latent_frames, height, width = hidden_states.shape
204
+ p_t, p_h, p_w = self.backbone.transformer.config.patch_size
205
+ frame_token_count = (height // p_h) * (width // p_w)
206
+ temporal_token_count = num_latent_frames // p_t
207
+ seq_len = temporal_token_count * frame_token_count
208
+ rope_max_seq_len = getattr(self.backbone.transformer.config, "rope_max_seq_len", None)
209
+ if rope_max_seq_len is not None and seq_len > rope_max_seq_len:
210
+ raise ValueError(
211
+ f"DreamZero Wan policy seq_len={seq_len} exceeds rope_max_seq_len={rope_max_seq_len}. "
212
+ "Reduce observation frames/resolution or disable optional future-image targets."
213
+ )
214
+
215
+ timestep_tokens = torch.zeros(
216
+ batch_size,
217
+ seq_len,
218
+ device=hidden_states.device,
219
+ dtype=torch.float32,
220
+ )
221
+ timestep = timestep.to(device=hidden_states.device, dtype=torch.float32) * self.timestep_scale
222
+ for target_idx in target_indices:
223
+ temporal_idx = int(target_idx) // p_t
224
+ start = temporal_idx * frame_token_count
225
+ end = start + frame_token_count
226
+ timestep_tokens[:, start:end] = timestep[:, None]
227
+ return timestep_tokens
228
+
229
+ def _make_policy_inputs(
230
+ self,
231
+ wm_inputs: dict,
232
+ target_frames: List[torch.Tensor],
233
+ timestep: torch.Tensor,
234
+ context_frames: Optional[List[torch.Tensor]] = None,
235
+ ):
236
+ condition_latents = wm_inputs["hidden_states"]
237
+ context_frames = context_frames or []
238
+ hidden_states = torch.cat(
239
+ [
240
+ condition_latents,
241
+ *[frame.unsqueeze(2).to(condition_latents.dtype) for frame in context_frames],
242
+ *[frame.unsqueeze(2).to(condition_latents.dtype) for frame in target_frames],
243
+ ],
244
+ dim=2,
245
+ )
246
+ condition_t = condition_latents.shape[2] + len(context_frames)
247
+ target_indices = list(range(condition_t, condition_t + len(target_frames)))
248
+ timestep_tokens = self._make_wan_timestep(hidden_states, target_indices=target_indices, timestep=timestep)
249
+ return {
250
+ "hidden_states": hidden_states,
251
+ "timestep": timestep_tokens,
252
+ "encoder_hidden_states": wm_inputs["encoder_hidden_states"],
253
+ "target_indices": target_indices,
254
+ }
255
+
256
+ def _run_transformer(self, policy_inputs: dict) -> torch.Tensor:
257
+ if hasattr(self.backbone, "_intermediate_features"):
258
+ self.backbone._intermediate_features.clear()
259
+ with torch.autocast("cuda", dtype=torch.bfloat16):
260
+ output = self.backbone.transformer(
261
+ hidden_states=policy_inputs["hidden_states"],
262
+ timestep=policy_inputs["timestep"],
263
+ encoder_hidden_states=policy_inputs["encoder_hidden_states"],
264
+ )
265
+ pred = output.sample if hasattr(output, "sample") else output
266
+ if isinstance(pred, tuple):
267
+ pred = pred[0]
268
+ pred = self._sanitize_tensor(pred, clip_value=self.prediction_clip_value)
269
+ if hasattr(self.backbone, "_intermediate_features"):
270
+ self.backbone._intermediate_features.clear()
271
+ return pred[:, :, policy_inputs["target_indices"]].float()
272
+
273
+ def _predict_velocity(
274
+ self,
275
+ wm_inputs: dict,
276
+ target_frames: List[torch.Tensor],
277
+ timestep: torch.Tensor,
278
+ context_frames: Optional[List[torch.Tensor]] = None,
279
+ ) -> torch.Tensor:
280
+ policy_inputs = self._make_policy_inputs(
281
+ wm_inputs=wm_inputs,
282
+ target_frames=target_frames,
283
+ timestep=timestep,
284
+ context_frames=context_frames,
285
+ )
286
+ return self._run_transformer(policy_inputs)
287
+
288
+ def _predict_velocity_autoregressive(
289
+ self,
290
+ wm_inputs: dict,
291
+ sample_frames: List[torch.Tensor],
292
+ timestep: torch.Tensor,
293
+ teacher_context_frames: Optional[List[torch.Tensor]] = None,
294
+ ) -> torch.Tensor:
295
+ pred_frames = []
296
+ context_frames = list(teacher_context_frames or [])
297
+ for frame_idx, sample_frame in enumerate(sample_frames):
298
+ pred_frame = self._predict_velocity(
299
+ wm_inputs=wm_inputs,
300
+ target_frames=[sample_frame],
301
+ timestep=timestep,
302
+ context_frames=context_frames,
303
+ )[:, :, 0]
304
+ pred_frames.append(pred_frame)
305
+ context_frames.append(sample_frame.detach())
306
+ return torch.stack(pred_frames, dim=2)
307
+
308
+ def _encode_future_image_frame(self, future_images: List, like_latents: torch.Tensor) -> Optional[torch.Tensor]:
309
+ if future_images is None or self.future_image_loss_weight <= 0:
310
+ return None
311
+ future_latents = self.backbone._encode_images_vae(future_images, num_frames=1).float()
312
+ future_frame = future_latents[:, :, 0].to(device=like_latents.device, dtype=like_latents.dtype)
313
+ return self._sanitize_tensor(future_frame, clip_value=self.latent_clip_value)
314
+
315
+ def _decode_latent_frames(self, latent_frames: torch.Tensor) -> List[np.ndarray]:
316
+ latent_video = latent_frames.to(device=latent_frames.device, dtype=self.backbone.vae.dtype)
317
+
318
+ if getattr(self.backbone.vae.config, "latents_mean", None) is not None:
319
+ latents_mean = (
320
+ torch.tensor(self.backbone.vae.config.latents_mean)
321
+ .view(1, self.backbone.vae.config.z_dim, 1, 1, 1)
322
+ .to(device=latent_video.device, dtype=latent_video.dtype)
323
+ )
324
+ latents_std = (
325
+ torch.tensor(self.backbone.vae.config.latents_std)
326
+ .view(1, self.backbone.vae.config.z_dim, 1, 1, 1)
327
+ .to(device=latent_video.device, dtype=latent_video.dtype)
328
+ )
329
+ latent_video = latent_video * latents_std + latents_mean
330
+
331
+ with torch.no_grad():
332
+ decoded = self.backbone.vae.decode(latent_video).sample
333
+
334
+ decoded = decoded.float().clamp(-1, 1)
335
+ decoded = ((decoded + 1.0) * 127.5).clamp(0, 255).byte()
336
+ decoded = decoded.permute(0, 2, 3, 4, 1).detach().cpu().numpy()
337
+ images = []
338
+ for sample in decoded:
339
+ frames = [sample[idx] for idx in range(sample.shape[0])]
340
+ images.append(frames[0] if len(frames) == 1 else np.concatenate(frames, axis=1))
341
+ return images
342
+
343
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
344
+ batch_images = [example["image"] for example in examples]
345
+ future_images = [example["future_image"] for example in examples] if "future_image" in examples[0] else None
346
+ instructions = [example["lang"] for example in examples]
347
+ actions = self._select_action_chunk([example["action"] for example in examples])
348
+
349
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
350
+ latents = wm_inputs["hidden_states"]
351
+ latents = self._sanitize_tensor(latents, clip_value=self.latent_clip_value)
352
+ wm_inputs["hidden_states"] = latents
353
+ actions = self._sanitize_tensor(actions.to(device=latents.device, dtype=torch.float32), clip_value=1.0)
354
+ target_action_frame = self._actions_to_latent_frame(actions, latents).float()
355
+ target_action_frame = self._sanitize_tensor(target_action_frame, clip_value=self.latent_clip_value)
356
+
357
+ target_frames = [target_action_frame.to(latents.dtype)]
358
+ future_frame = self._encode_future_image_frame(future_images, like_latents=latents)
359
+ if future_frame is not None:
360
+ target_frames.append(future_frame)
361
+
362
+ batch_size = latents.shape[0]
363
+ train_time = self._sample_train_times(batch_size, latents.device)
364
+ flow_time = self._shift_time(train_time)
365
+ time_view = flow_time.view(batch_size, 1, 1, 1).to(device=latents.device, dtype=latents.dtype)
366
+
367
+ noises = [torch.randn_like(target_frame).to(latents.dtype) for target_frame in target_frames]
368
+ sample_frames = [
369
+ self._sanitize_tensor(noise * time_view + target_frame * (1.0 - time_view), clip_value=self.latent_clip_value)
370
+ for target_frame, noise in zip(target_frames, noises)
371
+ ]
372
+ target_velocities = [
373
+ self._sanitize_tensor(noise.float() - target_frame.float(), clip_value=self.latent_clip_value)
374
+ for target_frame, noise in zip(target_frames, noises)
375
+ ]
376
+
377
+ if self.autoregressive:
378
+ pred_frames = self._predict_velocity_autoregressive(
379
+ wm_inputs=wm_inputs,
380
+ sample_frames=sample_frames,
381
+ timestep=flow_time,
382
+ )
383
+ else:
384
+ pred_frames = self._predict_velocity(wm_inputs=wm_inputs, target_frames=sample_frames, timestep=flow_time)
385
+ pred_frames = self._sanitize_tensor(pred_frames, clip_value=self.prediction_clip_value)
386
+ pred_action_frame = pred_frames[:, :, 0]
387
+
388
+ action_loss = F.mse_loss(pred_action_frame, target_velocities[0], reduction="none")
389
+ action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None
390
+ if action_mask is not None:
391
+ action_mask = torch.tensor(np.array(action_mask), device=latents.device, dtype=torch.float32)
392
+ action_mask = action_mask[:, -(self.future_action_window_size + 1):, :]
393
+ latent_mask = self._actions_to_latent_frame(action_mask, latents).float().clamp(0.0, 1.0)
394
+ action_loss_scalar = (action_loss * latent_mask).sum() / latent_mask.sum().clamp_min(1.0)
395
+ else:
396
+ action_loss_scalar = action_loss.mean()
397
+
398
+ total_loss = action_loss_scalar * self.action_loss_weight
399
+ output = {
400
+ "action_loss": total_loss,
401
+ "demo_sample_action_mse_loss": action_loss_scalar.detach(),
402
+ }
403
+
404
+ if future_frame is not None:
405
+ pred_future_frame = pred_frames[:, :, 1]
406
+ future_loss = F.mse_loss(pred_future_frame, target_velocities[1], reduction="mean")
407
+ total_loss = total_loss + future_loss * self.future_image_loss_weight
408
+ output["action_loss"] = total_loss
409
+ output["future_image_loss"] = future_loss.detach()
410
+
411
+ return output
412
+
413
+ @torch.inference_mode()
414
+ def predict_action(self, examples: List[dict], **kwargs) -> dict:
415
+ if type(examples) is not list:
416
+ examples = [examples]
417
+
418
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
419
+ instructions = [example["lang"] for example in examples]
420
+
421
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
422
+ if train_obs_image_size:
423
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
424
+
425
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
426
+ latents = wm_inputs["hidden_states"]
427
+ latents = self._sanitize_tensor(latents, clip_value=self.latent_clip_value)
428
+ wm_inputs["hidden_states"] = latents
429
+ batch_size, channels, _, height, width = latents.shape
430
+ action_shape = (batch_size, self.future_action_window_size + 1, self.action_dim)
431
+
432
+ num_inference_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps))
433
+ num_inference_steps = max(num_inference_steps, 1)
434
+ shift = float(kwargs.get("shift", self.shift))
435
+ debug_trace = self._begin_wm_debug_trace()
436
+ self._log_wm_debug(
437
+ debug_trace,
438
+ f"start requested_num_inference_steps={num_inference_steps} parameterization=rectified_flow shift={shift:g}",
439
+ obs_latents=latents,
440
+ )
441
+
442
+ decode_future_images = self._as_bool(kwargs.get("decode_future_images", self.decode_future_images))
443
+ action_frame = torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype)
444
+ future_frame = (
445
+ torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype)
446
+ if decode_future_images
447
+ else None
448
+ )
449
+
450
+ sigmas = self._flow_inference_schedule(num_inference_steps, latents.device, shift=shift)
451
+ for step_idx in range(num_inference_steps):
452
+ timestep = sigmas[step_idx].expand(batch_size)
453
+ sigma = sigmas[step_idx]
454
+ next_sigma = sigmas[step_idx + 1]
455
+ pred_action = self._predict_velocity(
456
+ wm_inputs=wm_inputs,
457
+ target_frames=[action_frame],
458
+ timestep=timestep,
459
+ )[:, :, 0]
460
+ pred_action = self._sanitize_tensor(pred_action, clip_value=self.prediction_clip_value)
461
+
462
+ pred_future = None
463
+ if decode_future_images and future_frame is not None:
464
+ pred_future = self._predict_velocity(
465
+ wm_inputs=wm_inputs,
466
+ target_frames=[future_frame],
467
+ timestep=timestep,
468
+ context_frames=[action_frame],
469
+ )[:, :, 0]
470
+ pred_future = self._sanitize_tensor(pred_future, clip_value=self.prediction_clip_value)
471
+
472
+ self._log_wm_debug(
473
+ debug_trace,
474
+ f"step={step_idx} sigma={sigma.item():.4g}->{next_sigma.item():.4g}",
475
+ sample_action_before=action_frame,
476
+ pred_action_velocity=pred_action,
477
+ pred_future_velocity=pred_future,
478
+ )
479
+ dt = (next_sigma - sigma).to(device=latents.device, dtype=latents.dtype)
480
+ action_frame = self._sanitize_tensor(
481
+ action_frame + dt * pred_action.to(dtype=latents.dtype),
482
+ clip_value=self.latent_clip_value,
483
+ )
484
+ if pred_future is not None and future_frame is not None:
485
+ future_frame = self._sanitize_tensor(
486
+ future_frame + dt * pred_future.to(dtype=latents.dtype),
487
+ clip_value=self.latent_clip_value,
488
+ )
489
+ pred_action_frame = action_frame.float()
490
+ pred_actions = self._latent_frame_to_actions(pred_action_frame, action_shape)
491
+ self._log_wm_debug(debug_trace, "final_action", pred_action_frame=pred_action_frame, pred_actions=pred_actions)
492
+
493
+ output = {"normalized_actions": pred_actions.detach().cpu().numpy()}
494
+ if decode_future_images and future_frame is not None:
495
+ output["pred_future_images"] = self._decode_latent_frames(future_frame.float().unsqueeze(2))
496
+ return output
starVLA/model/framework/M1.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 InternVLA-M1. All rights reserved.
2
+ # Modified by [Jinhui YE/ HKUST University] in [2025].
3
+ # Modification: [add fake sample and predict_action to match with starVLA].
4
+ """
5
+ InternVLA M1 framework:
6
+ Vision-Language-Action diffusion model integrating:
7
+ - Qwen2.5 vision-language backbone
8
+ - Layer-wise QFormer aggregation
9
+ - DINO multi-view visual encoder
10
+ - DiT diffusion head for future action sequence prediction
11
+ Primary goal: predict continuous future actions conditioned on multi-view images + instruction.
12
+ """
13
+
14
+ from typing import List
15
+ from tqdm import tqdm
16
+ from typing import List, Optional, Tuple
17
+ import torch
18
+ import torch.nn as nn
19
+ import numpy as np
20
+ from PIL import Image
21
+ from qwen_vl_utils import process_vision_info
22
+
23
+
24
+ from starVLA.training.trainer_utils import initialize_overwatch
25
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
26
+
27
+
28
+ logger = initialize_overwatch(__name__)
29
+
30
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
31
+ IGNORE_INDEX = -100
32
+
33
+ from starVLA.model.framework.base_framework import baseframework
34
+ from starVLA.model.modules.vlm import get_vlm_model
35
+ from starVLA.model.modules.projector.QFormer import get_layerwise_qformer
36
+ from starVLA.model.modules.action_model.DiTActionHeader import get_action_model
37
+ from starVLA.model.modules.dino_model.dino import get_dino_model
38
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
39
+
40
+
41
+ @FRAMEWORK_REGISTRY.register("InternVLA-M1")
42
+ class InternVLA_M1(baseframework):
43
+ """
44
+ Multimodal vision-language-action model.
45
+
46
+ Components:
47
+ - Qwen2.5 VL interface for fused language/vision token embeddings
48
+ - Layer-wise QFormer for multi-layer feature aggregation
49
+ - DINO encoder for dense multi-view spatial tokens
50
+ - DiT diffusion head for future action sequence modeling
51
+
52
+ Focus: Predict future continuous actions conditioned on images + instruction.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ config: Optional[dict] = None,
58
+ **kwargs,
59
+ ) -> None:
60
+ """
61
+ Construct all submodules and cache key configuration values.
62
+
63
+ Args:
64
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
65
+ **kwargs: Reserved for future overrides (unused).
66
+ """
67
+ super().__init__()
68
+ self.config = config
69
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
70
+ self.layer_qformer = get_layerwise_qformer(config=self.config)
71
+ self.action_model = get_action_model(config=self.config)
72
+ self.dino_encoder = get_dino_model(
73
+ backone_name=getattr(self.config.framework.dino, "dino_backbone", "dinov2_vits14")
74
+ )
75
+ self.dino_pro = nn.Linear(
76
+ in_features=self.dino_encoder.num_channels, out_features=self.qwen_vl_interface.model.config.hidden_size
77
+ )
78
+
79
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
80
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
81
+
82
+ def forward(
83
+ self,
84
+ examples: List[dict] = None,
85
+ **kwargs,
86
+ ) -> Tuple:
87
+ """
88
+ Forward pass for training (diffusion objective).
89
+
90
+ Flow:
91
+ 1. Build QwenVL inputs (images + instruction tokens)
92
+ 2. Extract hidden states from configured layer range
93
+ 3. Encode images with DINO, flatten multi-view tokens and project
94
+ 4. Concatenate per-layer language tokens with visual tokens
95
+ 5. Fuse via layer-wise QFormer -> action condition embeddings
96
+ 6. Prepare repeated future action windows (for diffusion efficiency)
97
+ 7. Predict noise and compute diffusion loss
98
+
99
+ Args:
100
+ examples: List[dict], each dict requires:
101
+ - image: List[PIL.Image] (multi-view)
102
+ - lang: str instruction
103
+ - action: np.ndarray or list shaped [T, action_dim]
104
+ **kwargs: Reserved.
105
+
106
+ Returns:
107
+ dict:
108
+ action_loss (torch.Tensor): Scalar diffusion noise prediction loss.
109
+ """
110
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
111
+ instructions = [example["lang"] for example in examples] # [B, str]
112
+ actions = [example["action"] for example in examples] # label [B, len, 7]
113
+
114
+ # Step 1: QWenVL input format
115
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
116
+ with torch.autocast("cuda", dtype=torch.bfloat16):
117
+ qwenvl_outputs = self.qwen_vl_interface(
118
+ **qwen_inputs,
119
+ output_attentions=False,
120
+ output_hidden_states=True,
121
+ return_dict=True,
122
+ )
123
+ pass
124
+
125
+ # Step 2: DINO Forward
126
+ image_tensors = self.dino_encoder.prepare_dino_input(batch_images) #
127
+ B = len(batch_images)
128
+ dino_features = self.dino_encoder(image_tensors) # DINO output is [B*num_view, token, dim]
129
+ dino_encoded_features = dino_features.reshape(B, -1, dino_features.shape[-1]) # [B, num_view * token, dim]
130
+ dino_encoded_features = self.dino_pro(dino_encoded_features) # [B, num_view * token, hidden_size]
131
+
132
+ # Step 3: aggregation condition for Action expert
133
+ start_layer = self.config.framework.layer_qformer.qformer_start_layer
134
+ end_layer = self.config.framework.layer_qformer.qformer_end_layer
135
+ condition_features = qwenvl_outputs.hidden_states[start_layer:end_layer]
136
+
137
+ cat_conditions = []
138
+ for layer_index in range(len(condition_features)):
139
+ layer_features = condition_features[layer_index] # [B, n_qformer_token, D]
140
+ layer_features = torch.cat(
141
+ [layer_features, dino_encoded_features], dim=1
142
+ ) # [B, n_qformer_token + num_view * token, D]
143
+ cat_conditions.append(layer_features)
144
+
145
+ action_condition = self.layer_qformer(cat_conditions) # [B, 64, D_action]
146
+
147
+ # Step 4: Action Expert Forward and Loss
148
+ with torch.autocast("cuda", dtype=torch.float32):
149
+
150
+ # here is a tips to accelerate training speed, by repeating each sample for several times @ref to CogACT
151
+ actions = torch.tensor(np.array(actions), device=action_condition.device) # [B, chunk, 7]
152
+ actions_future = actions[:, -(self.future_action_window_size + 1) :, :]
153
+
154
+ # tips: Repeat 'actions' 'repeated_diffusion_steps' times, resulting in [repeated_diffusion_steps*B, T, D]
155
+ repeated_diffusion_steps = (
156
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
157
+ )
158
+ actions_repeated = actions_future.repeat(repeated_diffusion_steps, 1, 1)
159
+ action_condition = action_condition.repeat(
160
+ repeated_diffusion_steps, 1, 1
161
+ ) # [repeated_diffusion_steps*B, T, D_action]
162
+
163
+ # DiT noise add and predict
164
+ noise_pred, noise, timestep = self.action_model(actions_repeated, action_condition)
165
+
166
+ # perdition loss
167
+ action_loss = self.action_model.loss(noise_pred, noise)
168
+
169
+ return {"action_loss": action_loss}
170
+
171
+ @torch.inference_mode()
172
+ def predict_action(
173
+ self,
174
+ batch_images: List[List[Image.Image]], # B * List of PIL Image as [view1, view2]
175
+ instructions: List[str],
176
+ cfg_scale: float = 1.5,
177
+ use_ddim: bool = True,
178
+ num_ddim_steps: int = 5,
179
+ resize_image = [224, 224],
180
+ **kwargs: str,
181
+ ) -> np.ndarray:
182
+ """
183
+ Inference: generate future normalized action sequence via diffusion sampling.
184
+
185
+ Steps:
186
+ 1. Resize images to training resolution (if specified)
187
+ 2. Encode with QwenVL (hidden states retained)
188
+ 3. Extract DINO tokens and project to vlm hidden size
189
+ 4. Build multi-layer fused QwenVL and DINO features via QFormer
190
+ 5. Run diffusion sampling (DDIM optional, CFG optional)
191
+ 6. Return normalized action trajectory
192
+
193
+ Args:
194
+ batch_images: List of samples; each sample is List[PIL.Image] (multi-view).
195
+ instructions: List[str] natural language task instructions.
196
+ cfg_scale: >1 enables classifier-free guidance (scales conditional vs unconditional).
197
+ use_ddim: Whether to use DDIM deterministic sampling.
198
+ num_ddim_steps: Number of DDIM steps if enabled.
199
+ **kwargs: Reserved.
200
+
201
+ Returns:
202
+ dict:
203
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
204
+ """
205
+ # align obs and lang # is policy's duty to make sure the image size?
206
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
207
+ if train_obs_image_size:
208
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
209
+ instructions = [instruction.lower() for instruction in instructions]
210
+
211
+ inferface_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
212
+ qwen_inputs = inferface_inputs
213
+
214
+ with torch.autocast("cuda", dtype=torch.bfloat16):
215
+ qwenvl_outputs = self.qwen_vl_interface(
216
+ **qwen_inputs,
217
+ output_hidden_states=True,
218
+ return_dict=True,
219
+ )
220
+
221
+ B = len(batch_images) # dino don't have smart resize in processing
222
+ image_tensors = self.dino_encoder.prepare_dino_input(batch_images)
223
+ dino_features = self.dino_encoder(image_tensors)
224
+
225
+ B = len(batch_images)
226
+ dino_encoded_features = dino_features.reshape(B, -1, dino_features.shape[-1]) # [B, num_view * token, dim]
227
+ dino_encoded_features = self.dino_pro(dino_encoded_features) # [B, 256, D]
228
+
229
+ with torch.autocast("cuda", dtype=torch.bfloat16):
230
+
231
+ start_layer = self.config.framework.layer_qformer.qformer_start_layer
232
+ end_layer = self.config.framework.layer_qformer.qformer_end_layer
233
+ condition_features = qwenvl_outputs.hidden_states[start_layer:end_layer]
234
+ cat_conditions = []
235
+ for layer_index in range(len(condition_features)):
236
+ layer_features = condition_features[layer_index] # [B, n_qformer_token, D]
237
+ layer_features = torch.cat(
238
+ [layer_features, dino_encoded_features], dim=1
239
+ ) # [B, n_qformer_token + num_view * token, D]
240
+ cat_conditions.append(layer_features)
241
+
242
+ action_condition_feature = self.layer_qformer(cat_conditions) # [B, 64, D_action]
243
+
244
+ using_cfg = cfg_scale > 1.0
245
+
246
+ model_dtype = next(self.action_model.net.parameters()).dtype
247
+ B = action_condition_feature.shape[0]
248
+
249
+ # Sample random noise
250
+ noise = torch.randn(
251
+ B,
252
+ self.future_action_window_size + 1,
253
+ self.action_model.in_channels,
254
+ device=action_condition_feature.device,
255
+ ).to(
256
+ model_dtype
257
+ ) # [B, T, D]
258
+
259
+ # Setup classifier-free guidance:
260
+ if using_cfg:
261
+ noise = torch.cat([noise, noise], 0) # [2,16,7]
262
+ uncondition = self.action_model.net.z_embedder.uncondition # [64, 768]
263
+ uncondition_shape = uncondition.shape
264
+ uncondition = uncondition.unsqueeze(0) # [1, 64, D]
265
+ uncondition = uncondition.expand(
266
+ B, uncondition_shape[0], uncondition_shape[1]
267
+ ) # [B, n_qformer_token, D]
268
+ z = torch.cat([action_condition_feature, uncondition], 0) # [2, 64, 768]
269
+ cfg_scale = cfg_scale
270
+ model_kwargs = dict(z=z, cfg_scale=cfg_scale)
271
+ sample_fn = self.action_model.net.forward_with_cfg
272
+ else:
273
+ model_kwargs = dict(z=action_condition_feature)
274
+ sample_fn = self.action_model.net.forward
275
+
276
+ # DDIM Sampling
277
+ if use_ddim and num_ddim_steps is not None:
278
+ if self.action_model.ddim_diffusion is None:
279
+ self.action_model.create_ddim(ddim_step=num_ddim_steps)
280
+ samples = self.action_model.ddim_diffusion.ddim_sample_loop(
281
+ sample_fn,
282
+ noise.shape,
283
+ noise,
284
+ clip_denoised=False,
285
+ model_kwargs=model_kwargs,
286
+ progress=False,
287
+ device=action_condition_feature.device,
288
+ eta=0.0,
289
+ )
290
+
291
+ if using_cfg:
292
+ samples, _ = samples.chunk(2, dim=0) # Remove null class samples
293
+ normalized_actions = samples.cpu().numpy()
294
+
295
+ raw_actions = None
296
+
297
+ return {"normalized_actions": normalized_actions} # [B, T, action_dim]
298
+
299
+
300
+ @torch.inference_mode()
301
+ def chat_with_M1(
302
+ self,
303
+ image: Image.Image,
304
+ text: str,
305
+ max_new_tokens: int = 128,
306
+ device: Optional[str] = "cuda",
307
+ ) -> List[str]:
308
+ processor = getattr(self.qwen_vl_interface, "processor", None)
309
+ model = getattr(self.qwen_vl_interface, "model", None)
310
+ # if processor is None or model is None:
311
+ # raise RuntimeError("qwen_vl_interface 缺少 processor 或 model。")
312
+
313
+ messages0 = [
314
+ {
315
+ "role": "user",
316
+ "content": [
317
+ {
318
+ "type": "image",
319
+ "image": image,
320
+ },
321
+ {"type": "text", "text": text},
322
+ ],
323
+ }
324
+ ]
325
+
326
+ messages = [messages0]
327
+ # text info
328
+ texts = [processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) for msg in messages]
329
+ # visual info
330
+ image_inputs, video_inputs = process_vision_info(messages)
331
+
332
+ # tokenizer
333
+ inputs = processor(
334
+ text=texts,
335
+ images=image_inputs,
336
+ videos=video_inputs,
337
+ padding=True,
338
+ return_tensors="pt",
339
+ ).to(device)
340
+
341
+ model.eval()
342
+ generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens)
343
+ generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
344
+ outputs = processor.batch_decode(
345
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
346
+ )
347
+ return outputs
348
+
349
+ if __name__ == "__main__":
350
+ from omegaconf import OmegaConf
351
+ import debugpy
352
+ import argparse
353
+ parser = argparse.ArgumentParser()
354
+ parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config")
355
+ args, clipargs = parser.parse_known_args()
356
+
357
+ debugpy.listen(("0.0.0.0", 10092))
358
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
359
+ debugpy.wait_for_client()
360
+
361
+ cfg = OmegaConf.load(args.config_yaml)
362
+
363
+ # try get model
364
+ model = InternVLA_M1(cfg)
365
+ print(model)
366
+
367
+
368
+ # fake sample
369
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
370
+ # Create a sample
371
+ sample = {
372
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
373
+ "image": [image, image], # two views
374
+ "lang": "This is a fake instruction for testing.",
375
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
376
+ }
377
+
378
+ batch = [sample, sample] # batch size 2
379
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
380
+ model = model.to(device)
381
+ forward_output = model(batch)
382
+ action_loss = forward_output['action_loss']
383
+ print(f"Action Loss: {action_loss.item()}")
384
+
385
+ # test predict action
386
+ predict_output = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]])
387
+ normalized_actions = predict_output['normalized_actions']
388
+ print(f"Unnormalized Action: {normalized_actions}")
389
+
390
+
391
+
392
+
393
+ # model_path = "./results/Checkpoints/1_need/0906_bestvla_retrain_sota2/checkpoints/steps_50000_pytorch_model.pt"
394
+ # state_dict = torch.load(model_path, map_location="cpu")
395
+
396
+ # model.load_state_dict(state_dict, strict=True)
397
+
398
+ # # try forward model
399
+ # # can be fake sample, but here get from dataloader for simpler
400
+ # from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
401
+
402
+ # vla_dataset_cfg = cfg.datasets.vla_data
403
+ # dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
404
+
405
+ # from torch.utils.data import DataLoader
406
+
407
+ # train_dataloader = DataLoader(
408
+ # dataset,
409
+ # batch_size=2,
410
+ # num_workers=1, # For Debug
411
+ # collate_fn=collate_fn,
412
+ # )
413
+
414
+ # for batch in tqdm(train_dataloader, desc="Processing Batches"):
415
+ # batch
416
+ # break
417
+
418
+ # # try get model
419
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
420
+ # model = model.to(device)
421
+ # model(batch)
starVLA/model/framework/QwenAdapter.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Junqiu YU / Fudan University] in [2025].
4
+ # Design and Merged by [Jinhui YE / HKUST University] in [2025].
5
+ """
6
+ Qwen-Adapter Framework
7
+ A lightweight implementation that Qwen-VL + Adapter Action head to directly predict continuous actions
8
+ Action head is copyright from VLA-Adapter,
9
+ """
10
+ from typing import List
11
+ from tqdm import tqdm
12
+ from typing import List, Optional, Tuple
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ import numpy as np
17
+ from PIL import Image
18
+
19
+
20
+ from starVLA.training.trainer_utils import initialize_overwatch
21
+
22
+ logger = initialize_overwatch(__name__)
23
+
24
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
25
+ IGNORE_INDEX = -100
26
+
27
+ from starVLA.model.framework.base_framework import baseframework
28
+ from starVLA.model.modules.vlm import get_vlm_model
29
+ from starVLA.model.modules.action_model.VLA_AdapterHeader import get_action_model, L1RegressionActionHead
30
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
31
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
32
+
33
+ def get_image_token_counts(batch_inputs):
34
+ IMAGE_TOKEN_ID = 151655
35
+
36
+ # input_ids shape: [Batch_Size, Seq_Len]
37
+ # result shape: [Batch_Size]
38
+ num_tokens_per_sample = torch.sum(batch_inputs['input_ids'] == IMAGE_TOKEN_ID, dim=1)
39
+
40
+ return num_tokens_per_sample
41
+
42
+
43
+ class ProprioProjector(nn.Module):
44
+ """
45
+ Projects proprio state inputs into the LLM's embedding space.
46
+ """
47
+ def __init__(self, llm_dim: int, proprio_dim: int) -> None:
48
+ super().__init__()
49
+ self.llm_dim = llm_dim
50
+ self.proprio_dim = proprio_dim
51
+
52
+ self.fc1 = nn.Linear(self.proprio_dim, self.llm_dim, bias=True)
53
+ self.fc2 = nn.Linear(self.llm_dim, self.llm_dim, bias=True)
54
+ self.act_fn1 = nn.GELU()
55
+
56
+ def forward(self, proprio: torch.Tensor = None) -> torch.Tensor:
57
+ # proprio: (bsz, proprio_dim)
58
+ projected_features = self.fc1(proprio)
59
+ projected_features = self.act_fn1(projected_features)
60
+ projected_features = self.fc2(projected_features)
61
+ return projected_features
62
+
63
+ # Only support for Qwen2.5 now @ PR 60
64
+ @FRAMEWORK_REGISTRY.register("QwenAdapter")
65
+ class Qwen_Adapter(baseframework):
66
+ """
67
+ Multimodal vision-language-action model.
68
+
69
+ Components:
70
+ - Qwen2.5 VL interface for fused language/vision token embeddings
71
+
72
+ Focus: Predict future continuous actions conditioned on images + instruction.
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ config: Optional[dict] = None,
78
+ **kwargs,
79
+ ) -> None:
80
+ """
81
+ Construct all submodules and cache key configuration values.
82
+
83
+ Args:
84
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
85
+ **kwargs: Reserved for future overrides (unused).
86
+ """
87
+ super().__init__()
88
+ self.config = config
89
+ self.use_proprio = self.config.framework.action_model.get("use_proprio", False)
90
+ self.proprio_projector = ProprioProjector(
91
+ llm_dim=self.qwen_vl_interface.model.config.hidden_size,
92
+ proprio_dim=self.config.framework.action_model.get("state_dim", 0),
93
+ ) if self.use_proprio else None
94
+ self.phase = self.config.framework.action_model.get("phase", "Training")
95
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
96
+ self.config.framework.qwenvl.vl_hidden_dim = self.qwen_vl_interface.model.config.hidden_size
97
+ self.action_query_num = self.config.framework.action_model.get("action_query_num", 64)
98
+ self.action_model: L1RegressionActionHead = get_action_model(config=self.config)
99
+ self.action_query = nn.Parameter(torch.randn(self.action_query_num, self.qwen_vl_interface.model.config.hidden_size))
100
+ nn.init.normal_(self.action_query, mean=0.0, std=0.02)
101
+
102
+
103
+ def forward(
104
+ self,
105
+ examples: List[dict] = None,
106
+ **kwargs,
107
+ ) -> Tuple:
108
+ """
109
+
110
+ """
111
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
112
+ instructions = [example["lang"] for example in examples] # [B, str]
113
+ gt_actions = [example["action"] for example in examples] # label [B, len, 7]
114
+
115
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
116
+
117
+
118
+ # Step 1: QWenVL input format
119
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
120
+ num_patches = get_image_token_counts(qwen_inputs) # [B, ]
121
+
122
+ batch_size = qwen_inputs['input_ids'].shape[0]
123
+ pad_id = self.qwen_vl_interface.model.config.pad_token_id
124
+ if pad_id is None:
125
+ pad_id = getattr(self.qwen_vl_interface.model.config, "eos_token_id", 0)
126
+ if pad_id is None:
127
+ pad_id = 0
128
+ device = qwen_inputs['input_ids'].device
129
+
130
+ dummy_ids = torch.full(
131
+ (batch_size, self.action_query_num),pad_id, device=device, dtype=qwen_inputs['input_ids'].dtype
132
+ ) # (B, action_query_num)
133
+ dummy_mask = torch.ones(
134
+ (batch_size, self.action_query_num), device=device, dtype=qwen_inputs['attention_mask'].dtype
135
+ ) # (B, action_query_num)
136
+
137
+ qwen_inputs['input_ids'] = torch.cat([qwen_inputs['input_ids'], dummy_ids], dim=1) # (B, L + action_query_num)
138
+ qwen_inputs['attention_mask'] = torch.cat([qwen_inputs['attention_mask'], dummy_mask], dim=1) # (B, L + action_query_num)
139
+
140
+ def inject_query_hook(module, inputs, output):
141
+ query_embed = self.action_query.to(dtype=output.dtype, device=output.device) # (action_query_num, hidden_dim)
142
+ batch_query = query_embed.unsqueeze(0).expand(output.shape[0], -1, -1) # (B, action_query_num, hidden_dim)
143
+ output[:, -self.action_query_num:, :] = batch_query
144
+ return output
145
+
146
+ embedding_layer = self.qwen_vl_interface.model.model.get_input_embeddings()
147
+ assert isinstance(embedding_layer, nn.Embedding), "Cannot find qwenvl embedding layer"
148
+ hook_handle = embedding_layer.register_forward_hook(inject_query_hook)
149
+ try:
150
+ with torch.autocast("cuda", dtype=torch.bfloat16):
151
+ qwenvl_outputs = self.qwen_vl_interface(
152
+ **qwen_inputs,
153
+ output_attentions=False,
154
+ output_hidden_states=True,
155
+ return_dict=True,
156
+ )
157
+ finally:
158
+ hook_handle.remove()
159
+
160
+
161
+ multi_layer_hidden_states = []
162
+
163
+ for item in qwenvl_outputs.hidden_states[0:]:
164
+ batch_size = item.shape[0]
165
+ hidden_dim = item.shape[-1]
166
+
167
+ max_patch_len = num_patches.max().item()
168
+
169
+ batch_vision_states = []
170
+ batch_action_query_states = []
171
+
172
+ for i in range(batch_size):
173
+ n_p = num_patches[i].item()
174
+ vis_feat = item[i, :n_p, :] # [n_p, D]
175
+ if n_p < max_patch_len:
176
+ pad_len = max_patch_len - n_p
177
+ padding = torch.zeros((pad_len, hidden_dim), device=vis_feat.device, dtype=vis_feat.dtype)
178
+ vis_feat = torch.cat([vis_feat, padding], dim=0) # [max_patch_len, D]
179
+
180
+ batch_vision_states.append(vis_feat)
181
+
182
+ act_query_feat = item[i, -self.action_query_num:, :] # [action_query_num, D]
183
+ batch_action_query_states.append(act_query_feat)
184
+
185
+ vision_hidden_states = torch.stack(batch_vision_states).unsqueeze(1) # [B, 1, max_patch_len, D]
186
+ action_query_hidden_states = torch.stack(batch_action_query_states).unsqueeze(1) # [B, 1, action_query_num, D]
187
+
188
+ all_hidden_states = torch.cat([vision_hidden_states, action_query_hidden_states], dim=2) # [B, 1, max_patch_len + action_query_num, D]
189
+ multi_layer_hidden_states.append(all_hidden_states) # [num_layers][B, 1, L_total, D]
190
+
191
+ multi_layer_hidden_states = torch.cat(multi_layer_hidden_states, dim=1) # [B, num_layers, L_total, D]
192
+
193
+
194
+ # Step 3: Action Expert Forward
195
+ self.action_model = self.action_model.to(device=multi_layer_hidden_states.device, dtype=multi_layer_hidden_states.dtype)
196
+ predicted_actions = self.action_model.predict_action(
197
+ multi_layer_hidden_states,
198
+ proprio=state if self.use_proprio else None,
199
+ proprio_projector=self.proprio_projector if self.use_proprio else None,
200
+ phase=self.phase,
201
+ ) # (B, chunk_len, action_dim)
202
+
203
+ gt_actions = torch.tensor(np.stack(gt_actions)).to(
204
+ device=predicted_actions.device,
205
+ dtype=predicted_actions.dtype
206
+ )
207
+
208
+ loss = torch.nn.L1Loss()(predicted_actions, gt_actions)
209
+
210
+ return {"action_loss": loss}
211
+
212
+ @torch.inference_mode()
213
+ def predict_action(
214
+ self,
215
+ examples: List[dict] = None,
216
+ **kwargs: str,
217
+ ) -> np.ndarray:
218
+ """
219
+ Inference: Predict future continuous actions aligned with the Forward logic (Hook + Multi-layer states).
220
+ """
221
+ from deployment.model_server.tools.image_tools import to_pil_preserve
222
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
223
+ instructions = [example["lang"] for example in examples] # [B, str]
224
+
225
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
226
+
227
+ # Step 0: Preprocessing (Resize)
228
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
229
+ if train_obs_image_size:
230
+ # Assuming resize_images is a valid helper function available in context
231
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
232
+
233
+ # Step 1: QWenVL input format
234
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
235
+ num_patches = get_image_token_counts(qwen_inputs) # [B, ]
236
+
237
+ # Step 2: Prepare Dummy Tokens & Hook for Action Query Injection
238
+ batch_size = qwen_inputs['input_ids'].shape[0]
239
+ pad_id = self.qwen_vl_interface.model.config.pad_token_id
240
+ if pad_id is None:
241
+ pad_id = getattr(self.qwen_vl_interface.model.config, "eos_token_id", 0)
242
+ if pad_id is None:
243
+ pad_id = 0
244
+ device = qwen_inputs['input_ids'].device
245
+
246
+ # Create dummy placeholders
247
+ dummy_ids = torch.full(
248
+ (batch_size, self.action_query_num), pad_id, device=device, dtype=qwen_inputs['input_ids'].dtype
249
+ )
250
+ dummy_mask = torch.ones(
251
+ (batch_size, self.action_query_num), device=device, dtype=qwen_inputs['attention_mask'].dtype
252
+ )
253
+
254
+ # Concat to inputs
255
+ qwen_inputs['input_ids'] = torch.cat([qwen_inputs['input_ids'], dummy_ids], dim=1)
256
+ qwen_inputs['attention_mask'] = torch.cat([qwen_inputs['attention_mask'], dummy_mask], dim=1)
257
+
258
+ # Define Hook
259
+ def inject_query_hook(module, inputs, output):
260
+ query_embed = self.action_query.to(dtype=output.dtype, device=output.device)
261
+ batch_query = query_embed.unsqueeze(0).expand(output.shape[0], -1, -1)
262
+ output[:, -self.action_query_num:, :] = batch_query
263
+ return output
264
+
265
+ # Register Hook
266
+ embedding_layer = self.qwen_vl_interface.model.model.get_input_embeddings()
267
+ hook_handle = embedding_layer.register_forward_hook(inject_query_hook)
268
+
269
+ try:
270
+ with torch.autocast("cuda", dtype=torch.bfloat16):
271
+ qwenvl_outputs = self.qwen_vl_interface(
272
+ **qwen_inputs,
273
+ output_attentions=False,
274
+ output_hidden_states=True,
275
+ return_dict=True,
276
+ )
277
+ finally:
278
+ hook_handle.remove()
279
+
280
+ # Step 3: Process Multi-layer Hidden States
281
+ # Logic copied from forward: Concatenate Vision Tokens + Action Query Tokens across layers
282
+ multi_layer_hidden_states = []
283
+
284
+ for item in qwenvl_outputs.hidden_states[0:]:
285
+ # item shape: [B, Seq_Len, H]
286
+ hidden_dim = item.shape[-1]
287
+ max_patch_len = num_patches.max().item()
288
+
289
+ batch_vision_states = []
290
+ batch_action_query_states = []
291
+
292
+ for i in range(batch_size):
293
+ n_p = num_patches[i].item()
294
+ # Extract vision features
295
+ vis_feat = item[i, :n_p, :] # [n_p, D]
296
+
297
+ # Handle padding for vision tokens if batch has varying aspect ratios
298
+ if n_p < max_patch_len:
299
+ pad_len = max_patch_len - n_p
300
+ padding = torch.zeros((pad_len, hidden_dim), device=vis_feat.device, dtype=vis_feat.dtype)
301
+ vis_feat = torch.cat([vis_feat, padding], dim=0) # [max_patch_len, D]
302
+
303
+ batch_vision_states.append(vis_feat)
304
+
305
+ # Extract action query features (last N tokens)
306
+ act_query_feat = item[i, -self.action_query_num:, :] # [action_query_num, D]
307
+ batch_action_query_states.append(act_query_feat)
308
+
309
+ vision_hidden_states = torch.stack(batch_vision_states).unsqueeze(1) # [B, 1, max_patch_len, D]
310
+ action_query_hidden_states = torch.stack(batch_action_query_states).unsqueeze(1) # [B, 1, action_query_num, D]
311
+
312
+ all_hidden_states = torch.cat([vision_hidden_states, action_query_hidden_states], dim=2)
313
+ multi_layer_hidden_states.append(all_hidden_states)
314
+
315
+ # [B, num_layers, L_total, D]
316
+ multi_layer_hidden_states = torch.cat(multi_layer_hidden_states, dim=1)
317
+
318
+ # Step 4: Proprioception Processing
319
+ proprio_tensor = None
320
+ if self.use_proprio and state is not None:
321
+ # Convert numpy state to tensor, match device/dtype of hidden states
322
+ proprio_tensor = torch.from_numpy(np.array(state)).to(
323
+ device=multi_layer_hidden_states.device,
324
+ dtype=multi_layer_hidden_states.dtype
325
+ )
326
+ # Ensure shape is [B, proprio_dim] or [B, 1, proprio_dim] depending on projector expectation
327
+ if proprio_tensor.ndim == 1:
328
+ proprio_tensor = proprio_tensor.unsqueeze(0) # Batch dim
329
+ if proprio_tensor.ndim == 3:
330
+ proprio_tensor = proprio_tensor.squeeze(1) # Remove seq dim if present for projector
331
+
332
+ # Step 5: Action Expert Prediction
333
+ # Handle DDP wrapper if present, otherwise call model directly
334
+ action_model_ref = self.action_model.module if hasattr(self.action_model, "module") else self.action_model
335
+
336
+ # Ensure model is on correct device/dtype
337
+ action_model_ref = action_model_ref.to(device=multi_layer_hidden_states.device, dtype=multi_layer_hidden_states.dtype)
338
+
339
+ with torch.autocast("cuda", dtype=torch.float32):
340
+ pred_actions = action_model_ref.predict_action(
341
+ multi_layer_hidden_states,
342
+ proprio=proprio_tensor,
343
+ proprio_projector=self.proprio_projector if self.use_proprio else None,
344
+ phase="Inference", # Explicitly set phase for inference logic
345
+ ) # (B, chunk_len, action_dim)
346
+
347
+ normalized_actions = pred_actions.detach().cpu().numpy()
348
+ return {"normalized_actions": normalized_actions}
349
+
350
+
351
+
352
+ if __name__ == "__main__":
353
+ from omegaconf import OmegaConf
354
+ import debugpy
355
+ import argparse
356
+ parser = argparse.ArgumentParser()
357
+ parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_train_adapter.yaml", help="Path to YAML config")
358
+ args, clipargs = parser.parse_known_args()
359
+
360
+ debugpy.listen(("0.0.0.0", 10092))
361
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
362
+ debugpy.wait_for_client()
363
+
364
+ cfg = OmegaConf.load(args.config_yaml)
365
+ # try get model
366
+ cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct"
367
+
368
+ model: Qwen_Adapter = Qwen_Adapter(cfg)
369
+ print(model)
370
+
371
+
372
+
373
+ # fake sample
374
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
375
+ # Create a sample
376
+ sample = {
377
+ "action": np.random.uniform(-1, 1, size=(16, 14)).astype(np.float16), # action_chunk, action_dim
378
+ "image": [image, image], # two views
379
+ "lang": "This is a fake for testing.",
380
+ # "state" : np.random.uniform(-1, 1, size=(1, 14)).astype(np.float16), # chunk, state_dim
381
+ }
382
+
383
+ batch = [sample, sample] # batch size 2
384
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
385
+ model = model.to(device)
386
+ forward_output = model(batch)
387
+ action_loss = forward_output['action_loss']
388
+ print(f"Action Loss: {action_loss.item()}")
389
+
390
+ # test predict action
391
+ predict_output = model.predict_action(examples=[batch[0]])
392
+ normalized_actions = predict_output['normalized_actions']
393
+ print(f"Unnormalized Action: {normalized_actions}")
394
+
395
+ # # Advance: try forward model with dataloader
396
+ # # can be fake sample, but here get from dataloader for simpler
397
+ # from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
398
+
399
+ # vla_dataset_cfg = cfg.datasets.vla_data
400
+ # dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
401
+
402
+ # from torch.utils.data import DataLoader
403
+
404
+ # train_dataloader = DataLoader(
405
+ # dataset,
406
+ # batch_size=2,
407
+ # num_workers=1, # For Debug
408
+ # collate_fn=collate_fn,
409
+ # )
410
+ # #
411
+ # for batch in tqdm(train_dataloader, desc="Processing Batches"):
412
+ # batch
413
+ # break
414
+
415
+ # # try get model
416
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
417
+ # model = model.to(device)
418
+ # model(batch)
419
+
420
+ # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]])
421
+
422
+ # # fake state
423
+ # for ba in batch:
424
+ # ba["state"] = ba["action"][0][None]
425
+
426
+ # model(batch)
427
+ # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]], state=[batch[0]["state"]])
starVLA/model/framework/QwenDual.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Jinhui YE / HKUST University] in [2025].
4
+
5
+ """
6
+ Qwen-Dual Framework
7
+ A lightweight implementation that Qwen2.5-vl + dinov2 + Flow-matching head to directly predict continuous actions
8
+ Flow-matching header is copyright from GR00T N1.5
9
+ """
10
+ from typing import List
11
+ from tqdm import tqdm
12
+ from typing import List, Optional, Tuple
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ import numpy as np
17
+ from PIL import Image
18
+
19
+
20
+ from starVLA.model.modules.dino_model.dino import get_dino_model
21
+ from starVLA.training.trainer_utils import initialize_overwatch
22
+
23
+ logger = initialize_overwatch(__name__)
24
+
25
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
26
+ IGNORE_INDEX = -100
27
+
28
+ from starVLA.model.framework.base_framework import baseframework
29
+ from starVLA.model.modules.vlm import get_vlm_model
30
+ from starVLA.model.modules.action_model.GR00T_ActionHeader import get_action_model, FlowmatchingActionHead
31
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
32
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
33
+ from deployment.model_server.tools.image_tools import to_pil_preserve
34
+
35
+
36
+ @FRAMEWORK_REGISTRY.register("QwenDual")
37
+ class Qwen_Dual(baseframework):
38
+ """
39
+ Multimodal vision-language-action model.
40
+
41
+ Components:
42
+ - Qwen2.5 VL interface for fused language/vision token embeddings
43
+ - Layer-wise QFormer for multi-layer feature aggregation
44
+ - DINO encoder for dense multi-view spatial tokens
45
+ - DiT diffusion head for future action sequence modeling
46
+
47
+ Focus: Predict future continuous actions conditioned on images + instruction.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ config: Optional[dict] = None,
53
+ **kwargs,
54
+ ) -> None:
55
+ """
56
+ Construct all submodules and cache key configuration values.
57
+
58
+ Args:
59
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
60
+ **kwargs: Reserved for future overrides (unused).
61
+ """
62
+ super().__init__()
63
+ self.config = config
64
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
65
+ # align dims --> we should put them to config or no?
66
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = self.qwen_vl_interface.model.config.hidden_size
67
+
68
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用
69
+
70
+ self.dino_encoder = get_dino_model(
71
+ backone_name=getattr(self.config.framework.dino, "dino_backbone", "dinov2_vits14")
72
+ )
73
+ self.dino_pro = nn.Linear(
74
+ in_features=self.dino_encoder.num_channels, out_features=self.qwen_vl_interface.model.config.hidden_size
75
+ )
76
+
77
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
78
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
79
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
80
+
81
+
82
+ def forward(
83
+ self,
84
+ examples: List[dict] = None,
85
+ **kwargs,
86
+ ) -> Tuple:
87
+ """
88
+ 训练前向:直接回归未来动作(无扩散)。
89
+
90
+ Flow:
91
+ 1. Build QwenVL inputs (images + instruction tokens)
92
+ 2. Extract hidden states from configured layer range
93
+ 7. Predict action and compute L1 loss
94
+
95
+ Args:
96
+ examples: List[dict], each dict requires:
97
+ - image: List[PIL.Image] (multi-view)
98
+ - lang: str instruction
99
+ - action: np.ndarray or list shaped [T, action_dim]
100
+ **kwargs: Reserved.
101
+
102
+ Returns:
103
+ dict:
104
+ action_loss (torch.Tensor): Scalar diffusion noise prediction loss.
105
+ """
106
+ batch_images, wrist_views, instructions, state = self.align_model_input(examples)
107
+ last_hidden, state = self.get_action_condition(batch_images, instructions, wrist_views, state)
108
+
109
+ # Step 4: Action Expert Forward and Loss
110
+ with torch.autocast("cuda", dtype=torch.float32):
111
+ # get action labels
112
+ actions = [example["action"] for example in examples] # List of [T_full, action_dim]
113
+ actions = torch.tensor(
114
+ np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype
115
+ ) # [B, T, action_dim]
116
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
117
+
118
+ # repeate for efficient training
119
+ repeated_diffusion_steps = (
120
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
121
+ )
122
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
123
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
124
+ state_repeated = None
125
+ if state is not None:
126
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
127
+ action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated) # (B, chunk_len, action_dim)
128
+
129
+ return {"action_loss": action_loss}
130
+
131
+ @torch.inference_mode()
132
+ def predict_action(
133
+ self,
134
+ examples: List[dict] = None,
135
+ **kwargs: str,
136
+ ) -> np.ndarray:
137
+ """
138
+ 推理:单次前向直接回归未来动作(无扩散采样)。
139
+
140
+ Steps:
141
+ 1. Resize images to training resolution (if specified)
142
+ 2. Encode with QwenVL (hidden states retained)
143
+ 6. Return normalized action trajectory
144
+ Returns:
145
+ dict:
146
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
147
+ """
148
+ batch_images, wrist_views, instructions, state = self.align_model_input(examples)
149
+ last_hidden, state = self.get_action_condition(batch_images, instructions, wrist_views, state)
150
+ # Step 4: Action Expert Forward
151
+ with torch.autocast("cuda", dtype=torch.float32):
152
+ pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim)
153
+ normalized_actions = pred_actions.detach().cpu().numpy()
154
+
155
+ return {"normalized_actions": normalized_actions}
156
+
157
+ def align_model_input(self, examples: List[dict]):
158
+
159
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
160
+ wrist_views = [to_pil_preserve(example["wrist_views"]) for example in examples] if "wrist_views" in examples[0] else None # [B,[PLT]]
161
+ instructions = [example["lang"] for example in examples] # [B, str]
162
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
163
+
164
+
165
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", [224,224])
166
+ if train_obs_image_size:
167
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
168
+ if train_obs_image_size and wrist_views is not None:
169
+ wrist_views = resize_images(wrist_views, target_size=train_obs_image_size)
170
+
171
+ return batch_images, wrist_views, instructions, state
172
+
173
+ def get_action_condition(self, batch_images, instructions, wrist_views=None, state=None):
174
+ # Step 1: QWenVL input format
175
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
176
+ with torch.autocast("cuda", dtype=torch.bfloat16):
177
+ qwenvl_outputs = self.qwen_vl_interface(
178
+ **qwen_inputs,
179
+ output_attentions=False,
180
+ output_hidden_states=True,
181
+ return_dict=True,
182
+ )
183
+ # last_hidden_state: [B, seq_len, H]
184
+ connect_layer_index = self.config.framework.action_model.get("connect_layer_index", -1)
185
+ last_hidden = qwenvl_outputs.hidden_states[connect_layer_index] # [B, L, H]
186
+
187
+ # Step 2: DINO Forward
188
+ if wrist_views == None:
189
+ wrist_views = batch_images
190
+ image_tensors = self.dino_encoder.prepare_dino_input(wrist_views) #
191
+ B = len(batch_images)
192
+ dino_features = self.dino_encoder(image_tensors) # DINO output is [B*num_view, token, dim]
193
+ dino_encoded_features = dino_features.reshape(B, -1, dino_features.shape[-1]) # [B, num_view * token, dim]
194
+ dino_encoded_features = self.dino_pro(dino_encoded_features) # [B, num_view * token, hidden_size]
195
+
196
+ # Step 3: Feature Concatenation
197
+ last_hidden = torch.cat(
198
+ [last_hidden, dino_encoded_features], dim=1
199
+ )
200
+ state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None
201
+
202
+ return last_hidden, state
203
+ if __name__ == "__main__":
204
+ from omegaconf import OmegaConf
205
+ import debugpy
206
+ import argparse
207
+ parser = argparse.ArgumentParser()
208
+ parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config")
209
+ args, clipargs = parser.parse_known_args()
210
+
211
+ debugpy.listen(("0.0.0.0", 10092))
212
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
213
+ debugpy.wait_for_client()
214
+
215
+ cfg = OmegaConf.load(args.config_yaml)
216
+ # try get model
217
+ # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen3-VL-4B-Instruct"
218
+ # # cfg.framework.action_model.connect_layer_index = 16
219
+ # cfg.framework.action_model.state_dim = 44
220
+ # cfg.datasets.vla_data.include_state = True
221
+
222
+ cfg.framework.action_model.action_hidden_dim = 2048
223
+ cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large"
224
+
225
+ model: Qwen_Dual = Qwen_Dual(cfg)
226
+ print(model)
227
+
228
+
229
+
230
+ # fake sample
231
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
232
+ # Create a sample
233
+ sample = {
234
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
235
+ "image": [image], # three views
236
+ # "wrist_views": [image, image],
237
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
238
+ # "state" : np.random.uniform(-1, 1, size=(1, 44)).astype(np.float16), # chunk, state_dim
239
+ }
240
+
241
+ sample2 = sample.copy()
242
+ sample2["lang"] = "Move the red cup from the table to the kitchen counter next to the sink."
243
+ batch = [sample, sample2] # batch size 2
244
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
245
+ model = model.to(device)
246
+ forward_output = model(batch)
247
+ action_loss = forward_output['action_loss']
248
+ print(f"Action Loss: {action_loss.item()}")
249
+
250
+ # test predict action
251
+ predict_output = model.predict_action([sample]) #, state=[batch[0]["state"]]
252
+ normalized_actions = predict_output['normalized_actions']
253
+ print(f"Unnormalized Action: {normalized_actions}")
254
+
255
+ # # Advance: try forward model with dataloader
256
+ # # can be fake sample, but here get from dataloader for simpler
257
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
258
+
259
+ vla_dataset_cfg = cfg.datasets.vla_data
260
+ # vla_dataset_cfg.include_state = True
261
+ # vla_dataset_cfg.data_mix = "BEHAVIOR_challenge"
262
+ # vla_dataset_cfg.data_mix = "BEHAVIOR_rgp_dual_history"
263
+ vla_dataset_cfg.task_id = 40
264
+ vla_dataset_cfg.video_backend = "torchvision_av"
265
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
266
+
267
+ from torch.utils.data import DataLoader
268
+
269
+ train_dataloader = DataLoader(
270
+ dataset,
271
+ batch_size=2,
272
+ num_workers=1, # For Debug
273
+ collate_fn=collate_fn,
274
+ )
275
+ #
276
+ count = 0
277
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
278
+ batch
279
+ count += 1
280
+ if count > 1:
281
+ break
282
+
283
+ # try get model
284
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
285
+ model = model.to(device)
286
+ model(batch)
287
+
288
+ action = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]]
starVLA/model/framework/QwenFast.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Jinhui YE / HKUST University] in [2025].
4
+
5
+ """
6
+ Qwen-Fast Framework
7
+
8
+ A lightweight implementation for autoregressive discrete action prediction conditioned on multi-view images + instruction.
9
+ fast tokenizer is copyright from physical-intelligence/fast
10
+
11
+ Key Points:
12
+ - Qwen2.5 vision-language backbone
13
+ - Unified action learning via next-token prediction (fast tokenizer)
14
+ - Autoregressive action tokens derived from discretized / symbolized continuous actions
15
+
16
+ Note: How to add special tokens to Qwen2.5:
17
+ download our model checkpoint with special tokens added: https://huggingface.co/StarVLA/Qwen2.5-VL-3B-Instruct-Action
18
+ """
19
+
20
+ from typing import List
21
+ from tqdm import tqdm
22
+ from typing import List, Optional, Tuple, Any
23
+ import torch
24
+ import torch.nn as nn
25
+ import torch.nn.functional as F
26
+ import numpy as np
27
+ from PIL import Image
28
+ from qwen_vl_utils import process_vision_info
29
+
30
+
31
+ from starVLA.training.trainer_utils import initialize_overwatch
32
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
33
+ from deployment.model_server.tools.image_tools import to_pil_preserve
34
+
35
+ logger = initialize_overwatch(__name__)
36
+
37
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
38
+ IGNORE_INDEX = -100
39
+
40
+ from starVLA.model.framework.base_framework import baseframework
41
+ from starVLA.model.modules.vlm import get_vlm_model
42
+ from starVLA.model.modules.action_model.fast_ActionHeader import get_action_model
43
+
44
+
45
+ @FRAMEWORK_REGISTRY.register("QwenFast")
46
+ class Qwenvl_Fast(baseframework):
47
+ """
48
+ Multimodal vision-language-action model.
49
+
50
+ Components:
51
+ - Qwen2.5 VL interface for fused language/vision token embeddings
52
+ - Layer-wise QFormer for multi-layer feature aggregation
53
+ - DINO encoder for dense multi-view spatial tokens
54
+ - DiT diffusion head for future action sequence modeling
55
+
56
+ Focus: Predict future continuous actions conditioned on images + instruction.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ config: Optional[dict] = None,
62
+ **kwargs,
63
+ ) -> None:
64
+ """
65
+ Construct all submodules and cache key configuration values.
66
+
67
+ Args:
68
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
69
+ **kwargs: Reserved for future overrides (unused).
70
+ """
71
+ super().__init__()
72
+ self.config = config
73
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
74
+ self.action_model = get_action_model(config=self.config)
75
+
76
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
77
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
78
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
79
+ # self.hidden_dim = config.framework.action_model.action_hidden_dim
80
+
81
+ self.action_model.fast_tokenizer.time_horizon = self.future_action_window_size + 1
82
+ self.action_model.fast_tokenizer.action_dim = self.config.framework.action_model.action_dim
83
+
84
+
85
+
86
+ def forward(
87
+ self,
88
+ examples: List[dict] = None,
89
+ **kwargs,
90
+ ) -> Tuple:
91
+ """
92
+ Training forward: directly predict future actions via next-token prediction (no diffusion).
93
+
94
+ Flow:
95
+ 1. Build QwenVL inputs (images + instruction tokens)
96
+ 2. Extract hidden states from configured layer range
97
+ 7. Predict action and compute L1 loss
98
+
99
+ Args:
100
+ examples: List[dict], each dict requires:
101
+ - image: List[PIL.Image] (multi-view)
102
+ - lang: str instruction
103
+ - action: np.ndarray or list shaped [T, action_dim]
104
+ **kwargs: Reserved.
105
+
106
+ Returns:
107
+ dict:
108
+ action_loss (torch.Tensor): Scalar diffusion noise prediction loss.
109
+ """
110
+ batch_images = [example["image"] for example in examples] # [B, [PIL]]
111
+ instructions = [example["lang"] for example in examples] # [B, str]
112
+ actions = [example["action"] for example in examples] # label [B, len, 7]
113
+
114
+ # step 0: map_raw_action_to_vlm_action
115
+ batch_fast_tokens = self.action_model.encoder_action2fastoken(actions) # List[str]
116
+
117
+ # batch_fast_tokens = [self.fast_tokenizer(raw_action)[0] for raw_action in raw_actions]
118
+ vlm_action_tokens = [self.map_fast_token_to_vlm_action(fast_tokens) for fast_tokens in batch_fast_tokens]
119
+
120
+ # Step 1: QWenVL input format
121
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions, solutions=vlm_action_tokens)
122
+
123
+ with torch.autocast("cuda", dtype=torch.bfloat16):
124
+ qwenvl_outputs = self.qwen_vl_interface(
125
+ **qwen_inputs,
126
+ output_attentions=False,
127
+ output_hidden_states=False,
128
+ return_dict=True,
129
+ )
130
+
131
+ vlm_action_loss = qwenvl_outputs.loss
132
+ if vlm_action_loss is None or torch.isnan(vlm_action_loss):
133
+ vlm_action_loss = torch.tensor(0.0, device=self.qwen_vl_interface.model.device)
134
+
135
+ return {"action_loss": vlm_action_loss}
136
+
137
+ @torch.inference_mode()
138
+ def predict_action(
139
+ self,
140
+ examples: List[dict] = None,
141
+ **kwargs: str,
142
+ ) -> np.ndarray:
143
+ """
144
+ Inference: single forward pass to obtain future actions (no diffusion sampling).
145
+ # can be batch forward
146
+ Steps:
147
+ 1. Resize images to training resolution (if specified)
148
+ 2. Encode with QwenVL (hidden states retained)
149
+ 6. Return normalized action trajectory
150
+
151
+ Returns:
152
+ dict:
153
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
154
+ """
155
+ if type(examples) is not list:
156
+ examples = [examples]
157
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
158
+ instructions = [example["lang"] for example in examples] # [B, str]
159
+
160
+ # train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
161
+ # if train_obs_image_size:
162
+ # batch_images = resize_images(batch_images, target_size=train_obs_image_size)
163
+ instructions = [instruction for instruction in instructions]
164
+
165
+
166
+ # Step 1: QWenVL input format
167
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
168
+
169
+ with torch.autocast("cuda", dtype=torch.bfloat16):
170
+ generated_ids = self.qwen_vl_interface.model.generate(
171
+ **qwen_inputs,
172
+ max_length=2048,
173
+ )
174
+ # --- Extract and decoder vlm_action to continue actions ---
175
+ # --- extrace token (index based on VLM) ---
176
+ batch_vlm_action_token_ids = self._extract_action_token_ids(generated_ids)
177
+ # --- map index to fast tokenizer index space ---
178
+ batch_fast_action_token_idx = self._decode_action_tokens(batch_vlm_action_token_ids)
179
+ # --- decode fast tokenizer index to action semantic ---
180
+ normalized_actions = self.action_model.fast_tokenizer.decode(batch_fast_action_token_idx)
181
+
182
+ return {"normalized_actions": normalized_actions}
183
+
184
+ def _extract_action_token_ids(
185
+ self,
186
+ generated_ids: torch.LongTensor,
187
+ ) -> List[List[int]]:
188
+ """
189
+ Extract action tokens (with offset) from the generated token sequence and return a 2D list:
190
+ ret[b] = [vlm_action_token_id_0, vlm_action_token_id_1, ...]
191
+ Rule: keep all tokens falling within [_ACTION_TOKEN_MIN, _ACTION_TOKEN_MAX] in order of appearance.
192
+ You may change it to "take only the first occurrence followed by continuous segment" as needed.
193
+ """
194
+ act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN
195
+ act_max = self.qwen_vl_interface._ACTION_TOKEN_MAX
196
+ mask = (generated_ids >= act_min) & (generated_ids <= act_max) # [B, L]
197
+ results = []
198
+ for b in range(generated_ids.size(0)):
199
+ idx = mask[b].nonzero(as_tuple=False).flatten()
200
+ if idx.numel() == 0:
201
+ results.append([])
202
+ continue
203
+ # all action tokens
204
+ tokens = generated_ids[b, idx].tolist()
205
+ results.append(tokens)
206
+ return results
207
+
208
+ def _decode_action_tokens(self, batch_vlm_tokens: List[List[int]]) -> List[Any]:
209
+ """
210
+ Decode the offset VLM action token list back to fast tokenizer semantics.
211
+ fast_tokenizer.decode expects the original fast token id sequence (without offset).
212
+ """
213
+ act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN
214
+ batch_fast_token_ids = []
215
+ for seq in batch_vlm_tokens:
216
+ if not seq:
217
+ batch_fast_token_ids.append(None)
218
+ continue
219
+ fast_ids = [t - act_min for t in seq]
220
+
221
+ batch_fast_token_ids.append(fast_ids)
222
+
223
+ return batch_fast_token_ids
224
+
225
+ def map_fast_token_to_vlm_action(self, tokens) -> str:
226
+ """Maps fast action tokens to the VLM action format.
227
+ Action token 0 is mapped to the string <robot_action_0> ... and so on
228
+ """
229
+ return ''.join([f"<robot_action_{token}>" for token in tokens]) # you should add <robot_action_{token}> to VLM as special tokens,
230
+
231
+
232
+ if __name__ == "__main__":
233
+ from omegaconf import OmegaConf
234
+ import debugpy
235
+ import argparse
236
+ parser = argparse.ArgumentParser()
237
+ parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config")
238
+ args, clipargs = parser.parse_known_args()
239
+
240
+ debugpy.listen(("0.0.0.0", 10092))
241
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
242
+ debugpy.wait_for_client()
243
+ args.config_yaml = "./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml"
244
+ cfg = OmegaConf.load(args.config_yaml)
245
+ # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action"
246
+
247
+ # try get model
248
+ model = Qwenvl_Fast(cfg)
249
+ print(model)
250
+
251
+ # fake sample
252
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
253
+ # Create a sample
254
+ sample = {
255
+ "action": np.random.uniform(-1, 1, size=(16, 14)).astype(np.float16), # action_chunk, action_dim
256
+ "image": [image, image], # two views
257
+ "lang": "This is a fake instruction for testing.",
258
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
259
+ }
260
+
261
+ sample2 = {
262
+ "action": np.random.uniform(-1, 1, size=(16, 14)).astype(np.float16), # action_chunk, action_dim
263
+ "image": [image, image], # two views
264
+ "lang": "The fake instruction for testing.",
265
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
266
+ }
267
+
268
+ batch = [sample, sample2] # batch size 2
269
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
270
+ model = model.to(device)
271
+ forward_output = model(batch)
272
+ action_loss = forward_output['action_loss']
273
+ print(f"Action Loss: {action_loss.item()}")
274
+
275
+ # test predict action. for new model, it didn't learn to predict action token, so you would meet empty action
276
+ predict_output = model.predict_action([sample])
277
+ normalized_actions = predict_output['normalized_actions']
278
+ print(f"Unnormalized Action: {normalized_actions}")
279
+
280
+
281
+
282
+
283
+ # # test with dataloader
284
+ # # can be fake sample, but here get from dataloader for simpler
285
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
286
+
287
+ vla_dataset_cfg = cfg.datasets.vla_data
288
+ vla_dataset_cfg.video_backend = "torchvision_av"
289
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
290
+
291
+ from torch.utils.data import DataLoader
292
+
293
+ train_dataloader = DataLoader(
294
+ dataset,
295
+ batch_size=2,
296
+ num_workers=1, # For Debug
297
+ collate_fn=collate_fn,
298
+ )
299
+
300
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
301
+ batch
302
+ break
303
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
304
+ model = model.to(device)
305
+ model(batch)
306
+ pass
307
+ action = model.predict_action(batch[0])
starVLA/model/framework/QwenFastWanPerceiver.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by combining QwenFast + QwenWanPerceiver.
4
+ """
5
+ QwenFastWanPerceiver Framework
6
+
7
+ VLM 内部通过 next-token prediction 学习 fast action(QwenFast),
8
+ 同时用纯 VL 条件(图像 + 指令,不含 action token)融合 Wan 特征后,
9
+ 交给 Perceiver flow-matching head 预测连续动作(QwenWanPerceiver)。
10
+
11
+ 因果 LM 下,action token 之前的 hidden state 与仅 VL 输入前向等价,
12
+ 因此训练时可单次前向(含 teacher-forced action)并截取 VL 段特征。
13
+ """
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ _workspace_root = Path(__file__).parent.parent.parent.parent
18
+ if str(_workspace_root) not in sys.path:
19
+ sys.path.insert(0, str(_workspace_root))
20
+
21
+ from typing import Any, List, Optional, Tuple
22
+
23
+ import numpy as np
24
+ import torch
25
+ from PIL import Image
26
+ from tqdm import tqdm
27
+
28
+ from deployment.model_server.tools.image_tools import to_pil_preserve
29
+ from starVLA.model.framework.base_framework import baseframework
30
+ from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model
31
+ from starVLA.model.modules.action_model.fast_ActionHeader import Fast_Action_Tokenizer
32
+ from starVLA.model.modules.vlm import get_vlm_model
33
+ from starVLA.model.modules.world_model import get_world_model
34
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
35
+ from starVLA.training.trainer_utils import initialize_overwatch
36
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
37
+
38
+ logger = initialize_overwatch(__name__)
39
+
40
+ IGNORE_INDEX = -100
41
+
42
+
43
+ @FRAMEWORK_REGISTRY.register("QwenFastWanPerceiver")
44
+ class QwenFastWanPerceiver(baseframework):
45
+ """
46
+ Qwen-VL + Wan + Perceiver,VLM 内部额外学习 fast action token 预测。
47
+
48
+ - Fast action:VLM 对离散 action token 做自回归监督(训练)/ generate(推理)
49
+ - Continuous action:仅用 VL hidden(不含 action token 段)+ Wan 特征 → Perceiver head
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ config: Optional[dict] = None,
55
+ **kwargs,
56
+ ) -> None:
57
+ super().__init__()
58
+ self.config = config
59
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
60
+ self.wan_interface = get_world_model(config=self.config)
61
+
62
+ wm_cfg = config.framework.get("world_model", {})
63
+ self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False))
64
+ wm_hidden = self.wan_interface.model.config.hidden_size
65
+ cross_dim = self.qwen_vl_interface.model.config.hidden_size
66
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = cross_dim
67
+ self.wm_projector = torch.nn.Linear(wm_hidden, cross_dim)
68
+ self.wm_post_norm = torch.nn.LayerNorm(cross_dim, eps=1e-6)
69
+ gain = float(wm_cfg.get("wm_projector_init_gain", 0.02))
70
+ torch.nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain)
71
+ torch.nn.init.zeros_(self.wm_projector.bias)
72
+
73
+ self.fast_action_model = Fast_Action_Tokenizer()
74
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
75
+
76
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
77
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
78
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
79
+
80
+ self.fast_action_model.fast_tokenizer.time_horizon = self.future_action_window_size + 1
81
+ self.fast_action_model.fast_tokenizer.action_dim = self.config.framework.action_model.action_dim
82
+
83
+ self.fast_loss_weight = float(config.framework.get("fast_loss_weight", 1.0))
84
+
85
+ self.freeze_vlm_for_vla = (
86
+ config.trainer.get("freeze_vlm_for_vla", False)
87
+ if config and hasattr(config, "trainer")
88
+ else False
89
+ )
90
+
91
+ logger.info(
92
+ f"QwenFastWanPerceiver: pool_wm_sequence={self._pool_wm_sequence}, "
93
+ f"fast_loss_weight={self.fast_loss_weight}"
94
+ )
95
+
96
+ @staticmethod
97
+ def _wm_images_head_only(batch_images: List) -> List:
98
+ wm_images = []
99
+ for imgs in batch_images:
100
+ if isinstance(imgs, (list, tuple)):
101
+ wm_images.append([imgs[0]] if len(imgs) > 0 else [])
102
+ else:
103
+ wm_images.append([imgs])
104
+ return wm_images
105
+
106
+ def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor:
107
+ if self._pool_wm_sequence:
108
+ last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True)
109
+ proj_dtype = self.wm_projector.weight.dtype
110
+ x = last_wm_hidden.to(dtype=proj_dtype)
111
+ wm_aligned = self.wm_post_norm(self.wm_projector(x)).to(dtype=last_vlm_hidden.dtype)
112
+ return torch.cat([last_vlm_hidden, wm_aligned], dim=1)
113
+
114
+ def _first_action_token_index(self, input_ids: torch.Tensor) -> int:
115
+ """返回 batch 内第一个 action token 的位置(各样本 VL 段长度应一致)。"""
116
+ act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN
117
+ act_max = self.qwen_vl_interface._ACTION_TOKEN_MAX
118
+ seq = input_ids[0]
119
+ is_action = (seq >= act_min) & (seq <= act_max)
120
+ nonzero = torch.nonzero(is_action, as_tuple=False)
121
+ return nonzero[0].item() if nonzero.numel() > 0 else input_ids.size(1)
122
+
123
+ def _extract_vl_only_hidden(
124
+ self,
125
+ hidden_states: torch.Tensor,
126
+ input_ids: torch.Tensor,
127
+ ) -> torch.Tensor:
128
+ """
129
+ 从含 fast action 的完整序列 hidden 中截取纯 VL 段。
130
+ 因果 LM 下,action token 之前的表示与仅 VL 输入前向一致。
131
+ """
132
+ end_idx = self._first_action_token_index(input_ids)
133
+ return hidden_states[:, :end_idx, :]
134
+
135
+ def _encode_wan_hidden(self, batch_images: List, instructions: List[str]) -> torch.Tensor:
136
+ with torch.no_grad():
137
+ with torch.autocast("cuda", dtype=torch.bfloat16):
138
+ wm_inputs = self.wan_interface.build_inputs(
139
+ images=self._wm_images_head_only(batch_images), instructions=instructions
140
+ )
141
+ wm_outputs = self.wan_interface(
142
+ **wm_inputs,
143
+ output_hidden_states=True,
144
+ return_dict=True,
145
+ )
146
+ return wm_outputs.hidden_states[-1]
147
+
148
+ def map_fast_token_to_vlm_action(self, tokens) -> str:
149
+ return "".join([f"<robot_action_{token}>" for token in tokens])
150
+
151
+ def forward(
152
+ self,
153
+ examples: List[dict] = None,
154
+ **kwargs,
155
+ ) -> dict:
156
+ batch_images = [example["image"] for example in examples]
157
+ instructions = [example["lang"] for example in examples]
158
+ actions = [example["action"] for example in examples]
159
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
160
+ embodiment_tag = (
161
+ [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
162
+ )
163
+
164
+ if "action_mask" in examples[0]:
165
+ action_mask = [example["action_mask"] for example in examples]
166
+ if all(mask is None for mask in action_mask):
167
+ action_mask = None
168
+ else:
169
+ action_mask = None
170
+
171
+ batch_fast_tokens = self.fast_action_model.encoder_action2fastoken(actions)
172
+ vlm_action_tokens = [self.map_fast_token_to_vlm_action(fast_tokens) for fast_tokens in batch_fast_tokens]
173
+
174
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(
175
+ images=batch_images, instructions=instructions, solutions=vlm_action_tokens
176
+ )
177
+ last_wm_hidden = self._encode_wan_hidden(batch_images, instructions)
178
+
179
+ with torch.autocast("cuda", dtype=torch.bfloat16):
180
+ qwenvl_outputs = self.qwen_vl_interface(
181
+ **qwen_inputs,
182
+ output_attentions=False,
183
+ output_hidden_states=True,
184
+ return_dict=True,
185
+ )
186
+ last_vlm_hidden = self._extract_vl_only_hidden(
187
+ qwenvl_outputs.hidden_states[-1], qwen_inputs["input_ids"]
188
+ )
189
+ if self.freeze_vlm_for_vla:
190
+ last_vlm_hidden = last_vlm_hidden.detach()
191
+
192
+ vlm_fast_loss = qwenvl_outputs.loss
193
+ if vlm_fast_loss is None or torch.isnan(vlm_fast_loss):
194
+ vlm_fast_loss = torch.tensor(0.0, device=last_vlm_hidden.device)
195
+
196
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
197
+
198
+ with torch.autocast("cuda", dtype=torch.float32):
199
+ actions_tensor = torch.tensor(
200
+ np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype
201
+ )
202
+ actions_target = actions_tensor[:, -(self.future_action_window_size + 1) :, :]
203
+
204
+ repeated_diffusion_steps = (
205
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
206
+ )
207
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
208
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
209
+
210
+ state_repeated = None
211
+ if state is not None:
212
+ state_tensor = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype)
213
+ state_repeated = state_tensor.repeat(repeated_diffusion_steps, 1, 1)
214
+
215
+ action_mask_repeated = None
216
+ if action_mask is not None:
217
+ action_mask_tensor = torch.tensor(
218
+ np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype
219
+ )
220
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1) :, :]
221
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
222
+
223
+ if embodiment_tag is not None:
224
+ embodiment_tag_tensor = torch.tensor(
225
+ np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64
226
+ )
227
+ embodiment_tag_repeated = embodiment_tag_tensor.repeat(repeated_diffusion_steps)
228
+ else:
229
+ embodiment_tag_repeated = None
230
+
231
+ diffusion_action_loss = self.action_model(
232
+ last_hidden_repeated,
233
+ actions_target_repeated,
234
+ state_repeated,
235
+ embodiment_tag_repeated,
236
+ action_mask=action_mask_repeated,
237
+ )
238
+
239
+ action_loss = diffusion_action_loss + self.fast_loss_weight * vlm_fast_loss
240
+ return {
241
+ "action_loss": action_loss,
242
+ "vlm_fast_loss": vlm_fast_loss,
243
+ "diffusion_action_loss": diffusion_action_loss,
244
+ }
245
+
246
+ @torch.inference_mode()
247
+ def predict_action(
248
+ self,
249
+ examples: List[dict],
250
+ **kwargs: str,
251
+ ) -> dict:
252
+ if not isinstance(examples, list):
253
+ examples = [examples]
254
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
255
+ instructions = [example["lang"] for example in examples]
256
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
257
+ embodiment_tag = (
258
+ [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
259
+ )
260
+
261
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
262
+ if train_obs_image_size:
263
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
264
+
265
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
266
+ last_wm_hidden = self._encode_wan_hidden(batch_images, instructions)
267
+
268
+ with torch.autocast("cuda", dtype=torch.bfloat16):
269
+ qwenvl_outputs = self.qwen_vl_interface(
270
+ **qwen_inputs,
271
+ output_attentions=False,
272
+ output_hidden_states=True,
273
+ return_dict=True,
274
+ )
275
+ last_vlm_hidden = qwenvl_outputs.hidden_states[-1]
276
+
277
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
278
+
279
+ state_tensor = (
280
+ torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
281
+ if state is not None
282
+ else None
283
+ )
284
+ embodiment_tag_tensor = (
285
+ torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
286
+ if embodiment_tag is not None
287
+ else None
288
+ )
289
+
290
+ with torch.autocast("cuda", dtype=torch.float32):
291
+ if embodiment_tag_tensor is not None:
292
+ pred_actions = self.action_model.predict_action(last_hidden, state_tensor, embodiment_tag_tensor)
293
+ else:
294
+ pred_actions = self.action_model.predict_action(last_hidden, state_tensor)
295
+
296
+ normalized_actions = pred_actions.detach().cpu().numpy()
297
+ return {"normalized_actions": normalized_actions}
298
+
299
+ @torch.inference_mode()
300
+ def predict_fast_action(
301
+ self,
302
+ examples: List[dict],
303
+ **kwargs,
304
+ ) -> dict:
305
+ """可选:单独通过 VLM generate 预测 fast 离散 action。"""
306
+ if not isinstance(examples, list):
307
+ examples = [examples]
308
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
309
+ instructions = [example["lang"] for example in examples]
310
+
311
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
312
+ with torch.autocast("cuda", dtype=torch.bfloat16):
313
+ generated_ids = self.qwen_vl_interface.model.generate(**qwen_inputs, max_length=2048)
314
+
315
+ batch_vlm_action_token_ids = self._extract_action_token_ids(generated_ids)
316
+ batch_fast_action_token_idx = self._decode_action_tokens(batch_vlm_action_token_ids)
317
+ normalized_actions = self.fast_action_model.fast_tokenizer.decode(batch_fast_action_token_idx)
318
+ return {"normalized_actions": normalized_actions}
319
+
320
+ def _extract_action_token_ids(self, generated_ids: torch.LongTensor) -> List[List[int]]:
321
+ act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN
322
+ act_max = self.qwen_vl_interface._ACTION_TOKEN_MAX
323
+ mask = (generated_ids >= act_min) & (generated_ids <= act_max)
324
+ results = []
325
+ for b in range(generated_ids.size(0)):
326
+ idx = mask[b].nonzero(as_tuple=False).flatten()
327
+ if idx.numel() == 0:
328
+ results.append([])
329
+ continue
330
+ results.append(generated_ids[b, idx].tolist())
331
+ return results
332
+
333
+ def _decode_action_tokens(self, batch_vlm_tokens: List[List[int]]) -> List[Any]:
334
+ act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN
335
+ batch_fast_token_ids = []
336
+ for seq in batch_vlm_tokens:
337
+ if not seq:
338
+ batch_fast_token_ids.append(None)
339
+ continue
340
+ batch_fast_token_ids.append([t - act_min for t in seq])
341
+ return batch_fast_token_ids
342
+
343
+
344
+ if __name__ == "__main__":
345
+ from omegaconf import OmegaConf
346
+
347
+ cfg = OmegaConf.load("examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml")
348
+ model: QwenFastWanPerceiver = QwenFastWanPerceiver(cfg)
349
+ print(model)
350
+
351
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
352
+ sample = {
353
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16),
354
+ "image": [image],
355
+ "lang": "Put all the toys in the child's room.",
356
+ }
357
+ sample2 = {
358
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16),
359
+ "image": [image],
360
+ "lang": "Put all the toys in the child's room.",
361
+ }
362
+
363
+ batch = [sample, sample2]
364
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
365
+ model = model.to(device)
366
+ forward_output = model(batch)
367
+ print(f"Action Loss: {forward_output['action_loss'].item()}")
368
+ print(f"VLM Fast Loss: {forward_output['vlm_fast_loss'].item()}")
369
+ print(f"Diffusion Loss: {forward_output['diffusion_action_loss'].item()}")
370
+
371
+ predict_output = model.predict_action(examples=[sample])
372
+ print(f"Predicted Actions: {predict_output['normalized_actions']}")
starVLA/model/framework/QwenGR00T.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Junqiu YU / Fudan University] in [2025].
4
+ # Design and Merged by [Jinhui YE / HKUST University] in [2025].
5
+ """
6
+ Qwen-GR00T Framework
7
+ A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions
8
+ Flow-matching header is copyright from GR00T N1.5,
9
+ """
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ # Add workspace root to Python path if not already there
14
+ _workspace_root = Path(__file__).parent.parent.parent.parent
15
+ if str(_workspace_root) not in sys.path:
16
+ sys.path.insert(0, str(_workspace_root))
17
+
18
+ from typing import List
19
+ from tqdm import tqdm
20
+ from typing import List, Optional, Tuple
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import numpy as np
25
+ from PIL import Image
26
+
27
+
28
+
29
+ from starVLA.training.trainer_utils import initialize_overwatch
30
+ from deployment.model_server.tools.image_tools import to_pil_preserve
31
+
32
+ logger = initialize_overwatch(__name__)
33
+
34
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
35
+ IGNORE_INDEX = -100
36
+
37
+ from starVLA.model.framework.base_framework import baseframework
38
+ from starVLA.model.modules.vlm import get_vlm_model
39
+ from starVLA.model.modules.action_model.GR00T_ActionHeader import get_action_model, FlowmatchingActionHead
40
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
41
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
42
+
43
+
44
+ @FRAMEWORK_REGISTRY.register("QwenGR00T")
45
+ class Qwen_GR00T(baseframework):
46
+ """
47
+ Multimodal vision-language-action model.
48
+
49
+ Components:
50
+ - Qwen2.5 VL interface for fused language/vision token embeddings
51
+ - Layer-wise QFormer for multi-layer feature aggregation
52
+ - DINO encoder for dense multi-view spatial tokens
53
+ - DiT diffusion head for future action sequence modeling
54
+
55
+ Focus: Predict future continuous actions conditioned on images + instruction.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ config: Optional[dict] = None,
61
+ **kwargs,
62
+ ) -> None:
63
+ """
64
+ Construct all submodules and cache key configuration values.
65
+
66
+ Args:
67
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
68
+ **kwargs: Reserved for future overrides (unused).
69
+ """
70
+ super().__init__()
71
+ self.config = config
72
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
73
+ # align dims --> we should put them to config or no?
74
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = self.qwen_vl_interface.model.config.hidden_size
75
+
76
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用
77
+
78
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
79
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
80
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
81
+
82
+
83
+ def forward(
84
+ self,
85
+ examples: List[dict] = None,
86
+ **kwargs,
87
+ ) -> Tuple:
88
+ """
89
+
90
+ """
91
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
92
+ instructions = [example["lang"] for example in examples] # [B, str]
93
+ actions = [example["action"] for example in examples] # label [B, len, 7]
94
+
95
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
96
+
97
+ # Extract action_mask if available
98
+
99
+ action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None # [B, len, action_dim]
100
+
101
+
102
+
103
+ # Step 1: QWenVL input format
104
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
105
+ with torch.autocast("cuda", dtype=torch.bfloat16):
106
+ qwenvl_outputs = self.qwen_vl_interface(
107
+ **qwen_inputs,
108
+ output_attentions=False,
109
+ output_hidden_states=True,
110
+ return_dict=True,
111
+ )
112
+ # last_hidden_state: [B, seq_len, H]
113
+ last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H]
114
+
115
+ # Step 4: Action Expert Forward and Loss
116
+ with torch.autocast("cuda", dtype=torch.float32):
117
+ actions = torch.tensor(
118
+ np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype
119
+ ) # [B, T_full, action_dim]
120
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
121
+
122
+ repeated_diffusion_steps = (
123
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
124
+ )
125
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
126
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
127
+
128
+ state_repeated = None
129
+ if state is not None:
130
+ state = torch.tensor(
131
+ np.array(state), device=last_hidden.device, dtype=last_hidden.dtype
132
+ )
133
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
134
+
135
+ # Process action_mask if available
136
+ action_mask_repeated = None
137
+ if action_mask is not None:
138
+ action_mask_tensor = torch.tensor(
139
+ np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype
140
+ ) # [B, T_full, action_dim]
141
+
142
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
143
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
144
+
145
+
146
+ action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated, action_mask=action_mask_repeated) # (B, chunk_len, action_dim)
147
+
148
+
149
+ return {"action_loss": action_loss}
150
+
151
+ @torch.inference_mode()
152
+ def predict_action(
153
+ self,
154
+ examples: List[dict],
155
+ **kwargs: str,
156
+ ) -> np.ndarray:
157
+ """
158
+ Steps:
159
+ 1. Resize images to training resolution (if specified)
160
+ 2. Encode with QwenVL (hidden states retained)
161
+ 6. Return normalized action trajectory
162
+ Returns:
163
+ dict:
164
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
165
+ """
166
+ if type(examples) is not list:
167
+ examples = [examples]
168
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
169
+ instructions = [example["lang"] for example in examples] # [B, str]
170
+
171
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
172
+
173
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
174
+ if train_obs_image_size:
175
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
176
+
177
+ # Step 1: QWenVL input format
178
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
179
+ with torch.autocast("cuda", dtype=torch.bfloat16):
180
+ qwenvl_outputs = self.qwen_vl_interface(
181
+ **qwen_inputs,
182
+ output_attentions=False,
183
+ output_hidden_states=True,
184
+ return_dict=True,
185
+ )
186
+
187
+ # last_hidden_state: [B, seq_len, H]
188
+ last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H]
189
+
190
+ state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None
191
+
192
+ # Step 4: Action Expert Forward
193
+ with torch.autocast("cuda", dtype=torch.float32):
194
+ pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim)
195
+
196
+ normalized_actions = pred_actions.detach().cpu().numpy()
197
+ return {"normalized_actions": normalized_actions}
198
+
199
+
200
+
201
+ if __name__ == "__main__":
202
+ from omegaconf import OmegaConf
203
+ import debugpy
204
+ import argparse
205
+ parser = argparse.ArgumentParser()
206
+ parser.add_argument("--config_yaml", type=str, default="/mnt/workspace/users/chenzengjue/starVLA2/examples/Robocasa_tabletop/train_files/starvla_cotrain_ego_sq.yaml", help="Path to YAML config")
207
+ args, clipargs = parser.parse_known_args()
208
+
209
+ debugpy.listen(("0.0.0.0", 10093))
210
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
211
+ debugpy.wait_for_client()
212
+ args.config_yaml = "/mnt/workspace/users/chenzengjue/starVLA2/examples/Robocasa_tabletop/train_files/test.yaml"
213
+ cfg = OmegaConf.load(args.config_yaml)
214
+ # try get model
215
+ # cfg.framework.action_model.action_hidden_dim = 2048
216
+
217
+ # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large"
218
+
219
+
220
+ model: Qwen_GR00T = Qwen_GR00T(cfg)
221
+ print(model)
222
+
223
+
224
+
225
+ # # fake sample
226
+ # image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
227
+ # # Create a sample
228
+ # sample = {
229
+ # "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
230
+ # "image": [image], # three views
231
+ # "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
232
+ # # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
233
+ # }
234
+ # sample2 = {
235
+ # "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
236
+ # "image": [image], # three views
237
+ # "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
238
+ # # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
239
+ # }
240
+
241
+ # batch = [sample, sample2] # batch size 2
242
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
243
+ # model = model.to(device)
244
+ # forward_output = model(batch)
245
+ # action_loss = forward_output['action_loss']
246
+ # print(f"Action Loss: {action_loss.item()}")
247
+
248
+ # # test predict action
249
+ # predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]]
250
+ # normalized_actions = predict_output['normalized_actions']
251
+ # print(f"Unnormalized Action: {normalized_actions}")
252
+
253
+ # # Advance: try forward model with dataloader
254
+ # # can be fake sample, but here get from dataloader for simpler
255
+ vla_dataset_cfg = cfg.datasets.vla_data
256
+ from torch.utils.data import DataLoader
257
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
258
+ cfg.datasets.vla_data.include_state = "False"
259
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
260
+
261
+ train_dataloader = DataLoader(
262
+ dataset,
263
+ batch_size=2,
264
+ num_workers=1, # For Debug
265
+ collate_fn=collate_fn,
266
+ )
267
+ # forward model with dataloader
268
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
269
+ # try get model
270
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
271
+ model = model.to(device)
272
+ model(batch)
273
+ # break
274
+
275
+ action = model.predict_action(examples=batch)
276
+ print("Finished")
starVLA/model/framework/QwenOFT.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Jinhui YE / HKUST University] in [2025].
4
+
5
+ """
6
+ Qwen-OFT Framework
7
+
8
+ A lightweight implementation that uses an action special token to parallelly predict continuous actions
9
+ conditioned on multi-view images plus a language instruction (shares parameters with the VLM).
10
+ Inspired by OpenVLA-OFT
11
+ Key Points:
12
+ - Qwen2.5 vision-language backbone
13
+ - Injects an action special token into the VLM
14
+ - Continuous action prediction via L1 regression over the action special token hidden states
15
+
16
+
17
+ Note: How to add special tokens to Qwen2.5:
18
+ download our model checkpoint with special tokens added: https://huggingface.co/StarVLA/Qwen2.5-VL-3B-Instruct-Action
19
+ or /starVLA/model/modules/vlm/tools/add_qwen_special_tokens/README.md (adpat a little code)
20
+
21
+ """
22
+ from typing import List
23
+ from tqdm import tqdm
24
+ from typing import List, Optional, Tuple
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ import numpy as np
29
+ from PIL import Image
30
+
31
+
32
+
33
+ from starVLA.training.trainer_utils import initialize_overwatch
34
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
35
+ from deployment.model_server.tools.image_tools import to_pil_preserve
36
+
37
+ logger = initialize_overwatch(__name__)
38
+
39
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
40
+ IGNORE_INDEX = -100
41
+
42
+ from starVLA.model.framework.base_framework import baseframework
43
+ from starVLA.model.modules.vlm import get_vlm_model
44
+ from starVLA.model.modules.action_model.MLP_ActionHeader import get_action_model
45
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
46
+
47
+ @FRAMEWORK_REGISTRY.register("QwenOFT")
48
+ class Qwenvl_OFT(baseframework):
49
+ """
50
+ Multimodal vision-language-action model.
51
+
52
+ Components:
53
+ - Qwen2.5 VL interface for fused language/vision token embeddings
54
+ - Layer-wise QFormer for multi-layer feature aggregation
55
+ - DINO encoder for dense multi-view spatial tokens
56
+ - DiT diffusion head for future action sequence modeling
57
+
58
+ Focus: Predict future continuous actions conditioned on images + instruction.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ config: Optional[dict] = None,
64
+ **kwargs,
65
+ ) -> None:
66
+ """
67
+ Construct all submodules and cache key configuration values.
68
+
69
+ Args:
70
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
71
+ **kwargs: Reserved for future overrides (unused).
72
+ """
73
+ super().__init__()
74
+ self.config = config
75
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
76
+ # align dims --> we should put them to config or no?
77
+ config.framework.action_model.action_hidden_dim = self.qwen_vl_interface.model.config.hidden_size
78
+ self.action_model = get_action_model(config=self.config)
79
+
80
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
81
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
82
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
83
+ # self.hidden_dim = config.framework.action_model.action_hidden_dim
84
+
85
+ self.action_token = "🔍" # TODO also can add spacail token to Qwen, but too complex
86
+ self.action_token_id = self.qwen_vl_interface.processor.tokenizer("🔍", add_special_tokens=False)["input_ids"][0]
87
+
88
+ # L1 损失
89
+ self.l1_loss = nn.L1Loss()
90
+
91
+ def forward(
92
+ self,
93
+ examples: List[dict] = None,
94
+ **kwargs,
95
+ ) -> Tuple:
96
+ """
97
+ 训练前向:直接回归未来动作(无扩散)。
98
+
99
+ Flow:
100
+ 1. Build QwenVL inputs (images + instruction tokens)
101
+ 2. Extract hidden states from configured layer range
102
+ 7. Predict action and compute L1 loss
103
+
104
+ Args:
105
+ examples: List[dict], each dict requires:
106
+ - image: List[PIL.Image] (multi-view)
107
+ - lang: str instruction
108
+ - action: np.ndarray or list shaped [T, action_dim]
109
+ **kwargs: Reserved.
110
+
111
+ Returns:
112
+ dict:
113
+ action_loss (torch.Tensor): Scalar diffusion noise prediction loss.
114
+ """
115
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
116
+ instructions = [example["lang"] for example in examples] # [B, str]
117
+ actions = [example["action"] for example in examples] # label [B, len, 7]
118
+
119
+ # step 0: add special action token to instruction
120
+ action_tokens = self.action_token* self.chunk_len #can't add " " between two tokens, otherwise will be tokenized to multiple tokens
121
+ prompt_suffix = f" Please predict the next {self.chunk_len} robot actions: <action>{action_tokens}<action>."
122
+ instructions = [instruction + prompt_suffix for instruction in instructions]
123
+
124
+ # Step 1: QWenVL input format
125
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
126
+ with torch.autocast("cuda", dtype=torch.bfloat16):
127
+ qwenvl_outputs = self.qwen_vl_interface(
128
+ **qwen_inputs,
129
+ output_attentions=False,
130
+ output_hidden_states=True,
131
+ return_dict=True,
132
+ )
133
+ # last_hidden_state: [B, seq_len, H]
134
+ last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H]
135
+
136
+ # Step 4: Action Expert Forward and Loss
137
+ with torch.autocast("cuda", dtype=torch.float32):
138
+ # 提取动作 token embedding 作为动作预测查询
139
+ input_ids = qwen_inputs.get("input_ids", None)
140
+ action_queries = self._gather_action_token_embeddings(last_hidden, input_ids, action_token_id=self.action_token_id) # [B, chunk_len, H]
141
+ pred_actions = self.action_model.predict_action(action_queries) # (B, chunk_len, action_dim)
142
+
143
+ # 标签对齐:取最后 chunk_len 段
144
+ actions = torch.tensor(
145
+ np.array(actions), device=pred_actions.device, dtype=pred_actions.dtype
146
+ ) # [B, T_full, action_dim]
147
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
148
+
149
+ # 计算 L1 损失
150
+ action_loss = self.l1_loss(pred_actions, actions_target)
151
+
152
+ return {"action_loss": action_loss}
153
+
154
+ @torch.inference_mode()
155
+ def predict_action(
156
+ self,
157
+ examples: List[dict] = None,
158
+ **kwargs: str,
159
+ ) -> np.ndarray:
160
+ """
161
+ 推理:单次前向直接回归未来动作(无扩散采样)。
162
+
163
+ Steps:
164
+ 1. Resize images to training resolution (if specified)
165
+ 2. Encode with QwenVL (hidden states retained)
166
+ 6. Return normalized action trajectory
167
+
168
+ Returns:
169
+ dict:
170
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
171
+ """
172
+
173
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
174
+ instructions = [example["lang"] for example in examples] # [B, str]
175
+
176
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
177
+ if train_obs_image_size:
178
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
179
+
180
+ # step 0: add special action token to instruction
181
+ action_tokens = self.action_token* self.chunk_len #can't add " " between two tokens, otherwise will be tokenized to multiple tokens
182
+ prompt_suffix = f" Please predict the next {self.chunk_len} robot actions: <action>{action_tokens}<action>."
183
+ instructions = [instruction + prompt_suffix for instruction in instructions]
184
+
185
+ # Step 1: QWenVL input format
186
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
187
+ with torch.autocast("cuda", dtype=torch.bfloat16):
188
+ qwenvl_outputs = self.qwen_vl_interface(
189
+ **qwen_inputs,
190
+ output_attentions=False,
191
+ output_hidden_states=True,
192
+ return_dict=True,
193
+ )
194
+ # last_hidden_state: [B, seq_len, H]
195
+ last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H]
196
+
197
+ # Step 4: Action Expert Forward and Loss
198
+ with torch.autocast("cuda", dtype=torch.float32):
199
+ # 提取动作 token embedding 作为动作预测查询
200
+ input_ids = qwen_inputs.get("input_ids", None)
201
+ action_queries = self._gather_action_token_embeddings(last_hidden, input_ids, action_token_id=self.action_token_id) # [B, chunk_len, H]
202
+ pred_actions = self.action_model.predict_action(action_queries) # (B, chunk_len, action_dim)
203
+
204
+ normalized_actions = pred_actions.detach().cpu().numpy()
205
+ return {"normalized_actions": normalized_actions}
206
+
207
+ def _gather_action_token_embeddings(
208
+ self,
209
+ last_hidden: torch.Tensor, # [B, L, H]
210
+ input_ids: torch.Tensor, # [B, L]
211
+ action_token_id=None, # 可为 int 或 List[int]
212
+ ) -> torch.Tensor:
213
+ """
214
+ 向量化批量提取动作 token embedding:
215
+ - 不再逐样本 for 循环
216
+ - 取每个样本里最靠后的 chunk_len 个动作占位 token
217
+ Args:
218
+ last_hidden: [B, L, H]
219
+ input_ids: [B, L]
220
+ action_token_id: int 或 List[int]
221
+ Returns:
222
+ action_queries: [B, chunk_len, H]
223
+ """
224
+ if action_token_id is None:
225
+ raise ValueError("action_token_id 不能为空")
226
+
227
+ device = input_ids.device
228
+ B, L, H = last_hidden.shape
229
+
230
+ # 支持多 id(如多个变体)
231
+ if isinstance(action_token_id, (list, tuple, set)):
232
+ id_list = torch.tensor(list(action_token_id), device=device, dtype=input_ids.dtype)
233
+ # torch.isin 需要 PyTorch >=1.10
234
+ mask = torch.isin(input_ids, id_list)
235
+ else:
236
+ mask = (input_ids == action_token_id) # [B, L]
237
+
238
+ counts = mask.sum(dim=1) # [B]
239
+ if (counts < self.chunk_len).any():
240
+ insufficient = (counts < self.chunk_len).nonzero(as_tuple=False).flatten().tolist()
241
+ raise RuntimeError(
242
+ f"以下样本动作 token 数量不足 {self.chunk_len}: {insufficient} | counts={counts.tolist()}"
243
+ )
244
+
245
+ # 位置索引
246
+ idx = torch.arange(L, device=device).unsqueeze(0).expand(B, L) # [B, L]
247
+ masked_pos = torch.where(mask, idx, torch.full_like(idx, -1)) # 非动作位置置 -1
248
+
249
+ # 取最后 chunk_len 个(索引大的在序列靠后)
250
+ # 注意: 已确保数量足够,不会出现 -1 被错误选中的问题
251
+ topk_pos = masked_pos.topk(k=self.chunk_len, dim=-1).values # [B, chunk_len] 未排序
252
+ # 时间顺序排序
253
+ selected_pos = topk_pos.sort(dim=-1).values # [B, chunk_len]
254
+
255
+ # Gather
256
+ expanded_index = selected_pos.unsqueeze(-1).expand(-1, -1, H) # [B, chunk_len, H]
257
+ action_queries = last_hidden.gather(dim=1, index=expanded_index) # [B, chunk_len, H]
258
+ return action_queries
259
+
260
+
261
+ if __name__ == "__main__":
262
+ from omegaconf import OmegaConf
263
+ import debugpy
264
+ import argparse
265
+ parser = argparse.ArgumentParser()
266
+ parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config")
267
+ args, clipargs = parser.parse_known_args()
268
+
269
+ debugpy.listen(("0.0.0.0", 10092))
270
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
271
+ debugpy.wait_for_client()
272
+
273
+ cfg = OmegaConf.load(args.config_yaml)
274
+ cfg.framework.action_model.action_hidden_dim = 2048
275
+
276
+ cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large"
277
+
278
+
279
+ # try get model
280
+ model = Qwenvl_OFT(cfg)
281
+ print(model)
282
+
283
+ # fake sample
284
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
285
+ # Create a sample
286
+ sample = {
287
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
288
+ "image": [image], # two views
289
+ "lang": "This is a fake instruction for testing.",
290
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
291
+ }
292
+
293
+ sample2 = {
294
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
295
+ "image": [image], # two views
296
+ "lang": "For testing.",
297
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
298
+ }
299
+
300
+ batch = [sample, sample2] # batch size 2
301
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
302
+ model = model.to(device)
303
+ forward_output = model(batch)
304
+ action_loss = forward_output['action_loss']
305
+ print(f"Action Loss: {action_loss.item()}")
306
+
307
+ # test predict action
308
+ predict_output = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]])
309
+ normalized_actions = predict_output['normalized_actions']
310
+ print(f"Unnormalized Action: {normalized_actions}")
311
+
312
+
313
+ # try forward model
314
+ # can be fake sample, but here get from dataloader for simpler
315
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
316
+
317
+ vla_dataset_cfg = cfg.datasets.vla_data
318
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
319
+
320
+ from torch.utils.data import DataLoader
321
+
322
+ train_dataloader = DataLoader(
323
+ dataset,
324
+ batch_size=2,
325
+ num_workers=1, # For Debug
326
+ collate_fn=collate_fn,
327
+ )
328
+ # zhe
329
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
330
+ batch
331
+ break
332
+
333
+ # try get model
334
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
335
+ model = model.to(device)
336
+ model(batch)
337
+ pass
338
+ action = model.predict_action(batch)
starVLA/model/framework/QwenPI.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by Jinhui YE / HKUST University] in [2025].
4
+ """
5
+ Qwen-GROOT Framework
6
+ A lightweight implementation that Qwen2.5-vl + Flow-matching head to directly predict continuous actions
7
+ Flow-matching header is copyright from GR00T N1.5, but a sample MoE inspired by PI_0
8
+ """
9
+ from typing import List
10
+ from tqdm import tqdm
11
+ from typing import List, Optional, Tuple
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ import numpy as np
16
+ from PIL import Image
17
+
18
+
19
+
20
+ from starVLA.training.trainer_utils import initialize_overwatch
21
+ from deployment.model_server.tools.image_tools import to_pil_preserve
22
+
23
+ logger = initialize_overwatch(__name__)
24
+
25
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
26
+ IGNORE_INDEX = -100
27
+
28
+ from starVLA.model.framework.base_framework import baseframework
29
+ from starVLA.model.modules.vlm import get_vlm_model
30
+ from starVLA.model.modules.action_model.LayerwiseFM_ActionHeader import get_action_model, LayerwiseFlowmatchingActionHead
31
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
32
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
33
+
34
+ ####################################################
35
+ # ⚠️ Warning: This framework has been restructured and is NOT compatible with checkpoints created before 2025-10-20.
36
+ ####################################################
37
+
38
+ @FRAMEWORK_REGISTRY.register("QwenPI")
39
+ class Qwen_PI(baseframework):
40
+ """
41
+ Multimodal vision-language-action model.
42
+
43
+ Components:
44
+ - Qwen2.5 VL interface for fused language/vision token embeddings
45
+ - Layer-wise cross DiT diffusion head
46
+
47
+
48
+ Focus: Predict future continuous actions conditioned on images + instruction.
49
+ """
50
+ #
51
+ def __init__(
52
+ self,
53
+ config: Optional[dict] = None,
54
+ **kwargs,
55
+ ) -> None:
56
+ """
57
+ Construct all submodules and cache key configuration values.
58
+
59
+ Args:
60
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
61
+ **kwargs: Reserved for future overrides (unused).
62
+ """
63
+
64
+ super().__init__()
65
+ self.config = config
66
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
67
+
68
+ # dynamic get llm config
69
+ num_vl_layers, llm_hidden_size = 36, self.qwen_vl_interface.model.config.hidden_size
70
+ self.config.framework.qwenvl.vl_hidden_dim = llm_hidden_size
71
+ self.config.framework.qwenvl.num_vl_layers = num_vl_layers
72
+
73
+ self.action_model: LayerwiseFlowmatchingActionHead = get_action_model(config=self.config)
74
+
75
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
76
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
77
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
78
+
79
+
80
+ def forward(
81
+ self,
82
+ examples: List[dict] = None,
83
+ **kwargs,
84
+ ) -> Tuple:
85
+ """
86
+ Args:
87
+ examples: List[dict], each dict requires:
88
+ - image: List[PIL.Image] (multi-view)
89
+ - lang: str instruction
90
+ - action: np.ndarray or list shaped [T, action_dim]
91
+ Returns:
92
+ dict:
93
+ action_loss (torch.Tensor): Scalar diffusion noise prediction loss.
94
+ """
95
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
96
+ instructions = [example["lang"] for example in examples] # [B, str]
97
+ actions = [example["action"] for example in examples] # label [B, len, 7]
98
+
99
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
100
+
101
+
102
+ # Step 1: QWenVL input format
103
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
104
+ with torch.autocast("cuda", dtype=torch.bfloat16):
105
+ qwenvl_outputs = self.qwen_vl_interface(
106
+ **qwen_inputs,
107
+ output_attentions=False,
108
+ output_hidden_states=True,
109
+ return_dict=True,
110
+ )
111
+ # 取与 DiT 层数匹配的最后 N 层隐藏态,按层喂给 DiT
112
+ all_hidden = qwenvl_outputs.hidden_states
113
+ expected_layers = len(self.action_model.model.transformer_blocks)
114
+ vl_embs_list = list(all_hidden[-expected_layers:])
115
+ base_hidden = vl_embs_list[-1]
116
+
117
+ # Step 4: Action Expert Forward and Loss
118
+ with torch.autocast("cuda", dtype=torch.float32):
119
+ # 标签对齐:取最后 chunk_len 段
120
+ actions = torch.tensor(
121
+ np.array(actions), device=base_hidden.device, dtype=base_hidden.dtype
122
+ ) # [B, T_full, action_dim]
123
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
124
+
125
+ repeated_diffusion_steps = (
126
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
127
+ )
128
+ repeated_diffusion_steps = 2 # NO repeat for big action FM
129
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
130
+ # 对每层特征做 repeat
131
+ vl_embs_list_repeated = [h.repeat(repeated_diffusion_steps, 1, 1) for h in vl_embs_list]
132
+
133
+ state_repeated = None
134
+ if state is not None:
135
+ state = torch.tensor(
136
+ np.array(state), device=base_hidden.device, dtype=base_hidden.dtype
137
+ )
138
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
139
+
140
+ action_loss = self.action_model(vl_embs_list_repeated, actions_target_repeated, state_repeated) # (B, chunk_len, action_dim)
141
+
142
+
143
+
144
+ return {"action_loss": action_loss}
145
+
146
+ @torch.inference_mode()
147
+ def predict_action( # TODO align predict_action with forward, make api more flexible
148
+ self,
149
+ examples: List[dict] = None,
150
+ **kwargs: str,
151
+ ) -> np.ndarray:
152
+ """
153
+ 推理:单次前向直接回归未来动作(无扩散采样)。
154
+
155
+ Steps:
156
+ 1. Resize images to training resolution (if specified)
157
+ 2. Encode with QwenVL (hidden states retained)
158
+ 6. Return normalized action trajectory
159
+
160
+ Returns:
161
+ dict:
162
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
163
+ """
164
+ from deployment.model_server.tools.image_tools import to_pil_preserve
165
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
166
+ instructions = [example["lang"] for example in examples] # [B, str]
167
+
168
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
169
+
170
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
171
+ if train_obs_image_size:
172
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
173
+
174
+ # Step 1: QWenVL input format
175
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
176
+ with torch.autocast("cuda", dtype=torch.bfloat16):
177
+ qwenvl_outputs = self.qwen_vl_interface(
178
+ **qwen_inputs,
179
+ output_attentions=False,
180
+ output_hidden_states=True,
181
+ return_dict=True,
182
+ )
183
+ all_hidden = qwenvl_outputs.hidden_states
184
+ expected_layers = len(self.action_model.model.transformer_blocks)
185
+ vl_embs_list = list(all_hidden[-expected_layers:])
186
+ base_hidden = vl_embs_list[-1]
187
+
188
+ state = torch.from_numpy(np.array(state)).to(base_hidden.device, dtype=base_hidden.dtype) if state is not None else None
189
+ # Step 4: Action Expert Forward and Loss
190
+ with torch.autocast("cuda", dtype=torch.float32):
191
+ pred_actions = self.action_model.predict_action(vl_embs_list, state) # (B, chunk_len, action_dim)
192
+
193
+ normalized_actions = pred_actions.detach().cpu().numpy()
194
+ return {"normalized_actions": normalized_actions}
195
+
196
+
197
+
198
+ if __name__ == "__main__":
199
+ from omegaconf import OmegaConf
200
+ import debugpy
201
+ import argparse
202
+ parser = argparse.ArgumentParser()
203
+ parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config")
204
+ args, clipargs = parser.parse_known_args()
205
+
206
+ debugpy.listen(("0.0.0.0", 10092))
207
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
208
+ debugpy.wait_for_client()
209
+
210
+ cfg = OmegaConf.load(args.config_yaml)
211
+ # try get model
212
+ cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen3-VL-4B-Instruct"
213
+
214
+
215
+ model = Qwen_PI(cfg)
216
+ # ckpt="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1011_qwenpi/checkpoints/need_steps_10000_pytorch_model.pt"
217
+ # model = Qwen_PI.from_pretrained(ckpt)
218
+ print(model)
219
+
220
+
221
+ # fake sample
222
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
223
+ # Create a sample
224
+ sample = {
225
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
226
+ "image": [image, image], # two views
227
+ "lang": "This is a fake instruction for testing.",
228
+ "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
229
+ }
230
+
231
+ batch = [sample, sample] # batch size 2
232
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
233
+ model = model.to(device)
234
+ forward_output = model(batch)
235
+ action_loss = forward_output['action_loss']
236
+ print(f"Action Loss: {action_loss.item()}")
237
+
238
+ # test predict action
239
+ predict_output = model.predict_action([sample])
240
+ normalized_actions = predict_output['normalized_actions']
241
+ print(f"Unnormalized Action: {normalized_actions}")
242
+
243
+ # # Advance: try forward model with dataloader
244
+ # # can be fake sample, but here get from dataloader for simpler
245
+ # from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
246
+
247
+ # vla_dataset_cfg = cfg.datasets.vla_data
248
+ # dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
249
+
250
+ # from torch.utils.data import DataLoader
251
+
252
+ # train_dataloader = DataLoader(
253
+ # dataset,
254
+ # batch_size=2,
255
+ # num_workers=1, # For Debug
256
+ # collate_fn=collate_fn,
257
+ # )
258
+ # #
259
+ # for batch in tqdm(train_dataloader, desc="Processing Batches"):
260
+ # batch
261
+ # break
262
+
263
+ # # try get model
264
+ # device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
265
+ # model = model.to(device)
266
+ # model(batch)
267
+
268
+ # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]])
269
+
270
+ # # fake state
271
+ # for ba in batch:
272
+ # ba["state"] = ba["action"][0][None]
273
+
274
+ # model(batch)
275
+ # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]], state=[batch[0]["state"]])
starVLA/model/framework/QwenPerceiver.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Junqiu YU / Fudan University] in [2025].
4
+ # Design and Merged by [Jinhui YE / HKUST University] in [2025].
5
+ """
6
+ Qwen-GR00T Framework
7
+ A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions
8
+ Flow-matching header is copyright from GR00T N1.5,
9
+ """
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ # Add workspace root to Python path if not already there
14
+ _workspace_root = Path(__file__).parent.parent.parent.parent
15
+ if str(_workspace_root) not in sys.path:
16
+ sys.path.insert(0, str(_workspace_root))
17
+
18
+ from typing import List
19
+ from tqdm import tqdm
20
+ from typing import List, Optional, Tuple
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import numpy as np
25
+ from PIL import Image
26
+
27
+
28
+
29
+ from starVLA.training.trainer_utils import initialize_overwatch
30
+ from deployment.model_server.tools.image_tools import to_pil_preserve
31
+
32
+ logger = initialize_overwatch(__name__)
33
+
34
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
35
+ IGNORE_INDEX = -100
36
+
37
+ from starVLA.model.framework.base_framework import baseframework
38
+ from starVLA.model.modules.vlm import get_vlm_model
39
+
40
+ from starVLA.model.modules.action_model.PerceiverHead import get_action_model, FlowmatchingActionHead
41
+ from starVLA.model.modules.action_model.time_aware_action_head import TimeAwareActionHead,TimeAwareActionHead_Config
42
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
43
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
44
+
45
+ # from starVLA.model.modules.action_model.flow_matching_action_head import (
46
+ # FlowmatchingActionHead,
47
+ # FlowmatchingActionHeadConfig,
48
+ # )
49
+
50
+
51
+ @FRAMEWORK_REGISTRY.register("QwenPerceiver")
52
+ class Qwen_Perceiver(baseframework):
53
+ """
54
+ Multimodal vision-language-action model.
55
+
56
+ Components:
57
+ - Qwen2.5 VL interface for fused language/vision token embeddings
58
+ - Layer-wise QFormer for multi-layer feature aggregation
59
+ - DINO encoder for dense multi-view spatial tokens
60
+ - DiT diffusion head for future action sequence modeling
61
+
62
+ Focus: Predict future continuous actions conditioned on images + instruction.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ config: Optional[dict] = None,
68
+ **kwargs,
69
+ ) -> None:
70
+ """
71
+ Construct all submodules and cache key configuration values.
72
+
73
+ Args:
74
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
75
+ **kwargs: Reserved for future overrides (unused).
76
+ """
77
+ super().__init__()
78
+ self.config = config
79
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
80
+ # align dims --> we should put them to config or no?
81
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = self.qwen_vl_interface.model.config.hidden_size
82
+
83
+ self.use_time_aware_action_head = True
84
+
85
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用
86
+
87
+ # if self.use_time_aware_action_head:
88
+ # # self.model = TimeAwareActionHead(config=time_aware_action_head_config)
89
+ # action_head_cfg = TimeAwareActionHead_Config()
90
+ # time_aware_action_head_config = action_head_cfg.convert_to_dict()
91
+ # time_aware_action_head_config['action_dim'] = 1536
92
+ # time_aware_action_head_config['layers'] = 16
93
+ # time_aware_action_head_config['heads'] = 16
94
+ # act_config = {}
95
+ # act_config['diffusion_model_cfg'] = time_aware_action_head_config
96
+ # act_config["tune_projector"] = True
97
+ # act_config["tune_diffusion_model"] = True
98
+ # act_config["use_time_aware_action_head"] = True
99
+ # action_model_params = dict(self.config.framework.action_model)
100
+ # # 2. 将这些参数合并到 act_config 中
101
+ # act_config.update(action_model_params)
102
+ # action_head_config = FlowmatchingActionHeadConfig(**act_config)
103
+ # # import ipdb;ipdb.set_trace()
104
+ # self.action_head = FlowmatchingActionHead(action_head_config)
105
+ # # self.action_model = TimeAwareActionHead(config=time_aware_action_head_config)
106
+ # else:
107
+ # self.action_model: TimeAwareActionHead = get_action_model(config=self.config) # 修复后续引用
108
+
109
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
110
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
111
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
112
+
113
+
114
+ def forward(
115
+ self,
116
+ examples: List[dict] = None,
117
+ **kwargs,
118
+ ) -> Tuple:
119
+ """
120
+
121
+ """
122
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
123
+ instructions = [example["lang"] for example in examples] # [B, str]
124
+ actions = [example["action"] for example in examples] # label [B, len, 7]
125
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
126
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1]
127
+
128
+ # Extract action_mask if available
129
+ action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None # [B, len, action_dim]
130
+
131
+ # Step 1: QWenVL input format
132
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
133
+ with torch.autocast("cuda", dtype=torch.bfloat16):
134
+ qwenvl_outputs = self.qwen_vl_interface(
135
+ **qwen_inputs,
136
+ output_attentions=False,
137
+ output_hidden_states=True,
138
+ return_dict=True,
139
+ )
140
+ # last_hidden_state: [B, seq_len, H]
141
+ last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H]
142
+
143
+ # Step 4: Action Expert Forward and Loss
144
+ with torch.autocast("cuda", dtype=torch.float32):
145
+ actions = torch.tensor(
146
+ np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype
147
+ ) # [B, T_full, action_dim]
148
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
149
+
150
+ repeated_diffusion_steps = (
151
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
152
+ )
153
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
154
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
155
+
156
+ state_repeated = None
157
+ if state is not None:
158
+ state = torch.tensor(
159
+ np.array(state), device=last_hidden.device, dtype=last_hidden.dtype
160
+ )
161
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
162
+
163
+ # Process action_mask if available
164
+ action_mask_repeated = None
165
+ if action_mask is not None:
166
+ action_mask_tensor = torch.tensor(
167
+ np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype
168
+ ) # [B, T_full, action_dim]
169
+
170
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
171
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
172
+
173
+ if embodiment_tag is not None:
174
+ embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64)
175
+ embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) # embodiment_tag is index
176
+ else:
177
+ embodiment_tag_repeated = None
178
+
179
+ action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated, embodiment_tag_repeated, action_mask=action_mask_repeated) # (B, chunk_len, action_dim)
180
+
181
+
182
+ return {"action_loss": action_loss}
183
+
184
+ @torch.inference_mode()
185
+ def predict_action(
186
+ self,
187
+ examples: List[dict],
188
+ **kwargs: str,
189
+ ) -> np.ndarray:
190
+ """
191
+ Steps:
192
+ 1. Resize images to training resolution (if specified)
193
+ 2. Encode with QwenVL (hidden states retained)
194
+ 6. Return normalized action trajectory
195
+ Returns:
196
+ dict:
197
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
198
+ """
199
+ if type(examples) is not list:
200
+ examples = [examples]
201
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
202
+ instructions = [example["lang"] for example in examples] # [B, str]
203
+
204
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
205
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1]
206
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
207
+ if train_obs_image_size:
208
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
209
+
210
+ # Step 1: QWenVL input format
211
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
212
+ with torch.autocast("cuda", dtype=torch.bfloat16):
213
+ qwenvl_outputs = self.qwen_vl_interface(
214
+ **qwen_inputs,
215
+ output_attentions=False,
216
+ output_hidden_states=True,
217
+ return_dict=True,
218
+ )
219
+
220
+ # last_hidden_state: [B, seq_len, H]
221
+ last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H]
222
+
223
+ state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None
224
+ embodiment_tag = torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) if embodiment_tag is not None else None
225
+
226
+ # Step 4: Action Expert Forward
227
+ with torch.autocast("cuda", dtype=torch.float32):
228
+ if embodiment_tag is not None:
229
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) # (B, chunk_len, action_dim)
230
+ else:
231
+ pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim)
232
+
233
+ normalized_actions = pred_actions.detach().cpu().numpy()
234
+ return {"normalized_actions": normalized_actions}
235
+
236
+
237
+
238
+ if __name__ == "__main__":
239
+ from omegaconf import OmegaConf
240
+ import debugpy
241
+ import argparse
242
+ parser = argparse.ArgumentParser()
243
+ parser.add_argument("--config_yaml", type=str, default="./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml", help="Path to YAML config")
244
+ args, clipargs = parser.parse_known_args()
245
+
246
+ debugpy.listen(("0.0.0.0", 10092))
247
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
248
+ debugpy.wait_for_client()
249
+ args.config_yaml = "examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml"
250
+ cfg = OmegaConf.load(args.config_yaml)
251
+ # try get model
252
+ # cfg.framework.action_model.action_hidden_dim = 2048
253
+
254
+ # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large"
255
+
256
+
257
+ model: Qwen_Perceiver = Qwen_Perceiver(cfg)
258
+ print(model)
259
+
260
+
261
+
262
+ # fake sample
263
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
264
+ # Create a sample
265
+ sample = {
266
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
267
+ "image": [image], # three views
268
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
269
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
270
+ }
271
+ sample2 = {
272
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
273
+ "image": [image], # three views
274
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
275
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
276
+ }
277
+
278
+ batch = [sample, sample2] # batch size 2
279
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
280
+ model = model.to(device)
281
+ forward_output = model(batch)
282
+ action_loss = forward_output['action_loss']
283
+ print(f"Action Loss: {action_loss.item()}")
284
+
285
+ # test predict action
286
+ predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]]
287
+ normalized_actions = predict_output['normalized_actions']
288
+ print(f"Unnormalized Action: {normalized_actions}")
289
+
290
+ # # Advance: try forward model with dataloader
291
+ # # can be fake sample, but here get from dataloader for simpler
292
+ vla_dataset_cfg = cfg.datasets.vla_data
293
+ from torch.utils.data import DataLoader
294
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
295
+ cfg.datasets.vla_data.include_state = "False"
296
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
297
+
298
+ train_dataloader = DataLoader(
299
+ dataset,
300
+ batch_size=2,
301
+ num_workers=1, # For Debug
302
+ collate_fn=collate_fn,
303
+ )
304
+ # forward model with dataloader
305
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
306
+ # try get model
307
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
308
+ model = model.to(device)
309
+ model(batch)
310
+ # break
311
+
312
+ action = model.predict_action(examples=batch)
313
+ print("Finished")
starVLA/model/framework/QwenWanPerceiver.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Junqiu YU / Fudan University] in [2025].
4
+ # Design and Merged by [Jinhui YE / HKUST University] in [2025].
5
+ """
6
+ Qwen-GR00T Framework
7
+ A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions
8
+ Flow-matching header is copyright from GR00T N1.5,
9
+ """
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ # Add workspace root to Python path if not already there
14
+ _workspace_root = Path(__file__).parent.parent.parent.parent
15
+ if str(_workspace_root) not in sys.path:
16
+ sys.path.insert(0, str(_workspace_root))
17
+
18
+ from typing import List
19
+ from tqdm import tqdm
20
+ from typing import List, Optional, Tuple
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import numpy as np
25
+ from PIL import Image
26
+
27
+
28
+
29
+ from starVLA.training.trainer_utils import initialize_overwatch
30
+ from deployment.model_server.tools.image_tools import to_pil_preserve
31
+
32
+ logger = initialize_overwatch(__name__)
33
+
34
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
35
+ IGNORE_INDEX = -100
36
+
37
+ from starVLA.model.framework.base_framework import baseframework
38
+ from starVLA.model.modules.vlm import get_vlm_model
39
+ from starVLA.model.modules.world_model import get_world_model
40
+
41
+ from starVLA.model.modules.action_model.PerceiverHead_original import get_action_model, FlowmatchingActionHead
42
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
43
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
44
+
45
+ # from starVLA.model.modules.action_model.flow_matching_action_head import (
46
+ # FlowmatchingActionHead,
47
+ # FlowmatchingActionHeadConfig,
48
+ # )
49
+
50
+
51
+ @FRAMEWORK_REGISTRY.register("QwenWanPerceiver")
52
+ class QwenWan_Perceiver(baseframework):
53
+ """
54
+ Multimodal vision-language-action model.
55
+
56
+ Components:
57
+ - Qwen2.5 VL interface for fused language/vision token embeddings
58
+ - Layer-wise QFormer for multi-layer feature aggregation
59
+ - DINO encoder for dense multi-view spatial tokens
60
+ - DiT diffusion head for future action sequence modeling
61
+
62
+ Focus: Predict future continuous actions conditioned on images + instruction.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ config: Optional[dict] = None,
68
+ **kwargs,
69
+ ) -> None:
70
+ """
71
+ Construct all submodules and cache key configuration values.
72
+
73
+ Args:
74
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
75
+ **kwargs: Reserved for future overrides (unused).
76
+ """
77
+ super().__init__()
78
+ self.config = config
79
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
80
+ self.wan_interface = get_world_model(config=self.config)
81
+
82
+ wm_cfg = config.framework.get("world_model", {})
83
+ # 将 Wan 多 token 压成 1 个全局条件,避免 action DiT 的 KV 比 QwenPerceiver 长数倍、稀释 cross-attn
84
+ self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False))
85
+ wm_hidden = self.wan_interface.model.config.hidden_size
86
+ cross_dim = self.qwen_vl_interface.model.config.hidden_size
87
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = cross_dim
88
+ self.wm_projector = torch.nn.Linear(wm_hidden, cross_dim)
89
+ self.wm_post_norm = torch.nn.LayerNorm(cross_dim, eps=1e-6)
90
+ gain = float(wm_cfg.get("wm_projector_init_gain", 0.02))
91
+ torch.nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain)
92
+ torch.nn.init.zeros_(self.wm_projector.bias)
93
+ logger.info(
94
+ f"QwenWanPerceiver: pool_wm_sequence={self._pool_wm_sequence}, wm_projector_init_gain={gain}"
95
+ )
96
+
97
+ self.use_time_aware_action_head = True
98
+
99
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用
100
+
101
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
102
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
103
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
104
+
105
+ # Whether to freeze VLM for VLA data (no gradient backprop to VLM)
106
+ self.freeze_vlm_for_vla = (
107
+ config.trainer.get("freeze_vlm_for_vla", False)
108
+ if config and hasattr(config, "trainer") else False
109
+ )
110
+ print("freeze_vlm_for_vla: ",self.freeze_vlm_for_vla)
111
+
112
+ @staticmethod
113
+ def _wm_images_head_only(batch_images: List) -> List:
114
+ """World model 只使用每个样本的第一路相机(例如 [头, 左手, 右手] 中的头部)。"""
115
+ wm_images = []
116
+ for imgs in batch_images:
117
+ if isinstance(imgs, (list, tuple)):
118
+ wm_images.append([imgs[0]] if len(imgs) > 0 else [])
119
+ else:
120
+ wm_images.append([imgs])
121
+ return wm_images
122
+
123
+ def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor:
124
+ """Wan 特征与 Qwen 最后一层 hidden 对齐维后沿序列维拼接。"""
125
+ if self._pool_wm_sequence:
126
+ last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True)
127
+ # Wan 在 bf16 autocast 下常为 BF16,Linear/LayerNorm 参数默认 FP32,需对齐后再乘权重
128
+ proj_dtype = self.wm_projector.weight.dtype
129
+ x = last_wm_hidden.to(dtype=proj_dtype)
130
+ wm_aligned = self.wm_post_norm(self.wm_projector(x)).to(dtype=last_vlm_hidden.dtype)
131
+ return torch.cat([last_vlm_hidden, wm_aligned], dim=1)
132
+
133
+ def forward(self, examples: List[dict] = None, **kwargs) -> Tuple:
134
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
135
+ instructions = [example["lang"] for example in examples] # [B, str]
136
+ actions = [example["action"] for example in examples] # label [B, len, 7]
137
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
138
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1]
139
+
140
+ # Extract action_mask if available
141
+ if "action_mask" in examples[0]:
142
+ action_mask = [example["action_mask"] for example in examples] # [B, len, action_dim]
143
+ # Check if all action_mask values are None, if so set to None
144
+ if all(mask is None for mask in action_mask):
145
+ action_mask = None
146
+ else:
147
+ action_mask = None
148
+
149
+ # Step 1: QWenVL input format
150
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
151
+
152
+ # Step 2–3: Wan 仅作冻结特征提取:no_grad 不保留反传激活;bf16 autocast 降低 Wan 前向峰值显存
153
+ # with torch.no_grad():
154
+ # with torch.autocast("cuda", dtype=torch.bfloat16):
155
+ # wm_inputs = self.wan_interface.build_inputs(
156
+ # images=self._wm_images_head_only(batch_images), instructions=instructions
157
+ # )
158
+ # wm_outputs = self.wan_interface(
159
+ # **wm_inputs,
160
+ # output_hidden_states=True,
161
+ # return_dict=True,
162
+ # )
163
+ # last_wm_hidden = wm_outputs.hidden_states[-1]
164
+ with torch.autocast("cuda", dtype=torch.bfloat16):
165
+ wm_inputs = self.wan_interface.build_inputs(
166
+ images=self._wm_images_head_only(batch_images), instructions=instructions
167
+ )
168
+ wm_outputs = self.wan_interface(
169
+ **wm_inputs,
170
+ output_hidden_states=True,
171
+ return_dict=True,
172
+ )
173
+ last_wm_hidden = wm_outputs.hidden_states[-1]
174
+
175
+ with torch.autocast("cuda", dtype=torch.bfloat16):
176
+ qwenvl_outputs = self.qwen_vl_interface(
177
+ **qwen_inputs,
178
+ output_attentions=False,
179
+ output_hidden_states=True,
180
+ return_dict=True,
181
+ )
182
+ # last_hidden_state: [B, seq_len, H]
183
+ last_vlm_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] [ 2, 221, 3072 ]
184
+
185
+ # Detach hidden states to prevent gradient backprop to VLM for VLA data
186
+ if self.freeze_vlm_for_vla:
187
+ last_vlm_hidden = last_vlm_hidden.detach()
188
+
189
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
190
+ # last_hidden = last_vlm_hidden
191
+
192
+ # Step 4: Action Expert Forward and Loss
193
+ with torch.autocast("cuda", dtype=torch.float32):
194
+ actions = torch.tensor(
195
+ np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype
196
+ ) # [B, T_full, action_dim]
197
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
198
+
199
+ repeated_diffusion_steps = (
200
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
201
+ )
202
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
203
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
204
+
205
+ state_repeated = None
206
+ if state is not None:
207
+ state = torch.tensor(
208
+ np.array(state), device=last_hidden.device, dtype=last_hidden.dtype
209
+ )
210
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
211
+
212
+ # Process action_mask if available
213
+ action_mask_repeated = None
214
+ if action_mask is not None:
215
+ action_mask_tensor = torch.tensor(
216
+ np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype
217
+ ) # [B, T_full, action_dim]
218
+
219
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
220
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
221
+
222
+ if embodiment_tag is not None:
223
+ embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64)
224
+ embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) # embodiment_tag is index
225
+ else:
226
+ embodiment_tag_repeated = None
227
+
228
+ action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated, embodiment_tag_repeated, action_mask=action_mask_repeated) # (B, chunk_len, action_dim)
229
+
230
+ return {"action_loss": action_loss}
231
+
232
+ @torch.inference_mode()
233
+ def predict_action(
234
+ self,
235
+ examples: List[dict],
236
+ **kwargs: str,
237
+ ) -> np.ndarray:
238
+ """
239
+ Steps:
240
+ 1. Resize images to training resolution (if specified)
241
+ 2. Encode with QwenVL (hidden states retained)
242
+ 6. Return normalized action trajectory
243
+ Returns:
244
+ dict:
245
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
246
+ """
247
+ if type(examples) is not list:
248
+ examples = [examples]
249
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
250
+ instructions = [example["lang"] for example in examples] # [B, str]
251
+
252
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
253
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1]
254
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
255
+ if train_obs_image_size:
256
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
257
+
258
+ # Step 1: QWenVL + Wan(与 forward 一致,否则推理与训练条件分布不一致)
259
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
260
+ with torch.no_grad():
261
+ with torch.autocast("cuda", dtype=torch.bfloat16):
262
+ wm_inputs = self.wan_interface.build_inputs(
263
+ images=self._wm_images_head_only(batch_images), instructions=instructions
264
+ )
265
+ wm_outputs = self.wan_interface(
266
+ **wm_inputs,
267
+ output_hidden_states=True,
268
+ return_dict=True,
269
+ )
270
+ last_wm_hidden = wm_outputs.hidden_states[-1]
271
+
272
+ with torch.autocast("cuda", dtype=torch.bfloat16):
273
+ qwenvl_outputs = self.qwen_vl_interface(
274
+ **qwen_inputs,
275
+ output_attentions=False,
276
+ output_hidden_states=True,
277
+ return_dict=True,
278
+ )
279
+ last_vlm_hidden = qwenvl_outputs.hidden_states[-1]
280
+
281
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
282
+
283
+ state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None
284
+ embodiment_tag = torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) if embodiment_tag is not None else None
285
+
286
+ # Step 4: Action Expert Forward
287
+ with torch.autocast("cuda", dtype=torch.float32):
288
+ if embodiment_tag is not None:
289
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) # (B, chunk_len, action_dim)
290
+ else:
291
+ pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim)
292
+
293
+ normalized_actions = pred_actions.detach().cpu().numpy()
294
+ return {"normalized_actions": normalized_actions}
295
+
296
+
297
+
298
+ if __name__ == "__main__":
299
+ from omegaconf import OmegaConf
300
+ import debugpy
301
+ import argparse
302
+ parser = argparse.ArgumentParser()
303
+ parser.add_argument("--config_yaml", type=str, default="./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml", help="Path to YAML config")
304
+ args, clipargs = parser.parse_known_args()
305
+
306
+ debugpy.listen(("0.0.0.0", 10092))
307
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
308
+ debugpy.wait_for_client()
309
+ args.config_yaml = "examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml"
310
+ cfg = OmegaConf.load(args.config_yaml)
311
+ # try get model
312
+ # cfg.framework.action_model.action_hidden_dim = 2048
313
+
314
+ # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large"
315
+
316
+
317
+ model: QwenWan_Perceiver = QwenWan_Perceiver(cfg)
318
+ print(model)
319
+
320
+
321
+
322
+ # fake sample
323
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
324
+ # Create a sample
325
+ sample = {
326
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
327
+ "image": [image], # three views
328
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
329
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
330
+ }
331
+ sample2 = {
332
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
333
+ "image": [image], # three views
334
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
335
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
336
+ }
337
+
338
+ batch = [sample, sample2] # batch size 2
339
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
340
+ model = model.to(device)
341
+ forward_output = model(batch)
342
+ action_loss = forward_output['action_loss']
343
+ print(f"Action Loss: {action_loss.item()}")
344
+
345
+ # test predict action
346
+ predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]]
347
+ normalized_actions = predict_output['normalized_actions']
348
+ print(f"Unnormalized Action: {normalized_actions}")
349
+
350
+ # # Advance: try forward model with dataloader
351
+ # # can be fake sample, but here get from dataloader for simpler
352
+ vla_dataset_cfg = cfg.datasets.vla_data
353
+ from torch.utils.data import DataLoader
354
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
355
+ cfg.datasets.vla_data.include_state = "False"
356
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
357
+
358
+ train_dataloader = DataLoader(
359
+ dataset,
360
+ batch_size=2,
361
+ num_workers=1, # For Debug
362
+ collate_fn=collate_fn,
363
+ )
364
+ # forward model with dataloader
365
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
366
+ # try get model
367
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
368
+ model = model.to(device)
369
+ model(batch)
370
+ # break
371
+
372
+ action = model.predict_action(examples=batch)
373
+ print("Finished")
starVLA/model/framework/QwenWanPerceiverACoT.py ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ # Implemented by [Junqiu YU / Fudan University] in [2025].
4
+ # Design and Merged by [Jinhui YE / HKUST University] in [2025].
5
+ """
6
+ Qwen-GR00T Framework
7
+ A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions
8
+ Flow-matching header is copyright from GR00T N1.5,
9
+ """
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ # Add workspace root to Python path if not already there
14
+ _workspace_root = Path(__file__).parent.parent.parent.parent
15
+ if str(_workspace_root) not in sys.path:
16
+ sys.path.insert(0, str(_workspace_root))
17
+
18
+ from typing import List
19
+ from tqdm import tqdm
20
+ from typing import List, Optional, Tuple
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ import numpy as np
25
+ from PIL import Image
26
+
27
+
28
+
29
+ from starVLA.training.trainer_utils import initialize_overwatch
30
+ from deployment.model_server.tools.image_tools import to_pil_preserve
31
+
32
+ logger = initialize_overwatch(__name__)
33
+
34
+ # HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels)
35
+ IGNORE_INDEX = -100
36
+
37
+ from starVLA.model.framework.base_framework import baseframework
38
+ from starVLA.model.modules.vlm import get_vlm_model
39
+ from starVLA.model.modules.world_model import get_world_model
40
+
41
+ from starVLA.model.modules.action_model.PerceiverHead import get_action_model, FlowmatchingActionHead
42
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
43
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
44
+
45
+ # from starVLA.model.modules.action_model.flow_matching_action_head import (
46
+ # FlowmatchingActionHead,
47
+ # FlowmatchingActionHeadConfig,
48
+ # )
49
+
50
+
51
+ @FRAMEWORK_REGISTRY.register("QwenWanPerceiverACoT")
52
+ class QwenWan_Perceiver_ACoT(baseframework):
53
+ """
54
+ Multimodal vision-language-action model.
55
+
56
+ Components:
57
+ - Qwen2.5 VL interface for fused language/vision token embeddings
58
+ - Layer-wise QFormer for multi-layer feature aggregation
59
+ - DINO encoder for dense multi-view spatial tokens
60
+ - DiT diffusion head for future action sequence modeling
61
+
62
+ Focus: Predict future continuous actions conditioned on images + instruction.
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ config: Optional[dict] = None,
68
+ **kwargs,
69
+ ) -> None:
70
+ """
71
+ Construct all submodules and cache key configuration values.
72
+
73
+ Args:
74
+ config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections.
75
+ **kwargs: Reserved for future overrides (unused).
76
+ """
77
+ super().__init__()
78
+ self.config = config
79
+
80
+ # 1. 初始化Qwen作为VLM-Backone、初始化Wan作为WAM-Backbone、初始化FlowmatchingActionHead作为ActionHead
81
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
82
+ self.wan_interface = get_world_model(config=self.config)
83
+
84
+ # for p in self.wan_interface.parameters():
85
+ # p.requires_grad = False
86
+ # for p in self.qwen_vl_interface.parameters():
87
+ # p.requires_grad = False
88
+
89
+ for p in self.wan_interface.text_encoder.parameters():
90
+ p.requires_grad = False
91
+ for p in self.wan_interface.vae.parameters():
92
+ p.requires_grad = False
93
+
94
+ wm_cfg = config.framework.get("world_model", {})
95
+ # 将 Wan 多 token 压成 1 个全局条件,避免 action DiT 的 KV 比 QwenPerceiver 长数倍、稀释 cross-attn
96
+ self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False))
97
+ wm_hidden = self.wan_interface.model.config.hidden_size
98
+ cross_dim = self.qwen_vl_interface.model.config.hidden_size
99
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = cross_dim
100
+ self.wm_projector = torch.nn.Linear(wm_hidden, cross_dim)
101
+ self.wm_post_norm = torch.nn.LayerNorm(cross_dim, eps=1e-6)
102
+ gain = float(wm_cfg.get("wm_projector_init_gain", 0.02))
103
+ torch.nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain)
104
+ torch.nn.init.zeros_(self.wm_projector.bias)
105
+ logger.info(
106
+ f"QwenWanPerceiver: pool_wm_sequence={self._pool_wm_sequence}, wm_projector_init_gain={gain}"
107
+ )
108
+
109
+ self.use_time_aware_action_head = True
110
+
111
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
112
+
113
+ self.future_action_window_size = config.framework.action_model.future_action_window_size
114
+ self.past_action_window_size = config.framework.action_model.past_action_window_size
115
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
116
+
117
+ # Whether to freeze VLM for VLA data (no gradient backprop to VLM)
118
+ self.freeze_vlm_for_vla = (
119
+ config.trainer.get("freeze_vlm_for_vla", False)
120
+ if config and hasattr(config, "trainer") else False
121
+ )
122
+ print("freeze_vlm_for_vla: ",self.freeze_vlm_for_vla)
123
+
124
+ # 2. 加载vjepa_encoder和vjepa_decoder,并将其权重固定为bf16
125
+ vjepa2_ac_cfg = self.config.framework.get("vjepa2_ac")
126
+ vjepa2_ac_repo_dir = vjepa2_ac_cfg.get("repo_dir")
127
+ vjepa2_ac_pretrained = vjepa2_ac_cfg.get("pretrained")
128
+ # print(vjepa2_ac_repo_dir) # /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main
129
+ # print(vjepa2_ac_pretrained) # /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt
130
+ self.vjepa_encoder, self.vjepa_predictor = torch.hub.load(
131
+ vjepa2_ac_repo_dir,
132
+ "vjepa2_ac_vit_giant",
133
+ source="local",
134
+ pretrained=vjepa2_ac_pretrained,
135
+ )
136
+ self.vjepa_encoder = self.vjepa_encoder.to(torch.bfloat16).cuda()
137
+ self.vjepa_predictor = self.vjepa_predictor.to(torch.bfloat16).cuda()
138
+ for p in self.vjepa_encoder.parameters():
139
+ p.requires_grad = False
140
+
141
+ # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用,
142
+ # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配
143
+ # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None,
144
+ # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重
145
+ for p in self.vjepa_predictor.action_encoder.parameters():
146
+ p.requires_grad = False
147
+ for p in self.vjepa_predictor.state_encoder.parameters():
148
+ p.requires_grad = False
149
+ for p in self.vjepa_predictor.extrinsics_encoder.parameters():
150
+ p.requires_grad = False
151
+
152
+ # print(type(self.vjepa_encoder)) # <class 'src.models.vision_transformer.VisionTransformer'>
153
+ # print(type(self.vjepa_predictor)) # <class 'src.models.ac_predictor.VisionTransformerPredictorAC'>
154
+
155
+ # 初始化VJEPA2-AC的图像预处理transform,与官方energy_landscape_example.ipynb保持一致
156
+ from starVLA.facebookresearch_vjepa2_main.app.vjepa_droid.transforms import make_transforms as vjepa2_make_transforms
157
+ self._vjepa2_transform = vjepa2_make_transforms(
158
+ random_horizontal_flip=False,
159
+ random_resize_aspect_ratio=(1., 1.),
160
+ random_resize_scale=(1., 1.),
161
+ reprob=0.,
162
+ auto_augment=False,
163
+ motion_shift=False,
164
+ crop_size=256,
165
+ )
166
+
167
+ self.state_dim = self.config.framework.action_model.get("state_dim", None)
168
+ self.state_projector = torch.nn.Linear(
169
+ self.state_dim,
170
+ self.vjepa_predictor.predictor_embed.out_features,
171
+ bias=True
172
+ ).to(torch.bfloat16)
173
+ # print(self.state_dim) # 64
174
+ # print(self.vjepa_predictor.predictor_embed.out_features) # 1024
175
+ self.action_projector = torch.nn.Linear(
176
+ self.action_model.model.config.output_dim,
177
+ self.vjepa_predictor.predictor_embed.out_features,
178
+ bias=True
179
+ ).to(torch.bfloat16)
180
+ # print(self.action_model.model.config.output_dim) # 1024
181
+ # print(self.vjepa_predictor.predictor_embed.out_features) # 1024
182
+
183
+ @staticmethod
184
+ def _wm_images_head_only(batch_images: List) -> List:
185
+ """World model 只使用每个样本的第一路相机(例如 [头, 左手, 右手] 中的头部)。"""
186
+ wm_images = []
187
+ for imgs in batch_images:
188
+ if isinstance(imgs, (list, tuple)):
189
+ wm_images.append([imgs[0]] if len(imgs) > 0 else [])
190
+ else:
191
+ wm_images.append([imgs])
192
+ return wm_images
193
+
194
+ def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor:
195
+ """Wan 特征与 Qwen 最后一层 hidden 对齐维后沿序列维拼接。"""
196
+ if self._pool_wm_sequence:
197
+ last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True)
198
+ # Wan 在 bf16 autocast 下常为 BF16,Linear/LayerNorm 参数默认 FP32,需对齐后再乘权重
199
+ proj_dtype = self.wm_projector.weight.dtype
200
+ x = last_wm_hidden.to(dtype=proj_dtype)
201
+ wm_aligned = self.wm_post_norm(self.wm_projector(x)).to(dtype=last_vlm_hidden.dtype)
202
+ return torch.cat([last_vlm_hidden, wm_aligned], dim=1)
203
+
204
+ def _as_bool(self, value) -> bool:
205
+ if isinstance(value, str):
206
+ return value.lower() in {"1", "true", "yes", "on"}
207
+ return bool(value)
208
+
209
+ def _as_sequence(self, images):
210
+ return list(images) if isinstance(images, (list, tuple)) else [images]
211
+
212
+ def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor:
213
+ if state is None or self.state_dim is None:
214
+ return state
215
+ target_dim = int(self.state_dim)
216
+ current_dim = state.shape[-1]
217
+ if current_dim == target_dim:
218
+ return state
219
+ if current_dim > target_dim:
220
+ return state[..., :target_dim]
221
+
222
+ pad_shape = (*state.shape[:-1], target_dim - current_dim)
223
+ padding = state.new_zeros(pad_shape)
224
+ return torch.cat([state, padding], dim=-1)
225
+
226
+ def _vjepa2ac_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]:
227
+ # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-1')
228
+ if "future_image" not in examples[0]:
229
+ return None
230
+
231
+ # 2. 从examples中取出当前图像和未来图像,并使用VJEPA2-AC官方的transform对图像做预处理
232
+ batch_current_images = [to_pil_preserve(example["image"]) for example in examples]
233
+ batch_future_images = [to_pil_preserve(example["future_image"]) for example in examples]
234
+ # print(len(examples)) # 8
235
+ clips_list = []
236
+ for current_images, future_images in zip(batch_current_images, batch_future_images):
237
+ current_seq = self._as_sequence(current_images)
238
+ future_seq = self._as_sequence(future_images)
239
+ # print(len(current_seq)) # 1
240
+ # print(len(future_seq)) # 1
241
+ current_np = np.array(current_seq[0])
242
+ future_np = np.array(future_seq[0])
243
+ # print(current_np.shape) # (224, 224, 3)
244
+ # print(future_np.shape) # (224, 224, 3)
245
+ clip_np = np.stack([current_np, future_np], axis=0)
246
+ # print(clip_np.shape) # (2, 224, 224, 3)
247
+ clip_tensor = self._vjepa2_transform(clip_np)
248
+ # print(clip_tensor.shape) # torch.Size([3, 2, 256, 256])
249
+ clips_list.append(clip_tensor)
250
+ clips = torch.stack(clips_list, dim=0).to(self.vjepa_encoder.patch_embed.proj.weight.device)
251
+ # print(clips.shape) # torch.Size([8, 3, 2, 256, 256])
252
+ B, C, T, H, W = clips.size()
253
+ # print(clips.shape) # torch.Size([8, 3, 2, 256, 256])
254
+ c = clips.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1).to(torch.bfloat16)
255
+ # print(c.shape) # torch.Size([16, 3, 2, 256, 256])
256
+
257
+ # 3. self.vjepa_encoder推理时使用b16
258
+ # 这是仿照self._cosmos25_future_image_loss中,当self.backbone作为编码器前向推理时使用bf16
259
+ crop_size = 256
260
+ tokens_per_frame = int((crop_size // self.vjepa_encoder.patch_size) ** 2)
261
+ # 仿照原始代码对self.backbone的处理,用bf16 autocast包裹vjepa_encoder
262
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
263
+ # print(type(self.vjepa_encoder)) # <class 'src.models.vision_transformer.VisionTransformer'>
264
+ h = self.vjepa_encoder(c)
265
+ # print(h.shape) # torch.Size([16, 256, 1408])
266
+ h = h.view(B, T, -1, h.size(-1)).flatten(1, 2)
267
+ # print(h.shape) # torch.Size([8, 512, 1408])
268
+ h = F.layer_norm(h, (h.size(-1),))
269
+ # print(h.shape) # torch.Size([8, 512, 1408])
270
+
271
+ # 4. 从h中分离出current_tokens和future_tokens
272
+ current_tokens = h[:, :tokens_per_frame]
273
+ future_tokens = h[:, tokens_per_frame:]
274
+ # print(current_tokens.shape) # torch.Size([8, 256, 1408])
275
+ # print(future_tokens.shape) # torch.Size([8, 256, 1408])
276
+
277
+ # 5. 从examples中取出current_state,参考predict_action()中的实现
278
+ current_state = [example["state"] for example in examples] if "state" in examples[0] else None
279
+ # print(len(current_state)) # 8
280
+ # print(current_state[0].shape) # (1, 64)
281
+ current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype))
282
+ # print(current_state.shape) # torch.Size([8, 1, 64])
283
+ current_state = self._align_state_dim(current_state)
284
+ # print(current_state.shape) # torch.Size([8, 1, 64])
285
+
286
+ # 6. self.vjepa_predictor推理时使用fp32
287
+ # 这是仿照CosmoPredict2Perceiver.forward()中,当self.action_model生成action前向推理时使用fp32
288
+ with torch.autocast("cuda", dtype=torch.float32):
289
+ # 通过projector映射维度
290
+ # print(current_state.shape) # torch.Size([8, 1, 64])
291
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
292
+ current_state_emb = self.state_projector(current_state)
293
+ target_emb_proj = self.action_projector(target_emb)
294
+ # print(current_state_emb.shape) # torch.Size([8, 1, 1024])
295
+ # print(target_emb_proj.shape) # torch.Size([8, 64, 1024])
296
+
297
+ # 7. 调用self.vjepa_predictor预测future_tokens
298
+ future_tokens_pred = self.vjepa_predictor.forward_for_WAM_VJEPA2AC(
299
+ x=current_tokens,
300
+ target_emb=target_emb_proj,
301
+ state_emb=current_state_emb,
302
+ )
303
+ # print(type(self.vjepa_predictor)) # <class 'src.models.ac_predictor.VisionTransformerPredictorAC'>
304
+ # print(current_tokens.shape) # torch.Size([8, 256, 1408])
305
+ # print(target_emb_proj.shape) # torch.Size([8, 64, 1024])
306
+ # print(current_state_emb.shape) # torch.Size([8, 1, 1024])
307
+ # print(future_tokens_pred.shape) # torch.Size([8, 256, 1408])
308
+
309
+ # 8. 计算future_latent_loss
310
+ future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens)
311
+ # print(future_latent_loss) # tensor(0.3229, device='cuda:0', grad_fn=<SmoothL1LossBackward0>)
312
+
313
+ # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-2')
314
+ return future_latent_loss
315
+
316
+ def forward(self, examples: List[dict] = None, **kwargs) -> Tuple:
317
+ # ACoT初始化
318
+ output = {}
319
+ future_image_cfg = dict(self.config.framework.get("future_image_training", {}))
320
+ future_latent_cfg = dict(self.config.framework.get("future_latent_training", {}))
321
+
322
+ # 加载数据
323
+ batch_images = [example["image"] for example in examples] # [B,[PLT]]
324
+ instructions = [example["lang"] for example in examples] # [B, str]
325
+ actions = [example["action"] for example in examples] # label [B, len, 7]
326
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
327
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1]
328
+
329
+ # Extract action_mask if available
330
+ if "action_mask" in examples[0]:
331
+ action_mask = [example["action_mask"] for example in examples] # [B, len, action_dim]
332
+ # Check if all action_mask values are None, if so set to None
333
+ if all(mask is None for mask in action_mask):
334
+ action_mask = None
335
+ else:
336
+ action_mask = None
337
+
338
+ # Step 1: QWenVL input format
339
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
340
+
341
+ # Step 2–3: Wan 仅作冻结特征提取:no_grad 不保留反传激活;bf16 autocast 降低 Wan 前向峰值显存
342
+ # with torch.no_grad():
343
+ # with torch.autocast("cuda", dtype=torch.bfloat16):
344
+ # wm_inputs = self.wan_interface.build_inputs(
345
+ # images=self._wm_images_head_only(batch_images), instructions=instructions
346
+ # )
347
+ # wm_outputs = self.wan_interface(
348
+ # **wm_inputs,
349
+ # output_hidden_states=True,
350
+ # return_dict=True,
351
+ # )
352
+ # last_wm_hidden = wm_outputs.hidden_states[-1]
353
+ with torch.autocast("cuda", dtype=torch.bfloat16):
354
+ wm_inputs = self.wan_interface.build_inputs(
355
+ images=self._wm_images_head_only(batch_images), instructions=instructions
356
+ )
357
+ wm_outputs = self.wan_interface(
358
+ **wm_inputs,
359
+ output_hidden_states=True,
360
+ return_dict=True,
361
+ )
362
+ last_wm_hidden = wm_outputs.hidden_states[-1]
363
+
364
+ with torch.autocast("cuda", dtype=torch.bfloat16):
365
+ qwenvl_outputs = self.qwen_vl_interface(
366
+ **qwen_inputs,
367
+ output_attentions=False,
368
+ output_hidden_states=True,
369
+ return_dict=True,
370
+ )
371
+ # last_hidden_state: [B, seq_len, H]
372
+ last_vlm_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] [ 2, 221, 3072 ]
373
+
374
+ # Detach hidden states to prevent gradient backprop to VLM for VLA data
375
+ if self.freeze_vlm_for_vla:
376
+ last_vlm_hidden = last_vlm_hidden.detach()
377
+
378
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
379
+ # last_hidden = last_vlm_hidden
380
+
381
+ # Step 4: Action Expert Forward and Loss
382
+ with torch.autocast("cuda", dtype=torch.float32):
383
+ actions = torch.tensor(
384
+ np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype
385
+ ) # [B, T_full, action_dim]
386
+ actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
387
+
388
+ repeated_diffusion_steps = (
389
+ self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4
390
+ )
391
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
392
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
393
+
394
+ state_repeated = None
395
+ if state is not None:
396
+ state = torch.tensor(
397
+ np.array(state), device=last_hidden.device, dtype=last_hidden.dtype
398
+ )
399
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
400
+
401
+ # Process action_mask if available
402
+ action_mask_repeated = None
403
+ if action_mask is not None:
404
+ action_mask_tensor = torch.tensor(
405
+ np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype
406
+ ) # [B, T_full, action_dim]
407
+
408
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim)
409
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
410
+
411
+ if embodiment_tag is not None:
412
+ embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64)
413
+ embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) # embodiment_tag is index
414
+ else:
415
+ embodiment_tag_repeated = None
416
+
417
+ action_loss, target_emb = self.action_model(
418
+ last_hidden_repeated,
419
+ actions_target_repeated,
420
+ state_repeated,
421
+ embodiment_tag_repeated,
422
+ action_mask=action_mask_repeated,
423
+ use_vjepa2ac=True,
424
+ repeated_diffusion_steps=repeated_diffusion_steps,
425
+ )
426
+
427
+ output = {}
428
+ output["perceiver_action_loss"] = action_loss.detach()
429
+ total_loss = action_loss
430
+
431
+ # Step 5: Calculate the future_latent_loss by VJEPA2-AC
432
+ # print(future_latent_cfg.get("enabled")) # True
433
+ # print(future_latent_cfg.get("loss_weight")) # 0.02
434
+ if self._as_bool(future_latent_cfg.get("enabled")):
435
+ future_latent_loss = self._vjepa2ac_future_latent_loss(examples, target_emb)
436
+ if future_latent_loss is not None:
437
+ future_latent_loss_weight = float(future_latent_cfg.get("loss_weight"))
438
+ output["future_latent_loss"] = future_latent_loss.detach()
439
+ total_loss = total_loss + future_latent_loss * future_latent_loss_weight
440
+
441
+ output["action_loss"] = total_loss
442
+
443
+ return output
444
+
445
+ @torch.inference_mode()
446
+ def predict_action(
447
+ self,
448
+ examples: List[dict],
449
+ **kwargs: str,
450
+ ) -> np.ndarray:
451
+ """
452
+ Steps:
453
+ 1. Resize images to training resolution (if specified)
454
+ 2. Encode with QwenVL (hidden states retained)
455
+ 6. Return normalized action trajectory
456
+ Returns:
457
+ dict:
458
+ normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions.
459
+ """
460
+ if type(examples) is not list:
461
+ examples = [examples]
462
+ batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]]
463
+ instructions = [example["lang"] for example in examples] # [B, str]
464
+
465
+ state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim]
466
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1]
467
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
468
+ if train_obs_image_size:
469
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
470
+
471
+ # Step 1: QWenVL + Wan(与 forward 一致,否则推理与训练条件分布不一致)
472
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
473
+ # with torch.no_grad():
474
+ # with torch.autocast("cuda", dtype=torch.bfloat16):
475
+ # wm_inputs = self.wan_interface.build_inputs(
476
+ # images=self._wm_images_head_only(batch_images), instructions=instructions
477
+ # )
478
+ # wm_outputs = self.wan_interface(
479
+ # **wm_inputs,
480
+ # output_hidden_states=True,
481
+ # return_dict=True,
482
+ # )
483
+ # last_wm_hidden = wm_outputs.hidden_states[-1]
484
+ with torch.autocast("cuda", dtype=torch.bfloat16):
485
+ wm_inputs = self.wan_interface.build_inputs(
486
+ images=self._wm_images_head_only(batch_images), instructions=instructions
487
+ )
488
+ wm_outputs = self.wan_interface(
489
+ **wm_inputs,
490
+ output_hidden_states=True,
491
+ return_dict=True,
492
+ )
493
+ last_wm_hidden = wm_outputs.hidden_states[-1]
494
+
495
+ with torch.autocast("cuda", dtype=torch.bfloat16):
496
+ qwenvl_outputs = self.qwen_vl_interface(
497
+ **qwen_inputs,
498
+ output_attentions=False,
499
+ output_hidden_states=True,
500
+ return_dict=True,
501
+ )
502
+ last_vlm_hidden = qwenvl_outputs.hidden_states[-1]
503
+
504
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
505
+
506
+ state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None
507
+ embodiment_tag = torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) if embodiment_tag is not None else None
508
+
509
+ # Step 4: Action Expert Forward
510
+ with torch.autocast("cuda", dtype=torch.float32):
511
+ if embodiment_tag is not None:
512
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) # (B, chunk_len, action_dim)
513
+ else:
514
+ pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim)
515
+
516
+ normalized_actions = pred_actions.detach().cpu().numpy()
517
+ return {"normalized_actions": normalized_actions}
518
+
519
+
520
+ if __name__ == "__main__":
521
+ from omegaconf import OmegaConf
522
+ import debugpy
523
+ import argparse
524
+ parser = argparse.ArgumentParser()
525
+ parser.add_argument("--config_yaml", type=str, default="./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml", help="Path to YAML config")
526
+ args, clipargs = parser.parse_known_args()
527
+
528
+ debugpy.listen(("0.0.0.0", 10092))
529
+ print("🔍 Rank 0 waiting for debugger attach on port 10092...")
530
+ debugpy.wait_for_client()
531
+ args.config_yaml = "examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml"
532
+ cfg = OmegaConf.load(args.config_yaml)
533
+ # try get model
534
+ # cfg.framework.action_model.action_hidden_dim = 2048
535
+
536
+ # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large"
537
+
538
+
539
+ model: QwenWan_Perceiver = QwenWan_Perceiver(cfg)
540
+ print(model)
541
+
542
+
543
+
544
+ # fake sample
545
+ image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8))
546
+ # Create a sample
547
+ sample = {
548
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
549
+ "image": [image], # three views
550
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
551
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
552
+ }
553
+ sample2 = {
554
+ "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim
555
+ "image": [image], # three views
556
+ "lang": "Put all the toys in the child's room - the three board games (two on the bed and one on the table), the two jigsaw puzzles on the table, and the tennis ball on the table - inside the toy box on the table in the child's room.",
557
+ # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim
558
+ }
559
+
560
+ batch = [sample, sample2] # batch size 2
561
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
562
+ model = model.to(device)
563
+ forward_output = model(batch)
564
+ action_loss = forward_output['action_loss']
565
+ print(f"Action Loss: {action_loss.item()}")
566
+
567
+ # test predict action
568
+ predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]]
569
+ normalized_actions = predict_output['normalized_actions']
570
+ print(f"Unnormalized Action: {normalized_actions}")
571
+
572
+ # # Advance: try forward model with dataloader
573
+ # # can be fake sample, but here get from dataloader for simpler
574
+ vla_dataset_cfg = cfg.datasets.vla_data
575
+ from torch.utils.data import DataLoader
576
+ from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn
577
+ cfg.datasets.vla_data.include_state = "False"
578
+ dataset = get_vla_dataset(data_cfg=vla_dataset_cfg)
579
+
580
+ train_dataloader = DataLoader(
581
+ dataset,
582
+ batch_size=2,
583
+ num_workers=1, # For Debug
584
+ collate_fn=collate_fn,
585
+ )
586
+ # forward model with dataloader
587
+ for batch in tqdm(train_dataloader, desc="Processing Batches"):
588
+ # try get model
589
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
590
+ model = model.to(device)
591
+ model(batch)
592
+ # break
593
+
594
+ action = model.predict_action(examples=batch)
595
+ print("Finished")
starVLA/model/framework/QwenWanPerceiverMask.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ QwenWanPerceiver with masked future-image denoising.
5
+
6
+ This variant keeps the existing action path and adds a Wan2 future-image
7
+ objective with a latent-grid change mask built from the current/future RGB
8
+ pair. The mask focuses the loss on changed regions and optionally adds noise
9
+ only inside those regions, turning future-image training into an
10
+ inpainting-style objective.
11
+
12
+ Key adaptation from CosmoPredict25PerceiverMaskedFutureImage:
13
+ - Wan2 uses expand_timesteps (per-token timestep) instead of Cosmos's
14
+ condition_mask / padding_mask. Condition-frame tokens receive
15
+ timestep=0 (clean); target-frame tokens receive flow_time.
16
+ - Wan2 VAE has z_dim=48 and temporal_downsample_factor=4.
17
+
18
+ ================================================================================
19
+ (1) datasets.py 修改说明
20
+ ================================================================================
21
+
22
+ 为了支持本模型对 future_image 的需求,对 datasets.py 做了两处最小化修改:
23
+
24
+ A. 新增 _get_future_images 方法(LeRobotMixtureDataset 类)
25
+
26
+ 逻辑:
27
+ - 取第一个 action key 的 delta_indices 最大值 +1 作为 future_offset
28
+ (即当前 action chunk 最后一步的下一帧)
29
+ - 遍历所有 video key,用 dataset.get_video(trajectory_id, video_key,
30
+ step + future_offset) 读取未来视频帧
31
+ - 取该视频的最后一帧,转为 PIL Image,返回每路相机的未来帧列表
32
+
33
+ B. 修改 __getitem__ 中的两处 return
34
+
35
+ 在 return 之前新增条件化获取和返回 future_image 的逻辑:
36
+ future_images = None
37
+ if self.data_cfg is not None and self.data_cfg.get("include_future_image", False):
38
+ future_images = self._get_future_images(dataset, trajectory_id, step, data)
39
+
40
+ 在两处 return 的 dict 中条件化添加:
41
+ if future_images is not None:
42
+ result["future_image"] = future_images
43
+
44
+ 核心原则:只有当 data_cfg.include_future_image=True 时才会获取并返回
45
+ future_image,其他模型的配置中没有该字段(默认 False),完全不受影响。
46
+
47
+ ================================================================================
48
+ (2) QwenWanPerceiverMask 与 QwenWanPerceiver 的区别
49
+ ================================================================================
50
+
51
+ QwenWan_Perceiver_Mask 继承自 QwenWan_Perceiver,保留了原有的 action 预测
52
+ 路径不变,新增了 masked future-image denoising loss。
53
+
54
+ 新增方法:
55
+ - _build_future_video_sequences():
56
+ 构建视频序列 [current_frame] + [future_frame]*4(5帧 → Wan2 VAE 编码
57
+ → 2个 latent frame:1个条件 + 1个目标)
58
+
59
+ - _build_latent_change_masks():
60
+ RGB 差异图下采样到 latent 分辨率,top-k 选择变化最大的 25% 区域,
61
+ 生成 binary mask + soft loss weight
62
+
63
+ - _wan_future_image_loss():
64
+ 核心方法,计算 masked future-image denoising loss,流程:
65
+ 1. 从 example 中取 future_image,若不存在则返回 None(不训练)
66
+ 2. 构建 5 帧视频序列,经 Wan2 VAE 编码得到 clean_latents [B,48,2,H,W]
67
+ 3. 构建变化 mask:当前帧 vs 未来帧的 RGB 差异 → 下采样到 latent
68
+ 分辨率 → top-k 选变化区域
69
+ 4. 采样 flow matching 时间步 t,加噪:x_t = (1-t)*x_0 + t*noise
70
+ 5. Masked denoising:只对目标帧中变化区域加噪,静态区域保持干净
71
+ 6. Per-token timestep(关键适配):Wan2 不支持 Cosmos 的
72
+ condition_mask,改用 expand_timesteps——条件帧 token timestep=0
73
+ (干净),目标帧 token timestep=flow_time
74
+ 7. Static region conditioning:未变化的目标区域也标记为条件帧
75
+ (timestep=0)
76
+ 8. 计算 MSE loss,用 change mask 加权
77
+
78
+ - _future_training_cfg():
79
+ 读取 config.framework.future_image_training 配置
80
+
81
+ - _sample_train_times():
82
+ 采样 flow matching 的时间步(支持 logitnormal / uniform 分布)
83
+
84
+ - _shift_time():
85
+ 对时间步施加 shift 偏移(默认 shift=5.0)
86
+
87
+ - 辅助方法:_as_sequence(), _pil_rgb_to_tensor(), _as_bool()
88
+
89
+ 重写的 forward 方法:
90
+
91
+ 原始 forward 只返回 {"action_loss": action_loss},新版本:
92
+ output = super().forward(examples=examples, **kwargs) # 先走原 action 路径
93
+ action_loss = output["action_loss"]
94
+ future_image_loss = self._wan_future_image_loss(examples)
95
+ # 总 loss = action_loss + future_image_loss * loss_weight
96
+ output["action_loss"] = action_loss + future_image_loss * loss_weight
97
+ ================================================================================
98
+ """
99
+
100
+ from __future__ import annotations
101
+
102
+ from typing import List, Optional
103
+
104
+ import numpy as np
105
+ import torch
106
+ import torch.nn.functional as F
107
+ from PIL import Image as PILImage
108
+
109
+ from deployment.model_server.tools.image_tools import to_pil_preserve
110
+ from starVLA.model.framework.QwenWanPerceiver import QwenWan_Perceiver
111
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
112
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
113
+
114
+
115
+ @FRAMEWORK_REGISTRY.register("QwenWanPerceiverMask")
116
+ class QwenWan_Perceiver_Mask(QwenWan_Perceiver):
117
+ """QwenWanPerceiver with masked future-image denoising."""
118
+
119
+ def __init__(self, config=None, **kwargs):
120
+ super().__init__(config=config, **kwargs)
121
+
122
+ qwenvl_cfg = self.config.framework.get("qwenvl", {}) if self.config is not None else {}
123
+ is_frozen = bool(qwenvl_cfg.get("is_frozen", False))
124
+
125
+ for p in self.wan_interface.text_encoder.parameters():
126
+ p.requires_grad = False
127
+ for p in self.wan_interface.vae.parameters():
128
+ p.requires_grad = False
129
+
130
+ if is_frozen:
131
+ for p in self.qwen_vl_interface.parameters():
132
+ p.requires_grad = False
133
+
134
+ @staticmethod
135
+ def _as_sequence(images):
136
+ return list(images) if isinstance(images, (list, tuple)) else [images]
137
+
138
+ @staticmethod
139
+ def _pil_rgb_to_tensor(image, size=None) -> torch.Tensor:
140
+ from PIL import Image as _Image
141
+ image = to_pil_preserve(image).convert("RGB")
142
+ if size is not None and image.size != size:
143
+ image = image.resize(size)
144
+ array = np.asarray(image, dtype=np.float32) / 255.0
145
+ return torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0)
146
+
147
+ @staticmethod
148
+ def _as_bool(value) -> bool:
149
+ if isinstance(value, str):
150
+ return value.lower() in {"1", "true", "yes", "on"}
151
+ return bool(value)
152
+
153
+ def _future_training_cfg(self) -> dict:
154
+ return dict(self.config.framework.get("future_image_training", {}))
155
+
156
+ def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor:
157
+ distribution = str(distribution).lower()
158
+ if distribution == "logitnormal":
159
+ return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32))
160
+ if distribution == "uniform":
161
+ return torch.rand(batch_size, device=device, dtype=torch.float32)
162
+ raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}")
163
+
164
+ @staticmethod
165
+ def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor:
166
+ return shift * time / (1.0 + (shift - 1.0) * time)
167
+
168
+ def _latent_frame_count(self, raw_frame_count: int) -> int:
169
+ temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4))
170
+ return (int(raw_frame_count) - 1) // temporal_factor + 1
171
+
172
+ def _maybe_apply_single_frame_condition(self, examples: List[dict], training_cfg: dict) -> tuple[List[dict], float]:
173
+ prob = float(training_cfg.get("single_frame_condition_prob", 0.0))
174
+ if prob <= 0.0 or not examples:
175
+ return examples, 0.0
176
+
177
+ prob = min(max(prob, 0.0), 1.0)
178
+ sampled_examples = []
179
+ single_frame_count = 0
180
+ for example in examples:
181
+ image_sequence = self._as_sequence(example.get("image"))
182
+ if len(image_sequence) > 1 and torch.rand((), device="cpu").item() < prob:
183
+ example = dict(example)
184
+ example["image"] = [image_sequence[-1]]
185
+ single_frame_count += 1
186
+ sampled_examples.append(example)
187
+
188
+ return sampled_examples, single_frame_count / max(1, len(examples))
189
+
190
+ def _build_future_video_sequences(self, batch_images: List, future_images: List):
191
+ """Build video sequences for Wan2 VAE encoding.
192
+
193
+ Keep all observed frames as condition frames, then append the future frame
194
+ repeated by temporal_factor. This mirrors
195
+ CosmoPredict25PerceiverFutureImage._build_future_video_sequences, with
196
+ only the video model swapped from Cosmos to Wan.
197
+
198
+ Returns:
199
+ raw_sequences: List of List[PIL Image]
200
+ condition_counts: List[int] — latent condition frame count
201
+ sample_counts: List[int] — latent total frame count
202
+ """
203
+ temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4))
204
+ raw_sequences = []
205
+ condition_counts = []
206
+ sample_counts = []
207
+
208
+ for images, future_image in zip(batch_images, future_images):
209
+ current_sequence = self._as_sequence(images)
210
+ future_sequence = self._as_sequence(future_image)
211
+ if not current_sequence or not future_sequence:
212
+ raise ValueError("future image training needs both current image and future_image.")
213
+
214
+ future_frame = future_sequence[0]
215
+ raw_sequence = current_sequence + [future_frame] * temporal_factor
216
+ raw_sequences.append(raw_sequence)
217
+ condition_counts.append(self._latent_frame_count(len(current_sequence)))
218
+ sample_counts.append(self._latent_frame_count(len(raw_sequence)))
219
+
220
+ return raw_sequences, condition_counts, sample_counts
221
+
222
+ def _build_latent_change_masks(
223
+ self,
224
+ batch_images: List,
225
+ future_images: List,
226
+ latent_height: int,
227
+ latent_width: int,
228
+ training_cfg: dict,
229
+ device: torch.device,
230
+ ) -> tuple:
231
+ """Return binary denoise mask and soft loss weights at latent resolution.
232
+
233
+ Adapted from CosmoPredict25PerceiverMaskedFutureImage._build_latent_change_masks.
234
+ """
235
+ top_ratio = float(training_cfg.get("change_mask_top_ratio", 0.25))
236
+ top_ratio = min(max(top_ratio, 1e-4), 1.0)
237
+ static_weight = float(training_cfg.get("change_mask_static_weight", 0.05))
238
+ static_weight = min(max(static_weight, 0.0), 1.0)
239
+ soft_loss = self._as_bool(training_cfg.get("change_mask_soft_loss", True))
240
+
241
+ binary_masks = []
242
+ loss_weights = []
243
+ for images, future_image in zip(batch_images, future_images):
244
+ current_sequence = self._as_sequence(images)
245
+ future_sequence = self._as_sequence(future_image)
246
+ current_frame = current_sequence[-1]
247
+ target_frame = future_sequence[0]
248
+
249
+ current = self._pil_rgb_to_tensor(current_frame)
250
+ target = self._pil_rgb_to_tensor(target_frame, size=to_pil_preserve(current_frame).size)
251
+ diff = (target - current).abs().mean(dim=1, keepdim=True)
252
+ score = F.interpolate(diff, size=(latent_height, latent_width), mode="area")
253
+ flat = score.flatten(1)
254
+ max_score = flat.amax(dim=1).view(-1, 1, 1, 1).clamp_min(1e-6)
255
+ normalized = (score / max_score).clamp(0.0, 1.0)
256
+
257
+ k = max(1, int(flat.shape[1] * top_ratio))
258
+ threshold = flat.topk(k, dim=1).values[:, -1].view(-1, 1, 1, 1)
259
+ binary = (score >= threshold).float()
260
+
261
+ weight_source = normalized if soft_loss else binary
262
+ loss_weight = static_weight + (1.0 - static_weight) * weight_source
263
+ binary_masks.append(binary)
264
+ loss_weights.append(loss_weight)
265
+
266
+ binary_mask = torch.cat(binary_masks, dim=0).to(device=device, dtype=torch.float32)
267
+ loss_weight = torch.cat(loss_weights, dim=0).to(device=device, dtype=torch.float32)
268
+ return binary_mask, loss_weight
269
+
270
+ def _wan_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
271
+ """Compute masked future-image denoising loss using Wan2 DiT.
272
+
273
+ Adaptation from CosmoPredict25PerceiverMaskedFutureImage for Wan2:
274
+ - Uses Wan2 _encode_images_vae instead of Cosmos _encode_images
275
+ - Uses per-token expand_timesteps instead of condition_mask / padding_mask
276
+ - Condition-frame tokens get timestep=0 (clean), target-frame tokens
277
+ get timestep=flow_time
278
+ """
279
+ if "future_image" not in examples[0]:
280
+ return None
281
+
282
+ training_cfg = self._future_training_cfg()
283
+ if not self._as_bool(training_cfg.get("enabled", True)):
284
+ return None
285
+
286
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
287
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
288
+ instructions = [example["lang"] for example in examples]
289
+
290
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
291
+ if not train_obs_image_size:
292
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
293
+ if train_obs_image_size:
294
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
295
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
296
+
297
+ # Build video sequences: [current_frame, future_frame * temporal_factor]
298
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
299
+ batch_images=batch_images,
300
+ future_images=future_images,
301
+ )
302
+
303
+ # Encode through Wan2 VAE — raw_sequences already contains head-only frames
304
+ # (batch_images/future_images were already filtered via _wm_images_head_only earlier,
305
+ # so we should NOT apply _wm_images_head_only again on the video sequences)
306
+ with torch.no_grad():
307
+ clean_latents = self.wan_interface._encode_images_vae(raw_sequences)
308
+
309
+ dtype = self.wan_interface.transformer.dtype
310
+ clean_latents = clean_latents.to(dtype)
311
+ batch_size, channels, num_latents, height, width = clean_latents.shape
312
+ device = clean_latents.device
313
+
314
+ # Build per-latent-frame masks
315
+ # condition_mask: which latent frames are conditions (timestep=0)
316
+ # target_mask: which latent frames are targets (to be denoised)
317
+ condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width))
318
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
319
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
320
+ condition_count = max(1, min(int(condition_count), num_latents))
321
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
322
+ condition_mask[batch_idx, :, :condition_count] = 1.0
323
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
324
+
325
+ # Build change masks at latent spatial resolution
326
+ change_binary, change_loss_weight = self._build_latent_change_masks(
327
+ batch_images=batch_images,
328
+ future_images=future_images,
329
+ latent_height=height,
330
+ latent_width=width,
331
+ training_cfg=training_cfg,
332
+ device=device,
333
+ )
334
+ change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype)
335
+ change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32)
336
+
337
+ # Sample training time
338
+ train_time = self._sample_train_times(
339
+ batch_size=batch_size,
340
+ device=device,
341
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
342
+ )
343
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
344
+
345
+ # Flow-matching interpolation: x_t = (1-t)*x_0 + t*noise
346
+ noise = torch.randn_like(clean_latents)
347
+ target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype)
348
+ noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time
349
+
350
+ # Masked denoising: only noise changed regions in target frames
351
+ use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", True))
352
+ use_static_conditioning = use_masked_denoising and self._as_bool(
353
+ training_cfg.get("condition_static_regions", True)
354
+ )
355
+
356
+ if use_masked_denoising:
357
+ denoise_mask = target_mask.to(dtype=clean_latents.dtype) * change_binary
358
+ else:
359
+ denoise_mask = target_mask.to(dtype=clean_latents.dtype)
360
+
361
+ # hidden_states: condition frames stay clean, target frames are noised
362
+ # (within target frames, only changed regions are noised if masked_denoising)
363
+ hidden_states = torch.where(denoise_mask.to(dtype=torch.bool), noisy_latents, clean_latents)
364
+ target_velocity = noise.float() - clean_latents.float()
365
+
366
+ # Static region conditioning: treat unchanged target regions as conditions
367
+ if use_static_conditioning:
368
+ static_target_mask = target_mask.to(dtype=clean_latents.dtype) * (1.0 - change_binary)
369
+ condition_mask = torch.maximum(condition_mask, static_target_mask)
370
+
371
+ # Build per-token timestep for Wan2 expand_timesteps mode
372
+ # Condition tokens → timestep=0, target tokens → timestep=flow_time
373
+ p_t, p_h, p_w = self.wan_interface.transformer.config.patch_size
374
+ tokens_per_frame = (height // p_h) * (width // p_w)
375
+
376
+ # flow_time is [B], expand to per-token: [B, num_latents * tokens_per_frame]
377
+ cond_timestep_val = 0.0 # clean condition
378
+ target_timestep_val = flow_time.to(dtype=torch.float32) # [B]
379
+
380
+ timestep_per_token = torch.zeros(
381
+ batch_size, num_latents * tokens_per_frame,
382
+ device=device, dtype=torch.float32,
383
+ )
384
+ for batch_idx in range(batch_size):
385
+ for latent_idx in range(num_latents):
386
+ start = latent_idx * tokens_per_frame
387
+ end = (latent_idx + 1) * tokens_per_frame
388
+ if target_mask[batch_idx, 0, latent_idx, 0, 0] > 0.5:
389
+ timestep_per_token[batch_idx, start:end] = target_timestep_val[batch_idx]
390
+ else:
391
+ timestep_per_token[batch_idx, start:end] = cond_timestep_val
392
+
393
+ # Encode text
394
+ with torch.no_grad():
395
+ prompt_embeds = self.wan_interface._encode_text(instructions)
396
+
397
+ # DiT forward pass
398
+ self.wan_interface._intermediate_features.clear()
399
+ with torch.autocast("cuda", dtype=torch.bfloat16):
400
+ pred = self.wan_interface.transformer(
401
+ hidden_states=hidden_states,
402
+ timestep=timestep_per_token,
403
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
404
+ )
405
+ pred = pred.sample if hasattr(pred, "sample") else pred
406
+ if isinstance(pred, tuple):
407
+ pred = pred[0]
408
+ self.wan_interface._intermediate_features.clear()
409
+
410
+ # Compute masked loss
411
+ temporal_loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width)
412
+ if use_static_conditioning:
413
+ change_loss_weight = change_loss_weight * change_binary.float()
414
+ spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width)
415
+ spatial_loss_weight = spatial_loss_weight.expand(batch_size, channels, num_latents, height, width)
416
+ loss_mask = temporal_loss_mask * spatial_loss_weight
417
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
418
+
419
+ return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
420
+
421
+ def forward(self, examples: List[dict] = None, **kwargs):
422
+ """Forward pass: action loss + masked future-image loss."""
423
+ output = super().forward(examples=examples, **kwargs)
424
+ action_loss = output["action_loss"]
425
+
426
+ future_image_loss = self._wan_future_image_loss(examples)
427
+ if future_image_loss is None:
428
+ return output
429
+
430
+ loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0))
431
+ output["perceiver_action_loss"] = action_loss.detach()
432
+ output["future_image_loss"] = future_image_loss.detach()
433
+ output["action_loss"] = action_loss + future_image_loss * loss_weight
434
+ return output
435
+
436
+ # ------------------------------------------------------------------
437
+ # Future-image generation (eval / inference)
438
+ # ------------------------------------------------------------------
439
+
440
+ def _get_future_image_generation_cfg(self, kwargs: dict) -> dict:
441
+ """Merge config defaults with runtime kwargs for future-image generation."""
442
+ cfg = dict(self.config.framework.get("future_image_generation", {}))
443
+ override = kwargs.get("future_image_generation", None)
444
+ if override:
445
+ cfg.update(dict(override))
446
+
447
+ if "decode_future_images" in kwargs:
448
+ cfg["enabled"] = kwargs["decode_future_images"]
449
+ if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs:
450
+ cfg["num_inference_steps"] = kwargs["num_ddim_steps"]
451
+
452
+ for key in (
453
+ "enabled",
454
+ "num_frames",
455
+ "num_inference_steps",
456
+ "guidance_scale",
457
+ "output_type",
458
+ "height",
459
+ "width",
460
+ "max_sequence_length",
461
+ "max_samples",
462
+ "return_full_video",
463
+ "future_frame_index",
464
+ "negative_prompt",
465
+ "generator",
466
+ "latents",
467
+ "prompt_embeds",
468
+ "negative_prompt_embeds",
469
+ ):
470
+ if key in kwargs:
471
+ cfg[key] = kwargs[key]
472
+ return cfg
473
+
474
+ def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict:
475
+ """Build generation inputs for Wan2 TI2V pipeline.
476
+ """
477
+ height = cfg.pop("height", getattr(self.wan_interface, "height", 704))
478
+ width = cfg.pop("width", getattr(self.wan_interface, "width", 1280))
479
+ heights = self._resolve_generation_size_values(batch_images, height, width)
480
+
481
+ # Wan2 TI2V: pass conditioning image directly; generate() handles
482
+ # VAE encoding + expand_timesteps internally
483
+ head_only_images = self._wm_images_head_only(batch_images)
484
+ condition_images = [self._as_sequence(imgs)[-1] for imgs in head_only_images]
485
+
486
+ generation_inputs = {
487
+ "prompt": instructions,
488
+ "image": condition_images,
489
+ "height": heights[0],
490
+ "width": heights[1],
491
+ "num_frames": cfg.pop("num_frames", 93),
492
+ "num_inference_steps": cfg.pop("num_inference_steps", 36),
493
+ "guidance_scale": cfg.pop("guidance_scale", 7.0),
494
+ "output_type": cfg.pop("output_type", "pil"),
495
+ "return_dict": True,
496
+ "max_sequence_length": cfg.pop("max_sequence_length", 512),
497
+ }
498
+
499
+ negative_prompt = cfg.pop("negative_prompt", None)
500
+ if negative_prompt is not None:
501
+ generation_inputs["negative_prompt"] = negative_prompt
502
+
503
+ passthrough_keys = (
504
+ "generator",
505
+ "latents",
506
+ "prompt_embeds",
507
+ "negative_prompt_embeds",
508
+ "num_videos_per_prompt",
509
+ "callback_on_step_end",
510
+ "callback_on_step_end_tensor_inputs",
511
+ )
512
+ for key in passthrough_keys:
513
+ if key in cfg and cfg[key] is not None:
514
+ generation_inputs[key] = cfg.pop(key)
515
+
516
+ generation_inputs.update({key: value for key, value in cfg.items() if value is not None})
517
+ return generation_inputs
518
+
519
+ @staticmethod
520
+ def _is_auto_size(value) -> bool:
521
+ return isinstance(value, str) and value.lower() == "auto"
522
+
523
+ @staticmethod
524
+ def _round_up_to_multiple(value: int, multiple: int) -> int:
525
+ return int(((max(1, value) + multiple - 1) // multiple) * multiple)
526
+
527
+ @staticmethod
528
+ def _image_size(image) -> tuple[int, int]:
529
+ size = getattr(image, "size", None)
530
+ if isinstance(size, (list, tuple)) and len(size) >= 2:
531
+ return int(size[0]), int(size[1])
532
+ if torch.is_tensor(image):
533
+ shape = tuple(image.shape)
534
+ if len(shape) >= 3 and shape[0] in (1, 3, 4):
535
+ return int(shape[-1]), int(shape[-2])
536
+ if len(shape) >= 2:
537
+ return int(shape[1]), int(shape[0])
538
+ array = np.asarray(image)
539
+ if array.ndim < 2:
540
+ raise ValueError(f"Cannot infer image size from shape {array.shape}")
541
+ return int(array.shape[1]), int(array.shape[0])
542
+
543
+ def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple:
544
+ if not self._is_auto_size(height) and not self._is_auto_size(width):
545
+ return int(height), int(width)
546
+
547
+ resolved_heights = []
548
+ resolved_widths = []
549
+ spatial_multiple = int(getattr(self.wan_interface, "vae_scale_factor_spatial", 16))
550
+ patch_size = getattr(getattr(self.wan_interface.transformer, "config", None), "patch_size", None)
551
+ if isinstance(patch_size, (list, tuple)) and len(patch_size) >= 3:
552
+ spatial_multiple *= max(int(patch_size[-2]), int(patch_size[-1]), 1)
553
+ elif isinstance(patch_size, int):
554
+ spatial_multiple *= max(int(patch_size), 1)
555
+ for images in batch_images:
556
+ image_sequence = self._as_sequence(images)
557
+ frame_sizes = [self._image_size(image) for image in image_sequence]
558
+ if not frame_sizes:
559
+ raise ValueError("Cannot infer auto generation size from empty image sequence.")
560
+
561
+ sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height)
562
+ sample_height = self._round_up_to_multiple(sample_height, spatial_multiple)
563
+ if self._is_auto_size(width):
564
+ max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes)
565
+ sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple)
566
+ else:
567
+ sample_width = self._round_up_to_multiple(int(width), spatial_multiple)
568
+ resolved_heights.append(int(sample_height))
569
+ resolved_widths.append(int(sample_width))
570
+
571
+ height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0]
572
+ width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0]
573
+ return height_value, width_value
574
+
575
+ @staticmethod
576
+ def _extract_videos(generation_output):
577
+ if hasattr(generation_output, "frames"):
578
+ return generation_output.frames
579
+ if hasattr(generation_output, "videos"):
580
+ return generation_output.videos
581
+ if hasattr(generation_output, "images"):
582
+ return generation_output.images
583
+ if isinstance(generation_output, tuple):
584
+ return generation_output[0]
585
+ return generation_output
586
+
587
+ def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool):
588
+ from PIL import Image as _Image
589
+ videos = self._extract_videos(generation_output)
590
+ if return_full_video:
591
+ return videos
592
+
593
+ if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], _Image.Image):
594
+ return [videos[future_frame_index]]
595
+
596
+ future_images = []
597
+ for sample in videos:
598
+ if torch.is_tensor(sample):
599
+ if sample.ndim >= 4:
600
+ future_images.append(sample[future_frame_index])
601
+ else:
602
+ future_images.append(sample)
603
+ elif isinstance(sample, np.ndarray):
604
+ if sample.ndim >= 4:
605
+ future_images.append(sample[future_frame_index])
606
+ else:
607
+ future_images.append(sample)
608
+ elif isinstance(sample, (list, tuple)):
609
+ future_images.append(sample[future_frame_index])
610
+ else:
611
+ future_images.append(sample)
612
+ return future_images
613
+
614
+ @staticmethod
615
+ def _slice_generation_value(key: str, value, index: int, batch_size: int):
616
+ if value is None:
617
+ return None
618
+ if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
619
+ return value[index]
620
+ if key in {"image", "video", "condition_image"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
621
+ return value[index]
622
+ if torch.is_tensor(value) and value.shape[0] == batch_size:
623
+ return value[index:index + 1]
624
+ if isinstance(value, np.ndarray) and value.shape[0] == batch_size:
625
+ return value[index:index + 1]
626
+ if isinstance(value, list) and len(value) == batch_size:
627
+ return [value[index]]
628
+ if isinstance(value, tuple) and len(value) == batch_size:
629
+ return (value[index],)
630
+ return value
631
+
632
+ def _generate_future_images(
633
+ self,
634
+ generation_inputs: dict,
635
+ batch_size: int,
636
+ max_samples: int,
637
+ future_frame_index: int,
638
+ return_full_video: bool,
639
+ ):
640
+ if max_samples is None or max_samples < 0:
641
+ sample_count = batch_size
642
+ else:
643
+ sample_count = min(batch_size, max(0, int(max_samples)))
644
+
645
+ pred_future_images = []
646
+ for sample_idx in range(sample_count):
647
+ single_inputs = {
648
+ key: self._slice_generation_value(key, value, sample_idx, batch_size)
649
+ for key, value in generation_inputs.items()
650
+ }
651
+ generation_output = self.wan_interface.generate(**single_inputs)
652
+ sample_images = self._select_future_images(
653
+ generation_output,
654
+ future_frame_index=future_frame_index,
655
+ return_full_video=return_full_video,
656
+ )
657
+ if isinstance(sample_images, (list, tuple)):
658
+ pred_future_images.extend(sample_images)
659
+ else:
660
+ pred_future_images.append(sample_images)
661
+ return pred_future_images
662
+
663
+ @torch.inference_mode()
664
+ def predict_action(self, examples: List[dict], is_run_parallel_eval_mxk: bool = False, **kwargs) -> dict:
665
+ """Predict actions and optionally generate future images."""
666
+ output = super().predict_action(examples=examples, **kwargs)
667
+
668
+ generation_cfg = self._get_future_image_generation_cfg(kwargs)
669
+ if not bool(generation_cfg.pop("enabled", True)):
670
+ return output
671
+
672
+ if type(examples) is not list:
673
+ examples = [examples]
674
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
675
+ instructions = [example["lang"] for example in examples]
676
+
677
+ train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None)
678
+ if not train_obs_image_size:
679
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
680
+ if train_obs_image_size:
681
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
682
+
683
+ return_full_video = bool(generation_cfg.pop("return_full_video", False))
684
+ future_frame_index = int(generation_cfg.pop("future_frame_index", -1))
685
+ max_samples = int(generation_cfg.pop("max_samples", 1))
686
+ generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg)
687
+ output["pred_future_images"] = self._generate_future_images(
688
+ generation_inputs,
689
+ batch_size=len(examples),
690
+ max_samples=max_samples,
691
+ future_frame_index=future_frame_index,
692
+ return_full_video=return_full_video,
693
+ )
694
+
695
+ # When called from websocket server, convert PIL Images to numpy arrays
696
+ # for msgpack serialization; otherwise keep PIL Image format
697
+ if is_run_parallel_eval_mxk and "pred_future_images" in output:
698
+ output["pred_future_images"] = [
699
+ np.array(img) if isinstance(img, PILImage.Image) else img
700
+ for img in output["pred_future_images"]
701
+ ]
702
+
703
+ return output
starVLA/model/framework/WAM_VJEPA/.ipynb_checkpoints/CosmoPredict25PerceiverVJEPA2AC-checkpoint.py ADDED
@@ -0,0 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver with future-image prediction.
5
+
6
+ This framework keeps the existing Cosmos hidden-state -> Perceiver action
7
+ path, and additionally runs the Cosmos2.5 generation/decoder path during
8
+ inference to return the image predicted after the action chunk horizon.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import List, Optional
13
+
14
+ import numpy as np
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from PIL import Image
18
+
19
+ from deployment.model_server.tools.image_tools import to_pil_preserve
20
+ from starVLA.model.framework.base_framework import baseframework
21
+ from starVLA.model.framework.share_tools import merge_framework_config
22
+ from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model
23
+ from starVLA.model.modules.world_model import get_world_model
24
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
25
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
26
+
27
+ from starVLA.model.framework.WAM_VJEPA.CosmoPredict25Perceiver import (
28
+ CosmoPredict25_Perceiver,
29
+ CosmoPredict25PerceiverDefaultConfig,
30
+ )
31
+
32
+
33
+ @dataclass
34
+ class CosmoPredict25PerceiverVJEPA2ACDefaultConfig(CosmoPredict25PerceiverDefaultConfig):
35
+ """Cosmos-Predict2.5-Perceiver + VJEPA2-AC defaults."""
36
+
37
+ name: str = "CosmoPredict25PerceiverFutureImage"
38
+
39
+ future_image_generation: dict = field(default_factory=lambda: {
40
+ "enabled": True,
41
+ "num_frames": 93,
42
+ "num_inference_steps": 36,
43
+ "guidance_scale": 7.0,
44
+ "output_type": "pil",
45
+ "height": 704,
46
+ "width": 1280,
47
+ "max_sequence_length": 512,
48
+ "conditional_frame_timestep": 0.1,
49
+ "num_latent_conditional_frames": 2,
50
+ "conditioning_mode": "auto",
51
+ "max_samples": 1,
52
+ "return_full_video": False,
53
+ "future_frame_index": -1,
54
+ "negative_prompt": None,
55
+ })
56
+
57
+ future_image_training: dict = field(default_factory=lambda: {
58
+ "enabled": True,
59
+ "loss_weight": 1.0,
60
+ "train_time_distribution": "logitnormal",
61
+ "shift": 5.0,
62
+ })
63
+
64
+
65
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverVJEPA2AC")
66
+ class CosmoPredict25_Perceiver_VJEPA2AC(CosmoPredict25_Perceiver):
67
+
68
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
69
+ # print('################# CosmoPredict25_Perceiver_VJEPA2AC-1')
70
+ baseframework.__init__(self)
71
+ self.config = merge_framework_config(CosmoPredict25PerceiverVJEPA2ACDefaultConfig, config)
72
+
73
+ # 1. 加载预训练的CosmoPredictr2.5类作为self.backbone
74
+ # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py
75
+ self.backbone = get_world_model(config=self.config)
76
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
77
+
78
+ wm_hidden = self.backbone.model.config.hidden_size
79
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
80
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
81
+ # print(wm_hidden) # 2048
82
+
83
+ # 2. 初始化FlowmatchingActionHead作为self.action_model
84
+ # WM4A/starVLA/model/modules/action_model/PerceiverHead.py
85
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
86
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
87
+
88
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
89
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
90
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
91
+ self.state_dim = self.config.framework.action_model.get("state_dim", None)
92
+ # print(self.future_action_window_size) # 15
93
+ # print(self.past_action_window_size) # 0
94
+ # print(self.chunk_len) # 16
95
+ # print(self.state_dim) # 64
96
+
97
+ # 3. 加载vjepa_encoder和vjepa_decoder,并将其权重固定为bf16
98
+ vjepa2_ac_cfg = self.config.framework.get("vjepa2_ac")
99
+ vjepa2_ac_repo_dir = vjepa2_ac_cfg.get("repo_dir")
100
+ vjepa2_ac_pretrained = vjepa2_ac_cfg.get("pretrained")
101
+ # print(vjepa2_ac_repo_dir) # /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main
102
+ # print(vjepa2_ac_pretrained) # /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt
103
+ self.vjepa_encoder, self.vjepa_predictor = torch.hub.load(
104
+ vjepa2_ac_repo_dir,
105
+ "vjepa2_ac_vit_giant",
106
+ source="local",
107
+ pretrained=vjepa2_ac_pretrained,
108
+ )
109
+ self.vjepa_encoder = self.vjepa_encoder.to(torch.bfloat16).cuda()
110
+ self.vjepa_predictor = self.vjepa_predictor.to(torch.bfloat16).cuda()
111
+ for p in self.vjepa_encoder.parameters():
112
+ p.requires_grad = False
113
+ # for p in self.vjepa_predictor.parameters():
114
+ # p.requires_grad = False
115
+
116
+ # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用,
117
+ # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配
118
+ # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None,
119
+ # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重
120
+ for p in self.vjepa_predictor.action_encoder.parameters():
121
+ p.requires_grad = False
122
+ for p in self.vjepa_predictor.state_encoder.parameters():
123
+ p.requires_grad = False
124
+ for p in self.vjepa_predictor.extrinsics_encoder.parameters():
125
+ p.requires_grad = False
126
+
127
+ for name, p in self.vjepa_encoder.named_parameters():
128
+ assert p.dtype == torch.bfloat16, f"vjepa_encoder.{name} dtype={p.dtype}, expected bfloat16"
129
+ for name, p in self.vjepa_predictor.named_parameters():
130
+ assert p.dtype == torch.bfloat16, f"vjepa_predictor.{name} dtype={p.dtype}, expected bfloat16"
131
+
132
+ # print(type(self.vjepa_encoder)) # <class 'src.models.vision_transformer.VisionTransformer'>
133
+ # print(type(self.vjepa_predictor)) # <class 'src.models.ac_predictor.VisionTransformerPredictorAC'>
134
+
135
+ # 初始化VJEPA2-AC的图像预处理transform,与官方energy_landscape_example.ipynb保持一致
136
+ from starVLA.facebookresearch_vjepa2_main.app.vjepa_droid.transforms import make_transforms as vjepa2_make_transforms
137
+ self._vjepa2_transform = vjepa2_make_transforms(
138
+ random_horizontal_flip=False,
139
+ random_resize_aspect_ratio=(1., 1.),
140
+ random_resize_scale=(1., 1.),
141
+ reprob=0.,
142
+ auto_augment=False,
143
+ motion_shift=False,
144
+ crop_size=256,
145
+ )
146
+
147
+ self.state_projector = torch.nn.Linear(
148
+ self.state_dim,
149
+ self.vjepa_predictor.predictor_embed.out_features,
150
+ bias=True
151
+ ).to(torch.bfloat16)
152
+ # print(self.state_dim) # 64
153
+ # print(self.vjepa_predictor.predictor_embed.out_features) # 1024
154
+ self.action_projector = torch.nn.Linear(
155
+ self.action_model.model.config.output_dim,
156
+ self.vjepa_predictor.predictor_embed.out_features,
157
+ bias=True
158
+ ).to(torch.bfloat16)
159
+ # print(self.action_model.model.config.output_dim) # 1024
160
+ # print(self.vjepa_predictor.predictor_embed.out_features) # 1024
161
+ # print('################# CosmoPredict25_Perceiver_FutureImage-2')
162
+
163
+ @staticmethod
164
+ def _as_sequence(images):
165
+ return list(images) if isinstance(images, (list, tuple)) else [images]
166
+
167
+ def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor:
168
+ if state is None or self.state_dim is None:
169
+ return state
170
+ target_dim = int(self.state_dim)
171
+ current_dim = state.shape[-1]
172
+ if current_dim == target_dim:
173
+ return state
174
+ if current_dim > target_dim:
175
+ return state[..., :target_dim]
176
+
177
+ pad_shape = (*state.shape[:-1], target_dim - current_dim)
178
+ padding = state.new_zeros(pad_shape)
179
+ return torch.cat([state, padding], dim=-1)
180
+
181
+ @staticmethod
182
+ def _as_bool(value) -> bool:
183
+ if isinstance(value, str):
184
+ return value.lower() in {"1", "true", "yes", "on"}
185
+ return bool(value)
186
+
187
+ def _future_image_training_cfg(self) -> dict:
188
+ return dict(self.config.framework.get("future_image_training", {}))
189
+
190
+ def _future_latent_training_cfg(self) -> dict:
191
+ return dict(self.config.framework.get("future_latent_training", {}))
192
+
193
+ def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor:
194
+ distribution = str(distribution).lower()
195
+ if distribution == "logitnormal":
196
+ return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32))
197
+ if distribution == "uniform":
198
+ return torch.rand(batch_size, device=device, dtype=torch.float32)
199
+ raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}")
200
+
201
+ @staticmethod
202
+ def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor:
203
+ return shift * time / (1.0 + (shift - 1.0) * time)
204
+
205
+ def _latent_frame_count(self, raw_frame_count: int) -> int:
206
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
207
+ return (int(raw_frame_count) - 1) // temporal_factor + 1
208
+
209
+ def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]:
210
+ # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1')
211
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
212
+ raw_sequences = []
213
+ condition_counts = []
214
+ sample_counts = []
215
+ # print(temporal_factor) # 4
216
+ # print(len(batch_images)) # 8
217
+ # print(len(future_images)) # 8
218
+
219
+ for images, future_image in zip(batch_images, future_images):
220
+ current_sequence = self._as_sequence(images)
221
+ future_sequence = self._as_sequence(future_image)
222
+ # print(len(current_sequence)) # 1
223
+ # print(len(future_sequence)) # 1
224
+ if not current_sequence or not future_sequence:
225
+ raise ValueError("future image training needs both current image and future_image.")
226
+
227
+ future_frame = future_sequence[0]
228
+ # print(type(future_frame)) # <class 'PIL.Image.Image'>
229
+ raw_sequence = current_sequence + [future_frame] * temporal_factor
230
+ raw_sequences.append(raw_sequence)
231
+
232
+ condition_count = self._latent_frame_count(len(current_sequence))
233
+ sample_count = self._latent_frame_count(len(raw_sequence))
234
+ # print(condition_count) # 1
235
+ # print(sample_count) # 2
236
+ condition_counts.append(condition_count)
237
+ sample_counts.append(sample_count)
238
+
239
+ # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2')
240
+ return raw_sequences, condition_counts, sample_counts
241
+
242
+ # 训练时
243
+ # future_image支路,self.backbone.transformer()
244
+ def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
245
+ # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1')
246
+ if "future_image" not in examples[0]:
247
+ return None
248
+ training_cfg = self._future_image_training_cfg()
249
+ if not self._as_bool(training_cfg.get("enabled", True)):
250
+ return None
251
+
252
+ # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状
253
+ # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt;
254
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
255
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
256
+ instructions = [example["lang"] for example in examples]
257
+ # print(len(examples)) # 8
258
+ # print(type(batch_images[0])) # <class 'list'>
259
+ # print(type(future_images[0])) # <class 'list'>
260
+ # print(type(instructions[0])) # <class 'str'>
261
+
262
+ # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs]
263
+ # 而raw_sequences也是由8个这样的raw_sequence组成的列表,
264
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
265
+ # print(train_obs_image_size) # None
266
+ if train_obs_image_size:
267
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
268
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
269
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
270
+ batch_images=batch_images,
271
+ future_images=future_images,
272
+ )
273
+ # print(len(raw_sequences)) # 8
274
+ # print(len(raw_sequences[0])) # 5
275
+ # print(raw_sequences[0][0]) # <PIL.Image.Image image mode=RGB size=224x224 at 0x7FF6B20D60E0>
276
+ # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1]
277
+ # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2]
278
+
279
+ # 2. 调用CosmosPredict的文本和视觉tokenizer,
280
+ # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28),
281
+ # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents
282
+ prompt_embeds = self.backbone._encode_text(instructions)
283
+ clean_latents, _, _ = self.backbone._encode_images(raw_sequences)
284
+ dtype = self.backbone.transformer.dtype
285
+ clean_latents = clean_latents.to(dtype)
286
+ batch_size, channels, num_latents, height, width = clean_latents.shape
287
+ device = clean_latents.device
288
+ # print(prompt_embeds.shape) # torch.Size([8, 512, 100352])
289
+ # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28])
290
+ # print(dtype) # torch.bfloat16
291
+ condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width))
292
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
293
+ cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
294
+ # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28])
295
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
296
+ # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1])
297
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
298
+ condition_count = max(1, min(int(condition_count), num_latents))
299
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
300
+ condition_mask[batch_idx, :, :condition_count] = 1.0
301
+ cond_indicator[batch_idx, :, :condition_count] = 1.0
302
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
303
+
304
+ # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪
305
+ train_time = self._sample_train_times(
306
+ batch_size=batch_size,
307
+ device=device,
308
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
309
+ )
310
+ # print(train_time.shape) # torch.Size([8])
311
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
312
+ # print(flow_time.shape) # torch.Size([8])
313
+ target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype)
314
+ # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1])
315
+ # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28])
316
+ noise = torch.randn_like(clean_latents)
317
+ # print(noise.shape) # torch.Size([8, 16, 2, 28, 28])
318
+ # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1])
319
+ noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time
320
+ # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28])
321
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
322
+ hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents)
323
+ # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28])
324
+
325
+ # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity
326
+ target_velocity = noise.float() - clean_latents.float()
327
+ # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28])
328
+
329
+ # 5. 计算timestep和padding_mask
330
+ cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1))
331
+ # print(cond_timestep) # 0.1
332
+ timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
333
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
334
+ timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep
335
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
336
+ timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep)
337
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
338
+
339
+ padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16))
340
+ padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16))
341
+ padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype)
342
+ # print(padding_height) # 224
343
+ # print(padding_width) # 224
344
+ # print(padding_mask.shape) # torch.Size([1, 1, 224, 224])
345
+
346
+ # 7. CosmosPredict前向传播
347
+ # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入,
348
+ # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中,
349
+ # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息,
350
+ # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分,
351
+ if hasattr(self.backbone, "_intermediate_features"):
352
+ self.backbone._intermediate_features.clear()
353
+ with torch.autocast("cuda", dtype=torch.bfloat16):
354
+ pred = self.backbone.transformer(
355
+ hidden_states=hidden_states,
356
+ timestep=timestep,
357
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
358
+ condition_mask=condition_mask.to(dtype),
359
+ padding_mask=padding_mask,
360
+ return_dict=False,
361
+ )
362
+ pred = pred[0] if isinstance(pred, tuple) else pred
363
+ pred = pred.sample if hasattr(pred, "sample") else pred
364
+ if hasattr(self.backbone, "_intermediate_features"):
365
+ self.backbone._intermediate_features.clear()
366
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
367
+ # print(pred.shape) # torch.Size([8, 16, 2, 28, 28])
368
+
369
+ # 8. 计算future-image-loss
370
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
371
+ loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width)
372
+ # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28])
373
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
374
+ # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28])
375
+ future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
376
+ # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=<DivBackward0>)
377
+ # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2')
378
+ return future_image_loss
379
+
380
+ # 训练时
381
+ # future_latent支路,self.vjepa_encoder + self.vjepa_predictor
382
+ def _vjepa2ac_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]:
383
+ # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-1')
384
+ if "future_image" not in examples[0]:
385
+ return None
386
+
387
+ # 2. 从examples中取出当前图像和未来图像,并使用VJEPA2-AC官方的transform对图像做预处理
388
+ batch_current_images = [to_pil_preserve(example["image"]) for example in examples]
389
+ batch_future_images = [to_pil_preserve(example["future_image"]) for example in examples]
390
+ # print(len(examples)) # 8
391
+ clips_list = []
392
+ for current_images, future_images in zip(batch_current_images, batch_future_images):
393
+ current_seq = self._as_sequence(current_images)
394
+ future_seq = self._as_sequence(future_images)
395
+ # print(len(current_seq)) # 1
396
+ # print(len(future_seq)) # 1
397
+ current_np = np.array(current_seq[0])
398
+ future_np = np.array(future_seq[0])
399
+ # print(current_np.shape) # (224, 224, 3)
400
+ # print(future_np.shape) # (224, 224, 3)
401
+ clip_np = np.stack([current_np, future_np], axis=0)
402
+ # print(clip_np.shape) # (2, 224, 224, 3)
403
+ clip_tensor = self._vjepa2_transform(clip_np)
404
+ # print(clip_tensor.shape) # torch.Size([3, 2, 256, 256])
405
+ clips_list.append(clip_tensor)
406
+ clips = torch.stack(clips_list, dim=0).to(self.vjepa_encoder.patch_embed.proj.weight.device)
407
+ # print(clips.shape) # torch.Size([8, 3, 2, 256, 256])
408
+ B, C, T, H, W = clips.size()
409
+ # print(clips.shape) # torch.Size([8, 3, 2, 256, 256])
410
+ c = clips.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1).to(torch.bfloat16)
411
+ # print(c.shape) # torch.Size([16, 3, 2, 256, 256])
412
+
413
+ # 3. self.vjepa_encoder推理时使用b16
414
+ # 这是仿照self._cosmos25_future_image_loss中,当self.backbone作为编码器前向推理时使用bf16
415
+ crop_size = 256
416
+ tokens_per_frame = int((crop_size // self.vjepa_encoder.patch_size) ** 2)
417
+ # 仿照原始代码对self.backbone的处理,用bf16 autocast包裹vjepa_encoder
418
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
419
+ # print(type(self.vjepa_encoder)) # <class 'src.models.vision_transformer.VisionTransformer'>
420
+ h = self.vjepa_encoder(c)
421
+ # print(h.shape) # torch.Size([16, 256, 1408])
422
+ h = h.view(B, T, -1, h.size(-1)).flatten(1, 2)
423
+ # print(h.shape) # torch.Size([8, 512, 1408])
424
+ h = F.layer_norm(h, (h.size(-1),))
425
+ # print(h.shape) # torch.Size([8, 512, 1408])
426
+
427
+ # 4. 从h中分离出current_tokens和future_tokens
428
+ current_tokens = h[:, :tokens_per_frame]
429
+ future_tokens = h[:, tokens_per_frame:]
430
+ # print(current_tokens.shape) # torch.Size([8, 256, 1408])
431
+ # print(future_tokens.shape) # torch.Size([8, 256, 1408])
432
+
433
+ # 5. 从examples中取出current_state,参考predict_action()中的实现
434
+ current_state = [example["state"] for example in examples] if "state" in examples[0] else None
435
+ # print(len(current_state)) # 8
436
+ # print(current_state[0].shape) # (1, 64)
437
+ current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype))
438
+ # print(current_state.shape) # torch.Size([8, 1, 64])
439
+ current_state = self._align_state_dim(current_state)
440
+ # print(current_state.shape) # torch.Size([8, 1, 64])
441
+
442
+ # 6. self.vjepa_predictor推理时使用fp32
443
+ # 这是仿照CosmoPredict2Perceiver.forward()中,当self.action_model生成action前向推理时使用fp32
444
+ with torch.autocast("cuda", dtype=torch.float32):
445
+ # 通过projector映射维度
446
+ # print(current_state.shape) # torch.Size([8, 1, 64])
447
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
448
+ current_state_emb = self.state_projector(current_state)
449
+ target_emb_proj = self.action_projector(target_emb)
450
+ # print(current_state_emb.shape) # torch.Size([8, 1, 1024])
451
+ # print(target_emb_proj.shape) # torch.Size([8, 64, 1024])
452
+
453
+ # 7. 调用self.vjepa_predictor预测future_tokens
454
+ future_tokens_pred = self.vjepa_predictor.forward_for_WAM_VJEPA2AC(
455
+ x=current_tokens,
456
+ target_emb=target_emb_proj,
457
+ state_emb=current_state_emb,
458
+ )
459
+ # print(type(self.vjepa_predictor)) # <class 'src.models.ac_predictor.VisionTransformerPredictorAC'>
460
+ # print(current_tokens.shape) # torch.Size([8, 256, 1408])
461
+ # print(target_emb_proj.shape) # torch.Size([8, 64, 1024])
462
+ # print(current_state_emb.shape) # torch.Size([8, 1, 1024])
463
+ # print(future_tokens_pred.shape) # torch.Size([8, 256, 1408])
464
+
465
+ # 8. 计算future_latent_loss
466
+ future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens)
467
+ # print(future_latent_loss) # tensor(0.3229, device='cuda:0', grad_fn=<SmoothL1LossBackward0>)
468
+
469
+ # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-2')
470
+ return future_latent_loss
471
+
472
+ # 训练时
473
+ # 生成future_image、future_latent和action
474
+ # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight+future_latent_loss*loss_weight
475
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
476
+ # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1')
477
+ output = {}
478
+ future_image_cfg = self._future_image_training_cfg()
479
+ future_latent_cfg = self._future_latent_training_cfg()
480
+
481
+ # 1. action支路(必定执行)
482
+ perceiver_action_loss, target_emb = super().forward(examples=examples, **kwargs)
483
+ output["perceiver_action_loss"] = perceiver_action_loss.detach()
484
+ total_loss = perceiver_action_loss
485
+ # 仿照原始代码对action_model输出target_emb的处理,不强制转换精度
486
+ # target_emb在float32 autocast内产生,后续_vjepa2ac_future_latent_loss也在float32 autocast内使用
487
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
488
+
489
+ # 2. future_image支路(根据enabled配置决定是否执行)
490
+ # print(future_image_cfg.get("enabled")) # False
491
+ # print(future_image_cfg.get("loss_weight")) # 1.0
492
+ if self._as_bool(future_image_cfg.get("enabled")):
493
+ future_image_loss = self._cosmos25_future_image_loss(examples)
494
+ if future_image_loss is not None:
495
+ future_image_loss_weight = float(future_image_cfg.get("loss_weight"))
496
+ output["future_image_loss"] = future_image_loss.detach()
497
+ total_loss = total_loss + future_image_loss * future_image_loss_weight
498
+
499
+ # 3. future_latent支路(根据enabled配置决定是否执行)
500
+ # print(future_latent_cfg.get("enabled")) # True
501
+ # print(future_latent_cfg.get("loss_weight")) # 1.0
502
+ if self._as_bool(future_latent_cfg.get("enabled")):
503
+ future_latent_loss = self._vjepa2ac_future_latent_loss(examples, target_emb)
504
+ if future_latent_loss is not None:
505
+ future_latent_loss_weight = float(future_latent_cfg.get("loss_weight"))
506
+ output["future_latent_loss"] = future_latent_loss.detach()
507
+ total_loss = total_loss + future_latent_loss * future_latent_loss_weight
508
+
509
+ output["action_loss"] = total_loss
510
+
511
+ # print(output)
512
+ # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2')
513
+ return output
514
+
515
+ def _get_future_image_generation_cfg(self, kwargs: dict) -> dict:
516
+ cfg = dict(self.config.framework.get("future_image_generation", {}))
517
+ override = kwargs.get("future_image_generation", None)
518
+ if override:
519
+ cfg.update(dict(override))
520
+
521
+ if "decode_future_images" in kwargs:
522
+ cfg["enabled"] = kwargs["decode_future_images"]
523
+ if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs:
524
+ cfg["num_inference_steps"] = kwargs["num_ddim_steps"]
525
+
526
+ for key in (
527
+ "enabled",
528
+ "num_frames",
529
+ "num_inference_steps",
530
+ "guidance_scale",
531
+ "output_type",
532
+ "height",
533
+ "width",
534
+ "max_sequence_length",
535
+ "conditional_frame_timestep",
536
+ "num_latent_conditional_frames",
537
+ "conditioning_mode",
538
+ "max_samples",
539
+ "return_full_video",
540
+ "future_frame_index",
541
+ "negative_prompt",
542
+ "generator",
543
+ "latents",
544
+ "prompt_embeds",
545
+ "negative_prompt_embeds",
546
+ ):
547
+ if key in kwargs:
548
+ cfg[key] = kwargs[key]
549
+ return cfg
550
+
551
+ def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict:
552
+ mode = str(cfg.pop("conditioning_mode", "auto")).lower()
553
+ height = cfg.pop("height", getattr(self.backbone, "_height", 704))
554
+ width = cfg.pop("width", getattr(self.backbone, "_width", 1280))
555
+ heights = self._resolve_generation_size_values(batch_images, height, width)
556
+ generation_inputs = {
557
+ "prompt": instructions,
558
+ "height": heights[0],
559
+ "width": heights[1],
560
+ "num_frames": cfg.pop("num_frames", 93),
561
+ "num_inference_steps": cfg.pop("num_inference_steps", 36),
562
+ "guidance_scale": cfg.pop("guidance_scale", 7.0),
563
+ "output_type": cfg.pop("output_type", "pil"),
564
+ "return_dict": True,
565
+ "max_sequence_length": cfg.pop("max_sequence_length", 512),
566
+ "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1),
567
+ "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2),
568
+ }
569
+
570
+ negative_prompt = cfg.pop("negative_prompt", None)
571
+ if negative_prompt is not None:
572
+ generation_inputs["negative_prompt"] = negative_prompt
573
+
574
+ if mode == "image":
575
+ generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images]
576
+ elif mode == "video":
577
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
578
+ elif mode == "auto":
579
+ if any(len(self._as_sequence(images)) > 1 for images in batch_images):
580
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
581
+ else:
582
+ generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images]
583
+ else:
584
+ raise ValueError(
585
+ "future_image_generation.conditioning_mode must be one of "
586
+ f"'auto', 'image', or 'video', got {mode!r}."
587
+ )
588
+
589
+ passthrough_keys = (
590
+ "generator",
591
+ "latents",
592
+ "prompt_embeds",
593
+ "negative_prompt_embeds",
594
+ "num_videos_per_prompt",
595
+ "callback_on_step_end",
596
+ "callback_on_step_end_tensor_inputs",
597
+ )
598
+ for key in passthrough_keys:
599
+ if key in cfg and cfg[key] is not None:
600
+ generation_inputs[key] = cfg.pop(key)
601
+
602
+ generation_inputs.update({key: value for key, value in cfg.items() if value is not None})
603
+ return generation_inputs
604
+
605
+ @staticmethod
606
+ def _is_auto_size(value) -> bool:
607
+ return isinstance(value, str) and value.lower() == "auto"
608
+
609
+ @staticmethod
610
+ def _round_up_to_multiple(value: int, multiple: int) -> int:
611
+ return int(((max(1, value) + multiple - 1) // multiple) * multiple)
612
+
613
+ @staticmethod
614
+ def _image_size(image) -> tuple[int, int]:
615
+ size = getattr(image, "size", None)
616
+ if isinstance(size, (list, tuple)) and len(size) >= 2:
617
+ return int(size[0]), int(size[1])
618
+ if torch.is_tensor(image):
619
+ shape = tuple(image.shape)
620
+ if len(shape) >= 3 and shape[0] in (1, 3, 4):
621
+ return int(shape[-1]), int(shape[-2])
622
+ if len(shape) >= 2:
623
+ return int(shape[1]), int(shape[0])
624
+ array = np.asarray(image)
625
+ if array.ndim < 2:
626
+ raise ValueError(f"Cannot infer image size from shape {array.shape}")
627
+ return int(array.shape[1]), int(array.shape[0])
628
+
629
+ def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple:
630
+ if not self._is_auto_size(height) and not self._is_auto_size(width):
631
+ return int(height), int(width)
632
+
633
+ resolved_heights = []
634
+ resolved_widths = []
635
+ spatial_multiple = int(getattr(self.backbone, "vae_scale_factor_spatial", 16))
636
+ for images in batch_images:
637
+ image_sequence = self._as_sequence(images)
638
+ frame_sizes = [self._image_size(image) for image in image_sequence]
639
+ if not frame_sizes:
640
+ raise ValueError("Cannot infer auto generation size from empty image sequence.")
641
+
642
+ sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height)
643
+ if self._is_auto_size(width):
644
+ max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes)
645
+ sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple)
646
+ else:
647
+ sample_width = int(width)
648
+ resolved_heights.append(int(sample_height))
649
+ resolved_widths.append(int(sample_width))
650
+
651
+ height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0]
652
+ width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0]
653
+ return height_value, width_value
654
+
655
+ @staticmethod
656
+ def _extract_videos(generation_output):
657
+ if hasattr(generation_output, "frames"):
658
+ return generation_output.frames
659
+ if hasattr(generation_output, "videos"):
660
+ return generation_output.videos
661
+ if hasattr(generation_output, "images"):
662
+ return generation_output.images
663
+ if isinstance(generation_output, tuple):
664
+ return generation_output[0]
665
+ return generation_output
666
+
667
+ def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool):
668
+ videos = self._extract_videos(generation_output)
669
+ if return_full_video:
670
+ return videos
671
+
672
+ if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image):
673
+ return [videos[future_frame_index]]
674
+
675
+ future_images = []
676
+ for sample in videos:
677
+ if torch.is_tensor(sample):
678
+ if sample.ndim >= 4:
679
+ future_images.append(sample[future_frame_index])
680
+ else:
681
+ future_images.append(sample)
682
+ elif isinstance(sample, np.ndarray):
683
+ if sample.ndim >= 4:
684
+ future_images.append(sample[future_frame_index])
685
+ else:
686
+ future_images.append(sample)
687
+ elif isinstance(sample, (list, tuple)):
688
+ future_images.append(sample[future_frame_index])
689
+ else:
690
+ future_images.append(sample)
691
+ return future_images
692
+
693
+ @staticmethod
694
+ def _slice_generation_value(key: str, value, index: int, batch_size: int):
695
+ if value is None:
696
+ return None
697
+ if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
698
+ return value[index]
699
+ if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
700
+ return value[index]
701
+ if torch.is_tensor(value) and value.shape[0] == batch_size:
702
+ return value[index:index + 1]
703
+ if isinstance(value, np.ndarray) and value.shape[0] == batch_size:
704
+ return value[index:index + 1]
705
+ if isinstance(value, list) and len(value) == batch_size:
706
+ return [value[index]]
707
+ if isinstance(value, tuple) and len(value) == batch_size:
708
+ return (value[index],)
709
+ return value
710
+
711
+ # 推理时
712
+ # future_image支路,self.backbone.generate()
713
+ def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool):
714
+ # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1')
715
+ if max_samples is None or max_samples < 0:
716
+ sample_count = batch_size
717
+ else:
718
+ sample_count = min(batch_size, max(0, int(max_samples)))
719
+ # print(sample_count) # 1
720
+
721
+ # print(generation_inputs)
722
+ """
723
+ {
724
+ 'prompt': [
725
+ 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.',
726
+ 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.',
727
+ 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.',
728
+ 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.',
729
+ 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.',
730
+ 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.',
731
+ 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.',
732
+ 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.'
733
+ ],
734
+ 'height': 224,
735
+ 'width': 224,
736
+ 'num_frames': 93,
737
+ 'num_inference_steps': 20,
738
+ 'guidance_scale': 7.0,
739
+ 'output_type': 'pil',
740
+ 'return_dict': True,
741
+ 'max_sequence_length': 512,
742
+ 'conditional_frame_timestep': 0.1,
743
+ 'num_latent_conditional_frames': 2,
744
+ 'image': [
745
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487370>,
746
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74872B0>,
747
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487280>,
748
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74872E0>,
749
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74877F0>,
750
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487850>,
751
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487F70>,
752
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487580>
753
+ ]
754
+ }
755
+ """
756
+ pred_future_images = []
757
+ for sample_idx in range(sample_count):
758
+
759
+ # 1. CosmosPredict:构建输入
760
+ # print(sample_idx) # 0
761
+ single_inputs = {
762
+ key: self._slice_generation_value(key, value, sample_idx, batch_size)
763
+ for key, value in generation_inputs.items()
764
+ }
765
+ # print(single_inputs)
766
+ """
767
+ {
768
+ 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'],
769
+ 'height': 224,
770
+ 'width': 224,
771
+ 'num_frames': 93,
772
+ 'num_inference_steps': 20,
773
+ 'guidance_scale': 7.0,
774
+ 'output_type': 'pil',
775
+ 'return_dict': True,
776
+ 'max_sequence_length': 512,
777
+ 'conditional_frame_timestep': 0.1,
778
+ 'num_latent_conditional_frames': 2,
779
+ 'image': <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487370>
780
+ }
781
+ """
782
+
783
+ # 2. CosmosPredict:前向推理
784
+ generation_output = self.backbone.generate(**single_inputs)
785
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
786
+ # print(type(generation_output)) # <class 'diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput'>
787
+ # print(future_frame_index) # -1
788
+ # print(return_full_video) # False
789
+ sample_images = self._select_future_images(
790
+ generation_output,
791
+ future_frame_index=future_frame_index,
792
+ return_full_video=return_full_video,
793
+ )
794
+ # print(sample_images) # [<PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7423220>]
795
+ if isinstance(sample_images, (list, tuple)):
796
+ pred_future_images.extend(sample_images)
797
+ else:
798
+ pred_future_images.append(sample_images)
799
+ # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2')
800
+ return pred_future_images
801
+
802
+ # 推理时
803
+ # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action()
804
+ @torch.inference_mode()
805
+ def predict_action(self, examples: List[dict], **kwargs) -> dict:
806
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1')
807
+ if type(examples) is not list:
808
+ examples = [examples]
809
+
810
+ # 1. CosmosPredict:构建输入
811
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
812
+ instructions = [example["lang"] for example in examples]
813
+ # print(len(examples)) # 8
814
+
815
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
816
+ # print(train_obs_image_size) # None
817
+ if train_obs_image_size:
818
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
819
+
820
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
821
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
822
+ # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input'])
823
+ # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28])
824
+ # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1])
825
+ # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352])
826
+ # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28])
827
+ # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224])
828
+ # print(wm_inputs['_is_wm_input']) # True
829
+
830
+ # 2. CosmosPredict:前向推理
831
+ # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens
832
+ with torch.autocast("cuda", dtype=torch.bfloat16):
833
+ wm_outputs = self.backbone(
834
+ **wm_inputs,
835
+ output_hidden_states=True,
836
+ return_dict=True,
837
+ )
838
+ last_hidden = wm_outputs.hidden_states[-1]
839
+ # print(type(wm_outputs)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface.forward.<locals>._WMOutput'>
840
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
841
+
842
+ # 3. ActionHead:构建输入
843
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
844
+ state = (
845
+ torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
846
+ if state is not None
847
+ else None
848
+ )
849
+ # print(state.shape) # torch.Size([8, 1, 64])
850
+ state = self._align_state_dim(state)
851
+ # print(state.shape) # torch.Size([8, 1, 64])
852
+
853
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
854
+ embodiment_tag = (
855
+ torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
856
+ if embodiment_tag is not None
857
+ else None
858
+ )
859
+ # print(embodiment_tag.shape) # torch.Size([8])
860
+ if embodiment_tag is not None:
861
+ embodiment_tag = embodiment_tag.view(-1)
862
+ # print(embodiment_tag.shape) # torch.Size([8])
863
+
864
+ # 4. ActionHead:前向推理
865
+ with torch.autocast("cuda", dtype=torch.float32):
866
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
867
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
868
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
869
+ # print(state.shape) # torch.Size([8, 1, 64])
870
+ # print(embodiment_tag.shape) # torch.Size([8])
871
+ # print(pred_actions.shape) # torch.Size([8, 16, 32])
872
+ output = {"normalized_actions": pred_actions.detach().cpu().numpy()}
873
+
874
+ # # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要
875
+ # generation_cfg = self._get_future_image_generation_cfg(kwargs)
876
+ # is_enabled = generation_cfg.pop("enabled", True)
877
+ # # print(is_enabled) # True
878
+ # if not bool(is_enabled):
879
+ # # print('is_enabled is False')
880
+ # # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2')
881
+ # return output
882
+
883
+ # return_full_video = bool(generation_cfg.pop("return_full_video", False))
884
+ # future_frame_index = int(generation_cfg.pop("future_frame_index", -1))
885
+ # max_samples = int(generation_cfg.pop("max_samples", 1))
886
+ # generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg)
887
+ # output["pred_future_images"] = self._generate_future_images(
888
+ # generation_inputs,
889
+ # batch_size=len(examples),
890
+ # max_samples=max_samples,
891
+ # future_frame_index=future_frame_index,
892
+ # return_full_video=return_full_video,
893
+ # )
894
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2')
895
+ return output
starVLA/model/framework/WAM_VJEPA/CosmoPredict25Perceiver.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver Framework.
5
+
6
+ This keeps Predict2.5 separate from the existing Cosmos-Predict2 framework
7
+ while reusing the same Perceiver action-head training/inference logic.
8
+ """
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Optional
12
+
13
+ from starVLA.model.framework.base_framework import baseframework
14
+ from starVLA.model.framework.share_tools import merge_framework_config
15
+ from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model
16
+ from starVLA.model.modules.world_model import get_world_model
17
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
18
+
19
+ from starVLA.model.framework.WAM_VJEPA.CosmoPredict2Perceiver import CosmoPredict2_Perceiver
20
+
21
+
22
+ @dataclass
23
+ class CosmoPredict25PerceiverDefaultConfig:
24
+ """Cosmos-Predict2.5-Perceiver default parameters."""
25
+
26
+ name: str = "CosmoPredict25Perceiver"
27
+
28
+ world_model: dict = field(default_factory=lambda: {
29
+ "base_wm": "nvidia/Cosmos-Predict2.5-2B",
30
+ "revision": "diffusers/base/post-trained",
31
+ "extract_layers": [-1],
32
+ })
33
+
34
+ qwenvl: dict = field(default_factory=lambda: {
35
+ "base_vlm": "nvidia/Cosmos-Predict2.5-2B",
36
+ "vl_hidden_dim": 2048,
37
+ })
38
+
39
+ action_model: dict = field(default_factory=lambda: {
40
+ "action_model_type": "DiT-B",
41
+ "action_hidden_dim": 1024,
42
+ "hidden_size": 1024,
43
+ "add_pos_embed": True,
44
+ "max_seq_len": 1024,
45
+ "action_dim": 7,
46
+ "state_dim": 7,
47
+ "future_action_window_size": 7,
48
+ "action_horizon": 8,
49
+ "past_action_window_size": 0,
50
+ "repeated_diffusion_steps": 8,
51
+ "noise_beta_alpha": 1.5,
52
+ "noise_beta_beta": 1.0,
53
+ "noise_s": 0.999,
54
+ "num_timestep_buckets": 1000,
55
+ "num_inference_timesteps": 4,
56
+ "num_target_vision_tokens": 32,
57
+ "max_num_embodiments": 32,
58
+ "use_category_specific": False,
59
+ "diffusion_model_cfg": {
60
+ "cross_attention_dim": 2048,
61
+ "dropout": 0.2,
62
+ "final_dropout": True,
63
+ "interleave_self_attention": True,
64
+ "norm_type": "ada_norm",
65
+ "num_layers": 16,
66
+ "output_dim": 1024,
67
+ "positional_embeddings": None,
68
+ },
69
+ })
70
+
71
+ obs_image_size: Optional[list] = None
72
+
73
+
74
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25Perceiver")
75
+ class CosmoPredict25_Perceiver(CosmoPredict2_Perceiver):
76
+ """World-model-for-action framework using Cosmos-Predict2.5 + Perceiver."""
77
+
78
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
79
+ baseframework.__init__(self)
80
+ self.config = merge_framework_config(CosmoPredict25PerceiverDefaultConfig, config)
81
+
82
+ self.backbone = get_world_model(config=self.config)
83
+
84
+ wm_hidden = self.backbone.model.config.hidden_size
85
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
86
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
87
+
88
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
89
+
90
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
91
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
92
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverDINO.py ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver with DINOv3 future-latent prediction.
5
+
6
+ This framework keeps the existing Cosmos hidden-state -> Perceiver action
7
+ path, and additionally uses DINOv3 encoder + kaiming-initialized predictor
8
+ to compute future-latent loss during training.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import List, Optional
13
+
14
+ import numpy as np
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from PIL import Image
18
+ from torchvision.transforms import v2
19
+
20
+ from deployment.model_server.tools.image_tools import to_pil_preserve
21
+ from starVLA.model.framework.base_framework import baseframework
22
+ from starVLA.model.framework.share_tools import merge_framework_config
23
+ from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model
24
+ from starVLA.model.modules.world_model import get_world_model
25
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
26
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
27
+
28
+ from starVLA.model.framework.WAM_VJEPA.CosmoPredict25Perceiver import (
29
+ CosmoPredict25_Perceiver,
30
+ CosmoPredict25PerceiverDefaultConfig,
31
+ )
32
+
33
+
34
+
35
+ @dataclass
36
+ class CosmoPredict25PerceiverDINODefaultConfig(CosmoPredict25PerceiverDefaultConfig):
37
+ """Cosmos-Predict2.5-Perceiver + DINOv3 defaults."""
38
+
39
+ name: str = "CosmoPredict25PerceiverFutureImage"
40
+
41
+ future_image_generation: dict = field(default_factory=lambda: {
42
+ "enabled": True,
43
+ "num_frames": 93,
44
+ "num_inference_steps": 36,
45
+ "guidance_scale": 7.0,
46
+ "output_type": "pil",
47
+ "height": 704,
48
+ "width": 1280,
49
+ "max_sequence_length": 512,
50
+ "conditional_frame_timestep": 0.1,
51
+ "num_latent_conditional_frames": 2,
52
+ "conditioning_mode": "auto",
53
+ "max_samples": 1,
54
+ "return_full_video": False,
55
+ "future_frame_index": -1,
56
+ "negative_prompt": None,
57
+ })
58
+
59
+ future_image_training: dict = field(default_factory=lambda: {
60
+ "enabled": True,
61
+ "loss_weight": 1.0,
62
+ "train_time_distribution": "logitnormal",
63
+ "shift": 5.0,
64
+ })
65
+
66
+
67
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverDINO")
68
+ class CosmoPredict25_Perceiver_DINO(CosmoPredict25_Perceiver):
69
+
70
+ # DINOv3 ViT-H+/16 常量
71
+ DINO_EMBED_DIM = 1280
72
+ DINO_PATCH_SIZE = 16
73
+ DINO_IMG_SIZE = 224
74
+ DINO_PREDICTOR_EMBED_DIM = 1024
75
+
76
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
77
+ baseframework.__init__(self)
78
+ self.config = merge_framework_config(CosmoPredict25PerceiverDINODefaultConfig, config)
79
+
80
+ # 1. 加载预训练的CosmoPredictr2.5类作为self.backbone
81
+ self.backbone = get_world_model(config=self.config)
82
+
83
+ wm_hidden = self.backbone.model.config.hidden_size
84
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
85
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
86
+
87
+ # 2. 初始化FlowmatchingActionHead作为self.action_model
88
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
89
+
90
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
91
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
92
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
93
+ self.state_dim = self.config.framework.action_model.get("state_dim", None)
94
+
95
+ # 3. 加载DINOv3编码器
96
+ dino_cfg = self.config.framework.get("dinov3")
97
+ dino_repo_dir = dino_cfg.get("repo_dir")
98
+ dino_pretrained = dino_cfg.get("pretrained")
99
+ # 直接从dinov3代码构建模型,绕过torch.hub.load()。
100
+ # 原因:torch.hub.load()内部dinov3_vith16plus会强制从远程URL下载.pth权重,
101
+ # 而本地权重是safetensors格式且网络不可达,导致URLError。
102
+ import sys as _sys
103
+ import os as _os
104
+ # 将dinov3 repo根目录加入sys.path,使 `from dinov3.hub.backbones import ...` 可用
105
+ # 注意:dinov3仓库结构为 repo_root/dinov3/hub/backbones.py,
106
+ # 需要将repo_root加入sys.path,Python才能找到内部的dinov3包(有__init__.py)。
107
+ # 若加入repo_root的父目录,Python会找到没有__init__.py的repo_root目录作为命名空间包,导致dinov3.hub找不到。
108
+ _dino_repo_root = _os.path.abspath(dino_repo_dir)
109
+ if _dino_repo_root not in _sys.path:
110
+ _sys.path.insert(0, _dino_repo_root)
111
+ # mock torchmetrics,dinov3的hubconf.py顶层import链依赖它
112
+ if "torchmetrics" not in _sys.modules:
113
+ import types as _types
114
+ _tm = _types.ModuleType("torchmetrics")
115
+ _tm.Metric = type("Metric", (), {})
116
+ _sys.modules["torchmetrics"] = _tm
117
+ _sys.modules["torchmetrics.utilities"] = _types.ModuleType("torchmetrics.utilities")
118
+ _sys.modules["torchmetrics.utilities.distributed"] = _types.ModuleType("torchmetrics.utilities.distributed")
119
+ _sys.modules["torchmetrics.utilities.distributed.gather"] = type("gather", (), {})
120
+ _sys.modules["torchmetrics.utilities.prints"] = _types.ModuleType("torchmetrics.utilities.prints")
121
+ from dinov3.hub.backbones import dinov3_vith16plus as _dinov3_vith16plus
122
+ # pretrained=False:只构建模型结构,不下载权重
123
+ self.dino_encoder = _dinov3_vith16plus(pretrained=False)
124
+ # 手动加载本地safetensors权重
125
+ _weight_file = _os.path.join(dino_pretrained, "model.safetensors")
126
+ if not _os.path.isfile(_weight_file):
127
+ raise FileNotFoundError(f"DINOv3 weight file not found: {_weight_file}")
128
+ from safetensors.torch import load_file as _load_safetensors
129
+ _state_dict = _load_safetensors(_weight_file)
130
+ self.dino_encoder.load_state_dict(_state_dict, strict=False)
131
+ self.dino_encoder = self.dino_encoder.to(torch.bfloat16).cuda()
132
+ # 冻结dino_encoder全部参数
133
+ for p in self.dino_encoder.parameters():
134
+ p.requires_grad = False
135
+
136
+ # 4. 初始化DINO Predictor(同结构kaiming随机初始化)
137
+ # 延迟导入VisionTransformerPredictorAC,避免模块级导入时因src不在sys.path而报错
138
+ # (VJEPA2AC版本通过torch.hub.load触发导入,此处仿照其思路在__init__内导入)
139
+ from starVLA.facebookresearch_vjepa2_main.src.models.ac_predictor import VisionTransformerPredictorAC
140
+ # num_frames=4, tubelet_size=2 → grid_depth=2 → attn_mask足够大
141
+ # forward_for_WAM_VJEPA2AC中实际序列长度=cond_tokens(65)+196=261,
142
+ # attn_mask大小=grid_depth*(add_tokens+H*W)=2*(2+196)=396>261 ✓
143
+ # 注意:若num_frames太小(如默认1),grid_depth=0会导致attn_mask=[0,0]崩溃
144
+ self.dino_predictor = VisionTransformerPredictorAC(
145
+ img_size=self.DINO_IMG_SIZE,
146
+ patch_size=self.DINO_PATCH_SIZE,
147
+ in_chans=3,
148
+ num_frames=4,
149
+ tubelet_size=2,
150
+ embed_dim=self.DINO_EMBED_DIM,
151
+ predictor_embed_dim=self.DINO_PREDICTOR_EMBED_DIM,
152
+ depth=24,
153
+ num_heads=16,
154
+ mlp_ratio=4.0,
155
+ qkv_bias=True,
156
+ action_embed_dim=self.state_dim,
157
+ )
158
+ # kaiming随机初始化
159
+ def _kaiming_init(m):
160
+ if isinstance(m, torch.nn.Linear):
161
+ torch.nn.init.kaiming_normal_(m.weight)
162
+ if m.bias is not None:
163
+ torch.nn.init.zeros_(m.bias)
164
+ self.dino_predictor.apply(_kaiming_init)
165
+ self.dino_predictor = self.dino_predictor.to(torch.bfloat16).cuda()
166
+
167
+ # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用,
168
+ # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配
169
+ # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None,
170
+ # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重
171
+ for p in self.dino_predictor.action_encoder.parameters():
172
+ p.requires_grad = False
173
+ for p in self.dino_predictor.state_encoder.parameters():
174
+ p.requires_grad = False
175
+ for p in self.dino_predictor.extrinsics_encoder.parameters():
176
+ p.requires_grad = False
177
+
178
+ for name, p in self.dino_encoder.named_parameters():
179
+ assert p.dtype == torch.bfloat16, f"dino_encoder.{name} dtype={p.dtype}, expected bfloat16"
180
+ for name, p in self.dino_predictor.named_parameters():
181
+ assert p.dtype == torch.bfloat16, f"dino_predictor.{name} dtype={p.dtype}, expected bfloat16"
182
+
183
+ # 初始化DINOv3的图像预处理transform(ImageNet标准)
184
+ self._dino_transform = v2.Compose([
185
+ v2.ToImage(),
186
+ v2.Resize((self.DINO_IMG_SIZE, self.DINO_IMG_SIZE), antialias=True),
187
+ v2.ToDtype(torch.float32, scale=True),
188
+ v2.Normalize(
189
+ mean=(0.485, 0.456, 0.406),
190
+ std=(0.229, 0.224, 0.225),
191
+ ),
192
+ ])
193
+
194
+ self.state_projector = torch.nn.Linear(
195
+ self.state_dim,
196
+ self.DINO_PREDICTOR_EMBED_DIM,
197
+ bias=True
198
+ ).to(torch.bfloat16)
199
+ self.action_projector = torch.nn.Linear(
200
+ self.action_model.model.config.output_dim,
201
+ self.DINO_PREDICTOR_EMBED_DIM,
202
+ bias=True
203
+ ).to(torch.bfloat16)
204
+
205
+ @staticmethod
206
+ def _as_sequence(images):
207
+ return list(images) if isinstance(images, (list, tuple)) else [images]
208
+
209
+ def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor:
210
+ if state is None or self.state_dim is None:
211
+ return state
212
+ target_dim = int(self.state_dim)
213
+ current_dim = state.shape[-1]
214
+ if current_dim == target_dim:
215
+ return state
216
+ if current_dim > target_dim:
217
+ return state[..., :target_dim]
218
+
219
+ pad_shape = (*state.shape[:-1], target_dim - current_dim)
220
+ padding = state.new_zeros(pad_shape)
221
+ return torch.cat([state, padding], dim=-1)
222
+
223
+ @staticmethod
224
+ def _as_bool(value) -> bool:
225
+ if isinstance(value, str):
226
+ return value.lower() in {"1", "true", "yes", "on"}
227
+ return bool(value)
228
+
229
+ def _future_image_training_cfg(self) -> dict:
230
+ return dict(self.config.framework.get("future_image_training", {}))
231
+
232
+ def _future_latent_training_cfg(self) -> dict:
233
+ return dict(self.config.framework.get("future_latent_training", {}))
234
+
235
+ def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor:
236
+ distribution = str(distribution).lower()
237
+ if distribution == "logitnormal":
238
+ return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32))
239
+ if distribution == "uniform":
240
+ return torch.rand(batch_size, device=device, dtype=torch.float32)
241
+ raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}")
242
+
243
+ @staticmethod
244
+ def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor:
245
+ return shift * time / (1.0 + (shift - 1.0) * time)
246
+
247
+ def _latent_frame_count(self, raw_frame_count: int) -> int:
248
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
249
+ return (int(raw_frame_count) - 1) // temporal_factor + 1
250
+
251
+ def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]:
252
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
253
+ raw_sequences = []
254
+ condition_counts = []
255
+ sample_counts = []
256
+
257
+ for images, future_image in zip(batch_images, future_images):
258
+ current_sequence = self._as_sequence(images)
259
+ future_sequence = self._as_sequence(future_image)
260
+ if not current_sequence or not future_sequence:
261
+ raise ValueError("future image training needs both current image and future_image.")
262
+
263
+ future_frame = future_sequence[0]
264
+ raw_sequence = current_sequence + [future_frame] * temporal_factor
265
+ raw_sequences.append(raw_sequence)
266
+
267
+ condition_count = self._latent_frame_count(len(current_sequence))
268
+ sample_count = self._latent_frame_count(len(raw_sequence))
269
+ condition_counts.append(condition_count)
270
+ sample_counts.append(sample_count)
271
+
272
+ return raw_sequences, condition_counts, sample_counts
273
+
274
+ # 训练时
275
+ # future_image支路,self.backbone.transformer()
276
+ def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
277
+ if "future_image" not in examples[0]:
278
+ return None
279
+ training_cfg = self._future_image_training_cfg()
280
+ if not self._as_bool(training_cfg.get("enabled", True)):
281
+ return None
282
+
283
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
284
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
285
+ instructions = [example["lang"] for example in examples]
286
+
287
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
288
+ if train_obs_image_size:
289
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
290
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
291
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
292
+ batch_images=batch_images,
293
+ future_images=future_images,
294
+ )
295
+
296
+ prompt_embeds = self.backbone._encode_text(instructions)
297
+ clean_latents, _, _ = self.backbone._encode_images(raw_sequences)
298
+ dtype = self.backbone.transformer.dtype
299
+ clean_latents = clean_latents.to(dtype)
300
+ batch_size, channels, num_latents, height, width = clean_latents.shape
301
+ device = clean_latents.device
302
+ condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width))
303
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
304
+ cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
305
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
306
+ condition_count = max(1, min(int(condition_count), num_latents))
307
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
308
+ condition_mask[batch_idx, :, :condition_count] = 1.0
309
+ cond_indicator[batch_idx, :, :condition_count] = 1.0
310
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
311
+
312
+ train_time = self._sample_train_times(
313
+ batch_size=batch_size,
314
+ device=device,
315
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
316
+ )
317
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
318
+ target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype)
319
+ noise = torch.randn_like(clean_latents)
320
+ noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time
321
+ hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents)
322
+
323
+ target_velocity = noise.float() - clean_latents.float()
324
+
325
+ cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1))
326
+ timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
327
+ timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep
328
+ timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep)
329
+
330
+ padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16))
331
+ padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16))
332
+ padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype)
333
+
334
+ if hasattr(self.backbone, "_intermediate_features"):
335
+ self.backbone._intermediate_features.clear()
336
+ with torch.autocast("cuda", dtype=torch.bfloat16):
337
+ pred = self.backbone.transformer(
338
+ hidden_states=hidden_states,
339
+ timestep=timestep,
340
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
341
+ condition_mask=condition_mask.to(dtype),
342
+ padding_mask=padding_mask,
343
+ return_dict=False,
344
+ )
345
+ pred = pred[0] if isinstance(pred, tuple) else pred
346
+ pred = pred.sample if hasattr(pred, "sample") else pred
347
+ if hasattr(self.backbone, "_intermediate_features"):
348
+ self.backbone._intermediate_features.clear()
349
+
350
+ loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width)
351
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
352
+ future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
353
+ return future_image_loss
354
+
355
+ # 训练时
356
+ # future_latent支路,self.dino_encoder + self.dino_predictor
357
+ def _dino_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]:
358
+ if "future_image" not in examples[0]:
359
+ return None
360
+
361
+ # 2. 从examples中取出当前图像和未来图像,并使用DINOv3的ImageNet标准transform做预处理
362
+ # to_pil_preserve可能返回PIL.Image或list[PIL.Image],需要统一取单帧
363
+ batch_current_images = [self._as_sequence(to_pil_preserve(example["image"]))[0] for example in examples]
364
+ batch_future_images = [self._as_sequence(to_pil_preserve(example["future_image"]))[0] for example in examples]
365
+
366
+ # DINOv3是2D图像编码器,需要分别处理当前图像和未来图像
367
+ current_tensors = torch.stack([
368
+ self._dino_transform(img) for img in batch_current_images
369
+ ]).to(self.dino_encoder.patch_embed.proj.weight.device)
370
+
371
+ future_tensors = torch.stack([
372
+ self._dino_transform(img) for img in batch_future_images
373
+ ]).to(self.dino_encoder.patch_embed.proj.weight.device)
374
+
375
+ # 3. DINOv3编码,分别获取当前图像和未来图像的patch tokens
376
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
377
+ current_tokens = self.dino_encoder.forward_features(current_tensors)["x_norm_patchtokens"]
378
+ future_tokens = self.dino_encoder.forward_features(future_tensors)["x_norm_patchtokens"]
379
+ # current_tokens: [B, 196, 1280], future_tokens: [B, 196, 1280]
380
+
381
+ # 4. 从examples中取出current_state
382
+ current_state = [example["state"] for example in examples] if "state" in examples[0] else None
383
+ current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype))
384
+ current_state = self._align_state_dim(current_state)
385
+
386
+ # 5. dino_predictor推理时使用fp32
387
+ with torch.autocast("cuda", dtype=torch.float32):
388
+ # 通过projector映射维度
389
+ current_state_emb = self.state_projector(current_state)
390
+ target_emb_proj = self.action_projector(target_emb)
391
+
392
+ # 6. 调用dino_predictor预测future_tokens
393
+ future_tokens_pred = self.dino_predictor.forward_for_WAM_VJEPA2AC(
394
+ x=current_tokens,
395
+ target_emb=target_emb_proj,
396
+ state_emb=current_state_emb,
397
+ )
398
+
399
+ # 7. 计算future_latent_loss
400
+ future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens)
401
+
402
+ return future_latent_loss
403
+
404
+ # 训练时
405
+ # 生成future_image、future_latent和action
406
+ # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight+future_latent_loss*loss_weight
407
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
408
+ output = {}
409
+ future_image_cfg = self._future_image_training_cfg()
410
+ future_latent_cfg = self._future_latent_training_cfg()
411
+
412
+ # 1. action支路(必定执行)
413
+ perceiver_action_loss, target_emb = super().forward(examples=examples, **kwargs)
414
+ output["perceiver_action_loss"] = perceiver_action_loss.detach()
415
+ total_loss = perceiver_action_loss
416
+
417
+ # 2. future_image支路(根据enabled配置决定是否执行)
418
+ if self._as_bool(future_image_cfg.get("enabled")):
419
+ future_image_loss = self._cosmos25_future_image_loss(examples)
420
+ if future_image_loss is not None:
421
+ future_image_loss_weight = float(future_image_cfg.get("loss_weight"))
422
+ output["future_image_loss"] = future_image_loss.detach()
423
+ total_loss = total_loss + future_image_loss * future_image_loss_weight
424
+
425
+ # 3. future_latent支路(根据enabled配置决定是否执行)
426
+ if self._as_bool(future_latent_cfg.get("enabled")):
427
+ future_latent_loss = self._dino_future_latent_loss(examples, target_emb)
428
+ if future_latent_loss is not None:
429
+ future_latent_loss_weight = float(future_latent_cfg.get("loss_weight"))
430
+ output["future_latent_loss"] = future_latent_loss.detach()
431
+ total_loss = total_loss + future_latent_loss * future_latent_loss_weight
432
+
433
+ output["action_loss"] = total_loss
434
+
435
+ return output
436
+
437
+ def _get_future_image_generation_cfg(self, kwargs: dict) -> dict:
438
+ cfg = dict(self.config.framework.get("future_image_generation", {}))
439
+ override = kwargs.get("future_image_generation", None)
440
+ if override:
441
+ cfg.update(dict(override))
442
+
443
+ if "decode_future_images" in kwargs:
444
+ cfg["enabled"] = kwargs["decode_future_images"]
445
+ if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs:
446
+ cfg["num_inference_steps"] = kwargs["num_ddim_steps"]
447
+
448
+ for key in (
449
+ "enabled",
450
+ "num_frames",
451
+ "num_inference_steps",
452
+ "guidance_scale",
453
+ "output_type",
454
+ "height",
455
+ "width",
456
+ "max_sequence_length",
457
+ "conditional_frame_timestep",
458
+ "num_latent_conditional_frames",
459
+ "conditioning_mode",
460
+ "max_samples",
461
+ "return_full_video",
462
+ "future_frame_index",
463
+ "negative_prompt",
464
+ "generator",
465
+ "latents",
466
+ "prompt_embeds",
467
+ "negative_prompt_embeds",
468
+ ):
469
+ if key in kwargs:
470
+ cfg[key] = kwargs[key]
471
+ return cfg
472
+
473
+ def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict:
474
+ mode = str(cfg.pop("conditioning_mode", "auto")).lower()
475
+ height = cfg.pop("height", getattr(self.backbone, "_height", 704))
476
+ width = cfg.pop("width", getattr(self.backbone, "_width", 1280))
477
+ heights = self._resolve_generation_size_values(batch_images, height, width)
478
+ generation_inputs = {
479
+ "prompt": instructions,
480
+ "height": heights[0],
481
+ "width": heights[1],
482
+ "num_frames": cfg.pop("num_frames", 93),
483
+ "num_inference_steps": cfg.pop("num_inference_steps", 36),
484
+ "guidance_scale": cfg.pop("guidance_scale", 7.0),
485
+ "output_type": cfg.pop("output_type", "pil"),
486
+ "return_dict": True,
487
+ "max_sequence_length": cfg.pop("max_sequence_length", 512),
488
+ "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1),
489
+ "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2),
490
+ }
491
+
492
+ negative_prompt = cfg.pop("negative_prompt", None)
493
+ if negative_prompt is not None:
494
+ generation_inputs["negative_prompt"] = negative_prompt
495
+
496
+ if mode == "image":
497
+ generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images]
498
+ elif mode == "video":
499
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
500
+ elif mode == "auto":
501
+ if any(len(self._as_sequence(images)) > 1 for images in batch_images):
502
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
503
+ else:
504
+ generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images]
505
+ else:
506
+ raise ValueError(
507
+ "future_image_generation.conditioning_mode must be one of "
508
+ f"'auto', 'image', or 'video', got {mode!r}."
509
+ )
510
+
511
+ passthrough_keys = (
512
+ "generator",
513
+ "latents",
514
+ "prompt_embeds",
515
+ "negative_prompt_embeds",
516
+ "num_videos_per_prompt",
517
+ "callback_on_step_end",
518
+ "callback_on_step_end_tensor_inputs",
519
+ )
520
+ for key in passthrough_keys:
521
+ if key in cfg and cfg[key] is not None:
522
+ generation_inputs[key] = cfg.pop(key)
523
+
524
+ generation_inputs.update({key: value for key, value in cfg.items() if value is not None})
525
+ return generation_inputs
526
+
527
+ @staticmethod
528
+ def _is_auto_size(value) -> bool:
529
+ return isinstance(value, str) and value.lower() == "auto"
530
+
531
+ @staticmethod
532
+ def _round_up_to_multiple(value: int, multiple: int) -> int:
533
+ return int(((max(1, value) + multiple - 1) // multiple) * multiple)
534
+
535
+ @staticmethod
536
+ def _image_size(image) -> tuple[int, int]:
537
+ size = getattr(image, "size", None)
538
+ if isinstance(size, (list, tuple)) and len(size) >= 2:
539
+ return int(size[0]), int(size[1])
540
+ if torch.is_tensor(image):
541
+ shape = tuple(image.shape)
542
+ if len(shape) >= 3 and shape[0] in (1, 3, 4):
543
+ return int(shape[-1]), int(shape[-2])
544
+ if len(shape) >= 2:
545
+ return int(shape[1]), int(shape[0])
546
+ array = np.asarray(image)
547
+ if array.ndim < 2:
548
+ raise ValueError(f"Cannot infer image size from shape {array.shape}")
549
+ return int(array.shape[1]), int(array.shape[0])
550
+
551
+ def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple:
552
+ if not self._is_auto_size(height) and not self._is_auto_size(width):
553
+ return int(height), int(width)
554
+
555
+ resolved_heights = []
556
+ resolved_widths = []
557
+ spatial_multiple = int(getattr(self.backbone, "vae_scale_factor_spatial", 16))
558
+ for images in batch_images:
559
+ image_sequence = self._as_sequence(images)
560
+ frame_sizes = [self._image_size(image) for image in image_sequence]
561
+ if not frame_sizes:
562
+ raise ValueError("Cannot infer auto generation size from empty image sequence.")
563
+
564
+ sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height)
565
+ if self._is_auto_size(width):
566
+ max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes)
567
+ sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple)
568
+ else:
569
+ sample_width = int(width)
570
+ resolved_heights.append(int(sample_height))
571
+ resolved_widths.append(int(sample_width))
572
+
573
+ height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0]
574
+ width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0]
575
+ return height_value, width_value
576
+
577
+ @staticmethod
578
+ def _extract_videos(generation_output):
579
+ if hasattr(generation_output, "frames"):
580
+ return generation_output.frames
581
+ if hasattr(generation_output, "videos"):
582
+ return generation_output.videos
583
+ if hasattr(generation_output, "images"):
584
+ return generation_output.images
585
+ if isinstance(generation_output, tuple):
586
+ return generation_output[0]
587
+ return generation_output
588
+
589
+ def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool):
590
+ videos = self._extract_videos(generation_output)
591
+ if return_full_video:
592
+ return videos
593
+
594
+ if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image):
595
+ return [videos[future_frame_index]]
596
+
597
+ future_images = []
598
+ for sample in videos:
599
+ if torch.is_tensor(sample):
600
+ if sample.ndim >= 4:
601
+ future_images.append(sample[future_frame_index])
602
+ else:
603
+ future_images.append(sample)
604
+ elif isinstance(sample, np.ndarray):
605
+ if sample.ndim >= 4:
606
+ future_images.append(sample[future_frame_index])
607
+ else:
608
+ future_images.append(sample)
609
+ elif isinstance(sample, (list, tuple)):
610
+ future_images.append(sample[future_frame_index])
611
+ else:
612
+ future_images.append(sample)
613
+ return future_images
614
+
615
+ @staticmethod
616
+ def _slice_generation_value(key: str, value, index: int, batch_size: int):
617
+ if value is None:
618
+ return None
619
+ if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
620
+ return value[index]
621
+ if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
622
+ return value[index]
623
+ if torch.is_tensor(value) and value.shape[0] == batch_size:
624
+ return value[index:index + 1]
625
+ if isinstance(value, np.ndarray) and value.shape[0] == batch_size:
626
+ return value[index:index + 1]
627
+ if isinstance(value, list) and len(value) == batch_size:
628
+ return [value[index]]
629
+ if isinstance(value, tuple) and len(value) == batch_size:
630
+ return (value[index],)
631
+ return value
632
+
633
+ # 推理时
634
+ # future_image支路,self.backbone.generate()
635
+ def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool):
636
+ if max_samples is None or max_samples < 0:
637
+ sample_count = batch_size
638
+ else:
639
+ sample_count = min(batch_size, max(0, int(max_samples)))
640
+
641
+ pred_future_images = []
642
+ for sample_idx in range(sample_count):
643
+ single_inputs = {
644
+ key: self._slice_generation_value(key, value, sample_idx, batch_size)
645
+ for key, value in generation_inputs.items()
646
+ }
647
+
648
+ generation_output = self.backbone.generate(**single_inputs)
649
+ sample_images = self._select_future_images(
650
+ generation_output,
651
+ future_frame_index=future_frame_index,
652
+ return_full_video=return_full_video,
653
+ )
654
+ if isinstance(sample_images, (list, tuple)):
655
+ pred_future_images.extend(sample_images)
656
+ else:
657
+ pred_future_images.append(sample_images)
658
+ return pred_future_images
659
+
660
+ # 推理时
661
+ # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action()
662
+ @torch.inference_mode()
663
+ def predict_action(self, examples: List[dict], **kwargs) -> dict:
664
+ if type(examples) is not list:
665
+ examples = [examples]
666
+
667
+ # 1. CosmosPredict:构建输入
668
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
669
+ instructions = [example["lang"] for example in examples]
670
+
671
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
672
+ if train_obs_image_size:
673
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
674
+
675
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
676
+
677
+ # 2. CosmosPredict:前向推理
678
+ with torch.autocast("cuda", dtype=torch.bfloat16):
679
+ wm_outputs = self.backbone(
680
+ **wm_inputs,
681
+ output_hidden_states=True,
682
+ return_dict=True,
683
+ )
684
+ last_hidden = wm_outputs.hidden_states[-1]
685
+
686
+ # 3. ActionHead:构建输入
687
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
688
+ state = (
689
+ torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
690
+ if state is not None
691
+ else None
692
+ )
693
+ state = self._align_state_dim(state)
694
+
695
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
696
+ embodiment_tag = (
697
+ torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
698
+ if embodiment_tag is not None
699
+ else None
700
+ )
701
+ if embodiment_tag is not None:
702
+ embodiment_tag = embodiment_tag.view(-1)
703
+
704
+ # 4. ActionHead:前向推理
705
+ with torch.autocast("cuda", dtype=torch.float32):
706
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
707
+ output = {"normalized_actions": pred_actions.detach().cpu().numpy()}
708
+
709
+ return output
starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverVJEPA2AC.py ADDED
@@ -0,0 +1,893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver with future-image prediction.
5
+
6
+ This framework keeps the existing Cosmos hidden-state -> Perceiver action
7
+ path, and additionally runs the Cosmos2.5 generation/decoder path during
8
+ inference to return the image predicted after the action chunk horizon.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import List, Optional
13
+
14
+ import numpy as np
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from PIL import Image
18
+
19
+ from deployment.model_server.tools.image_tools import to_pil_preserve
20
+ from starVLA.model.framework.base_framework import baseframework
21
+ from starVLA.model.framework.share_tools import merge_framework_config
22
+ from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model
23
+ from starVLA.model.modules.world_model import get_world_model
24
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
25
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
26
+
27
+ from starVLA.model.framework.WAM_VJEPA.CosmoPredict25Perceiver import (
28
+ CosmoPredict25_Perceiver,
29
+ CosmoPredict25PerceiverDefaultConfig,
30
+ )
31
+
32
+
33
+ @dataclass
34
+ class CosmoPredict25PerceiverVJEPA2ACDefaultConfig(CosmoPredict25PerceiverDefaultConfig):
35
+ """Cosmos-Predict2.5-Perceiver + VJEPA2-AC defaults."""
36
+
37
+ name: str = "CosmoPredict25PerceiverFutureImage"
38
+
39
+ future_image_generation: dict = field(default_factory=lambda: {
40
+ "enabled": True,
41
+ "num_frames": 93,
42
+ "num_inference_steps": 36,
43
+ "guidance_scale": 7.0,
44
+ "output_type": "pil",
45
+ "height": 704,
46
+ "width": 1280,
47
+ "max_sequence_length": 512,
48
+ "conditional_frame_timestep": 0.1,
49
+ "num_latent_conditional_frames": 2,
50
+ "conditioning_mode": "auto",
51
+ "max_samples": 1,
52
+ "return_full_video": False,
53
+ "future_frame_index": -1,
54
+ "negative_prompt": None,
55
+ })
56
+
57
+ future_image_training: dict = field(default_factory=lambda: {
58
+ "enabled": True,
59
+ "loss_weight": 1.0,
60
+ "train_time_distribution": "logitnormal",
61
+ "shift": 5.0,
62
+ })
63
+
64
+
65
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverVJEPA2AC")
66
+ class CosmoPredict25_Perceiver_VJEPA2AC(CosmoPredict25_Perceiver):
67
+
68
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
69
+ # print('################# CosmoPredict25_Perceiver_VJEPA2AC-1')
70
+ baseframework.__init__(self)
71
+ self.config = merge_framework_config(CosmoPredict25PerceiverVJEPA2ACDefaultConfig, config)
72
+
73
+ # 1. 加载预训练的CosmoPredictr2.5类作为self.backbone
74
+ # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py
75
+ self.backbone = get_world_model(config=self.config)
76
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
77
+
78
+ wm_hidden = self.backbone.model.config.hidden_size
79
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
80
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
81
+ # print(wm_hidden) # 2048
82
+
83
+ # 2. 初始化FlowmatchingActionHead作为self.action_model
84
+ # WM4A/starVLA/model/modules/action_model/PerceiverHead.py
85
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
86
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
87
+
88
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
89
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
90
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
91
+ self.state_dim = self.config.framework.action_model.get("state_dim", None)
92
+ # print(self.future_action_window_size) # 15
93
+ # print(self.past_action_window_size) # 0
94
+ # print(self.chunk_len) # 16
95
+ # print(self.state_dim) # 64
96
+
97
+ # 3. 加载vjepa_encoder和vjepa_decoder,并将其权重固定为bf16
98
+ vjepa2_ac_cfg = self.config.framework.get("vjepa2_ac")
99
+ vjepa2_ac_repo_dir = vjepa2_ac_cfg.get("repo_dir")
100
+ vjepa2_ac_pretrained = vjepa2_ac_cfg.get("pretrained")
101
+ # print(vjepa2_ac_repo_dir) # /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main
102
+ # print(vjepa2_ac_pretrained) # /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt
103
+ self.vjepa_encoder, self.vjepa_predictor = torch.hub.load(
104
+ vjepa2_ac_repo_dir,
105
+ "vjepa2_ac_vit_giant",
106
+ source="local",
107
+ pretrained=vjepa2_ac_pretrained,
108
+ )
109
+ self.vjepa_encoder = self.vjepa_encoder.to(torch.bfloat16).cuda()
110
+ self.vjepa_predictor = self.vjepa_predictor.to(torch.bfloat16).cuda()
111
+ for p in self.vjepa_encoder.parameters():
112
+ p.requires_grad = False
113
+
114
+ # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用,
115
+ # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配
116
+ # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None,
117
+ # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重
118
+ for p in self.vjepa_predictor.action_encoder.parameters():
119
+ p.requires_grad = False
120
+ for p in self.vjepa_predictor.state_encoder.parameters():
121
+ p.requires_grad = False
122
+ for p in self.vjepa_predictor.extrinsics_encoder.parameters():
123
+ p.requires_grad = False
124
+
125
+ for name, p in self.vjepa_encoder.named_parameters():
126
+ assert p.dtype == torch.bfloat16, f"vjepa_encoder.{name} dtype={p.dtype}, expected bfloat16"
127
+ for name, p in self.vjepa_predictor.named_parameters():
128
+ assert p.dtype == torch.bfloat16, f"vjepa_predictor.{name} dtype={p.dtype}, expected bfloat16"
129
+
130
+ # print(type(self.vjepa_encoder)) # <class 'src.models.vision_transformer.VisionTransformer'>
131
+ # print(type(self.vjepa_predictor)) # <class 'src.models.ac_predictor.VisionTransformerPredictorAC'>
132
+
133
+ # 初始化VJEPA2-AC的图像预处理transform,与官方energy_landscape_example.ipynb保持一致
134
+ from starVLA.facebookresearch_vjepa2_main.app.vjepa_droid.transforms import make_transforms as vjepa2_make_transforms
135
+ self._vjepa2_transform = vjepa2_make_transforms(
136
+ random_horizontal_flip=False,
137
+ random_resize_aspect_ratio=(1., 1.),
138
+ random_resize_scale=(1., 1.),
139
+ reprob=0.,
140
+ auto_augment=False,
141
+ motion_shift=False,
142
+ crop_size=256,
143
+ )
144
+
145
+ self.state_projector = torch.nn.Linear(
146
+ self.state_dim,
147
+ self.vjepa_predictor.predictor_embed.out_features,
148
+ bias=True
149
+ ).to(torch.bfloat16)
150
+ # print(self.state_dim) # 64
151
+ # print(self.vjepa_predictor.predictor_embed.out_features) # 1024
152
+ self.action_projector = torch.nn.Linear(
153
+ self.action_model.model.config.output_dim,
154
+ self.vjepa_predictor.predictor_embed.out_features,
155
+ bias=True
156
+ ).to(torch.bfloat16)
157
+ # print(self.action_model.model.config.output_dim) # 1024
158
+ # print(self.vjepa_predictor.predictor_embed.out_features) # 1024
159
+ # print('################# CosmoPredict25_Perceiver_FutureImage-2')
160
+
161
+ @staticmethod
162
+ def _as_sequence(images):
163
+ return list(images) if isinstance(images, (list, tuple)) else [images]
164
+
165
+ def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor:
166
+ if state is None or self.state_dim is None:
167
+ return state
168
+ target_dim = int(self.state_dim)
169
+ current_dim = state.shape[-1]
170
+ if current_dim == target_dim:
171
+ return state
172
+ if current_dim > target_dim:
173
+ return state[..., :target_dim]
174
+
175
+ pad_shape = (*state.shape[:-1], target_dim - current_dim)
176
+ padding = state.new_zeros(pad_shape)
177
+ return torch.cat([state, padding], dim=-1)
178
+
179
+ @staticmethod
180
+ def _as_bool(value) -> bool:
181
+ if isinstance(value, str):
182
+ return value.lower() in {"1", "true", "yes", "on"}
183
+ return bool(value)
184
+
185
+ def _future_image_training_cfg(self) -> dict:
186
+ return dict(self.config.framework.get("future_image_training", {}))
187
+
188
+ def _future_latent_training_cfg(self) -> dict:
189
+ return dict(self.config.framework.get("future_latent_training", {}))
190
+
191
+ def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor:
192
+ distribution = str(distribution).lower()
193
+ if distribution == "logitnormal":
194
+ return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32))
195
+ if distribution == "uniform":
196
+ return torch.rand(batch_size, device=device, dtype=torch.float32)
197
+ raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}")
198
+
199
+ @staticmethod
200
+ def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor:
201
+ return shift * time / (1.0 + (shift - 1.0) * time)
202
+
203
+ def _latent_frame_count(self, raw_frame_count: int) -> int:
204
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
205
+ return (int(raw_frame_count) - 1) // temporal_factor + 1
206
+
207
+ def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]:
208
+ # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1')
209
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
210
+ raw_sequences = []
211
+ condition_counts = []
212
+ sample_counts = []
213
+ # print(temporal_factor) # 4
214
+ # print(len(batch_images)) # 8
215
+ # print(len(future_images)) # 8
216
+
217
+ for images, future_image in zip(batch_images, future_images):
218
+ current_sequence = self._as_sequence(images)
219
+ future_sequence = self._as_sequence(future_image)
220
+ # print(len(current_sequence)) # 1
221
+ # print(len(future_sequence)) # 1
222
+ if not current_sequence or not future_sequence:
223
+ raise ValueError("future image training needs both current image and future_image.")
224
+
225
+ future_frame = future_sequence[0]
226
+ # print(type(future_frame)) # <class 'PIL.Image.Image'>
227
+ raw_sequence = current_sequence + [future_frame] * temporal_factor
228
+ raw_sequences.append(raw_sequence)
229
+
230
+ condition_count = self._latent_frame_count(len(current_sequence))
231
+ sample_count = self._latent_frame_count(len(raw_sequence))
232
+ # print(condition_count) # 1
233
+ # print(sample_count) # 2
234
+ condition_counts.append(condition_count)
235
+ sample_counts.append(sample_count)
236
+
237
+ # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2')
238
+ return raw_sequences, condition_counts, sample_counts
239
+
240
+ # 训练时
241
+ # future_image支路,self.backbone.transformer()
242
+ def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
243
+ # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1')
244
+ if "future_image" not in examples[0]:
245
+ return None
246
+ training_cfg = self._future_image_training_cfg()
247
+ if not self._as_bool(training_cfg.get("enabled", True)):
248
+ return None
249
+
250
+ # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状
251
+ # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt;
252
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
253
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
254
+ instructions = [example["lang"] for example in examples]
255
+ # print(len(examples)) # 8
256
+ # print(type(batch_images[0])) # <class 'list'>
257
+ # print(type(future_images[0])) # <class 'list'>
258
+ # print(type(instructions[0])) # <class 'str'>
259
+
260
+ # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs]
261
+ # 而raw_sequences也是由8个这样的raw_sequence组成的列表,
262
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
263
+ # print(train_obs_image_size) # None
264
+ if train_obs_image_size:
265
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
266
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
267
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
268
+ batch_images=batch_images,
269
+ future_images=future_images,
270
+ )
271
+ # print(len(raw_sequences)) # 8
272
+ # print(len(raw_sequences[0])) # 5
273
+ # print(raw_sequences[0][0]) # <PIL.Image.Image image mode=RGB size=224x224 at 0x7FF6B20D60E0>
274
+ # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1]
275
+ # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2]
276
+
277
+ # 2. 调用CosmosPredict的文本和视觉tokenizer,
278
+ # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28),
279
+ # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents
280
+ prompt_embeds = self.backbone._encode_text(instructions)
281
+ clean_latents, _, _ = self.backbone._encode_images(raw_sequences)
282
+ dtype = self.backbone.transformer.dtype
283
+ clean_latents = clean_latents.to(dtype)
284
+ batch_size, channels, num_latents, height, width = clean_latents.shape
285
+ device = clean_latents.device
286
+ # print(prompt_embeds.shape) # torch.Size([8, 512, 100352])
287
+ # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28])
288
+ # print(dtype) # torch.bfloat16
289
+ condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width))
290
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
291
+ cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
292
+ # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28])
293
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
294
+ # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1])
295
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
296
+ condition_count = max(1, min(int(condition_count), num_latents))
297
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
298
+ condition_mask[batch_idx, :, :condition_count] = 1.0
299
+ cond_indicator[batch_idx, :, :condition_count] = 1.0
300
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
301
+
302
+ # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪
303
+ train_time = self._sample_train_times(
304
+ batch_size=batch_size,
305
+ device=device,
306
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
307
+ )
308
+ # print(train_time.shape) # torch.Size([8])
309
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
310
+ # print(flow_time.shape) # torch.Size([8])
311
+ target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype)
312
+ # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1])
313
+ # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28])
314
+ noise = torch.randn_like(clean_latents)
315
+ # print(noise.shape) # torch.Size([8, 16, 2, 28, 28])
316
+ # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1])
317
+ noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time
318
+ # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28])
319
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
320
+ hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents)
321
+ # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28])
322
+
323
+ # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity
324
+ target_velocity = noise.float() - clean_latents.float()
325
+ # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28])
326
+
327
+ # 5. 计算timestep和padding_mask
328
+ cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1))
329
+ # print(cond_timestep) # 0.1
330
+ timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
331
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
332
+ timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep
333
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
334
+ timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep)
335
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
336
+
337
+ padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16))
338
+ padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16))
339
+ padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype)
340
+ # print(padding_height) # 224
341
+ # print(padding_width) # 224
342
+ # print(padding_mask.shape) # torch.Size([1, 1, 224, 224])
343
+
344
+ # 7. CosmosPredict前向传播
345
+ # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入,
346
+ # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中,
347
+ # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息,
348
+ # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分,
349
+ if hasattr(self.backbone, "_intermediate_features"):
350
+ self.backbone._intermediate_features.clear()
351
+ with torch.autocast("cuda", dtype=torch.bfloat16):
352
+ pred = self.backbone.transformer(
353
+ hidden_states=hidden_states,
354
+ timestep=timestep,
355
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
356
+ condition_mask=condition_mask.to(dtype),
357
+ padding_mask=padding_mask,
358
+ return_dict=False,
359
+ )
360
+ pred = pred[0] if isinstance(pred, tuple) else pred
361
+ pred = pred.sample if hasattr(pred, "sample") else pred
362
+ if hasattr(self.backbone, "_intermediate_features"):
363
+ self.backbone._intermediate_features.clear()
364
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
365
+ # print(pred.shape) # torch.Size([8, 16, 2, 28, 28])
366
+
367
+ # 8. 计算future-image-loss
368
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
369
+ loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width)
370
+ # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28])
371
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
372
+ # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28])
373
+ future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
374
+ # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=<DivBackward0>)
375
+ # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2')
376
+ return future_image_loss
377
+
378
+ # 训练时
379
+ # future_latent支路,self.vjepa_encoder + self.vjepa_predictor
380
+ def _vjepa2ac_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]:
381
+ # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-1')
382
+ if "future_image" not in examples[0]:
383
+ return None
384
+
385
+ # 2. 从examples中取出当前图像和未来图像,并使用VJEPA2-AC官方的transform对图像做预处理
386
+ batch_current_images = [to_pil_preserve(example["image"]) for example in examples]
387
+ batch_future_images = [to_pil_preserve(example["future_image"]) for example in examples]
388
+ # print(len(examples)) # 8
389
+ clips_list = []
390
+ for current_images, future_images in zip(batch_current_images, batch_future_images):
391
+ current_seq = self._as_sequence(current_images)
392
+ future_seq = self._as_sequence(future_images)
393
+ # print(len(current_seq)) # 1
394
+ # print(len(future_seq)) # 1
395
+ current_np = np.array(current_seq[0])
396
+ future_np = np.array(future_seq[0])
397
+ # print(current_np.shape) # (224, 224, 3)
398
+ # print(future_np.shape) # (224, 224, 3)
399
+ clip_np = np.stack([current_np, future_np], axis=0)
400
+ # print(clip_np.shape) # (2, 224, 224, 3)
401
+ clip_tensor = self._vjepa2_transform(clip_np)
402
+ # print(clip_tensor.shape) # torch.Size([3, 2, 256, 256])
403
+ clips_list.append(clip_tensor)
404
+ clips = torch.stack(clips_list, dim=0).to(self.vjepa_encoder.patch_embed.proj.weight.device)
405
+ # print(clips.shape) # torch.Size([8, 3, 2, 256, 256])
406
+ B, C, T, H, W = clips.size()
407
+ # print(clips.shape) # torch.Size([8, 3, 2, 256, 256])
408
+ c = clips.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1).to(torch.bfloat16)
409
+ # print(c.shape) # torch.Size([16, 3, 2, 256, 256])
410
+
411
+ # 3. self.vjepa_encoder推理时使用b16
412
+ # 这是仿照self._cosmos25_future_image_loss中,当self.backbone作为编码器前向推理时使用bf16
413
+ crop_size = 256
414
+ tokens_per_frame = int((crop_size // self.vjepa_encoder.patch_size) ** 2)
415
+ # 仿照原始代码对self.backbone的处理,用bf16 autocast包裹vjepa_encoder
416
+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
417
+ # print(type(self.vjepa_encoder)) # <class 'src.models.vision_transformer.VisionTransformer'>
418
+ h = self.vjepa_encoder(c)
419
+ # print(h.shape) # torch.Size([16, 256, 1408])
420
+ h = h.view(B, T, -1, h.size(-1)).flatten(1, 2)
421
+ # print(h.shape) # torch.Size([8, 512, 1408])
422
+ h = F.layer_norm(h, (h.size(-1),))
423
+ # print(h.shape) # torch.Size([8, 512, 1408])
424
+
425
+ # 4. 从h中分离出current_tokens和future_tokens
426
+ current_tokens = h[:, :tokens_per_frame]
427
+ future_tokens = h[:, tokens_per_frame:]
428
+ # print(current_tokens.shape) # torch.Size([8, 256, 1408])
429
+ # print(future_tokens.shape) # torch.Size([8, 256, 1408])
430
+
431
+ # 5. 从examples中取出current_state,参考predict_action()中的实现
432
+ current_state = [example["state"] for example in examples] if "state" in examples[0] else None
433
+ # print(len(current_state)) # 8
434
+ # print(current_state[0].shape) # (1, 64)
435
+ current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype))
436
+ # print(current_state.shape) # torch.Size([8, 1, 64])
437
+ current_state = self._align_state_dim(current_state)
438
+ # print(current_state.shape) # torch.Size([8, 1, 64])
439
+
440
+ # 6. self.vjepa_predictor推理时使用fp32
441
+ # 这是仿照CosmoPredict2Perceiver.forward()中,��self.action_model生成action前向推理时使用fp32
442
+ with torch.autocast("cuda", dtype=torch.float32):
443
+ # 通过projector映射维度
444
+ # print(current_state.shape) # torch.Size([8, 1, 64])
445
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
446
+ current_state_emb = self.state_projector(current_state)
447
+ target_emb_proj = self.action_projector(target_emb)
448
+ # print(current_state_emb.shape) # torch.Size([8, 1, 1024])
449
+ # print(target_emb_proj.shape) # torch.Size([8, 64, 1024])
450
+
451
+ # 7. 调用self.vjepa_predictor预测future_tokens
452
+ future_tokens_pred = self.vjepa_predictor.forward_for_WAM_VJEPA2AC(
453
+ x=current_tokens,
454
+ target_emb=target_emb_proj,
455
+ state_emb=current_state_emb,
456
+ )
457
+ # print(type(self.vjepa_predictor)) # <class 'src.models.ac_predictor.VisionTransformerPredictorAC'>
458
+ # print(current_tokens.shape) # torch.Size([8, 256, 1408])
459
+ # print(target_emb_proj.shape) # torch.Size([8, 64, 1024])
460
+ # print(current_state_emb.shape) # torch.Size([8, 1, 1024])
461
+ # print(future_tokens_pred.shape) # torch.Size([8, 256, 1408])
462
+
463
+ # 8. 计算future_latent_loss
464
+ future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens)
465
+ # print(future_latent_loss) # tensor(0.3229, device='cuda:0', grad_fn=<SmoothL1LossBackward0>)
466
+
467
+ # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-2')
468
+ return future_latent_loss
469
+
470
+ # 训练时
471
+ # 生成future_image、future_latent和action
472
+ # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight+future_latent_loss*loss_weight
473
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
474
+ # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1')
475
+ output = {}
476
+ future_image_cfg = self._future_image_training_cfg()
477
+ future_latent_cfg = self._future_latent_training_cfg()
478
+
479
+ # 1. action支路(必定执行)
480
+ perceiver_action_loss, target_emb = super().forward(examples=examples, **kwargs)
481
+ output["perceiver_action_loss"] = perceiver_action_loss.detach()
482
+ total_loss = perceiver_action_loss
483
+ # 仿照原始代码对action_model输出target_emb的处理,不强制转换精度
484
+ # target_emb在float32 autocast内产生,后续_vjepa2ac_future_latent_loss也在float32 autocast内使用
485
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
486
+
487
+ # 2. future_image支路(根据enabled配置决定是否执行)
488
+ # print(future_image_cfg.get("enabled")) # False
489
+ # print(future_image_cfg.get("loss_weight")) # 1.0
490
+ if self._as_bool(future_image_cfg.get("enabled")):
491
+ future_image_loss = self._cosmos25_future_image_loss(examples)
492
+ if future_image_loss is not None:
493
+ future_image_loss_weight = float(future_image_cfg.get("loss_weight"))
494
+ output["future_image_loss"] = future_image_loss.detach()
495
+ total_loss = total_loss + future_image_loss * future_image_loss_weight
496
+
497
+ # 3. future_latent支路(根据enabled配置决定是否执行)
498
+ # print(future_latent_cfg.get("enabled")) # True
499
+ # print(future_latent_cfg.get("loss_weight")) # 1.0
500
+ if self._as_bool(future_latent_cfg.get("enabled")):
501
+ future_latent_loss = self._vjepa2ac_future_latent_loss(examples, target_emb)
502
+ if future_latent_loss is not None:
503
+ future_latent_loss_weight = float(future_latent_cfg.get("loss_weight"))
504
+ output["future_latent_loss"] = future_latent_loss.detach()
505
+ total_loss = total_loss + future_latent_loss * future_latent_loss_weight
506
+
507
+ output["action_loss"] = total_loss
508
+
509
+ # print(output)
510
+ # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2')
511
+ return output
512
+
513
+ def _get_future_image_generation_cfg(self, kwargs: dict) -> dict:
514
+ cfg = dict(self.config.framework.get("future_image_generation", {}))
515
+ override = kwargs.get("future_image_generation", None)
516
+ if override:
517
+ cfg.update(dict(override))
518
+
519
+ if "decode_future_images" in kwargs:
520
+ cfg["enabled"] = kwargs["decode_future_images"]
521
+ if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs:
522
+ cfg["num_inference_steps"] = kwargs["num_ddim_steps"]
523
+
524
+ for key in (
525
+ "enabled",
526
+ "num_frames",
527
+ "num_inference_steps",
528
+ "guidance_scale",
529
+ "output_type",
530
+ "height",
531
+ "width",
532
+ "max_sequence_length",
533
+ "conditional_frame_timestep",
534
+ "num_latent_conditional_frames",
535
+ "conditioning_mode",
536
+ "max_samples",
537
+ "return_full_video",
538
+ "future_frame_index",
539
+ "negative_prompt",
540
+ "generator",
541
+ "latents",
542
+ "prompt_embeds",
543
+ "negative_prompt_embeds",
544
+ ):
545
+ if key in kwargs:
546
+ cfg[key] = kwargs[key]
547
+ return cfg
548
+
549
+ def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict:
550
+ mode = str(cfg.pop("conditioning_mode", "auto")).lower()
551
+ height = cfg.pop("height", getattr(self.backbone, "_height", 704))
552
+ width = cfg.pop("width", getattr(self.backbone, "_width", 1280))
553
+ heights = self._resolve_generation_size_values(batch_images, height, width)
554
+ generation_inputs = {
555
+ "prompt": instructions,
556
+ "height": heights[0],
557
+ "width": heights[1],
558
+ "num_frames": cfg.pop("num_frames", 93),
559
+ "num_inference_steps": cfg.pop("num_inference_steps", 36),
560
+ "guidance_scale": cfg.pop("guidance_scale", 7.0),
561
+ "output_type": cfg.pop("output_type", "pil"),
562
+ "return_dict": True,
563
+ "max_sequence_length": cfg.pop("max_sequence_length", 512),
564
+ "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1),
565
+ "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2),
566
+ }
567
+
568
+ negative_prompt = cfg.pop("negative_prompt", None)
569
+ if negative_prompt is not None:
570
+ generation_inputs["negative_prompt"] = negative_prompt
571
+
572
+ if mode == "image":
573
+ generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images]
574
+ elif mode == "video":
575
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
576
+ elif mode == "auto":
577
+ if any(len(self._as_sequence(images)) > 1 for images in batch_images):
578
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
579
+ else:
580
+ generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images]
581
+ else:
582
+ raise ValueError(
583
+ "future_image_generation.conditioning_mode must be one of "
584
+ f"'auto', 'image', or 'video', got {mode!r}."
585
+ )
586
+
587
+ passthrough_keys = (
588
+ "generator",
589
+ "latents",
590
+ "prompt_embeds",
591
+ "negative_prompt_embeds",
592
+ "num_videos_per_prompt",
593
+ "callback_on_step_end",
594
+ "callback_on_step_end_tensor_inputs",
595
+ )
596
+ for key in passthrough_keys:
597
+ if key in cfg and cfg[key] is not None:
598
+ generation_inputs[key] = cfg.pop(key)
599
+
600
+ generation_inputs.update({key: value for key, value in cfg.items() if value is not None})
601
+ return generation_inputs
602
+
603
+ @staticmethod
604
+ def _is_auto_size(value) -> bool:
605
+ return isinstance(value, str) and value.lower() == "auto"
606
+
607
+ @staticmethod
608
+ def _round_up_to_multiple(value: int, multiple: int) -> int:
609
+ return int(((max(1, value) + multiple - 1) // multiple) * multiple)
610
+
611
+ @staticmethod
612
+ def _image_size(image) -> tuple[int, int]:
613
+ size = getattr(image, "size", None)
614
+ if isinstance(size, (list, tuple)) and len(size) >= 2:
615
+ return int(size[0]), int(size[1])
616
+ if torch.is_tensor(image):
617
+ shape = tuple(image.shape)
618
+ if len(shape) >= 3 and shape[0] in (1, 3, 4):
619
+ return int(shape[-1]), int(shape[-2])
620
+ if len(shape) >= 2:
621
+ return int(shape[1]), int(shape[0])
622
+ array = np.asarray(image)
623
+ if array.ndim < 2:
624
+ raise ValueError(f"Cannot infer image size from shape {array.shape}")
625
+ return int(array.shape[1]), int(array.shape[0])
626
+
627
+ def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple:
628
+ if not self._is_auto_size(height) and not self._is_auto_size(width):
629
+ return int(height), int(width)
630
+
631
+ resolved_heights = []
632
+ resolved_widths = []
633
+ spatial_multiple = int(getattr(self.backbone, "vae_scale_factor_spatial", 16))
634
+ for images in batch_images:
635
+ image_sequence = self._as_sequence(images)
636
+ frame_sizes = [self._image_size(image) for image in image_sequence]
637
+ if not frame_sizes:
638
+ raise ValueError("Cannot infer auto generation size from empty image sequence.")
639
+
640
+ sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height)
641
+ if self._is_auto_size(width):
642
+ max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes)
643
+ sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple)
644
+ else:
645
+ sample_width = int(width)
646
+ resolved_heights.append(int(sample_height))
647
+ resolved_widths.append(int(sample_width))
648
+
649
+ height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0]
650
+ width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0]
651
+ return height_value, width_value
652
+
653
+ @staticmethod
654
+ def _extract_videos(generation_output):
655
+ if hasattr(generation_output, "frames"):
656
+ return generation_output.frames
657
+ if hasattr(generation_output, "videos"):
658
+ return generation_output.videos
659
+ if hasattr(generation_output, "images"):
660
+ return generation_output.images
661
+ if isinstance(generation_output, tuple):
662
+ return generation_output[0]
663
+ return generation_output
664
+
665
+ def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool):
666
+ videos = self._extract_videos(generation_output)
667
+ if return_full_video:
668
+ return videos
669
+
670
+ if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image):
671
+ return [videos[future_frame_index]]
672
+
673
+ future_images = []
674
+ for sample in videos:
675
+ if torch.is_tensor(sample):
676
+ if sample.ndim >= 4:
677
+ future_images.append(sample[future_frame_index])
678
+ else:
679
+ future_images.append(sample)
680
+ elif isinstance(sample, np.ndarray):
681
+ if sample.ndim >= 4:
682
+ future_images.append(sample[future_frame_index])
683
+ else:
684
+ future_images.append(sample)
685
+ elif isinstance(sample, (list, tuple)):
686
+ future_images.append(sample[future_frame_index])
687
+ else:
688
+ future_images.append(sample)
689
+ return future_images
690
+
691
+ @staticmethod
692
+ def _slice_generation_value(key: str, value, index: int, batch_size: int):
693
+ if value is None:
694
+ return None
695
+ if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
696
+ return value[index]
697
+ if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
698
+ return value[index]
699
+ if torch.is_tensor(value) and value.shape[0] == batch_size:
700
+ return value[index:index + 1]
701
+ if isinstance(value, np.ndarray) and value.shape[0] == batch_size:
702
+ return value[index:index + 1]
703
+ if isinstance(value, list) and len(value) == batch_size:
704
+ return [value[index]]
705
+ if isinstance(value, tuple) and len(value) == batch_size:
706
+ return (value[index],)
707
+ return value
708
+
709
+ # 推理时
710
+ # future_image支路,self.backbone.generate()
711
+ def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool):
712
+ # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1')
713
+ if max_samples is None or max_samples < 0:
714
+ sample_count = batch_size
715
+ else:
716
+ sample_count = min(batch_size, max(0, int(max_samples)))
717
+ # print(sample_count) # 1
718
+
719
+ # print(generation_inputs)
720
+ """
721
+ {
722
+ 'prompt': [
723
+ 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.',
724
+ 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.',
725
+ 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.',
726
+ 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.',
727
+ 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.',
728
+ 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.',
729
+ 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.',
730
+ 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.'
731
+ ],
732
+ 'height': 224,
733
+ 'width': 224,
734
+ 'num_frames': 93,
735
+ 'num_inference_steps': 20,
736
+ 'guidance_scale': 7.0,
737
+ 'output_type': 'pil',
738
+ 'return_dict': True,
739
+ 'max_sequence_length': 512,
740
+ 'conditional_frame_timestep': 0.1,
741
+ 'num_latent_conditional_frames': 2,
742
+ 'image': [
743
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487370>,
744
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74872B0>,
745
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487280>,
746
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74872E0>,
747
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74877F0>,
748
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487850>,
749
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487F70>,
750
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487580>
751
+ ]
752
+ }
753
+ """
754
+ pred_future_images = []
755
+ for sample_idx in range(sample_count):
756
+
757
+ # 1. CosmosPredict:构建输入
758
+ # print(sample_idx) # 0
759
+ single_inputs = {
760
+ key: self._slice_generation_value(key, value, sample_idx, batch_size)
761
+ for key, value in generation_inputs.items()
762
+ }
763
+ # print(single_inputs)
764
+ """
765
+ {
766
+ 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'],
767
+ 'height': 224,
768
+ 'width': 224,
769
+ 'num_frames': 93,
770
+ 'num_inference_steps': 20,
771
+ 'guidance_scale': 7.0,
772
+ 'output_type': 'pil',
773
+ 'return_dict': True,
774
+ 'max_sequence_length': 512,
775
+ 'conditional_frame_timestep': 0.1,
776
+ 'num_latent_conditional_frames': 2,
777
+ 'image': <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487370>
778
+ }
779
+ """
780
+
781
+ # 2. CosmosPredict:前向推理
782
+ generation_output = self.backbone.generate(**single_inputs)
783
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
784
+ # print(type(generation_output)) # <class 'diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput'>
785
+ # print(future_frame_index) # -1
786
+ # print(return_full_video) # False
787
+ sample_images = self._select_future_images(
788
+ generation_output,
789
+ future_frame_index=future_frame_index,
790
+ return_full_video=return_full_video,
791
+ )
792
+ # print(sample_images) # [<PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7423220>]
793
+ if isinstance(sample_images, (list, tuple)):
794
+ pred_future_images.extend(sample_images)
795
+ else:
796
+ pred_future_images.append(sample_images)
797
+ # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2')
798
+ return pred_future_images
799
+
800
+ # 推理时
801
+ # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action()
802
+ @torch.inference_mode()
803
+ def predict_action(self, examples: List[dict], **kwargs) -> dict:
804
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1')
805
+ if type(examples) is not list:
806
+ examples = [examples]
807
+
808
+ # 1. CosmosPredict:构建输入
809
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
810
+ instructions = [example["lang"] for example in examples]
811
+ # print(len(examples)) # 8
812
+
813
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
814
+ # print(train_obs_image_size) # None
815
+ if train_obs_image_size:
816
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
817
+
818
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
819
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
820
+ # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input'])
821
+ # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28])
822
+ # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1])
823
+ # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352])
824
+ # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28])
825
+ # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224])
826
+ # print(wm_inputs['_is_wm_input']) # True
827
+
828
+ # 2. CosmosPredict:前向推理
829
+ # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens
830
+ with torch.autocast("cuda", dtype=torch.bfloat16):
831
+ wm_outputs = self.backbone(
832
+ **wm_inputs,
833
+ output_hidden_states=True,
834
+ return_dict=True,
835
+ )
836
+ last_hidden = wm_outputs.hidden_states[-1]
837
+ # print(type(wm_outputs)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface.forward.<locals>._WMOutput'>
838
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
839
+
840
+ # 3. ActionHead:构建输入
841
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
842
+ state = (
843
+ torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
844
+ if state is not None
845
+ else None
846
+ )
847
+ # print(state.shape) # torch.Size([8, 1, 64])
848
+ state = self._align_state_dim(state)
849
+ # print(state.shape) # torch.Size([8, 1, 64])
850
+
851
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
852
+ embodiment_tag = (
853
+ torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
854
+ if embodiment_tag is not None
855
+ else None
856
+ )
857
+ # print(embodiment_tag.shape) # torch.Size([8])
858
+ if embodiment_tag is not None:
859
+ embodiment_tag = embodiment_tag.view(-1)
860
+ # print(embodiment_tag.shape) # torch.Size([8])
861
+
862
+ # 4. ActionHead:前向推理
863
+ with torch.autocast("cuda", dtype=torch.float32):
864
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
865
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
866
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
867
+ # print(state.shape) # torch.Size([8, 1, 64])
868
+ # print(embodiment_tag.shape) # torch.Size([8])
869
+ # print(pred_actions.shape) # torch.Size([8, 16, 32])
870
+ output = {"normalized_actions": pred_actions.detach().cpu().numpy()}
871
+
872
+ # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要
873
+ generation_cfg = self._get_future_image_generation_cfg(kwargs)
874
+ is_enabled = generation_cfg.pop("enabled", True)
875
+ # print(is_enabled) # True
876
+ if not bool(is_enabled):
877
+ # print('is_enabled is False')
878
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2')
879
+ return output
880
+
881
+ return_full_video = bool(generation_cfg.pop("return_full_video", False))
882
+ future_frame_index = int(generation_cfg.pop("future_frame_index", -1))
883
+ max_samples = int(generation_cfg.pop("max_samples", 1))
884
+ generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg)
885
+ output["pred_future_images"] = self._generate_future_images(
886
+ generation_inputs,
887
+ batch_size=len(examples),
888
+ max_samples=max_samples,
889
+ future_frame_index=future_frame_index,
890
+ return_full_video=return_full_video,
891
+ )
892
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2')
893
+ return output
starVLA/model/framework/WAM_VJEPA/CosmoPredict2Perceiver.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ CosmoPredict2-Perceiver Framework.
5
+
6
+ Uses Cosmos-Predict2 as the world-model backbone and the Perceiver-style
7
+ flow-matching action head for continuous action prediction.
8
+ """
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ _workspace_root = Path(__file__).parent.parent.parent.parent.parent
14
+ if str(_workspace_root) not in sys.path:
15
+ sys.path.insert(0, str(_workspace_root))
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import List, Optional, Tuple
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from deployment.model_server.tools.image_tools import to_pil_preserve
24
+ from starVLA.model.framework.base_framework import baseframework
25
+ from starVLA.model.framework.share_tools import merge_framework_config
26
+ from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model
27
+ from starVLA.model.modules.world_model import get_world_model
28
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
29
+ from starVLA.training.trainer_utils import initialize_overwatch
30
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
31
+
32
+ logger = initialize_overwatch(__name__)
33
+
34
+
35
+ @dataclass
36
+ class CosmoPredict2PerceiverDefaultConfig:
37
+ """CosmoPredict2-Perceiver default parameters."""
38
+
39
+ name: str = "CosmoPredict2Perceiver"
40
+
41
+ world_model: dict = field(default_factory=lambda: {
42
+ "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World",
43
+ "extract_layers": [-1],
44
+ })
45
+
46
+ # Kept for compatibility with shared utilities and action-head configs.
47
+ qwenvl: dict = field(default_factory=lambda: {
48
+ "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World",
49
+ "vl_hidden_dim": 2048,
50
+ })
51
+
52
+ action_model: dict = field(default_factory=lambda: {
53
+ "action_model_type": "DiT-B",
54
+ "action_hidden_dim": 1024,
55
+ "hidden_size": 1024,
56
+ "add_pos_embed": True,
57
+ "max_seq_len": 1024,
58
+ "action_dim": 7,
59
+ "state_dim": 7,
60
+ "future_action_window_size": 7,
61
+ "action_horizon": 8,
62
+ "past_action_window_size": 0,
63
+ "repeated_diffusion_steps": 8,
64
+ "noise_beta_alpha": 1.5,
65
+ "noise_beta_beta": 1.0,
66
+ "noise_s": 0.999,
67
+ "num_timestep_buckets": 1000,
68
+ "num_inference_timesteps": 4,
69
+ "num_target_vision_tokens": 32,
70
+ "max_num_embodiments": 32,
71
+ "use_category_specific": False,
72
+ "diffusion_model_cfg": {
73
+ "cross_attention_dim": 2048,
74
+ "dropout": 0.2,
75
+ "final_dropout": True,
76
+ "interleave_self_attention": True,
77
+ "norm_type": "ada_norm",
78
+ "num_layers": 16,
79
+ "output_dim": 1024,
80
+ "positional_embeddings": None,
81
+ },
82
+ })
83
+
84
+ obs_image_size: Optional[list] = None
85
+
86
+
87
+ @FRAMEWORK_REGISTRY.register("CosmoPredict2Perceiver")
88
+ class CosmoPredict2_Perceiver(baseframework):
89
+ """World-model-for-action framework using Cosmos-Predict2 + Perceiver head."""
90
+
91
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
92
+ super().__init__()
93
+ self.config = merge_framework_config(CosmoPredict2PerceiverDefaultConfig, config)
94
+
95
+ self.backbone = get_world_model(config=self.config)
96
+
97
+ wm_hidden = self.backbone.model.config.hidden_size
98
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
99
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
100
+
101
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
102
+
103
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
104
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
105
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
106
+
107
+ # 训练时
108
+ # action支路,self.backbone.build_inputs、self.backbone.forward()、self.action_model.forward()
109
+ def forward(self, examples: List[dict] = None, **kwargs) -> Tuple:
110
+ # print('################# CosmoPredict2_Perceiver.forward-1')
111
+
112
+ # 1. CosmosPredict:构建输入
113
+ batch_images = [example["image"] for example in examples]
114
+ instructions = [example["lang"] for example in examples]
115
+ # print(len(examples)) # 8
116
+
117
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
118
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
119
+ # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input'])
120
+ # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28])
121
+ # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1])
122
+ # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352])
123
+ # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28])
124
+ # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224])
125
+ # print(wm_inputs['_is_wm_input']) # True
126
+
127
+ # 2. CosmosPredict:前向推理
128
+ # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens
129
+ with torch.autocast("cuda", dtype=torch.bfloat16):
130
+ wm_outputs = self.backbone(
131
+ **wm_inputs,
132
+ output_hidden_states=True,
133
+ return_dict=True,
134
+ )
135
+ last_hidden = wm_outputs.hidden_states[-1]
136
+ # print(type(wm_outputs)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface.forward.<locals>._WMOutput'>
137
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
138
+
139
+ # 3. ActionHead:构建输入
140
+ with torch.autocast("cuda", dtype=torch.float32):
141
+
142
+ # 3.1 初始化action
143
+ actions = [example["action"] for example in examples]
144
+ actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype)
145
+ # print(actions.shape) # torch.Size([8, 16, 32])
146
+ actions_target = actions[:, -(self.future_action_window_size + 1):, :]
147
+ # print(self.future_action_window_size) # 15
148
+ # print(actions_target.shape) # torch.Size([8, 16, 32])
149
+
150
+ # 3.2 重复降噪
151
+ # 将action和vl-tokens复制多次,重复多次降噪
152
+ repeated_diffusion_steps = (
153
+ self.config.trainer.get("repeated_diffusion_steps", 4)
154
+ if self.config and hasattr(self.config, "trainer")
155
+ else self.config.framework.action_model.get("repeated_diffusion_steps", 4)
156
+ )
157
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
158
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
159
+ # print(actions_target_repeated.shape) # torch.Size([32, 16, 32])
160
+ # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048])
161
+
162
+ # 3.3 准备state、action_mask和embodiment_tag
163
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
164
+ if state is not None:
165
+ # print('state is not None')
166
+ state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype)
167
+ # print(state.shape) # torch.Size([8, 1, 64])
168
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
169
+ # print(state_repeated.shape) # torch.Size([32, 1, 64])
170
+ else:
171
+ state_repeated = None
172
+
173
+ action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None
174
+ if action_mask is not None:
175
+ # print('action_mask is not None')
176
+ action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype)
177
+ # print(action_mask_tensor.shape) # torch.Size([8, 16, 32])
178
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :]
179
+ # print(action_mask_target.shape) # torch.Size([8, 16, 32])
180
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
181
+ # print(action_mask_repeated.shape) # torch.Size([32, 16, 32])
182
+ else:
183
+ action_mask_repeated = None
184
+
185
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
186
+ if embodiment_tag is not None:
187
+ # print('embodiment_tag is not None')
188
+ embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64)
189
+ # print(embodiment_tag.shape) # torch.Size([8])
190
+ embodiment_tag = embodiment_tag.view(-1)
191
+ # print(embodiment_tag.shape) # torch.Size([8])
192
+ embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps)
193
+ # print(embodiment_tag_repeated.shape) # torch.Size([32])
194
+ else:
195
+ embodiment_tag_repeated = None
196
+
197
+ action_loss, target_emb = self.action_model(
198
+ last_hidden_repeated,
199
+ actions_target_repeated,
200
+ state_repeated,
201
+ embodiment_tag_repeated,
202
+ action_mask=action_mask_repeated,
203
+ use_vjepa2ac=True,
204
+ repeated_diffusion_steps=repeated_diffusion_steps,
205
+ )
206
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
207
+ # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048])
208
+ # print(actions_target_repeated.shape) # torch.Size([32, 16, 32])
209
+ # print(state_repeated.shape) # torch.Size([32, 1, 64])
210
+ # print(embodiment_tag_repeated.shape) # torch.Size([32])
211
+ # print(action_mask_repeated.shape) # torch.Size([32, 16, 32])
212
+ # print(action_loss) # tensor(1.5625, device='cuda:0', grad_fn=<DivBackward0>)
213
+ # print(target_emb.shape) # torch.Size([8, 64, 1024])
214
+
215
+ # print('################# CosmoPredict2_Perceiver.forward-2')
216
+ return action_loss, target_emb
217
+
218
+ # @torch.inference_mode()
219
+ # def predict_action(self, examples: List[dict], **kwargs) -> dict:
220
+ # if type(examples) is not list:
221
+ # examples = [examples]
222
+
223
+ # batch_images = [to_pil_preserve(example["image"]) for example in examples]
224
+ # instructions = [example["lang"] for example in examples]
225
+ # state = [example["state"] for example in examples] if "state" in examples[0] else None
226
+ # embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
227
+
228
+ # train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
229
+ # if train_obs_image_size:
230
+ # batch_images = resize_images(batch_images, target_size=train_obs_image_size)
231
+
232
+ # wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
233
+ # with torch.autocast("cuda", dtype=torch.bfloat16):
234
+ # wm_outputs = self.backbone(
235
+ # **wm_inputs,
236
+ # output_hidden_states=True,
237
+ # return_dict=True,
238
+ # )
239
+ # last_hidden = wm_outputs.hidden_states[-1]
240
+
241
+ # state = (
242
+ # torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
243
+ # if state is not None
244
+ # else None
245
+ # )
246
+ # embodiment_tag = (
247
+ # torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
248
+ # if embodiment_tag is not None
249
+ # else None
250
+ # )
251
+ # if embodiment_tag is not None:
252
+ # embodiment_tag = embodiment_tag.view(-1)
253
+
254
+ # with torch.autocast("cuda", dtype=torch.float32):
255
+ # pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
256
+
257
+ # normalized_actions = pred_actions.detach().cpu().numpy()
258
+ # return {"normalized_actions": normalized_actions}
starVLA/model/framework/WAM_VJEPA/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25Perceiver-checkpoint.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver Framework.
5
+
6
+ This keeps Predict2.5 separate from the existing Cosmos-Predict2 framework
7
+ while reusing the same Perceiver action-head training/inference logic.
8
+ """
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Optional
12
+
13
+ from starVLA.model.framework.WM4A.CosmoPredict2Perceiver import CosmoPredict2_Perceiver
14
+ from starVLA.model.framework.base_framework import baseframework
15
+ from starVLA.model.framework.share_tools import merge_framework_config
16
+ from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model
17
+ from starVLA.model.modules.world_model import get_world_model
18
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
19
+
20
+
21
+ @dataclass
22
+ class CosmoPredict25PerceiverDefaultConfig:
23
+ """Cosmos-Predict2.5-Perceiver default parameters."""
24
+
25
+ name: str = "CosmoPredict25Perceiver"
26
+
27
+ world_model: dict = field(default_factory=lambda: {
28
+ "base_wm": "nvidia/Cosmos-Predict2.5-2B",
29
+ "revision": "diffusers/base/post-trained",
30
+ "extract_layers": [-1],
31
+ })
32
+
33
+ qwenvl: dict = field(default_factory=lambda: {
34
+ "base_vlm": "nvidia/Cosmos-Predict2.5-2B",
35
+ "vl_hidden_dim": 2048,
36
+ })
37
+
38
+ action_model: dict = field(default_factory=lambda: {
39
+ "action_model_type": "DiT-B",
40
+ "action_hidden_dim": 1024,
41
+ "hidden_size": 1024,
42
+ "add_pos_embed": True,
43
+ "max_seq_len": 1024,
44
+ "action_dim": 7,
45
+ "state_dim": 7,
46
+ "future_action_window_size": 7,
47
+ "action_horizon": 8,
48
+ "past_action_window_size": 0,
49
+ "repeated_diffusion_steps": 8,
50
+ "noise_beta_alpha": 1.5,
51
+ "noise_beta_beta": 1.0,
52
+ "noise_s": 0.999,
53
+ "num_timestep_buckets": 1000,
54
+ "num_inference_timesteps": 4,
55
+ "num_target_vision_tokens": 32,
56
+ "max_num_embodiments": 32,
57
+ "use_category_specific": False,
58
+ "diffusion_model_cfg": {
59
+ "cross_attention_dim": 2048,
60
+ "dropout": 0.2,
61
+ "final_dropout": True,
62
+ "interleave_self_attention": True,
63
+ "norm_type": "ada_norm",
64
+ "num_layers": 16,
65
+ "output_dim": 1024,
66
+ "positional_embeddings": None,
67
+ },
68
+ })
69
+
70
+ obs_image_size: Optional[list] = None
71
+
72
+
73
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25Perceiver")
74
+ class CosmoPredict25_Perceiver(CosmoPredict2_Perceiver):
75
+ """World-model-for-action framework using Cosmos-Predict2.5 + Perceiver."""
76
+
77
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
78
+ baseframework.__init__(self)
79
+ self.config = merge_framework_config(CosmoPredict25PerceiverDefaultConfig, config)
80
+
81
+ self.backbone = get_world_model(config=self.config)
82
+
83
+ wm_hidden = self.backbone.model.config.hidden_size
84
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
85
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
86
+
87
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
88
+
89
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
90
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
91
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverFutureImage-checkpoint.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver with future-image prediction.
5
+
6
+ This framework keeps the existing Cosmos hidden-state -> Perceiver action
7
+ path, and additionally runs the Cosmos2.5 generation/decoder path during
8
+ inference to return the image predicted after the action chunk horizon.
9
+ """
10
+
11
+ from dataclasses import dataclass, field
12
+ from typing import List, Optional
13
+
14
+ import numpy as np
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from PIL import Image
18
+
19
+ from deployment.model_server.tools.image_tools import to_pil_preserve
20
+ from starVLA.model.framework.WM4A.CosmoPredict25Perceiver import (
21
+ CosmoPredict25_Perceiver,
22
+ CosmoPredict25PerceiverDefaultConfig,
23
+ )
24
+ from starVLA.model.framework.base_framework import baseframework
25
+ from starVLA.model.framework.share_tools import merge_framework_config
26
+ from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model
27
+ from starVLA.model.modules.world_model import get_world_model
28
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
29
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
30
+
31
+
32
+ @dataclass
33
+ class CosmoPredict25PerceiverFutureImageDefaultConfig(CosmoPredict25PerceiverDefaultConfig):
34
+ """Cosmos-Predict2.5-Perceiver + future-image defaults."""
35
+
36
+ name: str = "CosmoPredict25PerceiverFutureImage"
37
+
38
+ future_image_generation: dict = field(default_factory=lambda: {
39
+ "enabled": True,
40
+ "num_frames": 93,
41
+ "num_inference_steps": 36,
42
+ "guidance_scale": 7.0,
43
+ "output_type": "pil",
44
+ "height": 704,
45
+ "width": 1280,
46
+ "max_sequence_length": 512,
47
+ "conditional_frame_timestep": 0.1,
48
+ "num_latent_conditional_frames": 2,
49
+ "conditioning_mode": "auto",
50
+ "max_samples": 1,
51
+ "return_full_video": False,
52
+ "future_frame_index": -1,
53
+ "negative_prompt": None,
54
+ })
55
+
56
+ future_image_training: dict = field(default_factory=lambda: {
57
+ "enabled": True,
58
+ "loss_weight": 1.0,
59
+ "train_time_distribution": "logitnormal",
60
+ "shift": 5.0,
61
+ })
62
+
63
+
64
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverFutureImage")
65
+ class CosmoPredict25_Perceiver_FutureImage(CosmoPredict25_Perceiver):
66
+ """Cosmos-Predict2.5 hidden-state action head plus generated future images."""
67
+
68
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
69
+ print('################# CosmoPredict25_Perceiver_FutureImage-1')
70
+ baseframework.__init__(self)
71
+ self.config = merge_framework_config(CosmoPredict25PerceiverFutureImageDefaultConfig, config)
72
+
73
+ # 1. 初始化CosmosPredictr2.5类作为backbone
74
+ # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py
75
+ self.backbone = get_world_model(config=self.config)
76
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
77
+
78
+ wm_hidden = self.backbone.model.config.hidden_size
79
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
80
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
81
+ # print(wm_hidden) # 2048
82
+
83
+ # 2. 初始化FlowmatchingActionHead作为action-head
84
+ # WM4A/starVLA/model/modules/action_model/PerceiverHead.py
85
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
86
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
87
+
88
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
89
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
90
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
91
+ self.state_dim = self.config.framework.action_model.get("state_dim", None)
92
+ # print(self.future_action_window_size) # 15
93
+ # print(self.past_action_window_size) # 0
94
+ # print(self.chunk_len) # 16
95
+ # print(self.state_dim) # 64
96
+ print('################# CosmoPredict25_Perceiver_FutureImage-2')
97
+
98
+ @staticmethod
99
+ def _as_sequence(images):
100
+ return list(images) if isinstance(images, (list, tuple)) else [images]
101
+
102
+ def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor:
103
+ if state is None or self.state_dim is None:
104
+ return state
105
+ target_dim = int(self.state_dim)
106
+ current_dim = state.shape[-1]
107
+ if current_dim == target_dim:
108
+ return state
109
+ if current_dim > target_dim:
110
+ return state[..., :target_dim]
111
+
112
+ pad_shape = (*state.shape[:-1], target_dim - current_dim)
113
+ padding = state.new_zeros(pad_shape)
114
+ return torch.cat([state, padding], dim=-1)
115
+
116
+ @staticmethod
117
+ def _as_bool(value) -> bool:
118
+ if isinstance(value, str):
119
+ return value.lower() in {"1", "true", "yes", "on"}
120
+ return bool(value)
121
+
122
+ def _future_training_cfg(self) -> dict:
123
+ return dict(self.config.framework.get("future_image_training", {}))
124
+
125
+ def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor:
126
+ distribution = str(distribution).lower()
127
+ if distribution == "logitnormal":
128
+ return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32))
129
+ if distribution == "uniform":
130
+ return torch.rand(batch_size, device=device, dtype=torch.float32)
131
+ raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}")
132
+
133
+ @staticmethod
134
+ def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor:
135
+ return shift * time / (1.0 + (shift - 1.0) * time)
136
+
137
+ def _latent_frame_count(self, raw_frame_count: int) -> int:
138
+ if hasattr(self, 'backbone'):
139
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
140
+ else:
141
+ temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4))
142
+ return (int(raw_frame_count) - 1) // temporal_factor + 1
143
+
144
+ def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]:
145
+ # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1')
146
+ temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4))
147
+ raw_sequences = []
148
+ condition_counts = []
149
+ sample_counts = []
150
+ # print(temporal_factor) # 4
151
+ # print(len(batch_images)) # 8
152
+ # print(len(future_images)) # 8
153
+
154
+ for images, future_image in zip(batch_images, future_images):
155
+ current_sequence = self._as_sequence(images)
156
+ future_sequence = self._as_sequence(future_image)
157
+ # print(len(current_sequence)) # 1
158
+ # print(len(future_sequence)) # 1
159
+ if not current_sequence or not future_sequence:
160
+ raise ValueError("future image training needs both current image and future_image.")
161
+
162
+ future_frame = future_sequence[0]
163
+ # print(type(future_frame)) # <class 'PIL.Image.Image'>
164
+ raw_sequence = current_sequence + [future_frame] * temporal_factor
165
+ raw_sequences.append(raw_sequence)
166
+
167
+ condition_count = self._latent_frame_count(len(current_sequence))
168
+ sample_count = self._latent_frame_count(len(raw_sequence))
169
+ # print(condition_count) # 1
170
+ # print(sample_count) # 2
171
+ condition_counts.append(condition_count)
172
+ sample_counts.append(sample_count)
173
+
174
+ # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2')
175
+ return raw_sequences, condition_counts, sample_counts
176
+
177
+ # 训练时
178
+ # future_image支路,self.backbone.transformer()
179
+ def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
180
+ # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1')
181
+ if "future_image" not in examples[0]:
182
+ return None
183
+ training_cfg = self._future_training_cfg()
184
+ if not self._as_bool(training_cfg.get("enabled", True)):
185
+ return None
186
+
187
+ # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状
188
+ # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt;
189
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
190
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
191
+ instructions = [example["lang"] for example in examples]
192
+ # print(len(examples)) # 8
193
+ # print(type(batch_images[0])) # <class 'list'>
194
+ # print(type(future_images[0])) # <class 'list'>
195
+ # print(type(instructions[0])) # <class 'str'>
196
+
197
+ # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs]
198
+ # 而raw_sequences也是由8个这样的raw_sequence组成的列表,
199
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
200
+ # print(train_obs_image_size) # None
201
+ if train_obs_image_size:
202
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
203
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
204
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
205
+ batch_images=batch_images,
206
+ future_images=future_images,
207
+ )
208
+ # print(len(raw_sequences)) # 8
209
+ # print(len(raw_sequences[0])) # 5
210
+ # print(raw_sequences[0][0]) # <PIL.Image.Image image mode=RGB size=224x224 at 0x7FF6B20D60E0>
211
+ # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1]
212
+ # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2]
213
+
214
+ # 2. 调用CosmosPredict的文本和视觉tokenizer,
215
+ # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28),
216
+ # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents
217
+ prompt_embeds = self.backbone._encode_text(instructions)
218
+ clean_latents, _, _ = self.backbone._encode_images(raw_sequences)
219
+ dtype = self.backbone.transformer.dtype
220
+ clean_latents = clean_latents.to(dtype)
221
+ batch_size, channels, num_latents, height, width = clean_latents.shape
222
+ device = clean_latents.device
223
+ # print(prompt_embeds.shape) # torch.Size([8, 512, 100352])
224
+ # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28])
225
+ # print(dtype) # torch.bfloat16
226
+ condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width))
227
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
228
+ cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
229
+ # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28])
230
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
231
+ # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1])
232
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
233
+ condition_count = max(1, min(int(condition_count), num_latents))
234
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
235
+ condition_mask[batch_idx, :, :condition_count] = 1.0
236
+ cond_indicator[batch_idx, :, :condition_count] = 1.0
237
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
238
+
239
+ # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪
240
+ train_time = self._sample_train_times(
241
+ batch_size=batch_size,
242
+ device=device,
243
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
244
+ )
245
+ # print(train_time.shape) # torch.Size([8])
246
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
247
+ # print(flow_time.shape) # torch.Size([8])
248
+ target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype)
249
+ # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1])
250
+ # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28])
251
+ noise = torch.randn_like(clean_latents)
252
+ # print(noise.shape) # torch.Size([8, 16, 2, 28, 28])
253
+ # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1])
254
+ noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time
255
+ # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28])
256
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
257
+ hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents)
258
+ # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28])
259
+
260
+ # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity
261
+ target_velocity = noise.float() - clean_latents.float()
262
+ # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28])
263
+
264
+ # 5. 计算timestep和padding_mask
265
+ cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1))
266
+ # print(cond_timestep) # 0.1
267
+ timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
268
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
269
+ timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep
270
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
271
+ timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep)
272
+ # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1])
273
+
274
+ padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16))
275
+ padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16))
276
+ padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype)
277
+ # print(padding_height) # 224
278
+ # print(padding_width) # 224
279
+ # print(padding_mask.shape) # torch.Size([1, 1, 224, 224])
280
+
281
+ # 7. CosmosPredict前向传播
282
+ # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入,
283
+ # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中,
284
+ # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息,
285
+ # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分,
286
+ if hasattr(self.backbone, "_intermediate_features"):
287
+ self.backbone._intermediate_features.clear()
288
+ with torch.autocast("cuda", dtype=torch.bfloat16):
289
+ pred = self.backbone.transformer(
290
+ hidden_states=hidden_states,
291
+ timestep=timestep,
292
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
293
+ condition_mask=condition_mask.to(dtype),
294
+ padding_mask=padding_mask,
295
+ return_dict=False,
296
+ )
297
+ pred = pred[0] if isinstance(pred, tuple) else pred
298
+ pred = pred.sample if hasattr(pred, "sample") else pred
299
+ if hasattr(self.backbone, "_intermediate_features"):
300
+ self.backbone._intermediate_features.clear()
301
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
302
+ # print(pred.shape) # torch.Size([8, 16, 2, 28, 28])
303
+
304
+ # 8. 计算future-image-loss
305
+ # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1])
306
+ loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width)
307
+ # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28])
308
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
309
+ # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28])
310
+ future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
311
+ # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=<DivBackward0>)
312
+ # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2')
313
+ return future_image_loss
314
+
315
+ # 训练时
316
+ # 生成future_image和action
317
+ # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight
318
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
319
+ # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1')
320
+ # 1. 调用CosmosPredict+ActionHead生成action_loss,这个函数定义在父类中
321
+ output = super().forward(examples=examples, **kwargs)
322
+ action_loss = output["action_loss"]
323
+
324
+ # 2. 调用CosmosPredict生成future_image_loss
325
+ future_image_loss = self._cosmos25_future_image_loss(examples)
326
+ if future_image_loss is None:
327
+ return output
328
+
329
+ # 3. 最终返回的是total_loss=action_loss+future_image_loss*loss_weight
330
+ loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0))
331
+ # print(loss_weight) # 1.0
332
+ output["perceiver_action_loss"] = action_loss.detach()
333
+ output["future_image_loss"] = future_image_loss.detach()
334
+ output["action_loss"] = action_loss + future_image_loss * loss_weight
335
+ # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2')
336
+ return output
337
+
338
+ def _get_future_image_generation_cfg(self, kwargs: dict) -> dict:
339
+ cfg = dict(self.config.framework.get("future_image_generation", {}))
340
+ override = kwargs.get("future_image_generation", None)
341
+ if override:
342
+ cfg.update(dict(override))
343
+
344
+ if "decode_future_images" in kwargs:
345
+ cfg["enabled"] = kwargs["decode_future_images"]
346
+ if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs:
347
+ cfg["num_inference_steps"] = kwargs["num_ddim_steps"]
348
+
349
+ for key in (
350
+ "enabled",
351
+ "num_frames",
352
+ "num_inference_steps",
353
+ "guidance_scale",
354
+ "output_type",
355
+ "height",
356
+ "width",
357
+ "max_sequence_length",
358
+ "conditional_frame_timestep",
359
+ "num_latent_conditional_frames",
360
+ "conditioning_mode",
361
+ "max_samples",
362
+ "return_full_video",
363
+ "future_frame_index",
364
+ "negative_prompt",
365
+ "generator",
366
+ "latents",
367
+ "prompt_embeds",
368
+ "negative_prompt_embeds",
369
+ ):
370
+ if key in kwargs:
371
+ cfg[key] = kwargs[key]
372
+ return cfg
373
+
374
+ def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict:
375
+ mode = str(cfg.pop("conditioning_mode", "auto")).lower()
376
+ _wm = self.backbone if hasattr(self, "backbone") else self.wan_interface
377
+ height = cfg.pop("height", getattr(_wm, "_height", 704))
378
+ width = cfg.pop("width", getattr(_wm, "_width", 1280))
379
+ heights = self._resolve_generation_size_values(batch_images, height, width)
380
+ generation_inputs = {
381
+ "prompt": instructions,
382
+ "height": heights[0],
383
+ "width": heights[1],
384
+ "num_frames": cfg.pop("num_frames", 93),
385
+ "num_inference_steps": cfg.pop("num_inference_steps", 36),
386
+ "guidance_scale": cfg.pop("guidance_scale", 7.0),
387
+ "output_type": cfg.pop("output_type", "pil"),
388
+ "return_dict": True,
389
+ "max_sequence_length": cfg.pop("max_sequence_length", 512),
390
+ "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1),
391
+ "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2),
392
+ }
393
+
394
+ negative_prompt = cfg.pop("negative_prompt", None)
395
+ if negative_prompt is not None:
396
+ generation_inputs["negative_prompt"] = negative_prompt
397
+
398
+ if mode == "image":
399
+ generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images]
400
+ elif mode == "video":
401
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
402
+ elif mode == "auto":
403
+ if any(len(self._as_sequence(images)) > 1 for images in batch_images):
404
+ generation_inputs["video"] = [self._as_sequence(images) for images in batch_images]
405
+ else:
406
+ generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images]
407
+ else:
408
+ raise ValueError(
409
+ "future_image_generation.conditioning_mode must be one of "
410
+ f"'auto', 'image', or 'video', got {mode!r}."
411
+ )
412
+
413
+ passthrough_keys = (
414
+ "generator",
415
+ "latents",
416
+ "prompt_embeds",
417
+ "negative_prompt_embeds",
418
+ "num_videos_per_prompt",
419
+ "callback_on_step_end",
420
+ "callback_on_step_end_tensor_inputs",
421
+ )
422
+ for key in passthrough_keys:
423
+ if key in cfg and cfg[key] is not None:
424
+ generation_inputs[key] = cfg.pop(key)
425
+
426
+ generation_inputs.update({key: value for key, value in cfg.items() if value is not None})
427
+ return generation_inputs
428
+
429
+ @staticmethod
430
+ def _is_auto_size(value) -> bool:
431
+ return isinstance(value, str) and value.lower() == "auto"
432
+
433
+ @staticmethod
434
+ def _round_up_to_multiple(value: int, multiple: int) -> int:
435
+ return int(((max(1, value) + multiple - 1) // multiple) * multiple)
436
+
437
+ @staticmethod
438
+ def _image_size(image) -> tuple[int, int]:
439
+ size = getattr(image, "size", None)
440
+ if isinstance(size, (list, tuple)) and len(size) >= 2:
441
+ return int(size[0]), int(size[1])
442
+ if torch.is_tensor(image):
443
+ shape = tuple(image.shape)
444
+ if len(shape) >= 3 and shape[0] in (1, 3, 4):
445
+ return int(shape[-1]), int(shape[-2])
446
+ if len(shape) >= 2:
447
+ return int(shape[1]), int(shape[0])
448
+ array = np.asarray(image)
449
+ if array.ndim < 2:
450
+ raise ValueError(f"Cannot infer image size from shape {array.shape}")
451
+ return int(array.shape[1]), int(array.shape[0])
452
+
453
+ def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple:
454
+ if not self._is_auto_size(height) and not self._is_auto_size(width):
455
+ return int(height), int(width)
456
+
457
+ resolved_heights = []
458
+ resolved_widths = []
459
+ _wm = self.backbone if hasattr(self, "backbone") else self.wan_interface
460
+ spatial_multiple = int(getattr(_wm, "vae_scale_factor_spatial", 16))
461
+ for images in batch_images:
462
+ image_sequence = self._as_sequence(images)
463
+ frame_sizes = [self._image_size(image) for image in image_sequence]
464
+ if not frame_sizes:
465
+ raise ValueError("Cannot infer auto generation size from empty image sequence.")
466
+
467
+ sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height)
468
+ if self._is_auto_size(width):
469
+ max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes)
470
+ sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple)
471
+ else:
472
+ sample_width = int(width)
473
+ resolved_heights.append(int(sample_height))
474
+ resolved_widths.append(int(sample_width))
475
+
476
+ height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0]
477
+ width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0]
478
+ return height_value, width_value
479
+
480
+ @staticmethod
481
+ def _extract_videos(generation_output):
482
+ if hasattr(generation_output, "frames"):
483
+ return generation_output.frames
484
+ if hasattr(generation_output, "videos"):
485
+ return generation_output.videos
486
+ if hasattr(generation_output, "images"):
487
+ return generation_output.images
488
+ if isinstance(generation_output, tuple):
489
+ return generation_output[0]
490
+ return generation_output
491
+
492
+ def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool):
493
+ videos = self._extract_videos(generation_output)
494
+ if return_full_video:
495
+ return videos
496
+
497
+ if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image):
498
+ return [videos[future_frame_index]]
499
+
500
+ future_images = []
501
+ for sample in videos:
502
+ if torch.is_tensor(sample):
503
+ if sample.ndim >= 4:
504
+ future_images.append(sample[future_frame_index])
505
+ else:
506
+ future_images.append(sample)
507
+ elif isinstance(sample, np.ndarray):
508
+ if sample.ndim >= 4:
509
+ future_images.append(sample[future_frame_index])
510
+ else:
511
+ future_images.append(sample)
512
+ elif isinstance(sample, (list, tuple)):
513
+ future_images.append(sample[future_frame_index])
514
+ else:
515
+ future_images.append(sample)
516
+ return future_images
517
+
518
+ @staticmethod
519
+ def _slice_generation_value(key: str, value, index: int, batch_size: int):
520
+ if value is None:
521
+ return None
522
+ if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
523
+ return value[index]
524
+ if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size:
525
+ return value[index]
526
+ if torch.is_tensor(value) and value.shape[0] == batch_size:
527
+ return value[index:index + 1]
528
+ if isinstance(value, np.ndarray) and value.shape[0] == batch_size:
529
+ return value[index:index + 1]
530
+ if isinstance(value, list) and len(value) == batch_size:
531
+ return [value[index]]
532
+ if isinstance(value, tuple) and len(value) == batch_size:
533
+ return (value[index],)
534
+ return value
535
+
536
+ # 推理时
537
+ # future_image支路,self.backbone.generate()
538
+ def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool):
539
+ # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1')
540
+ if max_samples is None or max_samples < 0:
541
+ sample_count = batch_size
542
+ else:
543
+ sample_count = min(batch_size, max(0, int(max_samples)))
544
+ # print(sample_count) # 1
545
+
546
+ # print(generation_inputs)
547
+ """
548
+ {
549
+ 'prompt': [
550
+ 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.',
551
+ 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.',
552
+ 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.',
553
+ 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.',
554
+ 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.',
555
+ 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.',
556
+ 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.',
557
+ 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.'
558
+ ],
559
+ 'height': 224,
560
+ 'width': 224,
561
+ 'num_frames': 93,
562
+ 'num_inference_steps': 20,
563
+ 'guidance_scale': 7.0,
564
+ 'output_type': 'pil',
565
+ 'return_dict': True,
566
+ 'max_sequence_length': 512,
567
+ 'conditional_frame_timestep': 0.1,
568
+ 'num_latent_conditional_frames': 2,
569
+ 'image': [
570
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487370>,
571
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74872B0>,
572
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487280>,
573
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74872E0>,
574
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D74877F0>,
575
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487850>,
576
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487F70>,
577
+ <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487580>
578
+ ]
579
+ }
580
+ """
581
+ pred_future_images = []
582
+ for sample_idx in range(sample_count):
583
+
584
+ # 1. CosmosPredict:构建输入
585
+ # print(sample_idx) # 0
586
+ single_inputs = {
587
+ key: self._slice_generation_value(key, value, sample_idx, batch_size)
588
+ for key, value in generation_inputs.items()
589
+ }
590
+ # print(single_inputs)
591
+ """
592
+ {
593
+ 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'],
594
+ 'height': 224,
595
+ 'width': 224,
596
+ 'num_frames': 93,
597
+ 'num_inference_steps': 20,
598
+ 'guidance_scale': 7.0,
599
+ 'output_type': 'pil',
600
+ 'return_dict': True,
601
+ 'max_sequence_length': 512,
602
+ 'conditional_frame_timestep': 0.1,
603
+ 'num_latent_conditional_frames': 2,
604
+ 'image': <PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7487370>
605
+ }
606
+ """
607
+
608
+ # 2. CosmosPredict:前向推理
609
+ generation_output = self.backbone.generate(**single_inputs) if hasattr(self, "backbone") else self.wan_interface.generate(**single_inputs)
610
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
611
+ # print(type(generation_output)) # <class 'diffusers.pipelines.cosmos.pipeline_output.CosmosPipelineOutput'>
612
+ # print(future_frame_index) # -1
613
+ # print(return_full_video) # False
614
+ sample_images = self._select_future_images(
615
+ generation_output,
616
+ future_frame_index=future_frame_index,
617
+ return_full_video=return_full_video,
618
+ )
619
+ # print(sample_images) # [<PIL.Image.Image image mode=RGB size=224x224 at 0x7F96D7423220>]
620
+ if isinstance(sample_images, (list, tuple)):
621
+ pred_future_images.extend(sample_images)
622
+ else:
623
+ pred_future_images.append(sample_images)
624
+ # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2')
625
+ return pred_future_images
626
+
627
+ # 推理时
628
+ # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action()
629
+ @torch.inference_mode()
630
+ def predict_action(self, examples: List[dict], is_run_parallel_eval_mxk: bool = False, **kwargs) -> dict:
631
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1')
632
+ if type(examples) is not list:
633
+ examples = [examples]
634
+
635
+ # 1. CosmosPredict:构建输入
636
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
637
+ instructions = [example["lang"] for example in examples]
638
+ # print(len(examples)) # 8
639
+
640
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
641
+ # print(train_obs_image_size) # None
642
+ if train_obs_image_size:
643
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
644
+
645
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
646
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
647
+ # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input'])
648
+ # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28])
649
+ # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1])
650
+ # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352])
651
+ # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28])
652
+ # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224])
653
+ # print(wm_inputs['_is_wm_input']) # True
654
+
655
+ # 2. CosmosPredict:前向推理
656
+ # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens
657
+ with torch.autocast("cuda", dtype=torch.bfloat16):
658
+ wm_outputs = self.backbone(
659
+ **wm_inputs,
660
+ output_hidden_states=True,
661
+ return_dict=True,
662
+ )
663
+ last_hidden = wm_outputs.hidden_states[-1]
664
+ # print(type(wm_outputs)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface.forward.<locals>._WMOutput'>
665
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
666
+
667
+ # 3. ActionHead:构建输入
668
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
669
+ state = (
670
+ torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
671
+ if state is not None
672
+ else None
673
+ )
674
+ # print(state.shape) # torch.Size([8, 1, 64])
675
+ state = self._align_state_dim(state)
676
+ # print(state.shape) # torch.Size([8, 1, 64])
677
+
678
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
679
+ embodiment_tag = (
680
+ torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
681
+ if embodiment_tag is not None
682
+ else None
683
+ )
684
+ # print(embodiment_tag.shape) # torch.Size([8])
685
+ if embodiment_tag is not None:
686
+ embodiment_tag = embodiment_tag.view(-1)
687
+ # print(embodiment_tag.shape) # torch.Size([8])
688
+
689
+ # 4. ActionHead:前向推理
690
+ with torch.autocast("cuda", dtype=torch.float32):
691
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
692
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
693
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
694
+ # print(state.shape) # torch.Size([8, 1, 64])
695
+ # print(embodiment_tag.shape) # torch.Size([8])
696
+ # print(pred_actions.shape) # torch.Size([8, 16, 32])
697
+ output = {"normalized_actions": pred_actions.detach().cpu().numpy()}
698
+
699
+ # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要
700
+ generation_cfg = self._get_future_image_generation_cfg(kwargs)
701
+ is_enabled = generation_cfg.pop("enabled", True)
702
+ # print(is_enabled) # True
703
+ if not bool(is_enabled):
704
+ # print('is_enabled is False')
705
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2')
706
+ return output
707
+
708
+ return_full_video = bool(generation_cfg.pop("return_full_video", False))
709
+ future_frame_index = int(generation_cfg.pop("future_frame_index", -1))
710
+ max_samples = int(generation_cfg.pop("max_samples", 1))
711
+ generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg)
712
+ output["pred_future_images"] = self._generate_future_images(
713
+ generation_inputs,
714
+ batch_size=len(examples),
715
+ max_samples=max_samples,
716
+ future_frame_index=future_frame_index,
717
+ return_full_video=return_full_video,
718
+ )
719
+ # When called from websocket server, convert PIL Images to numpy arrays
720
+ # for msgpack serialization; otherwise keep PIL Image format
721
+ if is_run_parallel_eval_mxk and "pred_future_images" in output:
722
+ output["pred_future_images"] = [
723
+ np.array(img) if isinstance(img, Image.Image) else img
724
+ for img in output["pred_future_images"]
725
+ ]
726
+ # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2')
727
+ return output
starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverMaskedFutureImage-checkpoint.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """Cosmos-Predict2.5 Perceiver with masked future-image denoising.
4
+
5
+ This variant keeps the existing action path and Cosmos future-image objective,
6
+ but builds a latent-grid change mask from the current/future RGB pair. The mask
7
+ can focus the loss on changed regions and optionally add noise only inside those
8
+ regions, turning future-image training into an inpainting-style objective.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import List, Optional
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn.functional as F
18
+
19
+ from deployment.model_server.tools.image_tools import to_pil_preserve
20
+ from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import (
21
+ CosmoPredict25_Perceiver_FutureImage,
22
+ )
23
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
24
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
25
+
26
+
27
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverMaskedFutureImage")
28
+ class CosmoPredict25_Perceiver_MaskedFutureImage(CosmoPredict25_Perceiver_FutureImage):
29
+ """Future-image training that denoises mostly/only changed regions."""
30
+
31
+ @staticmethod
32
+ def _pil_rgb_to_tensor(image, size: tuple[int, int] | None = None) -> torch.Tensor:
33
+ image = to_pil_preserve(image).convert("RGB")
34
+ if size is not None and image.size != size:
35
+ image = image.resize(size)
36
+ array = np.asarray(image, dtype=np.float32) / 255.0
37
+ return torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0)
38
+
39
+ def _build_latent_change_masks(
40
+ self,
41
+ batch_images: List,
42
+ future_images: List,
43
+ latent_height: int,
44
+ latent_width: int,
45
+ training_cfg: dict,
46
+ device: torch.device,
47
+ ) -> tuple[torch.Tensor, torch.Tensor]:
48
+ """Return binary denoise mask and soft loss weights at latent resolution."""
49
+ top_ratio = float(training_cfg.get("change_mask_top_ratio", 0.25))
50
+ top_ratio = min(max(top_ratio, 1e-4), 1.0)
51
+ static_weight = float(training_cfg.get("change_mask_static_weight", 0.05))
52
+ static_weight = min(max(static_weight, 0.0), 1.0)
53
+ soft_loss = self._as_bool(training_cfg.get("change_mask_soft_loss", True))
54
+
55
+ binary_masks = []
56
+ loss_weights = []
57
+ for images, future_image in zip(batch_images, future_images):
58
+ current_sequence = self._as_sequence(images)
59
+ future_sequence = self._as_sequence(future_image)
60
+ current_frame = current_sequence[-1]
61
+ target_frame = future_sequence[0]
62
+
63
+ current = self._pil_rgb_to_tensor(current_frame)
64
+ target = self._pil_rgb_to_tensor(target_frame, size=to_pil_preserve(current_frame).size)
65
+ diff = (target - current).abs().mean(dim=1, keepdim=True)
66
+ score = F.interpolate(diff, size=(latent_height, latent_width), mode="area")
67
+ flat = score.flatten(1)
68
+ max_score = flat.amax(dim=1).view(-1, 1, 1, 1).clamp_min(1e-6)
69
+ normalized = (score / max_score).clamp(0.0, 1.0)
70
+
71
+ k = max(1, int(flat.shape[1] * top_ratio))
72
+ threshold = flat.topk(k, dim=1).values[:, -1].view(-1, 1, 1, 1)
73
+ binary = (score >= threshold).float()
74
+
75
+ weight_source = normalized if soft_loss else binary
76
+ loss_weight = static_weight + (1.0 - static_weight) * weight_source
77
+ binary_masks.append(binary)
78
+ loss_weights.append(loss_weight)
79
+
80
+ binary_mask = torch.cat(binary_masks, dim=0).to(device=device, dtype=torch.float32)
81
+ loss_weight = torch.cat(loss_weights, dim=0).to(device=device, dtype=torch.float32)
82
+ return binary_mask, loss_weight
83
+
84
+ def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
85
+ if "future_image" not in examples[0]:
86
+ return None
87
+
88
+ training_cfg = self._future_training_cfg()
89
+ if not self._as_bool(training_cfg.get("enabled", True)):
90
+ return None
91
+ if not self._as_bool(training_cfg.get("change_mask_enabled", True)):
92
+ return super()._cosmos25_future_image_loss(examples)
93
+
94
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
95
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
96
+ instructions = [example["lang"] for example in examples]
97
+
98
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
99
+ if train_obs_image_size:
100
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
101
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
102
+
103
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
104
+ batch_images=batch_images,
105
+ future_images=future_images,
106
+ )
107
+
108
+ prompt_embeds = self.backbone._encode_text(instructions)
109
+ clean_latents, _, _ = self.backbone._encode_images(raw_sequences)
110
+ dtype = self.backbone.transformer.dtype
111
+ clean_latents = clean_latents.to(dtype)
112
+ batch_size, channels, num_latents, height, width = clean_latents.shape
113
+ device = clean_latents.device
114
+
115
+ condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width))
116
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
117
+ cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
118
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
119
+ condition_count = max(1, min(int(condition_count), num_latents))
120
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
121
+ condition_mask[batch_idx, :, :condition_count] = 1.0
122
+ cond_indicator[batch_idx, :, :condition_count] = 1.0
123
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
124
+
125
+ change_binary, change_loss_weight = self._build_latent_change_masks(
126
+ batch_images=batch_images,
127
+ future_images=future_images,
128
+ latent_height=height,
129
+ latent_width=width,
130
+ training_cfg=training_cfg,
131
+ device=device,
132
+ )
133
+ change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype)
134
+ change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32)
135
+
136
+ train_time = self._sample_train_times(
137
+ batch_size=batch_size,
138
+ device=device,
139
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
140
+ )
141
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
142
+ target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype)
143
+
144
+ noise = torch.randn_like(clean_latents)
145
+ noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time
146
+ target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width)
147
+
148
+ use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", True))
149
+ use_static_conditioning = use_masked_denoising and self._as_bool(
150
+ training_cfg.get("condition_static_regions", True)
151
+ )
152
+
153
+ if use_masked_denoising:
154
+ denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) * change_binary
155
+ else:
156
+ denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype)
157
+ hidden_states = torch.where(denoise_mask.to(dtype=torch.bool), noisy_latents, clean_latents)
158
+ target_velocity = noise.float() - clean_latents.float()
159
+
160
+ if use_static_conditioning:
161
+ static_target_mask = target_spatial_mask.to(dtype=clean_latents.dtype) * (1.0 - change_binary)
162
+ condition_mask = torch.maximum(condition_mask, static_target_mask)
163
+
164
+ cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1))
165
+ timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1))
166
+ timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep
167
+ timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep)
168
+
169
+ padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16))
170
+ padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16))
171
+ padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype)
172
+
173
+ if hasattr(self.backbone, "_intermediate_features"):
174
+ self.backbone._intermediate_features.clear()
175
+ with torch.autocast("cuda", dtype=torch.bfloat16):
176
+ pred = self.backbone.transformer(
177
+ hidden_states=hidden_states,
178
+ timestep=timestep,
179
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
180
+ condition_mask=condition_mask.to(dtype),
181
+ padding_mask=padding_mask,
182
+ return_dict=False,
183
+ )
184
+ pred = pred[0] if isinstance(pred, tuple) else pred
185
+ pred = pred.sample if hasattr(pred, "sample") else pred
186
+ if hasattr(self.backbone, "_intermediate_features"):
187
+ self.backbone._intermediate_features.clear()
188
+
189
+ temporal_loss_mask = target_spatial_mask.expand(batch_size, channels, num_latents, height, width)
190
+ if use_static_conditioning:
191
+ change_loss_weight = change_loss_weight * change_binary.float()
192
+ spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width)
193
+ spatial_loss_weight = spatial_loss_weight.expand(batch_size, channels, num_latents, height, width)
194
+ loss_mask = temporal_loss_mask * spatial_loss_weight
195
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
196
+ return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PolicyNative-checkpoint.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Native Cosmos-Predict2.5 Policy backend.
5
+
6
+ This wrapper intentionally does not use the diffusers Cosmos pipeline. It
7
+ loads NVIDIA's native Cosmos Policy implementation and adapts starVLA batches
8
+ to the official ``CosmosPolicyVideo2WorldModelRectifiedFlow`` data_batch
9
+ format. The policy model, scheduler, tokenizer/VAE, latent injection, and
10
+ loss computation are therefore owned by the official code.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import pickle
17
+ import sys
18
+ import traceback
19
+ import types
20
+ import importlib
21
+ import importlib.metadata
22
+ from dataclasses import dataclass, field
23
+ from typing import Dict, List, Optional
24
+
25
+ import numpy as np
26
+ import torch
27
+ from PIL import Image
28
+
29
+ from starVLA.model.framework.base_framework import baseframework
30
+ from starVLA.model.framework.share_tools import merge_framework_config
31
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
32
+
33
+
34
+ @dataclass
35
+ class CosmoPredict25PolicyNativeDefaultConfig:
36
+ name: str = "CosmoPredict25PolicyNative"
37
+
38
+ world_model: dict = field(default_factory=lambda: {
39
+ # Native checkpoint path, not a diffusers folder.
40
+ "base_wm": "",
41
+ })
42
+
43
+ qwenvl: dict = field(default_factory=lambda: {
44
+ "base_vlm": "",
45
+ "vl_hidden_dim": 2048,
46
+ })
47
+
48
+ action_model: dict = field(default_factory=lambda: {
49
+ "action_dim": 7,
50
+ "state_dim": 7,
51
+ "future_action_window_size": 15,
52
+ "action_horizon": 16,
53
+ "past_action_window_size": 0,
54
+ })
55
+
56
+ policy: dict = field(default_factory=lambda: {
57
+ "native_repo_path": "",
58
+ "config_file": "cosmos_predict2/_src/predict2/cosmos_policy/config/config.py",
59
+ "experiment": "cosmos_predict2p5_2b_480p_robocasa_50_demos_per_task_no_s3",
60
+ "text_embeddings_path": "",
61
+ "text_embeddings_kind": "reason1",
62
+ "use_online_text_encoder": True,
63
+ "text_encoder_ckpt_path": "",
64
+ "height": 224,
65
+ "width": 224,
66
+ "shift": 5.0,
67
+ "num_inference_steps": 5,
68
+ # starVLA currently trains demos, so only supervise action + future
69
+ # primary image instead of blank unused future/value slots.
70
+ "mask_policy_loss": True,
71
+ "action_loss_multiplier": 16,
72
+ "load_ema_to_reg": True,
73
+ "instantiate_ema": False,
74
+ "skip_native_package_init": True,
75
+ })
76
+
77
+ obs_image_size: Optional[list] = None
78
+
79
+
80
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25PolicyNative")
81
+ class CosmoPredict25_Policy_Native(baseframework):
82
+ """Adapter around NVIDIA's native Cosmos-Predict2.5 policy model."""
83
+
84
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
85
+ super().__init__()
86
+ self.config = merge_framework_config(CosmoPredict25PolicyNativeDefaultConfig, config)
87
+ self.policy_cfg = self.config.framework.get("policy", {})
88
+
89
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
90
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
91
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
92
+ self.action_dim = self.config.framework.action_model.action_dim
93
+ self.state_dim = self.config.framework.action_model.get("state_dim", self.action_dim)
94
+
95
+ self.height = int(self.policy_cfg.get("height", 224))
96
+ self.width = int(self.policy_cfg.get("width", 224))
97
+ self.shift = float(self.policy_cfg.get("shift", 5.0))
98
+ self.num_inference_steps = int(self.policy_cfg.get("num_inference_steps", 5))
99
+
100
+ self._add_native_repo_to_path()
101
+ self.native_model, self.native_config = self._load_native_model()
102
+ self._configure_native_policy_loss()
103
+ self._freeze_native_non_policy_modules()
104
+ self._use_online_text_encoder = bool(self.policy_cfg.get("use_online_text_encoder", True))
105
+ self._text_embedding_cache = {} if self._use_online_text_encoder else self._load_text_embedding_cache()
106
+ self._iteration = 0
107
+
108
+ def _add_native_repo_to_path(self) -> None:
109
+ repo_path = self.policy_cfg.get("native_repo_path") or os.getenv("COSMOS_PREDICT25_REPO", "")
110
+ if repo_path:
111
+ repo_path = os.path.abspath(os.path.expanduser(repo_path))
112
+ if bool(self.policy_cfg.get("skip_native_package_init", True)):
113
+ self._install_cosmos_predict2_package_shim(repo_path)
114
+ self._install_optional_dependency_shims()
115
+ packages_root = os.path.join(repo_path, "packages")
116
+ package_paths = []
117
+ if os.path.isdir(packages_root):
118
+ package_paths = [
119
+ os.path.join(packages_root, name)
120
+ for name in sorted(os.listdir(packages_root))
121
+ if os.path.isdir(os.path.join(packages_root, name))
122
+ ]
123
+ extra_paths = [repo_path, *package_paths]
124
+ for extra_path in reversed(extra_paths):
125
+ if os.path.isdir(extra_path) and extra_path not in sys.path:
126
+ sys.path.insert(0, extra_path)
127
+
128
+ @staticmethod
129
+ def _install_cosmos_predict2_package_shim(repo_path: str) -> None:
130
+ """Expose cosmos_predict2 submodules without running its top-level check."""
131
+ package_root = os.path.join(repo_path, "cosmos_predict2")
132
+ if not os.path.isdir(package_root):
133
+ return
134
+ existing = sys.modules.get("cosmos_predict2")
135
+ if existing is not None and getattr(existing, "__file__", None):
136
+ return
137
+
138
+ module = types.ModuleType("cosmos_predict2")
139
+ module.__path__ = [package_root]
140
+ module.__package__ = "cosmos_predict2"
141
+ module.__file__ = os.path.join(package_root, "__init__.py")
142
+ module.__version__ = "1.5.0"
143
+
144
+ about_path = os.path.join(package_root, "__about__.py")
145
+ if os.path.exists(about_path):
146
+ namespace = {}
147
+ with open(about_path, "r", encoding="utf-8") as f:
148
+ exec(compile(f.read(), about_path, "exec"), namespace)
149
+ module.__version__ = namespace.get("__version__", module.__version__)
150
+
151
+ sys.modules["cosmos_predict2"] = module
152
+
153
+ @staticmethod
154
+ def _install_optional_dependency_shims() -> None:
155
+ """Let local-only official config imports pass without S3 packages."""
156
+ if "boto3" not in sys.modules:
157
+ boto3_module = types.ModuleType("boto3")
158
+
159
+ def _missing_boto3(*args, **kwargs):
160
+ raise RuntimeError("boto3 is not installed; S3 access is disabled in CosmoPredict25PolicyNative.")
161
+
162
+ boto3_module.client = _missing_boto3
163
+ boto3_module.Session = _missing_boto3
164
+ sys.modules["boto3"] = boto3_module
165
+
166
+ if "botocore" not in sys.modules:
167
+ botocore_module = types.ModuleType("botocore")
168
+ sys.modules["botocore"] = botocore_module
169
+
170
+ if "botocore.config" not in sys.modules:
171
+ config_module = types.ModuleType("botocore.config")
172
+
173
+ class Config:
174
+ def __init__(self, *args, **kwargs):
175
+ self.args = args
176
+ self.kwargs = kwargs
177
+
178
+ config_module.Config = Config
179
+ sys.modules["botocore.config"] = config_module
180
+
181
+ if "botocore.exceptions" not in sys.modules:
182
+ exceptions_module = types.ModuleType("botocore.exceptions")
183
+
184
+ class ClientError(Exception):
185
+ pass
186
+
187
+ exceptions_module.ClientError = ClientError
188
+ sys.modules["botocore.exceptions"] = exceptions_module
189
+
190
+ if "multistorageclient" not in sys.modules:
191
+ msc_module = types.ModuleType("multistorageclient")
192
+
193
+ class StorageClient:
194
+ def __init__(self, *args, **kwargs):
195
+ raise RuntimeError(
196
+ "multistorageclient is not installed; MSC/S3 access is disabled in "
197
+ "CosmoPredict25PolicyNative."
198
+ )
199
+
200
+ class StorageClientConfig:
201
+ @staticmethod
202
+ def read_msc_config(*args, **kwargs):
203
+ raise RuntimeError(
204
+ "multistorageclient is not installed; MSC/S3 access is disabled in "
205
+ "CosmoPredict25PolicyNative."
206
+ )
207
+
208
+ @staticmethod
209
+ def from_dict(*args, **kwargs):
210
+ return None
211
+
212
+ msc_module.StorageClient = StorageClient
213
+ msc_module.StorageClientConfig = StorageClientConfig
214
+ sys.modules["multistorageclient"] = msc_module
215
+
216
+ if "multistorageclient.types" not in sys.modules:
217
+ msc_types_module = types.ModuleType("multistorageclient.types")
218
+
219
+ class Range:
220
+ def __init__(self, *args, **kwargs):
221
+ self.args = args
222
+ self.kwargs = kwargs
223
+
224
+ msc_types_module.Range = Range
225
+ sys.modules["multistorageclient.types"] = msc_types_module
226
+
227
+ if "transformer_engine" not in sys.modules:
228
+ te_module = types.ModuleType("transformer_engine")
229
+ te_pytorch_module = types.ModuleType("transformer_engine.pytorch")
230
+ te_attention_module = types.ModuleType("transformer_engine.pytorch.attention")
231
+ te_rope_module = types.ModuleType("transformer_engine.pytorch.attention.rope")
232
+ te_optimizers_module = types.ModuleType("transformer_engine.pytorch.optimizers")
233
+
234
+ class RMSNorm(torch.nn.Module):
235
+ def __init__(self, hidden_size, eps=1e-5, **kwargs):
236
+ super().__init__()
237
+ self.eps = eps
238
+ self.weight = torch.nn.Parameter(torch.ones(hidden_size))
239
+
240
+ def reset_parameters(self):
241
+ torch.nn.init.ones_(self.weight)
242
+
243
+ def forward(self, x):
244
+ out = x.float() * torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) + self.eps)
245
+ return out.to(dtype=x.dtype) * self.weight
246
+
247
+ def _rotate_half(x):
248
+ x1, x2 = x.chunk(2, dim=-1)
249
+ return torch.cat((-x2, x1), dim=-1)
250
+
251
+ def apply_rotary_pos_emb(x, rope_emb, tensor_format="bshd", fused=True):
252
+ del tensor_format, fused
253
+ if rope_emb is None:
254
+ return x
255
+ cos = rope_emb.cos().to(device=x.device, dtype=x.dtype)
256
+ sin = rope_emb.sin().to(device=x.device, dtype=x.dtype)
257
+ while cos.dim() < x.dim():
258
+ cos = cos.unsqueeze(0)
259
+ sin = sin.unsqueeze(0)
260
+ return (x * cos) + (_rotate_half(x) * sin)
261
+
262
+ class DotProductAttention(torch.nn.Module):
263
+ def __init__(self, *args, **kwargs):
264
+ super().__init__()
265
+
266
+ def set_context_parallel_group(self, *args, **kwargs):
267
+ return None
268
+
269
+ def forward(self, q, k, v, *args, **kwargs):
270
+ del args, kwargs
271
+ q_bhsd = q.permute(0, 2, 1, 3)
272
+ k_bhsd = k.permute(0, 2, 1, 3)
273
+ v_bhsd = v.permute(0, 2, 1, 3)
274
+ out = torch.nn.functional.scaled_dot_product_attention(q_bhsd, k_bhsd, v_bhsd)
275
+ out = out.permute(0, 2, 1, 3).contiguous()
276
+ return out.flatten(start_dim=2)
277
+
278
+ def _missing_multi_tensor_applier(*args, **kwargs):
279
+ raise RuntimeError(
280
+ "transformer_engine is not installed; official FusedAdam is unavailable. "
281
+ "Use the starVLA optimizer path instead."
282
+ )
283
+
284
+ te_pytorch_module.RMSNorm = RMSNorm
285
+ te_attention_module.DotProductAttention = DotProductAttention
286
+ te_attention_module.apply_rotary_pos_emb = apply_rotary_pos_emb
287
+ te_rope_module.apply_rotary_pos_emb = apply_rotary_pos_emb
288
+ te_optimizers_module.multi_tensor_applier = _missing_multi_tensor_applier
289
+ te_pytorch_module.attention = te_attention_module
290
+ te_pytorch_module.optimizers = te_optimizers_module
291
+ te_module.pytorch = te_pytorch_module
292
+ sys.modules["transformer_engine"] = te_module
293
+ sys.modules["transformer_engine.pytorch"] = te_pytorch_module
294
+ sys.modules["transformer_engine.pytorch.attention"] = te_attention_module
295
+ sys.modules["transformer_engine.pytorch.attention.rope"] = te_rope_module
296
+ sys.modules["transformer_engine.pytorch.optimizers"] = te_optimizers_module
297
+
298
+ if "transformer_engine_torch" not in sys.modules:
299
+ tex_module = types.ModuleType("transformer_engine_torch")
300
+
301
+ def _missing_transformer_engine_torch(*args, **kwargs):
302
+ raise RuntimeError(
303
+ "transformer_engine_torch is not installed; official FusedAdam is unavailable."
304
+ )
305
+
306
+ tex_module.multi_tensor_adam = _missing_transformer_engine_torch
307
+ tex_module.multi_tensor_adam_capturable = _missing_transformer_engine_torch
308
+ tex_module.multi_tensor_adam_capturable_master = _missing_transformer_engine_torch
309
+ sys.modules["transformer_engine_torch"] = tex_module
310
+
311
+ try:
312
+ from transformers import cache_utils as transformers_cache_utils
313
+
314
+ if not hasattr(transformers_cache_utils, "SlidingWindowCache"):
315
+ class SlidingWindowCache(transformers_cache_utils.DynamicCache):
316
+ pass
317
+
318
+ transformers_cache_utils.SlidingWindowCache = SlidingWindowCache
319
+ except Exception:
320
+ pass
321
+
322
+ if "megatron" not in sys.modules:
323
+ sys.modules["megatron"] = types.ModuleType("megatron")
324
+ if "megatron.core" not in sys.modules:
325
+ core_module = types.ModuleType("megatron.core")
326
+ sys.modules["megatron.core"] = core_module
327
+ else:
328
+ core_module = sys.modules["megatron.core"]
329
+ sys.modules["megatron"].core = core_module
330
+
331
+ if not hasattr(core_module, "ModelParallelConfig"):
332
+ try:
333
+ import attrs as _attrs
334
+
335
+ @_attrs.define(slots=False)
336
+ class ModelParallelConfig:
337
+ tensor_model_parallel_size: int = 1
338
+ pipeline_model_parallel_size: int = 1
339
+ context_parallel_size: int = 1
340
+ expert_model_parallel_size: int = 1
341
+ sequence_parallel: bool = False
342
+
343
+ except Exception:
344
+ @dataclass
345
+ class ModelParallelConfig:
346
+ tensor_model_parallel_size: int = 1
347
+ pipeline_model_parallel_size: int = 1
348
+ context_parallel_size: int = 1
349
+ expert_model_parallel_size: int = 1
350
+ sequence_parallel: bool = False
351
+
352
+ core_module.ModelParallelConfig = ModelParallelConfig
353
+
354
+ if "megatron.core.parallel_state" not in sys.modules:
355
+ parallel_state_module = types.ModuleType("megatron.core.parallel_state")
356
+
357
+ class _SingleProcessGroup:
358
+ def size(self):
359
+ return 1
360
+
361
+ def rank(self):
362
+ return 0
363
+
364
+ _group = _SingleProcessGroup()
365
+ parallel_state_module.sequence_parallel = False
366
+ parallel_state_module.cp_size_t = 1
367
+ parallel_state_module.is_initialized = lambda: False
368
+ parallel_state_module.initialize_model_parallel = lambda *args, **kwargs: None
369
+ parallel_state_module.destroy_model_parallel = lambda *args, **kwargs: None
370
+ parallel_state_module.get_data_parallel_world_size = lambda *args, **kwargs: 1
371
+ parallel_state_module.get_data_parallel_rank = lambda *args, **kwargs: 0
372
+ parallel_state_module.get_context_parallel_world_size = lambda *args, **kwargs: 1
373
+ parallel_state_module.get_context_parallel_rank = lambda *args, **kwargs: 0
374
+ parallel_state_module.get_context_parallel_group = lambda *args, **kwargs: None
375
+ parallel_state_module.get_tensor_model_parallel_world_size = lambda *args, **kwargs: 1
376
+ parallel_state_module.get_tensor_model_parallel_rank = lambda *args, **kwargs: 0
377
+ parallel_state_module.get_pipeline_model_parallel_world_size = lambda *args, **kwargs: 1
378
+ parallel_state_module.get_pipeline_model_parallel_rank = lambda *args, **kwargs: 0
379
+ parallel_state_module.get_expert_model_parallel_world_size = lambda *args, **kwargs: 1
380
+ parallel_state_module.get_model_parallel_group = lambda *args, **kwargs: _group
381
+ parallel_state_module.get_data_parallel_group = lambda *args, **kwargs: None
382
+ sys.modules["megatron.core.parallel_state"] = parallel_state_module
383
+ core_module.parallel_state = parallel_state_module
384
+ else:
385
+ core_module.parallel_state = sys.modules["megatron.core.parallel_state"]
386
+
387
+ def _load_native_model(self):
388
+ try:
389
+ from cosmos_predict2._src.imaginaire.lazy_config import instantiate
390
+ from cosmos_predict2._src.imaginaire.utils.config_helper import get_config_module, override
391
+ except ImportError as exc:
392
+ raise ImportError(
393
+ "Failed to import the minimal NVIDIA cosmos-predict2.5 config/model helpers. "
394
+ "This can mean framework.policy.native_repo_path is wrong, or one of the native repo "
395
+ "dependencies is missing from the current Python environment. "
396
+ f"native_repo_path={self.policy_cfg.get('native_repo_path')!r}, "
397
+ f"COSMOS_PREDICT25_REPO={os.getenv('COSMOS_PREDICT25_REPO')!r}. "
398
+ f"Original ImportError: {exc!r}\n{traceback.format_exc()}"
399
+ ) from exc
400
+
401
+ checkpoint_path = (
402
+ self.policy_cfg.get("checkpoint_path")
403
+ or self.config.framework.world_model.get("base_wm")
404
+ or self.config.framework.qwenvl.get("base_vlm")
405
+ )
406
+ if not checkpoint_path:
407
+ raise ValueError(
408
+ "CosmoPredict25PolicyNative needs a native Cosmos checkpoint path in "
409
+ "framework.world_model.base_wm or framework.policy.checkpoint_path."
410
+ )
411
+
412
+ use_online_text_encoder = bool(self.policy_cfg.get("use_online_text_encoder", True))
413
+ if use_online_text_encoder:
414
+ transformers_version = importlib.metadata.version("transformers")
415
+ if transformers_version != "4.51.3":
416
+ raise ValueError(
417
+ "Online Reason1 must run with transformers==4.51.3 to match the official "
418
+ f"cosmos-predict2.5 lockfile, but the current environment has transformers=={transformers_version}. "
419
+ "Please switch/pin the training environment before online Reason1 training."
420
+ )
421
+ text_encoder_ckpt_path = self.policy_cfg.get("text_encoder_ckpt_path", "")
422
+ if not text_encoder_ckpt_path:
423
+ raise ValueError(
424
+ "Online Reason1 requires framework.policy.text_encoder_ckpt_path to point to a local "
425
+ "Reason1 checkpoint. The official default is an internal S3 path, which this wrapper "
426
+ "does not use."
427
+ )
428
+ if not os.path.exists(os.path.abspath(os.path.expanduser(text_encoder_ckpt_path))):
429
+ raise FileNotFoundError(
430
+ "framework.policy.text_encoder_ckpt_path does not exist: "
431
+ f"{text_encoder_ckpt_path!r}"
432
+ )
433
+
434
+ experiment_opts = list(self.policy_cfg.get("experiment_opts", []))
435
+ experiment_opts.extend([
436
+ "model.config.fsdp_shard_size=1",
437
+ "model.config.ema.enabled=false",
438
+ "model.config.net.atten_backend=torch",
439
+ f"model.config.action_loss_multiplier={int(self.policy_cfg.get('action_loss_multiplier', 16))}",
440
+ ])
441
+ if bool(self.policy_cfg.get("mask_policy_loss", True)):
442
+ experiment_opts.append("model.config.mask_value_prediction_loss_for_policy_prediction=true")
443
+
444
+ config_module = get_config_module(self.policy_cfg.get("config_file"))
445
+ native_config = importlib.import_module(config_module).make_config()
446
+ native_config = override(
447
+ native_config,
448
+ ["--", f"experiment={self.policy_cfg.get('experiment')}", *experiment_opts],
449
+ )
450
+ if use_online_text_encoder:
451
+ text_encoder_ckpt_path = self.policy_cfg.get("text_encoder_ckpt_path", "")
452
+ from cosmos_predict2._src.predict2.text_encoders.text_encoder import TextEncoderConfig
453
+
454
+ text_encoder_config = TextEncoderConfig(
455
+ compute_online=True,
456
+ ckpt_path=os.path.abspath(os.path.expanduser(text_encoder_ckpt_path)),
457
+ )
458
+ native_config.model.config.text_encoder_class = "reason1p1_7B"
459
+ native_config.model.config.text_encoder_config = text_encoder_config
460
+
461
+ model = instantiate(native_config.model)
462
+ if hasattr(model, "on_train_start"):
463
+ model.on_train_start()
464
+ if torch.cuda.is_available():
465
+ model = model.cuda()
466
+ self._load_local_checkpoint(model, checkpoint_path)
467
+ return model, native_config
468
+
469
+ @staticmethod
470
+ def _candidate_checkpoint_files(checkpoint_path: str) -> List[str]:
471
+ if os.path.isfile(checkpoint_path):
472
+ return [checkpoint_path]
473
+ candidates = [
474
+ os.path.join(checkpoint_path, "model.pt"),
475
+ os.path.join(checkpoint_path, "model.pth"),
476
+ os.path.join(checkpoint_path, "pytorch_model.pt"),
477
+ os.path.join(checkpoint_path, "pytorch_model.bin"),
478
+ ]
479
+ base_dir = os.path.join(checkpoint_path, "base", "pre-trained")
480
+ candidates.extend([
481
+ os.path.join(base_dir, "model.pt"),
482
+ os.path.join(base_dir, "model.pth"),
483
+ os.path.join(base_dir, "pytorch_model.pt"),
484
+ ])
485
+ return [path for path in candidates if os.path.isfile(path)]
486
+
487
+ def _load_local_checkpoint(self, model, checkpoint_path: str) -> None:
488
+ checkpoint_files = self._candidate_checkpoint_files(os.path.expanduser(checkpoint_path))
489
+ if not checkpoint_files:
490
+ raise FileNotFoundError(
491
+ "CosmoPredict25PolicyNative now uses a minimal local torch.load checkpoint path "
492
+ "and does not import NVIDIA model_loader/easy_io/boto3. Please point "
493
+ "framework.policy.checkpoint_path or framework.world_model.base_wm to a local .pt/.pth file. "
494
+ f"No supported checkpoint file found under: {checkpoint_path}"
495
+ )
496
+
497
+ state = torch.load(checkpoint_files[0], map_location="cpu")
498
+ if isinstance(state, dict) and "model" in state:
499
+ state = state["model"]
500
+ elif isinstance(state, dict) and "state_dict" in state:
501
+ state = state["state_dict"]
502
+ load_info = model.load_state_dict(state, strict=False)
503
+ if load_info is not None and (load_info.missing_keys or load_info.unexpected_keys):
504
+ print(
505
+ "[CosmoPredict25PolicyNative] checkpoint loaded with "
506
+ f"{len(load_info.missing_keys)} missing keys and "
507
+ f"{len(load_info.unexpected_keys)} unexpected keys. "
508
+ f"First missing={load_info.missing_keys[:5]}, "
509
+ f"first unexpected={load_info.unexpected_keys[:5]}",
510
+ flush=True,
511
+ )
512
+
513
+ def _configure_native_policy_loss(self) -> None:
514
+ if bool(self.policy_cfg.get("mask_policy_loss", True)):
515
+ self.native_model.config.mask_value_prediction_loss_for_policy_prediction = True
516
+ self.native_model.config.action_loss_multiplier = int(self.policy_cfg.get("action_loss_multiplier", 16))
517
+
518
+ def _freeze_native_non_policy_modules(self) -> None:
519
+ for module_name in ("tokenizer", "text_encoder"):
520
+ module = getattr(self.native_model, module_name, None)
521
+ if module is not None and hasattr(module, "requires_grad_"):
522
+ module.requires_grad_(False)
523
+
524
+ def _load_text_embedding_cache(self) -> Dict[str, torch.Tensor]:
525
+ path = self.policy_cfg.get("text_embeddings_path", "")
526
+ if not path:
527
+ return {}
528
+ path = os.path.abspath(os.path.expanduser(path))
529
+ with open(path, "rb") as f:
530
+ return pickle.load(f)
531
+
532
+ @staticmethod
533
+ def _as_image_list(images) -> List:
534
+ return list(images) if isinstance(images, (list, tuple)) else [images]
535
+
536
+ @staticmethod
537
+ def _blank_like(image):
538
+ if isinstance(image, Image.Image):
539
+ return Image.new(image.mode, image.size)
540
+ image_array = np.asarray(image)
541
+ return np.zeros_like(image_array)
542
+
543
+ @staticmethod
544
+ def _to_uint8_array(image) -> np.ndarray:
545
+ if isinstance(image, Image.Image):
546
+ return np.asarray(image.convert("RGB"))
547
+ if torch.is_tensor(image):
548
+ array = image.detach().cpu().numpy()
549
+ else:
550
+ array = np.asarray(image)
551
+ if array.ndim == 3 and array.shape[0] in (1, 3) and array.shape[-1] not in (1, 3):
552
+ array = np.transpose(array, (1, 2, 0))
553
+ if array.dtype != np.uint8:
554
+ if array.max() <= 1.0 and array.min() >= 0.0:
555
+ array = array * 255.0
556
+ elif array.min() >= -1.0 and array.max() <= 1.0:
557
+ array = (array + 1.0) * 127.5
558
+ array = np.clip(array, 0, 255).astype(np.uint8)
559
+ if array.ndim == 2:
560
+ array = np.repeat(array[..., None], 3, axis=-1)
561
+ if array.shape[-1] == 1:
562
+ array = np.repeat(array, 3, axis=-1)
563
+ return array[..., :3]
564
+
565
+ def _resize_uint8(self, image) -> np.ndarray:
566
+ array = self._to_uint8_array(image)
567
+ pil = Image.fromarray(array)
568
+ pil = pil.resize((self.width, self.height), Image.BILINEAR)
569
+ return np.asarray(pil, dtype=np.uint8)
570
+
571
+ def _split_policy_views(self, images: List, blank_image):
572
+ primary = images[0] if images else blank_image
573
+ wrist = images[1] if len(images) > 1 else blank_image
574
+ secondary = images[2] if len(images) > 2 else blank_image
575
+ return wrist, primary, secondary
576
+
577
+ def _build_video_frames(self, example: dict, include_future: bool) -> List[np.ndarray]:
578
+ temporal_factor = 4
579
+ current_images = self._as_image_list(example["image"])
580
+ future_images = self._as_image_list(example.get("future_image", current_images)) if include_future else []
581
+ blank_image = self._blank_like(current_images[0])
582
+
583
+ wrist, primary, secondary = self._split_policy_views(current_images, blank_image)
584
+ if future_images:
585
+ future_wrist, future_primary, future_secondary = self._split_policy_views(future_images, blank_image)
586
+ else:
587
+ future_wrist, future_primary, future_secondary = blank_image, blank_image, blank_image
588
+
589
+ slot_images = [
590
+ blank_image, # 0: special blank, not repeated
591
+ blank_image, # 1: current proprio placeholder
592
+ wrist, # 2: current wrist
593
+ primary, # 3: current primary
594
+ secondary, # 4: current secondary
595
+ blank_image, # 5: action placeholder
596
+ blank_image, # 6: future proprio placeholder
597
+ future_wrist, # 7: future wrist
598
+ future_primary, # 8: future primary
599
+ future_secondary, # 9: future secondary
600
+ blank_image, # 10: value placeholder
601
+ ]
602
+
603
+ frames = [self._resize_uint8(slot_images[0])]
604
+ for slot_image in slot_images[1:]:
605
+ resized = self._resize_uint8(slot_image)
606
+ frames.extend([resized] * temporal_factor)
607
+ return frames
608
+
609
+ def _stack_video(self, examples: List[dict], include_future: bool) -> torch.Tensor:
610
+ videos = []
611
+ for example in examples:
612
+ frames = np.stack(self._build_video_frames(example, include_future=include_future), axis=0)
613
+ videos.append(torch.from_numpy(frames).permute(3, 0, 1, 2).contiguous())
614
+ return torch.stack(videos, dim=0).to(dtype=torch.uint8)
615
+
616
+ def _select_action_chunk(self, actions) -> torch.Tensor:
617
+ actions = torch.tensor(np.array(actions), dtype=torch.float32)
618
+ return actions[:, -(self.future_action_window_size + 1):, :]
619
+
620
+ def _stack_state(self, examples: List[dict], key: str, device: torch.device) -> torch.Tensor:
621
+ if key in examples[0]:
622
+ return torch.tensor(np.array([example[key] for example in examples]), device=device, dtype=torch.float32)
623
+ return torch.zeros((len(examples), self.state_dim), device=device, dtype=torch.float32)
624
+
625
+ def _stack_text_embeddings(self, examples: List[dict], device: torch.device) -> torch.Tensor:
626
+ if self._use_online_text_encoder:
627
+ raise RuntimeError("_stack_text_embeddings should not be called when use_online_text_encoder=true.")
628
+ if "t5_text_embeddings" in examples[0]:
629
+ embeddings = [example["t5_text_embeddings"] for example in examples]
630
+ else:
631
+ embeddings = []
632
+ missing = []
633
+ for example in examples:
634
+ instruction = example.get("lang") or example.get("instruction") or example.get("ai_caption")
635
+ if instruction in self._text_embedding_cache:
636
+ embeddings.append(self._text_embedding_cache[instruction])
637
+ else:
638
+ missing.append(instruction)
639
+ if missing:
640
+ raise KeyError(
641
+ "CosmoPredict25PolicyNative needs official text embeddings. "
642
+ "Provide example['t5_text_embeddings'] or set framework.policy.text_embeddings_path. "
643
+ f"Missing instruction example: {missing[0]!r}"
644
+ )
645
+
646
+ tensors = []
647
+ for embedding in embeddings:
648
+ tensor = embedding if torch.is_tensor(embedding) else torch.as_tensor(embedding)
649
+ tensor = tensor.squeeze(0).to(device=device, dtype=torch.bfloat16)
650
+ tensors.append(tensor)
651
+ return torch.stack(tensors, dim=0)
652
+
653
+ def _make_native_batch(self, examples: List[dict], include_future: bool = True) -> dict:
654
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
655
+ batch_size = len(examples)
656
+
657
+ actions = self._select_action_chunk([example["action"] for example in examples]).to(device=device)
658
+ video = self._stack_video(examples, include_future=include_future)
659
+ proprio = self._stack_state(examples, "state", device=device)
660
+ future_proprio = self._stack_state(examples, "future_state", device=device)
661
+
662
+ captions = [
663
+ example.get("ai_caption") or example.get("lang") or example.get("instruction") or ""
664
+ for example in examples
665
+ ]
666
+ if self._use_online_text_encoder:
667
+ text_embeddings = None
668
+ text_mask = None
669
+ else:
670
+ text_embeddings = self._stack_text_embeddings(examples, device=device)
671
+ text_mask = torch.ones(
672
+ (batch_size, text_embeddings.shape[1]),
673
+ device=device,
674
+ dtype=torch.int64,
675
+ )
676
+
677
+ def full_idx(value: int) -> torch.Tensor:
678
+ return torch.full((batch_size,), value, device=device, dtype=torch.int64)
679
+
680
+ zeros = torch.zeros((batch_size,), device=device, dtype=torch.int64)
681
+ data_batch = {
682
+ "video": video,
683
+ "actions": actions,
684
+ "proprio": proprio,
685
+ "future_proprio": future_proprio,
686
+ "ai_caption": captions,
687
+ "num_conditional_frames": torch.tensor(5, device=device, dtype=torch.int64),
688
+ "current_proprio_latent_idx": full_idx(1) if "state" in examples[0] else full_idx(-1),
689
+ "action_latent_idx": full_idx(5),
690
+ "future_proprio_latent_idx": full_idx(-1),
691
+ "future_wrist_image_latent_idx": full_idx(-1),
692
+ "future_wrist_image2_latent_idx": full_idx(-1),
693
+ "future_image_latent_idx": full_idx(8) if include_future else full_idx(-1),
694
+ "future_image2_latent_idx": full_idx(-1),
695
+ "value_latent_idx": full_idx(10),
696
+ "rollout_data_mask": zeros.clone(),
697
+ "world_model_sample_mask": zeros.clone(),
698
+ "value_function_sample_mask": zeros.clone(),
699
+ "value_function_return": torch.zeros((batch_size,), device=device, dtype=torch.float32),
700
+ }
701
+ if not self._use_online_text_encoder:
702
+ data_batch["t5_text_embeddings"] = text_embeddings
703
+ data_batch["t5_text_mask"] = text_mask
704
+ return data_batch
705
+
706
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
707
+ data_batch = self._make_native_batch(examples, include_future=True)
708
+ output_batch, loss = self.native_model.training_step(data_batch, self._iteration)
709
+ self._iteration += 1
710
+
711
+ metrics = {"action_loss": loss}
712
+ for key in (
713
+ "demo_sample_action_mse_loss",
714
+ "demo_sample_action_l1_loss",
715
+ "demo_sample_future_image_mse_loss",
716
+ "demo_sample_future_image_l1_loss",
717
+ "velocity_mse_loss",
718
+ "edm_loss",
719
+ ):
720
+ value = output_batch.get(key)
721
+ if torch.is_tensor(value):
722
+ metrics[key] = value.detach()
723
+ return metrics
724
+
725
+ @torch.inference_mode()
726
+ def predict_action(self, examples: List[dict], **kwargs) -> dict:
727
+ from cosmos_predict2._src.predict2.cosmos_policy.experiments.robot.cosmos_utils import (
728
+ extract_action_chunk_from_latent_sequence,
729
+ )
730
+
731
+ data_batch = self._make_native_batch(examples, include_future=True)
732
+ batch_size = len(examples)
733
+ num_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps))
734
+ generated_latent = self.native_model.generate_samples_from_batch(
735
+ data_batch,
736
+ n_sample=batch_size,
737
+ num_steps=num_steps,
738
+ seed=int(kwargs.get("seed", 0)),
739
+ is_negative_prompt=False,
740
+ use_variance_scale=False,
741
+ return_orig_clean_latent_frames=False,
742
+ shift=float(kwargs.get("shift", self.shift)),
743
+ guidance=0,
744
+ )
745
+ action_indices = torch.full(
746
+ (batch_size,),
747
+ 5,
748
+ dtype=torch.int64,
749
+ device=generated_latent.device,
750
+ )
751
+ actions = extract_action_chunk_from_latent_sequence(
752
+ generated_latent,
753
+ action_shape=(self.future_action_window_size + 1, self.action_dim),
754
+ action_indices=action_indices,
755
+ )
756
+ return {"normalized_actions": actions.detach().float().cpu().numpy()}
starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict2Perceiver-checkpoint.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ CosmoPredict2-Perceiver Framework.
5
+
6
+ Uses Cosmos-Predict2 as the world-model backbone and the Perceiver-style
7
+ flow-matching action head for continuous action prediction.
8
+ """
9
+
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ _workspace_root = Path(__file__).parent.parent.parent.parent.parent
14
+ if str(_workspace_root) not in sys.path:
15
+ sys.path.insert(0, str(_workspace_root))
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import List, Optional, Tuple
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from deployment.model_server.tools.image_tools import to_pil_preserve
24
+ from starVLA.model.framework.base_framework import baseframework
25
+ from starVLA.model.framework.share_tools import merge_framework_config
26
+ from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model
27
+ from starVLA.model.modules.world_model import get_world_model
28
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
29
+ from starVLA.training.trainer_utils import initialize_overwatch
30
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
31
+
32
+ logger = initialize_overwatch(__name__)
33
+
34
+
35
+ @dataclass
36
+ class CosmoPredict2PerceiverDefaultConfig:
37
+ """CosmoPredict2-Perceiver default parameters."""
38
+
39
+ name: str = "CosmoPredict2Perceiver"
40
+
41
+ world_model: dict = field(default_factory=lambda: {
42
+ "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World",
43
+ "extract_layers": [-1],
44
+ })
45
+
46
+ # Kept for compatibility with shared utilities and action-head configs.
47
+ qwenvl: dict = field(default_factory=lambda: {
48
+ "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World",
49
+ "vl_hidden_dim": 2048,
50
+ })
51
+
52
+ action_model: dict = field(default_factory=lambda: {
53
+ "action_model_type": "DiT-B",
54
+ "action_hidden_dim": 1024,
55
+ "hidden_size": 1024,
56
+ "add_pos_embed": True,
57
+ "max_seq_len": 1024,
58
+ "action_dim": 7,
59
+ "state_dim": 7,
60
+ "future_action_window_size": 7,
61
+ "action_horizon": 8,
62
+ "past_action_window_size": 0,
63
+ "repeated_diffusion_steps": 8,
64
+ "noise_beta_alpha": 1.5,
65
+ "noise_beta_beta": 1.0,
66
+ "noise_s": 0.999,
67
+ "num_timestep_buckets": 1000,
68
+ "num_inference_timesteps": 4,
69
+ "num_target_vision_tokens": 32,
70
+ "max_num_embodiments": 32,
71
+ "use_category_specific": False,
72
+ "diffusion_model_cfg": {
73
+ "cross_attention_dim": 2048,
74
+ "dropout": 0.2,
75
+ "final_dropout": True,
76
+ "interleave_self_attention": True,
77
+ "norm_type": "ada_norm",
78
+ "num_layers": 16,
79
+ "output_dim": 1024,
80
+ "positional_embeddings": None,
81
+ },
82
+ })
83
+
84
+ obs_image_size: Optional[list] = None
85
+
86
+
87
+ @FRAMEWORK_REGISTRY.register("CosmoPredict2Perceiver")
88
+ class CosmoPredict2_Perceiver(baseframework):
89
+ """World-model-for-action framework using Cosmos-Predict2 + Perceiver head."""
90
+
91
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
92
+ super().__init__()
93
+ self.config = merge_framework_config(CosmoPredict2PerceiverDefaultConfig, config)
94
+
95
+ self.backbone = get_world_model(config=self.config)
96
+
97
+ wm_hidden = self.backbone.model.config.hidden_size
98
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
99
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
100
+
101
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
102
+
103
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
104
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
105
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
106
+
107
+ # 训练时
108
+ # action支路,self.backbone.build_inputs、self.backbone.forward()、self.action_model.forward()
109
+ def forward(self, examples: List[dict] = None, **kwargs) -> Tuple:
110
+ # print('################# CosmoPredict2_Perceiver.forward-1')
111
+
112
+ # 1. CosmosPredict:构建输入
113
+ batch_images = [example["image"] for example in examples]
114
+ instructions = [example["lang"] for example in examples]
115
+ # print(len(examples)) # 8
116
+
117
+ wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
118
+ # print(type(self.backbone)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface'>
119
+ # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input'])
120
+ # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28])
121
+ # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1])
122
+ # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352])
123
+ # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28])
124
+ # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224])
125
+ # print(wm_inputs['_is_wm_input']) # True
126
+
127
+ # 2. CosmosPredict:前向推理
128
+ # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens
129
+ with torch.autocast("cuda", dtype=torch.bfloat16):
130
+ wm_outputs = self.backbone(
131
+ **wm_inputs,
132
+ output_hidden_states=True,
133
+ return_dict=True,
134
+ )
135
+ last_hidden = wm_outputs.hidden_states[-1]
136
+ # print(type(wm_outputs)) # <class 'starVLA.model.modules.world_model.CosmoPredict25._CosmoPredict25_Interface.forward.<locals>._WMOutput'>
137
+ # print(last_hidden.shape) # torch.Size([8, 196, 2048])
138
+
139
+ # 3. ActionHead:构建输入
140
+ with torch.autocast("cuda", dtype=torch.float32):
141
+
142
+ # 3.1 初始化action
143
+ actions = [example["action"] for example in examples]
144
+ actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype)
145
+ # print(actions.shape) # torch.Size([8, 16, 32])
146
+ actions_target = actions[:, -(self.future_action_window_size + 1):, :]
147
+ # print(self.future_action_window_size) # 15
148
+ # print(actions_target.shape) # torch.Size([8, 16, 32])
149
+
150
+ # 3.2 重复降噪
151
+ # 将action和vl-tokens复制多次,重复多次降噪
152
+ repeated_diffusion_steps = (
153
+ self.config.trainer.get("repeated_diffusion_steps", 4)
154
+ if self.config and hasattr(self.config, "trainer")
155
+ else self.config.framework.action_model.get("repeated_diffusion_steps", 4)
156
+ )
157
+ # print(repeated_diffusion_steps) # 4
158
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
159
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
160
+ # print(actions_target_repeated.shape) # torch.Size([32, 16, 32])
161
+ # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048])
162
+
163
+ # 3.3 准备state、action_mask和embodiment_tag
164
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
165
+ if state is not None:
166
+ # print('state is not None')
167
+ state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype)
168
+ # print(state.shape) # torch.Size([8, 1, 64])
169
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
170
+ # print(state_repeated.shape) # torch.Size([32, 1, 64])
171
+ else:
172
+ state_repeated = None
173
+
174
+ action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None
175
+ if action_mask is not None:
176
+ # print('action_mask is not None')
177
+ action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype)
178
+ # print(action_mask_tensor.shape) # torch.Size([8, 16, 32])
179
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :]
180
+ # print(action_mask_target.shape) # torch.Size([8, 16, 32])
181
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
182
+ # print(action_mask_repeated.shape) # torch.Size([32, 16, 32])
183
+ else:
184
+ action_mask_repeated = None
185
+
186
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
187
+ if embodiment_tag is not None:
188
+ # print('embodiment_tag is not None')
189
+ embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64)
190
+ # print(embodiment_tag.shape) # torch.Size([8])
191
+ embodiment_tag = embodiment_tag.view(-1)
192
+ # print(embodiment_tag.shape) # torch.Size([8])
193
+ embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps)
194
+ # print(embodiment_tag_repeated.shape) # torch.Size([32])
195
+ else:
196
+ embodiment_tag_repeated = None
197
+
198
+ action_loss = self.action_model(
199
+ last_hidden_repeated,
200
+ actions_target_repeated,
201
+ state_repeated,
202
+ embodiment_tag_repeated,
203
+ action_mask=action_mask_repeated,
204
+ )
205
+ # print(type(self.action_model)) # <class 'starVLA.model.modules.action_model.PerceiverHead.FlowmatchingActionHead'>
206
+ # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048])
207
+ # print(actions_target_repeated.shape) # torch.Size([32, 16, 32])
208
+ # print(state_repeated.shape) # torch.Size([32, 1, 64])
209
+ # print(embodiment_tag_repeated.shape) # torch.Size([32])
210
+ # print(action_mask_repeated.shape) # torch.Size([32, 16, 32])
211
+ # print(action_loss) # tensor(1.5625, device='cuda:0', grad_fn=<DivBackward0>)
212
+
213
+ # print('################# CosmoPredict2_Perceiver.forward-2')
214
+ return {"action_loss": action_loss}
215
+
216
+ # @torch.inference_mode()
217
+ # def predict_action(self, examples: List[dict], **kwargs) -> dict:
218
+ # if type(examples) is not list:
219
+ # examples = [examples]
220
+
221
+ # batch_images = [to_pil_preserve(example["image"]) for example in examples]
222
+ # instructions = [example["lang"] for example in examples]
223
+ # state = [example["state"] for example in examples] if "state" in examples[0] else None
224
+ # embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
225
+
226
+ # train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
227
+ # if train_obs_image_size:
228
+ # batch_images = resize_images(batch_images, target_size=train_obs_image_size)
229
+
230
+ # wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions)
231
+ # with torch.autocast("cuda", dtype=torch.bfloat16):
232
+ # wm_outputs = self.backbone(
233
+ # **wm_inputs,
234
+ # output_hidden_states=True,
235
+ # return_dict=True,
236
+ # )
237
+ # last_hidden = wm_outputs.hidden_states[-1]
238
+
239
+ # state = (
240
+ # torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
241
+ # if state is not None
242
+ # else None
243
+ # )
244
+ # embodiment_tag = (
245
+ # torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
246
+ # if embodiment_tag is not None
247
+ # else None
248
+ # )
249
+ # if embodiment_tag is not None:
250
+ # embodiment_tag = embodiment_tag.view(-1)
251
+
252
+ # with torch.autocast("cuda", dtype=torch.float32):
253
+ # pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
254
+
255
+ # normalized_actions = pred_actions.detach().cpu().numpy()
256
+ # return {"normalized_actions": normalized_actions}
starVLA/model/framework/WM4A/.ipynb_checkpoints/JoyRA05MaskFutureImage-checkpoint.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """Wan2.2-TI2V Perceiver with masked future-image denoising."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from typing import List, Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+ from deployment.model_server.tools.image_tools import to_pil_preserve
16
+ from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import (
17
+ CosmoPredict25PerceiverFutureImageDefaultConfig,
18
+ )
19
+ from starVLA.model.framework.WM4A.CosmoPredict25PerceiverMaskedFutureImage import (
20
+ CosmoPredict25_Perceiver_MaskedFutureImage,
21
+ )
22
+ from starVLA.model.framework.base_framework import baseframework
23
+ from starVLA.model.framework.share_tools import merge_framework_config
24
+ from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model
25
+ from starVLA.model.modules.vlm import get_vlm_model
26
+ from starVLA.model.modules.world_model import get_world_model
27
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
28
+ from starVLA.training.trainer_utils.trainer_tools import resize_images
29
+
30
+
31
+ @dataclass
32
+ class JoyRA05MaskFutureImageDefaultConfig(CosmoPredict25PerceiverFutureImageDefaultConfig):
33
+ """Wan2.2-TI2V Perceiver + masked future-image defaults."""
34
+
35
+ name: str = "JoyRA05MaskFutureImage"
36
+
37
+ world_model: dict = field(default_factory=lambda: {
38
+ "base_wm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers",
39
+ "extract_layers": [-1],
40
+ "height": 224,
41
+ "width": 224,
42
+ "freeze_text_encoder": True,
43
+ "freeze_vae": True,
44
+ })
45
+
46
+ qwenvl: dict = field(default_factory=lambda: {
47
+ "base_vlm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers",
48
+ "vl_hidden_dim": 3072,
49
+ })
50
+
51
+ future_image_training: dict = field(default_factory=lambda: {
52
+ "enabled": True,
53
+ "loss_weight": 1.0,
54
+ "train_time_distribution": "logitnormal",
55
+ "shift": 5.0,
56
+ "timestep_scale": 1000.0,
57
+ "single_frame_condition_prob": 0.0,
58
+ "change_mask_enabled": True,
59
+ "change_mask_top_ratio": 0.25,
60
+ "change_mask_static_weight": 0.05,
61
+ "change_mask_soft_loss": True,
62
+ "masked_denoising": False,
63
+ "condition_static_regions": False,
64
+ })
65
+
66
+ future_image_generation: dict = field(default_factory=lambda: {
67
+ "enabled": True,
68
+ "num_frames": 81,
69
+ "num_inference_steps": 50,
70
+ "guidance_scale": 5.0,
71
+ "output_type": "pil",
72
+ "height": 224,
73
+ "width": 224,
74
+ "max_sequence_length": 512,
75
+ "conditioning_mode": "image",
76
+ "max_samples": 1,
77
+ "return_full_video": False,
78
+ "future_frame_index": -1,
79
+ "negative_prompt": None,
80
+ })
81
+
82
+
83
+ @FRAMEWORK_REGISTRY.register("JoyRA05MaskFutureImage")
84
+ class JoyRA05_MaskedFutureImage(CosmoPredict25_Perceiver_MaskedFutureImage):
85
+ """Perceiver action head plus Wan2.2 per-token masked flow matching."""
86
+
87
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
88
+ baseframework.__init__(self)
89
+ self.config = merge_framework_config(JoyRA05MaskFutureImageDefaultConfig, config)
90
+
91
+ self.qwen_vl_interface = get_vlm_model(config=self.config)
92
+ # 保持与历史 checkpoint 键名一致:主模块名使用 wan_interface.*
93
+ self.wan_interface = get_world_model(config=self.config)
94
+
95
+ qwen_hidden = self.qwen_vl_interface.model.config.hidden_size
96
+ wm_hidden = self.wan_interface.model.config.hidden_size
97
+ self.config.framework.qwenvl.vl_hidden_dim = qwen_hidden
98
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = qwen_hidden
99
+
100
+ wm_cfg = self.config.framework.get("world_model", {}) if self.config is not None else {}
101
+ self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False))
102
+ self.wm_projector = nn.Linear(wm_hidden, qwen_hidden)
103
+ self.wm_post_norm = nn.LayerNorm(qwen_hidden, eps=1e-6)
104
+ gain = float(wm_cfg.get("wm_projector_init_gain", 0.02))
105
+ nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain)
106
+ nn.init.zeros_(self.wm_projector.bias)
107
+
108
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
109
+
110
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
111
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
112
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size
113
+ self.state_dim = self.config.framework.action_model.get("state_dim", None)
114
+
115
+ qwenvl_cfg = self.config.framework.get("qwenvl", {}) if self.config is not None else {}
116
+ if self._as_bool(wm_cfg.get("freeze_text_encoder", True)) and hasattr(self.wan_interface, "text_encoder"):
117
+ for p in self.wan_interface.text_encoder.parameters():
118
+ p.requires_grad = False
119
+ if self._as_bool(wm_cfg.get("freeze_vae", True)) and hasattr(self.wan_interface, "vae"):
120
+ for p in self.wan_interface.vae.parameters():
121
+ p.requires_grad = False
122
+ if self._as_bool(qwenvl_cfg.get("is_frozen", True)):
123
+ for p in self.qwen_vl_interface.parameters():
124
+ p.requires_grad = False
125
+
126
+
127
+ def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor:
128
+ if self._pool_wm_sequence:
129
+ last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True)
130
+ wm_input = last_wm_hidden.to(dtype=self.wm_projector.weight.dtype)
131
+ wm_aligned = self.wm_post_norm(self.wm_projector(wm_input)).to(dtype=last_vlm_hidden.dtype)
132
+ return torch.cat([last_vlm_hidden, wm_aligned], dim=1)
133
+
134
+ def forward(self, examples: List[dict] = None, **kwargs) -> dict:
135
+ training_cfg = self._future_training_cfg()
136
+ examples, single_frame_ratio = self._maybe_apply_single_frame_condition(examples, training_cfg)
137
+
138
+ batch_images = [example["image"] for example in examples]
139
+ instructions = [example["lang"] for example in examples]
140
+ actions = [example["action"] for example in examples]
141
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
142
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
143
+ action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None
144
+
145
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
146
+ wm_inputs = self.wan_interface.build_inputs(images=batch_images, instructions=instructions)
147
+
148
+ with torch.autocast("cuda", dtype=torch.bfloat16):
149
+ wm_outputs = self.wan_interface(**wm_inputs, output_hidden_states=True, return_dict=True)
150
+ last_wm_hidden = wm_outputs.hidden_states[-1]
151
+ qwen_outputs = self.qwen_vl_interface(
152
+ **qwen_inputs,
153
+ output_attentions=False,
154
+ output_hidden_states=True,
155
+ return_dict=True,
156
+ )
157
+ last_vlm_hidden = qwen_outputs.hidden_states[-1]
158
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
159
+
160
+ with torch.autocast("cuda", dtype=torch.float32):
161
+ actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype)
162
+ actions_target = actions[:, -(self.future_action_window_size + 1):, :]
163
+ repeated_diffusion_steps = (
164
+ self.config.trainer.get("repeated_diffusion_steps", 4)
165
+ if self.config and hasattr(self.config, "trainer")
166
+ else self.config.framework.action_model.get("repeated_diffusion_steps", 4)
167
+ )
168
+ actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1)
169
+ last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1)
170
+
171
+ state_repeated = None
172
+ if state is not None:
173
+ state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype)
174
+ state = self._align_state_dim(state)
175
+ state_repeated = state.repeat(repeated_diffusion_steps, 1, 1)
176
+
177
+ action_mask_repeated = None
178
+ if action_mask is not None:
179
+ action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype)
180
+ action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :]
181
+ action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1)
182
+
183
+ embodiment_tag_repeated = None
184
+ if embodiment_tag is not None:
185
+ embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64).view(-1)
186
+ embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps)
187
+
188
+ action_loss = self.action_model(
189
+ last_hidden_repeated,
190
+ actions_target_repeated,
191
+ state_repeated,
192
+ embodiment_tag_repeated,
193
+ action_mask=action_mask_repeated,
194
+ )
195
+
196
+ output = {"action_loss": action_loss}
197
+ future_image_loss = self._cosmos25_future_image_loss(examples)
198
+ if future_image_loss is None:
199
+ if single_frame_ratio > 0.0:
200
+ output["single_frame_condition_ratio"] = single_frame_ratio
201
+ return output
202
+
203
+ loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0))
204
+ output["perceiver_action_loss"] = action_loss.detach()
205
+ output["future_image_loss"] = future_image_loss.detach()
206
+ if single_frame_ratio > 0.0:
207
+ output["single_frame_condition_ratio"] = single_frame_ratio
208
+ output["action_loss"] = action_loss + future_image_loss * loss_weight
209
+ return output
210
+
211
+ @torch.inference_mode()
212
+ def predict_action(self, examples: List[dict], **kwargs) -> dict:
213
+ if type(examples) is not list:
214
+ examples = [examples]
215
+
216
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
217
+ instructions = [example["lang"] for example in examples]
218
+ state = [example["state"] for example in examples] if "state" in examples[0] else None
219
+ embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None
220
+
221
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
222
+ if train_obs_image_size:
223
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
224
+
225
+ qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions)
226
+ wm_inputs = self.wan_interface.build_inputs(images=batch_images, instructions=instructions)
227
+
228
+ with torch.autocast("cuda", dtype=torch.bfloat16):
229
+ wm_outputs = self.wan_interface(
230
+ **wm_inputs,
231
+ output_hidden_states=True,
232
+ return_dict=True,
233
+ )
234
+ last_wm_hidden = wm_outputs.hidden_states[-1]
235
+
236
+ qwen_outputs = self.qwen_vl_interface(
237
+ **qwen_inputs,
238
+ output_attentions=False,
239
+ output_hidden_states=True,
240
+ return_dict=True,
241
+ )
242
+ last_vlm_hidden = qwen_outputs.hidden_states[-1]
243
+
244
+ last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden)
245
+
246
+ state = (
247
+ torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype)
248
+ if state is not None
249
+ else None
250
+ )
251
+ state = self._align_state_dim(state)
252
+ embodiment_tag = (
253
+ torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64)
254
+ if embodiment_tag is not None
255
+ else None
256
+ )
257
+ if embodiment_tag is not None:
258
+ embodiment_tag = embodiment_tag.view(-1)
259
+
260
+ with torch.autocast("cuda", dtype=torch.float32):
261
+ pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag)
262
+
263
+ output = {"normalized_actions": pred_actions.detach().cpu().numpy()}
264
+
265
+ generation_cfg = self._get_future_image_generation_cfg(kwargs)
266
+ if not bool(generation_cfg.pop("enabled", True)):
267
+ return output
268
+
269
+ return_full_video = bool(generation_cfg.pop("return_full_video", False))
270
+ future_frame_index = int(generation_cfg.pop("future_frame_index", -1))
271
+ max_samples = int(generation_cfg.pop("max_samples", 1))
272
+ generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg)
273
+ output["pred_future_images"] = self._generate_future_images(
274
+ generation_inputs,
275
+ batch_size=len(examples),
276
+ max_samples=max_samples,
277
+ future_frame_index=future_frame_index,
278
+ return_full_video=return_full_video,
279
+ )
280
+
281
+ return output
282
+
283
+ def _make_wan_timestep(
284
+ self,
285
+ hidden_states: torch.Tensor,
286
+ denoise_mask: torch.Tensor,
287
+ flow_time: torch.Tensor,
288
+ timestep_scale: float,
289
+ ) -> torch.Tensor:
290
+ """Convert the latent denoise mask into Wan's per-patch timestep tokens."""
291
+ batch_size, _, num_frames, height, width = hidden_states.shape
292
+ p_t, p_h, p_w = self.wan_interface.transformer.config.patch_size
293
+ if num_frames % p_t or height % p_h or width % p_w:
294
+ raise ValueError(
295
+ "Wan latent shape must be divisible by transformer.patch_size; "
296
+ f"got {(num_frames, height, width)} and {(p_t, p_h, p_w)}."
297
+ )
298
+
299
+ patch_mask = F.max_pool3d(
300
+ denoise_mask.float(),
301
+ kernel_size=(p_t, p_h, p_w),
302
+ stride=(p_t, p_h, p_w),
303
+ )
304
+ patch_mask = patch_mask[:, 0].flatten(1)
305
+ seq_len = patch_mask.shape[1]
306
+ rope_max_seq_len = getattr(self.wan_interface.transformer.config, "rope_max_seq_len", None)
307
+ if rope_max_seq_len is not None and seq_len > int(rope_max_seq_len):
308
+ raise ValueError(
309
+ f"Wan future-image seq_len={seq_len} exceeds rope_max_seq_len={rope_max_seq_len}. "
310
+ "Reduce observation frames or image resolution."
311
+ )
312
+
313
+ scaled_time = flow_time.to(device=hidden_states.device, dtype=torch.float32) * float(timestep_scale)
314
+ return patch_mask * scaled_time[:, None]
315
+
316
+ def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]:
317
+ """Compute masked Wan flow loss (method name retained for parent forward compatibility)."""
318
+ if "future_image" not in examples[0]:
319
+ return None
320
+
321
+ training_cfg = self._future_training_cfg()
322
+ if not self._as_bool(training_cfg.get("enabled", True)):
323
+ return None
324
+
325
+ batch_images = [to_pil_preserve(example["image"]) for example in examples]
326
+ future_images = [to_pil_preserve(example["future_image"]) for example in examples]
327
+ instructions = [example["lang"] for example in examples]
328
+
329
+ train_obs_image_size = getattr(self.config.framework, "obs_image_size", None)
330
+ if train_obs_image_size:
331
+ batch_images = resize_images(batch_images, target_size=train_obs_image_size)
332
+ future_images = resize_images(future_images, target_size=train_obs_image_size)
333
+
334
+ raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences(
335
+ batch_images=batch_images,
336
+ future_images=future_images,
337
+ )
338
+ prompt_embeds = self.wan_interface._encode_text(instructions)
339
+ clean_latents = self.wan_interface._encode_images_vae(raw_sequences)
340
+ dtype = self.wan_interface.transformer.dtype
341
+ clean_latents = clean_latents.to(dtype=dtype)
342
+ batch_size, channels, num_latents, height, width = clean_latents.shape
343
+ device = clean_latents.device
344
+
345
+ target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32)
346
+ for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)):
347
+ condition_count = max(1, min(int(condition_count), num_latents))
348
+ sample_count = min(max(condition_count + 1, int(sample_count)), num_latents)
349
+ target_mask[batch_idx, :, condition_count:sample_count] = 1.0
350
+ target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width)
351
+
352
+ use_change_mask = self._as_bool(training_cfg.get("change_mask_enabled", True))
353
+ if use_change_mask:
354
+ change_binary, change_loss_weight = self._build_latent_change_masks(
355
+ batch_images=batch_images,
356
+ future_images=future_images,
357
+ latent_height=height,
358
+ latent_width=width,
359
+ training_cfg=training_cfg,
360
+ device=device,
361
+ )
362
+ change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype)
363
+ change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32)
364
+ else:
365
+ change_binary = clean_latents.new_ones((batch_size, 1, 1, height, width))
366
+ change_loss_weight = clean_latents.new_ones(
367
+ (batch_size, 1, 1, height, width), dtype=torch.float32
368
+ )
369
+
370
+ train_time = self._sample_train_times(
371
+ batch_size=batch_size,
372
+ device=device,
373
+ distribution=training_cfg.get("train_time_distribution", "logitnormal"),
374
+ )
375
+ flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0)))
376
+ time_view = flow_time.view(batch_size, 1, 1, 1, 1).to(dtype=clean_latents.dtype)
377
+
378
+ noise = torch.randn_like(clean_latents)
379
+ noisy_latents = clean_latents * (1.0 - time_view) + noise * time_view
380
+ use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", False))
381
+ use_static_conditioning = use_masked_denoising and self._as_bool(
382
+ training_cfg.get("condition_static_regions", False)
383
+ )
384
+ denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype)
385
+ if use_masked_denoising:
386
+ denoise_mask = denoise_mask * change_binary
387
+ hidden_states = torch.where(denoise_mask.bool(), noisy_latents, clean_latents)
388
+ target_velocity = noise.float() - clean_latents.float()
389
+
390
+ timestep_mask = denoise_mask if use_static_conditioning else target_spatial_mask
391
+ timestep = self._make_wan_timestep(
392
+ hidden_states=hidden_states,
393
+ denoise_mask=timestep_mask,
394
+ flow_time=flow_time,
395
+ timestep_scale=float(training_cfg.get("timestep_scale", 1000.0)),
396
+ )
397
+
398
+ if hasattr(self.wan_interface, "_intermediate_features"):
399
+ self.wan_interface._intermediate_features.clear()
400
+ with torch.autocast("cuda", dtype=torch.bfloat16):
401
+ pred = self.wan_interface.transformer(
402
+ hidden_states=hidden_states,
403
+ timestep=timestep,
404
+ encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype),
405
+ return_dict=False,
406
+ )
407
+ pred = pred[0] if isinstance(pred, tuple) else pred
408
+ pred = pred.sample if hasattr(pred, "sample") else pred
409
+ if hasattr(self.wan_interface, "_intermediate_features"):
410
+ self.wan_interface._intermediate_features.clear()
411
+
412
+ if use_static_conditioning:
413
+ change_loss_weight = change_loss_weight * change_binary.float()
414
+ spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width)
415
+ loss_mask = target_spatial_mask * spatial_loss_weight
416
+ loss_mask = loss_mask.expand(batch_size, channels, num_latents, height, width)
417
+ future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none")
418
+ return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0)
419
+
420
+ def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict:
421
+ """Build arguments accepted by Diffusers WanImageToVideoPipeline."""
422
+ mode = str(cfg.pop("conditioning_mode", "image")).lower()
423
+ if mode not in {"auto", "image", "video"}:
424
+ raise ValueError(
425
+ "future_image_generation.conditioning_mode must be one of "
426
+ f"'auto', 'image', or 'video', got {mode!r}."
427
+ )
428
+
429
+ height = cfg.pop("height", getattr(self.wan_interface, "height", 480))
430
+ width = cfg.pop("width", getattr(self.wan_interface, "width", 832))
431
+ resolved_height, resolved_width = self._resolve_generation_size_values(batch_images, height, width)
432
+ generation_inputs = {
433
+ "image": [self._as_sequence(images)[-1] for images in batch_images],
434
+ "prompt": instructions,
435
+ "height": resolved_height,
436
+ "width": resolved_width,
437
+ "num_frames": cfg.pop("num_frames", 81),
438
+ "num_inference_steps": cfg.pop("num_inference_steps", 50),
439
+ "guidance_scale": cfg.pop("guidance_scale", 5.0),
440
+ "output_type": cfg.pop("output_type", "pil"),
441
+ "return_dict": True,
442
+ "max_sequence_length": cfg.pop("max_sequence_length", 512),
443
+ }
444
+ negative_prompt = cfg.pop("negative_prompt", None)
445
+ if negative_prompt is not None:
446
+ generation_inputs["negative_prompt"] = negative_prompt
447
+
448
+ # Cosmos-only knobs may still be present in a shared YAML.
449
+ cfg.pop("conditional_frame_timestep", None)
450
+ cfg.pop("num_latent_conditional_frames", None)
451
+ generation_inputs.update({key: value for key, value in cfg.items() if value is not None})
452
+ return generation_inputs
starVLA/model/framework/WM4A/CosmoPredict25Perceiver.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License, Version 1.0 (the "License");
3
+ """
4
+ Cosmos-Predict2.5-Perceiver Framework.
5
+
6
+ This keeps Predict2.5 separate from the existing Cosmos-Predict2 framework
7
+ while reusing the same Perceiver action-head training/inference logic.
8
+ """
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Optional
12
+
13
+ from starVLA.model.framework.WM4A.CosmoPredict2Perceiver import CosmoPredict2_Perceiver
14
+ from starVLA.model.framework.base_framework import baseframework
15
+ from starVLA.model.framework.share_tools import merge_framework_config
16
+ from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model
17
+ from starVLA.model.modules.world_model import get_world_model
18
+ from starVLA.model.tools import FRAMEWORK_REGISTRY
19
+
20
+
21
+ @dataclass
22
+ class CosmoPredict25PerceiverDefaultConfig:
23
+ """Cosmos-Predict2.5-Perceiver default parameters."""
24
+
25
+ name: str = "CosmoPredict25Perceiver"
26
+
27
+ world_model: dict = field(default_factory=lambda: {
28
+ "base_wm": "nvidia/Cosmos-Predict2.5-2B",
29
+ "revision": "diffusers/base/post-trained",
30
+ "extract_layers": [-1],
31
+ })
32
+
33
+ qwenvl: dict = field(default_factory=lambda: {
34
+ "base_vlm": "nvidia/Cosmos-Predict2.5-2B",
35
+ "vl_hidden_dim": 2048,
36
+ })
37
+
38
+ action_model: dict = field(default_factory=lambda: {
39
+ "action_model_type": "DiT-B",
40
+ "action_hidden_dim": 1024,
41
+ "hidden_size": 1024,
42
+ "add_pos_embed": True,
43
+ "max_seq_len": 1024,
44
+ "action_dim": 7,
45
+ "state_dim": 7,
46
+ "future_action_window_size": 7,
47
+ "action_horizon": 8,
48
+ "past_action_window_size": 0,
49
+ "repeated_diffusion_steps": 8,
50
+ "noise_beta_alpha": 1.5,
51
+ "noise_beta_beta": 1.0,
52
+ "noise_s": 0.999,
53
+ "num_timestep_buckets": 1000,
54
+ "num_inference_timesteps": 4,
55
+ "num_target_vision_tokens": 32,
56
+ "max_num_embodiments": 32,
57
+ "use_category_specific": False,
58
+ "diffusion_model_cfg": {
59
+ "cross_attention_dim": 2048,
60
+ "dropout": 0.2,
61
+ "final_dropout": True,
62
+ "interleave_self_attention": True,
63
+ "norm_type": "ada_norm",
64
+ "num_layers": 16,
65
+ "output_dim": 1024,
66
+ "positional_embeddings": None,
67
+ },
68
+ })
69
+
70
+ obs_image_size: Optional[list] = None
71
+
72
+
73
+ @FRAMEWORK_REGISTRY.register("CosmoPredict25Perceiver")
74
+ class CosmoPredict25_Perceiver(CosmoPredict2_Perceiver):
75
+ """World-model-for-action framework using Cosmos-Predict2.5 + Perceiver."""
76
+
77
+ def __init__(self, config: Optional[dict] = None, **kwargs) -> None:
78
+ baseframework.__init__(self)
79
+ self.config = merge_framework_config(CosmoPredict25PerceiverDefaultConfig, config)
80
+
81
+ self.backbone = get_world_model(config=self.config)
82
+
83
+ wm_hidden = self.backbone.model.config.hidden_size
84
+ self.config.framework.qwenvl.vl_hidden_dim = wm_hidden
85
+ self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden
86
+
87
+ self.action_model: FlowmatchingActionHead = get_action_model(config=self.config)
88
+
89
+ self.future_action_window_size = self.config.framework.action_model.future_action_window_size
90
+ self.past_action_window_size = self.config.framework.action_model.past_action_window_size
91
+ self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size