diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py b/starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..18ff76f92d9c90192fcf953b8610e80ebea7e1c2 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py @@ -0,0 +1,309 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from functools import partial + +import torch +import torch.nn as nn + +from src.models.utils.modules import ACBlock as Block +from src.models.utils.modules import build_action_block_causal_attention_mask +from src.utils.tensors import trunc_normal_ + + +class VisionTransformerPredictorAC(nn.Module): + """Action Conditioned Vision Transformer Predictor""" + + def __init__( + self, + img_size=(224, 224), + patch_size=16, + num_frames=1, + tubelet_size=2, + embed_dim=768, + predictor_embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + init_std=0.02, + uniform_power=True, + use_silu=False, + wide_silu=True, + is_frame_causal=True, + use_activation_checkpointing=False, + use_rope=True, + action_embed_dim=7, + use_extrinsics=False, + **kwargs + ): + super().__init__() + self.is_frame_causal = is_frame_causal + self.use_extrinsics = use_extrinsics + + # Map input to predictor dimension + self.predictor_embed = nn.Linear(embed_dim, predictor_embed_dim, bias=True) + self.action_encoder = nn.Linear(action_embed_dim, predictor_embed_dim, bias=True) + self.state_encoder = nn.Linear(action_embed_dim, predictor_embed_dim, bias=True) + self.extrinsics_encoder = nn.Linear(action_embed_dim - 1, predictor_embed_dim, bias=True) + + # Determine positional embedding + if type(img_size) is int: + img_size = (img_size, img_size) + self.img_height, self.img_width = img_size + self.patch_size = patch_size + # -- + self.num_frames = num_frames + self.tubelet_size = tubelet_size + self.is_video = num_frames > 1 + + self.grid_height = img_size[0] // self.patch_size + self.grid_width = img_size[1] // self.patch_size + self.use_activation_checkpointing = use_activation_checkpointing + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + # Position embedding + self.uniform_power = uniform_power + + # Attention Blocks + self.use_rope = use_rope + self.predictor_blocks = nn.ModuleList( + [ + Block( + use_rope=use_rope, + grid_size=self.grid_height, + dim=predictor_embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=nn.SiLU if use_silu else nn.GELU, + wide_silu=wide_silu, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ) + for i in range(depth) + ] + ) + + # Normalize & project back to input dimension + self.predictor_norm = norm_layer(predictor_embed_dim) + self.predictor_proj = nn.Linear(predictor_embed_dim, embed_dim, bias=True) + + # ------ initialize weights + self.init_std = init_std + self.apply(self._init_weights) + self._rescale_blocks() + + attn_mask = None + if self.is_frame_causal: + grid_depth = self.num_frames // self.tubelet_size + grid_height = self.img_height // self.patch_size + grid_width = self.img_width // self.patch_size + attn_mask = build_action_block_causal_attention_mask( + grid_depth, grid_height, grid_width, add_tokens=3 if use_extrinsics else 2 + ) + self.attn_mask = attn_mask + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=self.init_std) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def _rescale_blocks(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.predictor_blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def forward_for_WAM_VJEPA2AC(self, x, target_emb, state_emb, extrinsics=None): + # print('############ VisionTransformerPredictorAC.forward-1') + # print(x.shape) # torch.Size([8, 256, 1408]) + x = self.predictor_embed(x) + # print(x.shape) # torch.Size([8, 256, 1024]) + + # 这里T是在计算x是由几张图片经过VJEPA2-AC-Encoder编码得到的表征 + B, N_ctxt, D = x.size() + T = N_ctxt // (self.grid_height * self.grid_width) + # print(self.grid_height) # 16 + # print(self.grid_width) # 16 + # print(T) # 1 + + # print(state_emb.shape) # torch.Size([8, 1, 1024]) + s = state_emb.unsqueeze(1) + # print(s.shape) # torch.Size([8, 1, 1, 1024]) + + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + a = target_emb.unsqueeze(1) + # print(a.shape) # torch.Size([8, 1, 64, 1024]) + + x = x.view(B, T, self.grid_height * self.grid_width, D) + # print(x.shape) # torch.Size([8, 1, 256, 1024]) + + # print(self.use_extrinsics) # False + # print(extrinsics) # None + if self.use_extrinsics: + e = self.extrinsics_encoder(extrinsics).unsqueeze(2) + x = torch.cat([a, s, e, x], dim=2).flatten(1, 2) # [B, T*(H*W+3), D] + else: + x = torch.cat([a, s, x], dim=2).flatten(1, 2) # [B, T*(H*W+2), D] + # print(x.shape) # torch.Size([8, 321, 1024]) + + cond_tokens = (a.shape[2]+s.shape[2]+1) if self.use_extrinsics else (a.shape[2]+s.shape[2]) + # print(cond_tokens) # 65 + attn_mask = self.attn_mask[: x.size(1), : x.size(1)].to(x.device, non_blocking=True) + # print(self.attn_mask.shape) # torch.Size([8256, 8256]) + # print(attn_mask.shape) # torch.Size([321, 312]) + + # print(self.use_activation_checkpointing) # False + # print(len(self.predictor_blocks)) # 24 + for i, blk in enumerate(self.predictor_blocks): + # print(type(blk)) # + # print(x.shape) # torch.Size([8, 321, 1024]) + if self.use_activation_checkpointing: + x = torch.utils.checkpoint.checkpoint( + blk, + x, + mask=None, + attn_mask=attn_mask, + T=T, + H=self.grid_height, + W=self.grid_width, + action_tokens=cond_tokens, + use_reentrant=False, + ) + else: + x = blk( + x, + mask=None, + attn_mask=attn_mask, + T=T, + H=self.grid_height, + W=self.grid_width, + action_tokens=cond_tokens, + ) + # print(x.shape) # torch.Size([8, 321, 1024]) + + # Split out action and frame tokens + # print(x.shape) # torch.Size([8, 321, 1024]) + x = x.view(B, T, cond_tokens + self.grid_height * self.grid_width, D) # [B, T, K+H*W, D] + # print(x.shape) # torch.Size([8, 1, 321, 1024]) + x = x[:, :, cond_tokens:, :].flatten(1, 2) + # print(x.shape) # torch.Size([8, 256, 1024]) + x = self.predictor_norm(x) + # print(x.shape) # torch.Size([8, 256, 1024]) + x = self.predictor_proj(x) + # print(x.shape) # torch.Size([8, 256, 1408]) + + # print('############ VisionTransformerPredictorAC.forward-2') + return x + + def forward(self, x, actions, states, extrinsics=None): + # print('############ VisionTransformerPredictorAC.forward-1') + print('Warning: this function should not used in WAM-VJEPA !!!!!! ' + '(in /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main/src/models/ac_predictor.py)') + + # print(x.shape) # torch.Size([125, 256, 1408]) + x = self.predictor_embed(x) + # print(x.shape) # torch.Size([125, 256, 1024]) + + # 这里T是在计算x是由几张图片经过VJEPA2-AC-Encoder编码得到的表征 + B, N_ctxt, D = x.size() + T = N_ctxt // (self.grid_height * self.grid_width) + # print(self.grid_height) # 16 + # print(self.grid_width) # 16 + # print(T) # 1 + + # print(states.shape) # torch.Size([125, 1, 7]) + # print(actions.shape) # torch.Size([125, 1, 7]) + s = self.state_encoder(states).unsqueeze(2) + a = self.action_encoder(actions).unsqueeze(2) + # print(s.shape) # torch.Size([125, 1, 1, 1024]) + # print(a.shape) # torch.Size([125, 1, 1, 1024]) + + x = x.view(B, T, self.grid_height * self.grid_width, D) + # print(x.shape) # torch.Size([125, 1, 256, 1024]) + + # print(self.use_extrinsics) # False + # print(extrinsics) # None + if self.use_extrinsics: + e = self.extrinsics_encoder(extrinsics).unsqueeze(2) + x = torch.cat([a, s, e, x], dim=2).flatten(1, 2) # [B, T*(H*W+3), D] + else: + x = torch.cat([a, s, x], dim=2).flatten(1, 2) # [B, T*(H*W+2), D] + # print(x.shape) # torch.Size([125, 258, 1024]) + + cond_tokens = 3 if self.use_extrinsics else 2 + # print(cond_tokens) # 2 + attn_mask = self.attn_mask[: x.size(1), : x.size(1)].to(x.device, non_blocking=True) + # print(self.attn_mask.shape) # torch.Size([8256, 8256]) + # print(attn_mask.shape) # torch.Size([258, 258]) + + # print(self.use_activation_checkpointing) # False + # print(len(self.predictor_blocks)) # 24 + for i, blk in enumerate(self.predictor_blocks): + # print(type(blk)) # + # print(x.shape) # torch.Size([125, 258, 1024]) + if self.use_activation_checkpointing: + x = torch.utils.checkpoint.checkpoint( + blk, + x, + mask=None, + attn_mask=attn_mask, + T=T, + H=self.grid_height, + W=self.grid_width, + action_tokens=cond_tokens, + use_reentrant=False, + ) + else: + x = blk( + x, + mask=None, + attn_mask=attn_mask, + T=T, + H=self.grid_height, + W=self.grid_width, + action_tokens=cond_tokens, + ) + # print(x.shape) # torch.Size([125, 258, 1024]) + + # Split out action and frame tokens + # print(x.shape) # torch.Size([125, 258, 1024]) + x = x.view(B, T, cond_tokens + self.grid_height * self.grid_width, D) # [B, T, K+H*W, D] + # print(x.shape) # torch.Size([125, 1, 258, 1024]) + x = x[:, :, cond_tokens:, :].flatten(1, 2) + # print(x.shape) # torch.Size([125, 256, 1024]) + x = self.predictor_norm(x) + # print(x.shape) # torch.Size([125, 256, 1024]) + x = self.predictor_proj(x) + # print(x.shape) # torch.Size([125, 256, 1408]) + + # print('############ VisionTransformerPredictorAC.forward-2') + return x + +def vit_ac_predictor(**kwargs): + model = VisionTransformerPredictorAC( + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/attentive_pooler.py b/starVLA/facebookresearch_vjepa2_main/src/models/attentive_pooler.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc2802c26e2f4a6af9d5d930deb8e488f887e25 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/attentive_pooler.py @@ -0,0 +1,137 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + + +import math + +import torch +import torch.nn as nn + +from src.models.utils.modules import Block, CrossAttention, CrossAttentionBlock +from src.utils.tensors import trunc_normal_ + + +class AttentivePooler(nn.Module): + """Attentive Pooler""" + + def __init__( + self, + num_queries=1, + embed_dim=768, + num_heads=12, + mlp_ratio=4.0, + depth=1, + norm_layer=nn.LayerNorm, + init_std=0.02, + qkv_bias=True, + complete_block=True, + use_activation_checkpointing=False, + ): + super().__init__() + self.use_activation_checkpointing = use_activation_checkpointing + self.query_tokens = nn.Parameter(torch.zeros(1, num_queries, embed_dim)) + + self.complete_block = complete_block + if complete_block: + self.cross_attention_block = CrossAttentionBlock( + dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer + ) + else: + self.cross_attention_block = CrossAttention(dim=embed_dim, num_heads=num_heads, qkv_bias=qkv_bias) + + self.blocks = None + if depth > 1: + self.blocks = nn.ModuleList( + [ + Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=False, + norm_layer=norm_layer, + ) + for i in range(depth - 1) + ] + ) + + self.init_std = init_std + trunc_normal_(self.query_tokens, std=self.init_std) + self.apply(self._init_weights) + self._rescale_blocks() + + def _rescale_blocks(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + layer_id = 0 + if self.blocks is not None: + for layer_id, layer in enumerate(self.blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + if self.complete_block: + rescale(self.cross_attention_block.mlp.fc2.weight.data, layer_id + 1) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=self.init_std) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + trunc_normal_(m.weight, std=self.init_std) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x): + if self.blocks is not None: + for blk in self.blocks: + if self.use_activation_checkpointing: + x = torch.utils.checkpoint.checkpoint(blk, x, False, None, use_reentrant=False) + else: + x = blk(x) + q = self.query_tokens.repeat(len(x), 1, 1) + q = self.cross_attention_block(q, x) + return q + + +class AttentiveClassifier(nn.Module): + """Attentive Classifier""" + + def __init__( + self, + embed_dim=768, + num_heads=12, + mlp_ratio=4.0, + depth=1, + norm_layer=nn.LayerNorm, + init_std=0.02, + qkv_bias=True, + num_classes=1000, + complete_block=True, + use_activation_checkpointing=False, + ): + super().__init__() + self.pooler = AttentivePooler( + num_queries=1, + embed_dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + depth=depth, + norm_layer=norm_layer, + init_std=init_std, + qkv_bias=qkv_bias, + complete_block=complete_block, + use_activation_checkpointing=use_activation_checkpointing, + ) + self.linear = nn.Linear(embed_dim, num_classes, bias=True) + + def forward(self, x): + x = self.pooler(x).squeeze(1) + x = self.linear(x) + return x diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/predictor.py b/starVLA/facebookresearch_vjepa2_main/src/models/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..968c5cc553f1ed3931a02b42d9b5d87a3020f6f0 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/predictor.py @@ -0,0 +1,261 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from functools import partial + +import torch +import torch.nn as nn + +from src.masks.utils import apply_masks +from src.models.utils.modules import Block +from src.models.utils.pos_embs import get_2d_sincos_pos_embed, get_3d_sincos_pos_embed +from src.utils.tensors import repeat_interleave_batch, trunc_normal_ + + +class VisionTransformerPredictor(nn.Module): + """Vision Transformer""" + + def __init__( + self, + img_size=(224, 224), + patch_size=16, + num_frames=1, + tubelet_size=2, + embed_dim=768, + predictor_embed_dim=384, + out_embed_dim=None, + depth=6, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + init_std=0.02, + uniform_power=False, + use_mask_tokens=False, + num_mask_tokens=2, + zero_init_mask_tokens=True, + use_silu=False, + wide_silu=True, + use_activation_checkpointing=False, + return_all_tokens=False, + chop_last_n_tokens=0, + use_rope=False, + **kwargs + ): + super().__init__() + self.return_all_tokens = return_all_tokens + self.chop_last_n_tokens = chop_last_n_tokens + + # Map input to predictor dimension + self.predictor_embed = nn.Linear(embed_dim, predictor_embed_dim, bias=True) + + # Mask tokens + self.mask_tokens = None + self.num_mask_tokens = 0 + if use_mask_tokens: + self.num_mask_tokens = num_mask_tokens + self.mask_tokens = nn.ParameterList( + [nn.Parameter(torch.zeros(1, 1, predictor_embed_dim)) for i in range(num_mask_tokens)] + ) + + # Determine positional embedding + if type(img_size) is int: + img_size = (img_size, img_size) + self.img_height, self.img_width = img_size + self.patch_size = patch_size + # -- + self.num_frames = num_frames + self.tubelet_size = tubelet_size + self.is_video = num_frames > 1 + + self.grid_height = img_size[0] // self.patch_size + self.grid_width = img_size[1] // self.patch_size + self.grid_depth = num_frames // self.tubelet_size + self.use_activation_checkpointing = use_activation_checkpointing + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + if self.is_video: + self.num_patches = num_patches = ( + (num_frames // tubelet_size) * (img_size[0] // patch_size) * (img_size[1] // patch_size) + ) + else: + self.num_patches = num_patches = (img_size[0] // patch_size) * (img_size[1] // patch_size) + # Position embedding + self.uniform_power = uniform_power + + self.predictor_pos_embed = None + if not use_rope: + self.predictor_pos_embed = nn.Parameter( + torch.zeros(1, num_patches, predictor_embed_dim), requires_grad=False + ) + + # Attention Blocks + self.use_rope = use_rope + self.predictor_blocks = nn.ModuleList( + [ + Block( + use_rope=use_rope, + grid_size=self.grid_height, + grid_depth=self.grid_depth, + dim=predictor_embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=nn.SiLU if use_silu else nn.GELU, + wide_silu=wide_silu, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ) + for i in range(depth) + ] + ) + + if out_embed_dim is None: + teacher_embed_dim = kwargs.get("teacher_embed_dim", None) + if teacher_embed_dim is not None: + out_embed_dim = teacher_embed_dim + else: + out_embed_dim = embed_dim + + # Normalize & project back to input dimension + self.predictor_norm = norm_layer(predictor_embed_dim) + self.predictor_proj = nn.Linear(predictor_embed_dim, out_embed_dim, bias=True) + + # ------ initialize weights + if self.predictor_pos_embed is not None: + self._init_pos_embed(self.predictor_pos_embed.data) # sincos pos-embed + self.init_std = init_std + if not zero_init_mask_tokens: + for mt in self.mask_tokens: + trunc_normal_(mt, std=init_std) + self.apply(self._init_weights) + self._rescale_blocks() + + def _init_pos_embed(self, pos_embed): + embed_dim = pos_embed.size(-1) + grid_size = self.img_height // self.patch_size # TODO: update; currently assumes square input + if self.is_video: + grid_depth = self.num_frames // self.tubelet_size + sincos = get_3d_sincos_pos_embed( + embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=self.uniform_power + ) + else: + sincos = get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False) + pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0)) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=self.init_std) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def _rescale_blocks(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.predictor_blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def forward(self, x, masks_x, masks_y, mask_index=1, has_cls=False): + """ + :param x: context tokens + :param masks_x: indices of context tokens in input + :params masks_y: indices of target tokens in input + """ + assert (masks_x is not None) and (masks_y is not None), "Cannot run predictor without mask indices" + if not isinstance(masks_x, list): + masks_x = [masks_x] + if not isinstance(masks_y, list): + masks_y = [masks_y] + + # Batch Size + B = len(x) // len(masks_x) + + # Map context tokens to predictor dimensions + x = self.predictor_embed(x) + if has_cls: + x_cls = x[:, :1, :] + x = x[:, 1:, :] + _, N_ctxt, D = x.shape + + # Add positional embedding to ctxt tokens + if not self.use_rope: + x_pos_embed = self.predictor_pos_embed.repeat(B, 1, 1) + x += apply_masks(x_pos_embed, masks_x) + + # Make target tokens + mask_index = mask_index % self.num_mask_tokens + pred_tokens = self.mask_tokens[mask_index] + pred_tokens = pred_tokens.repeat(B, self.num_patches, 1) + pred_tokens = apply_masks(pred_tokens, masks_y) + # -- add pos embed + if not self.use_rope: + pos_embs = self.predictor_pos_embed.repeat(B, 1, 1) + pos_embs = apply_masks(pos_embs, masks_y) + pos_embs = repeat_interleave_batch(pos_embs, B, repeat=len(masks_x)) + pred_tokens += pos_embs + + # Concatenate context & target tokens + x = x.repeat(len(masks_x), 1, 1) + x = torch.cat([x, pred_tokens], dim=1) + + # Positions of context & target tokens + masks_x = torch.cat(masks_x, dim=0) + masks_y = torch.cat(masks_y, dim=0) + masks = torch.cat([masks_x, masks_y], dim=1) + + # Put tokens in sorted order + argsort = torch.argsort(masks, dim=1) # [B, N] + masks = torch.stack([masks[i, row] for i, row in enumerate(argsort)], dim=0) + x = torch.stack([x[i, row, :] for i, row in enumerate(argsort)], dim=0) + + # Remove the last n tokens of sorted sequence before processing + if self.chop_last_n_tokens > 0: + x = x[:, : -self.chop_last_n_tokens] + masks = masks[:, : -self.chop_last_n_tokens] + + if has_cls: + x = torch.cat([x_cls, x], dim=1) + + # Fwd prop + for i, blk in enumerate(self.predictor_blocks): + if self.use_activation_checkpointing: + x = torch.utils.checkpoint.checkpoint(blk, x, masks, None, use_reentrant=False) + else: + x = blk(x, mask=masks, attn_mask=None) + x = self.predictor_norm(x) + + if has_cls: + x = x[:, 1:, :] + + # Return output corresponding to target tokens + if not self.return_all_tokens: + reverse_argsort = torch.argsort(argsort, dim=1) # [B, N] + x = torch.stack([x[i, row, :] for i, row in enumerate(reverse_argsort)], dim=0) + x = x[:, N_ctxt:] + + x = self.predictor_proj(x) + + return x + + +def vit_predictor(**kwargs): + model = VisionTransformerPredictor( + mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs + ) + return model diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/utils/__init__.py b/starVLA/facebookresearch_vjepa2_main/src/models/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/utils/modules.py b/starVLA/facebookresearch_vjepa2_main/src/models/utils/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..c67c6d93b28d41912f7738d77fc18a9da69689c5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/utils/modules.py @@ -0,0 +1,616 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F +from timm.models.layers import drop_path + + +def build_action_block_causal_attention_mask(T, H, W, add_tokens=1): + N_T = add_tokens + (H * W) + N = T * N_T + mask = torch.zeros(N, N).bool() + mask_block = torch.ones(N_T, N_T).bool() + local_window_time = T + + for t1 in range(T): + for t2 in range(max(0, t1 - local_window_time + 1), t1 + 1): + mask[t1 * N_T : (t1 + 1) * N_T, t2 * N_T : (t2 + 1) * N_T] = mask_block + + return mask + + +def rotate_queries_or_keys(x, pos): + B, num_heads, N, D = x.size() + orig_dtype = x.dtype + assert D % 2 == 0, "Embedding dimension must be a multiple of 2 for block matrix rotation" + + # -- compute angle for each position + omega = torch.arange(D // 2, dtype=x.dtype, device=x.device) + omega /= D / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + freq = torch.einsum("..., f -> ... f", pos, omega) # (..., N, D/2), outer product + + # -- build rotation matrix and apply + emb_sin = freq.sin() # (..., N, D/2) + emb_cos = freq.cos() # (..., N, D/2) + # -- NOTE: This expansion has a subtle bug where frequencies are duplicated across the vector pair. + # -- Fixing the bug would break compatibility with the pretrained model, but the fix can be applied by commenting + # -- out the two lines below, and uncommenting the following two lines. + # -- Thanks to @echosprint, original PR: https://github.com/facebookresearch/vjepa2/pull/15 + emb_sin = emb_sin.squeeze(-1).repeat(1, 1, 1, 2) + emb_cos = emb_cos.squeeze(-1).repeat(1, 1, 1, 2) + # emb_sin = emb_sin.repeat_interleave(2, dim=-1) # (..., N, D) + # emb_cos = emb_cos.repeat_interleave(2, dim=-1) # (..., N, D) + + # -- + y = x.unflatten(-1, (-1, 2)) + y1, y2 = y.unbind( + dim=-1, + ) + y = torch.stack((-y2, y1), dim=-1) + y = y.flatten(-2) + return ((x * emb_cos) + (y * emb_sin)).to(orig_dtype) + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + def extra_repr(self) -> str: + return "p={}".format(self.drop_prob) + + +class MLP(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class SwiGLUFFN(nn.Module): + def __init__( + self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.0, wide_silu=True + ): + super().__init__() + out_features = out_features or in_features + swiglu_hidden_features = hidden_features = hidden_features or in_features + if wide_silu: + swiglu_hidden_features = int(2 * hidden_features / 3) + align_as = 8 + swiglu_hidden_features = (swiglu_hidden_features + align_as - 1) // align_as * align_as + self.fc1 = nn.Linear(in_features, swiglu_hidden_features) + self.fc2 = nn.Linear(in_features, swiglu_hidden_features) + self.act = act_layer() + self.fc3 = nn.Linear(swiglu_hidden_features, out_features) + + def forward(self, x): + x1 = self.fc1(x) + x2 = self.fc2(x) + hidden = F.silu(x1) * x2 + return self.fc3(hidden) + + +class ACRoPEAttention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + use_sdpa=True, + is_causal=False, + grid_size=16, + ): + super().__init__() + self.num_heads = num_heads + self.head_dim = head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop_prob = proj_drop + self.proj_drop = nn.Dropout(proj_drop) + self.use_sdpa = use_sdpa + # -- + self.d_dim = int(2 * ((head_dim // 3) // 2)) + self.h_dim = int(2 * ((head_dim // 3) // 2)) + self.w_dim = int(2 * ((head_dim // 3) // 2)) + self.grid_size = grid_size + self.is_causal = is_causal + + def _get_frame_pos(self, ids, H_patches, W_patches): + tokens_per_frame = int(H_patches * W_patches) + return ids // tokens_per_frame + + def _get_height_pos(self, ids, H_patches, W_patches): + # Remove frame component from ids + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = self._get_frame_pos(ids, H_patches, W_patches) + ids = ids - tokens_per_frame * frame_ids + # -- + return ids // tokens_per_row + + def separate_positions(self, ids, H_patches, W_patches): + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = self._get_frame_pos(ids, H_patches, W_patches) + # -- + height_ids = self._get_height_pos(ids, H_patches, W_patches) + # -- + # Remove frame component from ids (1st term) and height component (2nd term) + width_ids = (ids - tokens_per_frame * frame_ids) - tokens_per_row * height_ids + return 1.0 * frame_ids, 1.0 * height_ids, 1.0 * width_ids + + def forward(self, x, mask=None, attn_mask=None, T=None, H=None, W=None, action_tokens=0): + B, N, C = x.size() + + # -- compute position of each frame token + if mask is not None: + mask = mask.unsqueeze(1).repeat(1, self.num_heads, 1) + d_mask, h_mask, w_mask = self.separate_positions(mask, H, W) + else: + mask = torch.arange(int(T * H * W), device=x.device) + d_mask, h_mask, w_mask = self.separate_positions(mask, H, W) + + # -- snap spatial positions to grid size + h_mask *= self.grid_size / H + w_mask *= self.grid_size / W + + # -- split out action tokens from sequence + if action_tokens > 0: + x = x.view(B, -1, action_tokens + H * W, C) # [B, T, 1+H*W, D] + + action_q, action_k, action_v = [], [], [] + for i in range(action_tokens): + a = x[:, :, i : i + 1, :].flatten(1, 2) + # Note action tokens do not work with masking + # -- compute qkv for action tokens and rotate + qkv = self.qkv(a).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D] + # -- + qd = rotate_queries_or_keys(q[..., : self.d_dim], pos=torch.arange(T, device=x.device)) + kd = rotate_queries_or_keys(k[..., : self.d_dim], pos=torch.arange(T, device=x.device)) + qr = q[..., self.d_dim :] + kr = k[..., self.d_dim :] + action_q += [torch.cat([qd, qr], dim=-1).view(B, self.num_heads, T, 1, -1)] + action_k += [torch.cat([kd, kr], dim=-1).view(B, self.num_heads, T, 1, -1)] + action_v += [v.view(B, self.num_heads, T, 1, -1)] + + action_q = torch.cat(action_q, dim=3).flatten(2, 3) + action_k = torch.cat(action_k, dim=3).flatten(2, 3) + action_v = torch.cat(action_v, dim=3).flatten(2, 3) + x = x[:, :, action_tokens:, :].flatten(1, 2) + + # -- compute qkv for frame tokens and rotate + qkv = self.qkv(x).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D] + + s = 0 + # Rotate depth + qd = rotate_queries_or_keys(q[..., s : s + self.d_dim], pos=d_mask) + kd = rotate_queries_or_keys(k[..., s : s + self.d_dim], pos=d_mask) + s += self.d_dim + # Rotate height dim + qh = rotate_queries_or_keys(q[..., s : s + self.h_dim], pos=h_mask) + kh = rotate_queries_or_keys(k[..., s : s + self.h_dim], pos=h_mask) + s += self.h_dim + # Rotate width dim + qw = rotate_queries_or_keys(q[..., s : s + self.w_dim], pos=w_mask) + kw = rotate_queries_or_keys(k[..., s : s + self.w_dim], pos=w_mask) + s += self.w_dim + + # Combine rotated dimension + if s < self.head_dim: + qr = q[..., s:] + kr = k[..., s:] + q = torch.cat([qd, qh, qw, qr], dim=-1) + k = torch.cat([kd, kh, kw, kr], dim=-1) + else: + q = torch.cat([qd, qh, qw], dim=-1) + k = torch.cat([kd, kh, kw], dim=-1) + + if action_tokens > 0: + + def merge_(tx, ta): + """tx, tx in [B, num_heads, N, D]""" + tx = tx.view(B, self.num_heads, T, H * W, -1) # [B, T, H*W, D] + ta = ta.view(B, self.num_heads, T, action_tokens, -1) # [B, T, A, D] + return torch.cat([ta, tx], dim=3).flatten(2, 3) + + q = merge_(q, action_q) + k = merge_(k, action_k) + v = merge_(v, action_v) + + if attn_mask is not None or self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal, attn_mask=attn_mask + ) + attn = None + else: + attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, D, D] + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class RoPEAttention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + use_sdpa=True, + grid_size=14, + is_causal=False, + ): + super().__init__() + self.num_heads = num_heads + self.head_dim = head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop_prob = proj_drop + self.proj_drop = nn.Dropout(proj_drop) + self.use_sdpa = use_sdpa + # -- + self.d_dim = int(2 * ((head_dim // 3) // 2)) + self.h_dim = int(2 * ((head_dim // 3) // 2)) + self.w_dim = int(2 * ((head_dim // 3) // 2)) + self.grid_size = grid_size + self.is_causal = is_causal + + def _get_frame_pos(self, ids, H_patches=None, W_patches=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(self.grid_size * self.grid_size) + else: + tokens_per_frame = int(H_patches * W_patches) + return ids // tokens_per_frame + + def _get_height_pos(self, ids, H_patches=None, W_patches=None): + # Remove frame component from ids + if H_patches is None or W_patches is None: + tokens_per_frame = int(self.grid_size * self.grid_size) + tokens_per_row = self.grid_size + else: + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = self._get_frame_pos(ids, H_patches, W_patches) + ids = ids - tokens_per_frame * frame_ids + # -- + return ids // tokens_per_row + + def separate_positions(self, ids, H_patches=None, W_patches=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(self.grid_size * self.grid_size) + tokens_per_row = self.grid_size + else: + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = self._get_frame_pos(ids, H_patches, W_patches) + # -- + height_ids = self._get_height_pos(ids, H_patches, W_patches) + # -- + # Remove frame component from ids (1st term) and height component (2nd term) + width_ids = (ids - tokens_per_frame * frame_ids) - tokens_per_row * height_ids + return frame_ids, height_ids, width_ids + + def forward(self, x, mask=None, attn_mask=None, T=None, H_patches=None, W_patches=None): + B, N, C = x.size() + grid_depth = int(N // (self.grid_size * self.grid_size)) + + qkv = self.qkv(x).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D] + + if mask is not None: + mask = mask.unsqueeze(1).repeat(1, self.num_heads, 1) + d_mask, h_mask, w_mask = self.separate_positions(mask, H_patches, W_patches) + else: + if T is None or H_patches is None or W_patches is None: + mask = torch.arange(int(grid_depth * self.grid_size * self.grid_size), device=x.device) + else: + mask = torch.arange(int(T * H_patches * W_patches), device=x.device) + d_mask, h_mask, w_mask = self.separate_positions(mask, H_patches, W_patches) + + s = 0 + # Rotate depth + qd = rotate_queries_or_keys(q[..., s : s + self.d_dim], pos=d_mask) + kd = rotate_queries_or_keys(k[..., s : s + self.d_dim], pos=d_mask) + s += self.d_dim + # Rotate height dim + qh = rotate_queries_or_keys(q[..., s : s + self.h_dim], pos=h_mask) + kh = rotate_queries_or_keys(k[..., s : s + self.h_dim], pos=h_mask) + s += self.h_dim + # Rotate width dim + qw = rotate_queries_or_keys(q[..., s : s + self.w_dim], pos=w_mask) + kw = rotate_queries_or_keys(k[..., s : s + self.w_dim], pos=w_mask) + s += self.w_dim + + # Combine rotated dimension + if s < self.head_dim: + qr = q[..., s:] + kr = k[..., s:] + q = torch.cat([qd, qh, qw, qr], dim=-1) + k = torch.cat([kd, kh, kw, kr], dim=-1) + else: + q = torch.cat([qd, qh, qw], dim=-1) + k = torch.cat([kd, kh, kw], dim=-1) + + if attn_mask is not None or self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal, attn_mask=attn_mask + ) + attn = None + else: + attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, D, D] + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + use_sdpa=True, + is_causal=False, + ): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop_prob = proj_drop + self.proj_drop = nn.Dropout(proj_drop) + self.use_sdpa = use_sdpa + self.is_causal = is_causal + + def forward(self, x, mask=None, attn_mask=None): + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] # [B, num_heads, N, D] + + if attn_mask is not None or self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal, attn_mask=attn_mask + ) + attn = None + else: + attn = (q @ k.transpose(-2, -1)) * self.scale # [B, num_heads, D, D] + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class ACBlock(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + wide_silu=True, + norm_layer=nn.LayerNorm, + use_sdpa=True, + is_causal=False, + grid_size=16, + use_rope=False, + **kwargs, + ): + super().__init__() + self.norm1 = norm_layer(dim) + if use_rope: + self.attn = ACRoPEAttention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + use_sdpa=use_sdpa, + is_causal=is_causal, + grid_size=grid_size, + proj_drop=drop, + ) + else: + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + use_sdpa=use_sdpa, + is_causal=is_causal, + proj_drop=drop, + ) + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + if act_layer is nn.SiLU: + self.mlp = SwiGLUFFN( + in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, wide_silu=wide_silu, drop=drop + ) + else: + self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, mask=None, attn_mask=None, T=None, H=None, W=None, action_tokens=0): + y = self.norm1(x) + if isinstance(self.attn, ACRoPEAttention): + y = self.attn(y, mask=mask, attn_mask=attn_mask, T=T, H=H, W=W, action_tokens=action_tokens) + else: + y = self.attn(y, mask=mask, attn_mask=attn_mask) + x = x + self.drop_path(y) + y = self.norm2(x) + x = x + self.drop_path(self.mlp(y)) + return x + + +class Block(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + wide_silu=True, + norm_layer=nn.LayerNorm, + use_sdpa=True, + is_causal=False, + grid_size=16, + use_rope=False, + **kwargs, + ): + super().__init__() + self.norm1 = norm_layer(dim) + if use_rope: + self.attn = RoPEAttention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + use_sdpa=use_sdpa, + is_causal=is_causal, + grid_size=grid_size, + proj_drop=drop, + ) + else: + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + use_sdpa=use_sdpa, + is_causal=is_causal, + proj_drop=drop, + ) + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + if act_layer is nn.SiLU: + self.mlp = SwiGLUFFN( + in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, wide_silu=wide_silu, drop=drop + ) + else: + self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + def forward(self, x, mask=None, attn_mask=None, T=None, H_patches=None, W_patches=None): + if isinstance(self.attn, RoPEAttention): + y = self.attn(self.norm1(x), mask=mask, attn_mask=attn_mask, T=T, H_patches=H_patches, W_patches=W_patches) + else: + y = self.attn(self.norm1(x), mask=mask, attn_mask=attn_mask) + x = x + self.drop_path(y) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class CrossAttention(nn.Module): + def __init__(self, dim, num_heads=12, qkv_bias=False, use_sdpa=True): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, int(dim * 2), bias=qkv_bias) + # self.proj = nn.Linear(dim, dim) + self.use_sdpa = use_sdpa + + def forward(self, q, x): + B, n, C = q.shape + q = self.q(q).reshape(B, n, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + B, N, C = x.shape + kv = self.kv(x).reshape(B, N, 2, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) + k, v = kv[0], kv[1] # (batch_size, num_heads, seq_len, feature_dim_per_head) + + if self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + q = F.scaled_dot_product_attention(q, k, v) + else: + xattn = (q @ k.transpose(-2, -1)) * self.scale + xattn = xattn.softmax(dim=-1) # (batch_size, num_heads, query_len, seq_len) + q = xattn @ v + + q = q.transpose(1, 2).reshape(B, n, C) + return q + + +class CrossAttentionBlock(nn.Module): + def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.norm1 = norm_layer(dim) + self.xattn = CrossAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias) + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer) + + def forward(self, q, x): + y = self.xattn(q, self.norm1(x)) + q = q + y + q = q + self.mlp(self.norm2(q)) + return q diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/utils/patch_embed.py b/starVLA/facebookresearch_vjepa2_main/src/models/utils/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..f6405f0e804a6278b712ae255570700cfa7445b7 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/utils/patch_embed.py @@ -0,0 +1,52 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch.nn as nn +from einops import rearrange + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding + """ + + def __init__(self, patch_size=16, in_chans=3, embed_dim=768): + super().__init__() + self.patch_size = patch_size + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + + def forward(self, x): + B, C, H, W = x.shape + x = self.proj(x).flatten(2).transpose(1, 2) + return x + + +class PatchEmbed3D(nn.Module): + """ + Image to Patch Embedding + """ + + def __init__( + self, + patch_size=16, + tubelet_size=2, + in_chans=3, + embed_dim=768, + ): + super().__init__() + self.patch_size = patch_size + self.tubelet_size = tubelet_size + + self.proj = nn.Conv3d( + in_channels=in_chans, + out_channels=embed_dim, + kernel_size=(tubelet_size, patch_size, patch_size), + stride=(tubelet_size, patch_size, patch_size), + ) + + def forward(self, x, **kwargs): + B, C, T, H, W = x.shape + x = self.proj(x).flatten(2).transpose(1, 2) + return x diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/utils/pos_embs.py b/starVLA/facebookresearch_vjepa2_main/src/models/utils/pos_embs.py new file mode 100644 index 0000000000000000000000000000000000000000..8630c14c844344316dc38b1f14b9adfc51e81f9d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/utils/pos_embs.py @@ -0,0 +1,93 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np + + +def get_3d_sincos_pos_embed(embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=False): + """ + grid_size: int of the grid height and width + grid_depth: int of the grid depth + returns: + pos_embed: [grid_depth*grid_size*grid_size, embed_dim] (w/o cls_token) + or [1+grid_depth*grid_size*grid_size, embed_dim] (w/ cls_token) + """ + grid_d = np.arange(grid_depth, dtype=float) + grid_h = np.arange(grid_size, dtype=float) + grid_w = np.arange(grid_size, dtype=float) + grid_h, grid_d, grid_w = np.meshgrid( + grid_h, grid_d, grid_w + ) # order of meshgrid is very important for indexing as [d,h,w] + + if not uniform_power: + h_embed_dim = embed_dim // 4 + w_embed_dim = embed_dim // 4 + d_embed_dim = embed_dim // 2 + else: + h_embed_dim = w_embed_dim = d_embed_dim = int(np.ceil(embed_dim / 6) * 2) + + emb_h = get_1d_sincos_pos_embed_from_grid(h_embed_dim, grid_h) # (T*H*W, D1) + emb_w = get_1d_sincos_pos_embed_from_grid(w_embed_dim, grid_w) # (T*H*W, D2) + emb_d = get_1d_sincos_pos_embed_from_grid(d_embed_dim, grid_d) # (T*H*W, D3) + pos_embed = np.concatenate([emb_d, emb_h, emb_w], axis=1) + pos_embed = pos_embed[:, :embed_dim] + if cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): + """ + grid_size: int of the grid height and width + returns: + pos_embed: [grid_size*grid_size, embed_dim] (w/o cls_token) + or [1+grid_size*grid_size, embed_dim] (w/ cls_token) + """ + grid_h = np.arange(grid_size, dtype=float) + grid_w = np.arange(grid_size, dtype=float) + grid_w, grid_h = np.meshgrid(grid_w, grid_h) # order of meshgrid is very important for indexing as [h, w] + + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid_h) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid_w) # (H*W, D/2) + pos_embed = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + if cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_1d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): + """ + embed_dim: output dimension for each position + grid_size: int of the grid length + returns: + pos_embed: [grid_size, embed_dim] (w/o cls_token) + or [1+grid_size, embed_dim] (w/ cls_token) + """ + grid = np.arange(grid_size, dtype=float) + pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid) + if cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + returns: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/vision_transformer.py b/starVLA/facebookresearch_vjepa2_main/src/models/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..be2bbfc50f7b828dedbb8da648038f00f0592595 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/models/vision_transformer.py @@ -0,0 +1,487 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from functools import partial + +import torch +import torch.nn as nn + +from src.masks.utils import apply_masks +from src.models.utils.modules import Block +from src.models.utils.patch_embed import PatchEmbed, PatchEmbed3D +from src.models.utils.pos_embs import get_2d_sincos_pos_embed, get_3d_sincos_pos_embed +from src.utils.tensors import trunc_normal_ + + +class VisionTransformer(nn.Module): + """Vision Transformer""" + + def __init__( + self, + img_size=(224, 224), + patch_size=16, + num_frames=1, + tubelet_size=2, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + init_std=0.02, + out_layers=None, + uniform_power=False, + use_silu=False, + wide_silu=True, + use_sdpa=True, + use_activation_checkpointing=False, + use_rope=False, + handle_nonsquare_inputs=True, + **kwargs + ): + super().__init__() + self.num_features = self.embed_dim = embed_dim + self.num_heads = num_heads + self.out_layers = out_layers + self.handle_nonsquare_inputs = handle_nonsquare_inputs + + if type(img_size) is int: + img_size = (img_size, img_size) + self.img_height, self.img_width = img_size + self.patch_size = patch_size + self.num_frames = num_frames + self.tubelet_size = tubelet_size + self.is_video = num_frames > 1 + + self.use_activation_checkpointing = use_activation_checkpointing + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule + + # Tokenize pixels with convolution + if self.is_video: + self.patch_embed = PatchEmbed3D( + patch_size=patch_size, tubelet_size=tubelet_size, in_chans=in_chans, embed_dim=embed_dim + ) + self.num_patches = (num_frames // tubelet_size) * (img_size[0] // patch_size) * (img_size[1] // patch_size) + else: + self.patch_embed = PatchEmbed(patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) + self.num_patches = (img_size[0] // patch_size) * (img_size[1] // patch_size) + + # Position embedding + self.uniform_power = uniform_power + self.use_rope = use_rope + if self.use_rope: + self.pos_embed = None + else: + self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim), requires_grad=False) + + # Attention Blocks + self.blocks = nn.ModuleList( + [ + Block( + use_rope=use_rope, + grid_size=img_size[0] // patch_size, + grid_depth=num_frames // tubelet_size, + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + use_sdpa=use_sdpa, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=nn.SiLU if use_silu else nn.GELU, + wide_silu=wide_silu, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + ) + for i in range(depth) + ] + ) + self.norm = norm_layer(embed_dim) + + # ------ initialize weights + if self.pos_embed is not None: + self._init_pos_embed(self.pos_embed.data) # sincos pos-embed + self.init_std = init_std + self.apply(self._init_weights) + self._rescale_blocks() + + def _init_pos_embed(self, pos_embed): + embed_dim = pos_embed.size(-1) + grid_size = self.img_height // self.patch_size # TODO: update; currently assumes square input + if self.is_video: + grid_depth = self.num_frames // self.tubelet_size + sincos = get_3d_sincos_pos_embed( + embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=self.uniform_power + ) + else: + sincos = get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False) + pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0)) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=self.init_std) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + elif isinstance(m, nn.Conv2d): + trunc_normal_(m.weight, std=self.init_std) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv3d): + trunc_normal_(m.weight, std=self.init_std) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def _rescale_blocks(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def get_num_layers(self): + return len(self.blocks) + + def no_weight_decay(self): + return {} + + def forward(self, x, masks=None): + """ + :param x: input image/video + :param masks: indices of patch tokens to mask (remove) + """ + if masks is not None and not isinstance(masks, list): + masks = [masks] + + # Tokenize input + # Image + if x.ndim == 4: + _, _, H, W = x.shape + T = 1 + # Video + elif x.ndim == 5: + _, _, T, H, W = x.shape + T = T // self.tubelet_size + H_patches = H // self.patch_size + W_patches = W // self.patch_size + if not self.handle_nonsquare_inputs: + T = H_patches = W_patches = None + + if not self.use_rope: + pos_embed = self.interpolate_pos_encoding(x, self.pos_embed) + x = self.patch_embed(x) + x += pos_embed + else: + x = self.patch_embed(x) + + # Mask away unwanted tokens (if masks provided) + if masks is not None: + x = apply_masks(x, masks) + masks = torch.cat(masks, dim=0) + + # Fwd prop + outs = [] + for i, blk in enumerate(self.blocks): + if self.use_activation_checkpointing: + x = torch.utils.checkpoint.checkpoint( + blk, x, masks, None, T=T, H_patches=H_patches, W_patches=W_patches, use_reentrant=False + ) + else: + x = blk(x, mask=masks, attn_mask=None, T=T, H_patches=H_patches, W_patches=W_patches) + if self.out_layers is not None and i in self.out_layers: + outs.append(self.norm(x)) + + if self.out_layers is not None: + return outs + + if self.norm is not None: + x = self.norm(x) + + return x + + def interpolate_pos_encoding(self, x, pos_embed): + + _, N, dim = pos_embed.shape + + if self.is_video: + + # If pos_embed already correct size, just return + _, _, T, H, W = x.shape + if H == self.img_height and W == self.img_width and T == self.num_frames: + return pos_embed + + # Just chop off last N tokens of positional embedding + elif H == self.img_height and W == self.img_width and T < self.num_frames: + new_N = int((T // self.tubelet_size) * (H // self.patch_size) * (W // self.patch_size)) + return pos_embed[:, :new_N, :] + + # Convert depth, height, width of input to be measured in patches + # instead of pixels/frames + T = T // self.tubelet_size + H = H // self.patch_size + W = W // self.patch_size + + # Compute the initialized shape of the positional embedding measured + # in patches + N_t = self.num_frames // self.tubelet_size + N_h = self.img_height // self.patch_size + N_w = self.img_width // self.patch_size + assert N_h * N_w * N_t == N, "Positional embedding initialized incorrectly" + + # Compute scale factor for spatio-temporal interpolation + scale_factor = (T / N_t, H / N_h, W / N_w) + + pos_embed = nn.functional.interpolate( + pos_embed.reshape(1, N_t, N_h, N_w, dim).permute(0, 4, 1, 2, 3), + scale_factor=scale_factor, + mode="trilinear", + ) + pos_embed = pos_embed.permute(0, 2, 3, 4, 1).view(1, -1, dim) + return pos_embed + + else: + + # If pos_embed already correct size, just return + _, _, H, W = x.shape + if H == self.img_height and W == self.img_width: + return pos_embed + + # Compute scale factor for spatial interpolation + npatch = (H // self.patch_size) * (W // self.patch_size) + scale_factor = math.sqrt(npatch / N) + + pos_embed = nn.functional.interpolate( + pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), + scale_factor=scale_factor, + mode="bicubic", + ) + pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return pos_embed + + +def vit_large(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_huge(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1280, + depth=32, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_giant_xformers(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=22, + mlp_ratio=48 / 11, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +# We do not use any of the following ViT definitions in V-JEPA 2, but retain them for +# compatibility reasons. +def vit_synthetic(patch_size=16, **kwargs): + # For performance testing only + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1, + depth=1, + num_heads=1, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_tiny(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=192, + depth=12, + num_heads=3, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_small(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_base(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_large_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_huge_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1280, + depth=32, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_giant(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=16, + mlp_ratio=48 / 11, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_giant_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=16, + mlp_ratio=48 / 11, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_giant_xformers_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=22, + mlp_ratio=48 / 11, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_gigantic(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1664, + depth=48, + num_heads=16, + mlp_ratio=64 / 13, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +def vit_gigantic_xformers(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1664, + depth=48, + num_heads=26, + mlp_ratio=64 / 13, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs + ) + return model + + +VIT_EMBED_DIMS = { + "vit_synthetic": 1, + "vit_tiny": 192, + "vit_small": 384, + "vit_base": 768, + "vit_large": 1024, + "vit_huge": 1280, + "vit_giant": 1408, + "vit_gigantic": 1664, +} diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/checkpoint_loader.py b/starVLA/facebookresearch_vjepa2_main/src/utils/checkpoint_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..e9e7b2f055f818528c490183e1b6d1b11a5a6bd1 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/checkpoint_loader.py @@ -0,0 +1,37 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +import random +import time +from typing import Any + +import torch +from torch.serialization import MAP_LOCATION + +from src.utils.logging import get_logger + +logger = get_logger(os.path.basename(__file__)) + + +def robust_checkpoint_loader(r_path: str, map_location: MAP_LOCATION = "cpu", max_retries: int = 3) -> Any: + """ + Loads a checkpoint from a path, retrying up to max_retries times if the checkpoint is not found. + """ + retries = 0 + + while retries < max_retries: + try: + return torch.load(r_path, map_location=map_location) + except Exception as e: + logger.warning(f"Encountered exception when loading checkpoint {e}") + retries += 1 + if retries < max_retries: + sleep_time_s = (2**retries) * random.uniform(1.0, 1.1) + logger.warning(f"Sleeping {sleep_time_s}s and trying again, count {retries}/{max_retries}") + time.sleep(sleep_time_s) + continue + else: + raise e diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/distributed.py b/starVLA/facebookresearch_vjepa2_main/src/utils/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cef30fe5a2f31376a6929c0f2e646dbe423052 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/distributed.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +from pathlib import Path + +import torch +import torch.distributed as dist + +from src.utils.logging import get_logger + +logger = get_logger() + + +def init_distributed(port=37129, rank_and_world_size=(None, None)): + # try to set all environment variables to avoid triggering a segfault + # environment variables can be reallocated during the execution of torch.distributed.init_process_group + # the idea is a race condition may trigger if init_progress_group is modifying an environment variable at + # the same time as Python, so we try to set all environs before initializing distributed + if "SLURM_JOB_ID" in os.environ: + # Use the slurm_tmpdir (if it exists) instead of /tmp + tmpdir = Path(f"/scratch/slurm_tmpdir/{os.environ['SLURM_JOB_ID']}") + if tmpdir.exists(): + os.environ["TMPDIR"] = str(tmpdir) + + if dist.is_available() and dist.is_initialized(): + return dist.get_world_size(), dist.get_rank() + + rank, world_size = rank_and_world_size + os.environ["MASTER_ADDR"] = "localhost" + + if (rank is None) or (world_size is None): + try: + world_size = int(os.environ["SLURM_NTASKS"]) + rank = int(os.environ["SLURM_PROCID"]) + os.environ["MASTER_ADDR"] = os.environ["HOSTNAME"] + except Exception: + logger.info("SLURM vars not set (distributed training not available)") + world_size, rank = 1, 0 + return world_size, rank + + try: + os.environ["MASTER_PORT"] = str(port) + torch.distributed.init_process_group(backend="nccl", world_size=world_size, rank=rank) + except Exception as e: + world_size, rank = 1, 0 + logger.info(f"Rank: {rank}. Distributed training not available {e}") + + return world_size, rank + + +class AllGather(torch.autograd.Function): + + @staticmethod + def forward(ctx, x): + if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1): + x = x.contiguous() + outputs = [torch.zeros_like(x) for _ in range(dist.get_world_size())] + dist.all_gather(outputs, x) + return torch.cat(outputs, 0) + return x + + @staticmethod + def backward(ctx, grads): + if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1): + s = (grads.shape[0] // dist.get_world_size()) * dist.get_rank() + e = (grads.shape[0] // dist.get_world_size()) * (dist.get_rank() + 1) + grads = grads.contiguous() + dist.all_reduce(grads) + return grads[s:e] + return grads + + +class AllReduceSum(torch.autograd.Function): + + @staticmethod + def forward(ctx, x): + if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1): + x = x.contiguous() + dist.all_reduce(x) + return x + + @staticmethod + def backward(ctx, grads): + return grads + + +class AllReduce(torch.autograd.Function): + + @staticmethod + def forward(ctx, x): + if dist.is_available() and dist.is_initialized() and (dist.get_world_size() > 1): + x = x.contiguous() / dist.get_world_size() + dist.all_reduce(x) + return x + + @staticmethod + def backward(ctx, grads): + return grads diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/logging.py b/starVLA/facebookresearch_vjepa2_main/src/utils/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..949c0e5ffbd5f8bcec1209a7f5a9ee829ff1b311 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/logging.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import os +import subprocess +import sys + +import torch + + +def gpu_timer(closure, log_timings=True): + """Helper to time gpu-time to execute closure()""" + log_timings = log_timings and torch.cuda.is_available() + + elapsed_time = -1.0 + if log_timings: + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + start.record() + + result = closure() + + if log_timings: + end.record() + torch.cuda.synchronize() + elapsed_time = start.elapsed_time(end) + + return result, elapsed_time + + +LOG_FORMAT = "[%(levelname)-8s][%(asctime)s][%(name)-20s][%(funcName)-25s] %(message)s" +DATE_FORMAT = "%Y-%m-%d %H:%M:%S" + + +def get_logger(name=None, force=False): + logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT, force=force) + return logging.getLogger(name=name) + + +class CSVLogger(object): + + def __init__(self, fname, *argv, **kwargs): + self.fname = fname + self.types = [] + mode = kwargs.get("mode", "+a") + self.delim = kwargs.get("delim", ",") + # -- print headers + with open(self.fname, mode) as f: + for i, v in enumerate(argv, 1): + self.types.append(v[0]) + if i < len(argv): + print(v[1], end=self.delim, file=f) + else: + print(v[1], end="\n", file=f) + + def log(self, *argv): + with open(self.fname, "+a") as f: + for i, tv in enumerate(zip(self.types, argv), 1): + end = self.delim if i < len(argv) else "\n" + print(tv[0] % tv[1], end=end, file=f) + + +class AverageMeter(object): + """computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.max = float("-inf") + self.min = float("inf") + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + try: + self.max = max(val, self.max) + self.min = min(val, self.min) + except Exception: + pass + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + +def jepa_rootpath(): + this_file = os.path.abspath(__file__) + return "/".join(this_file.split("/")[:-3]) + + +def git_information(): + jepa_root = jepa_rootpath() + try: + resp = ( + subprocess.check_output(["git", "-C", jepa_root, "rev-parse", "HEAD", "--abbrev-ref", "HEAD"]) + .decode("ascii") + .strip() + ) + commit, branch = resp.split("\n") + return f"branch: {branch}\ncommit: {commit}\n" + except Exception: + return "unknown" diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/monitoring.py b/starVLA/facebookresearch_vjepa2_main/src/utils/monitoring.py new file mode 100644 index 0000000000000000000000000000000000000000..33c2c903858e77fee6c418e6fed51497512d3096 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/monitoring.py @@ -0,0 +1,171 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import dataclasses +import threading +import time +from typing import Dict, Tuple + +import psutil + + +@dataclasses.dataclass +class ResourceStatsSample: + timestamp: float + cpu_percent: float + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_chars: int + write_chars: int + cpu_times_user: float + cpu_times_system: float + cpu_times_children_user: float + cpu_times_children_system: float + cpu_times_iowait: float + cpu_affinity: str + cpu_num: int + num_threads: int + num_voluntary_ctx_switches: int + num_involuntary_ctx_switches: int + + def as_tuple(self) -> Dict: + """Return values mirroring fields.""" + return dataclasses.astuple(self) + + def fields(self) -> Tuple[dataclasses.Field, ...]: + """Return fields in this dataclass.""" + return dataclasses.fields(self.__class__) + + +class ResourceMonitoringThread(threading.Thread): + def __init__(self, pid=None, refresh_interval=None, stats_callback_fn=None): + """Starts a thread to monitor pid every refresh_interval seconds. + + Passes a ResourceStatsSample object to the callback.""" + super(ResourceMonitoringThread, self).__init__() + if refresh_interval is None: + refresh_interval = 5 + self.is_running_event = threading.Event() + self.p = psutil.Process(pid) + self.refresh_interval = refresh_interval + if stats_callback_fn is None: + # Default callback + def stats_callback_fn(resource_sample: ResourceStatsSample): + print(f"PID {self.p.pid} Stats: {resource_sample.resource_stats}") + + elif not callable(stats_callback_fn): + raise ValueError("Callback needs to be callable, got {}".format(type(stats_callback_fn))) + self.stats_callback_fn = stats_callback_fn + + def stop(self) -> None: + self.is_running_event.set() + + def run(self) -> None: + while not self.is_running_event.is_set(): + self.sample_counters() + self.is_running_event.wait(self.refresh_interval) + + def log_sample(self, resource_sample: ResourceStatsSample) -> None: + self.stats_callback_fn(resource_sample) + + def sample_counters(self) -> None: + if not self.p.is_running(): + self.stop() + return + + with self.p.oneshot(): + cpu_percent = self.p.cpu_percent() + cpu_times = self.p.cpu_times() + io_counters = self.p.io_counters() + cpu_affinity = self.p.cpu_affinity() + cpu_num = self.p.cpu_num() + num_threads = self.p.num_threads() + num_ctx_switches = self.p.num_ctx_switches() + timestamp = time.time() + + read_count = io_counters.read_count + write_count = io_counters.write_count + read_bytes = io_counters.read_bytes + write_bytes = io_counters.write_bytes + read_chars = io_counters.read_chars + write_chars = io_counters.write_chars + + def compress_cpu_affinity(cpu_affinity): + """Change list representation to interval/range representation.""" + if not cpu_affinity: + return "" + cpu_affinity_compressed = [] + min_x = None + max_x = None + last_x = None + + # Find contiguous ranges + for x in cpu_affinity: + if last_x is None: + # Start interval + min_x = x + max_x = x + last_x = x + continue + elif x == (last_x + 1): + # Move interval up + max_x = x + elif max_x is not None: + # Interval ended, start again + if min_x == max_x: + cpu_affinity_compressed.append("{}".format(min_x)) + else: + cpu_affinity_compressed.append("{}-{}".format(min_x, max_x)) + min_x = x + max_x = x + last_x = x + # Terminate last range + if max_x is not None: + if min_x == max_x: + cpu_affinity_compressed.append("{}".format(min_x)) + else: + cpu_affinity_compressed.append("{}-{}".format(min_x, max_x)) + + # Concat + cpu_affinity_compressed = ",".join(cpu_affinity_compressed) + + return cpu_affinity_compressed + + cpu_affinity = compress_cpu_affinity(cpu_affinity) + + resource_sample = ResourceStatsSample( + timestamp=timestamp, + cpu_percent=cpu_percent, + read_count=read_count, + write_count=write_count, + read_bytes=read_bytes, + write_bytes=write_bytes, + read_chars=read_chars, + write_chars=write_chars, + cpu_times_user=cpu_times.user, + cpu_times_system=cpu_times.system, + cpu_times_children_user=cpu_times.children_user, + cpu_times_children_system=cpu_times.children_system, + cpu_times_iowait=cpu_times.iowait, + cpu_affinity=cpu_affinity, + cpu_num=cpu_num, + num_threads=num_threads, + num_voluntary_ctx_switches=num_ctx_switches.voluntary, + num_involuntary_ctx_switches=num_ctx_switches.involuntary, + ) + self.log_sample(resource_sample) + + +if __name__ == "__main__": + import multiprocessing + + pid = multiprocessing.current_process().pid + monitor_thread = ResourceMonitoringThread(pid, 1) + monitor_thread.start() + time.sleep(5) + print("Shutdown") + monitor_thread.stop() diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/schedulers.py b/starVLA/facebookresearch_vjepa2_main/src/utils/schedulers.py new file mode 100644 index 0000000000000000000000000000000000000000..4339fe2be7422499c50e25736879c18750531e00 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/schedulers.py @@ -0,0 +1,112 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math + + +class WSDSchedule(object): + + def __init__(self, optimizer, warmup_steps, anneal_steps, T_max, start_lr, ref_lr, final_lr=0.0): + self.optimizer = optimizer + self.start_lr = start_lr + self.ref_lr = ref_lr + self.final_lr = final_lr + self.anneal_steps = anneal_steps + self.warmup_steps = warmup_steps + self.T_max = T_max - warmup_steps - anneal_steps + self._step = 0.0 + + def step(self): + self._step += 1 + if self._step < self.warmup_steps: + progress = float(self._step) / float(max(1, self.warmup_steps)) + new_lr = self.start_lr + progress * (self.ref_lr - self.start_lr) + elif self._step < self.T_max + self.warmup_steps: + new_lr = self.ref_lr + else: + _step = self._step - (self.T_max + self.warmup_steps) + progress = float(_step) / float(max(1, self.anneal_steps)) + new_lr = self.ref_lr + progress * (self.final_lr - self.ref_lr) + + for group in self.optimizer.param_groups: + group["lr"] = new_lr + if "lr_scale" in group: + group["lr"] *= group["lr_scale"] + + return new_lr + + +class WarmupCosineSchedule(object): + + def __init__(self, optimizer, warmup_steps, start_lr, ref_lr, T_max, last_epoch=-1, final_lr=0.0): + self.optimizer = optimizer + self.start_lr = start_lr + self.ref_lr = ref_lr + self.final_lr = final_lr + self.warmup_steps = warmup_steps + self.T_max = T_max - warmup_steps + self._step = 0.0 + + def step(self): + self._step += 1 + if self._step < self.warmup_steps: + progress = float(self._step) / float(max(1, self.warmup_steps)) + new_lr = self.start_lr + progress * (self.ref_lr - self.start_lr) + else: + # -- progress after warmup + progress = float(self._step - self.warmup_steps) / float(max(1, self.T_max)) + new_lr = max( + self.final_lr, + self.final_lr + (self.ref_lr - self.final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), + ) + + for group in self.optimizer.param_groups: + group["lr"] = new_lr + + return new_lr + + +class CosineWDSchedule(object): + + def __init__(self, optimizer, ref_wd, T_max, final_wd=0.0): + self.optimizer = optimizer + self.ref_wd = ref_wd + self.final_wd = final_wd + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + progress = self._step / self.T_max + new_wd = self.final_wd + (self.ref_wd - self.final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) + + if self.final_wd <= self.ref_wd: + new_wd = max(self.final_wd, new_wd) + else: + new_wd = min(self.final_wd, new_wd) + + for group in self.optimizer.param_groups: + if ("WD_exclude" not in group) or not group["WD_exclude"]: + group["weight_decay"] = new_wd + return new_wd + + +class LinearDecaySchedule(object): + + def __init__(self, optimizer, ref_lr, T_max, last_epoch=-1, final_lr=0.0): + self.optimizer = optimizer + self.ref_lr = ref_lr + self.final_lr = final_lr + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + progress = float(self._step) / float(max(1, self.T_max)) + new_lr = self.ref_lr + progress * (self.final_lr - self.ref_lr) + for group in self.optimizer.param_groups: + group["lr"] = new_lr + + return new_lr diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/tensors.py b/starVLA/facebookresearch_vjepa2_main/src/utils/tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7bfafc67c69bfd10f663ce259c4fd7bfe6ab45 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/tensors.py @@ -0,0 +1,53 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from logging import getLogger + +import torch + +logger = getLogger() + + +def _no_grad_trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0 + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + lower = norm_cdf((a - mean) / std) + upper = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [lower, upper], then translate to + # [2*lower-1, 2*upper-1]. + tensor.uniform_(2 * lower - 1, 2 * upper - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.0)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0): + # type: (Tensor, float, float, float, float) -> Tensor + return _no_grad_trunc_normal_(tensor, mean, std, a, b) + + +def repeat_interleave_batch(x, B, repeat): + N = len(x) // B + x = torch.cat([torch.cat([x[i * B : (i + 1) * B] for _ in range(repeat)], dim=0) for i in range(N)], dim=0) + return x diff --git a/starVLA/facebookresearch_vjepa2_main/src/utils/wrappers.py b/starVLA/facebookresearch_vjepa2_main/src/utils/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..cb24a136c3831bc7c13efd39a49ee30079834ec5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/utils/wrappers.py @@ -0,0 +1,44 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch.nn as nn + + +class MultiSeqWrapper(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + self.embed_dim = backbone.embed_dim + + def forward(self, x, masks=None): + """ + :param x: [list] List of Tensors of different seq lengths + :param masks: [list[list]] List of Tensors (out index: masks for given seq length, inner index: multimasks for that seq len) + """ + if masks is None: + return [self.backbone(xi) for xi in x] + + outs = [[] for _ in x] + for i, (xi, mi) in enumerate(zip(x, masks)): + for mij in mi: + outs[i] += [self.backbone(xi, masks=mij)] + return outs + + +class PredictorMultiSeqWrapper(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + + def forward(self, x, masks_x, masks_y, has_cls=False): + n = 0 + outs = [[] for _ in x] + for i, (xi, mxi, myi) in enumerate(zip(x, masks_x, masks_y)): + for xij, mxij, myij in zip(xi, mxi, myi): + outs[i] += [self.backbone(xij, mxij, myij, mask_index=i, has_cls=has_cls)] + n += 1 + return outs diff --git a/starVLA/facebookresearch_vjepa2_main/tests/__init__.py b/starVLA/facebookresearch_vjepa2_main/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b671f45cb34d1ef1259062fecce89a2338c3ab40 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +import sys + +JEPA_ROOT = os.path.dirname(os.path.dirname(__file__)) +sys.path.append(JEPA_ROOT) diff --git a/starVLA/facebookresearch_vjepa2_main/tests/datasets/__init__.py b/starVLA/facebookresearch_vjepa2_main/tests/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b671f45cb34d1ef1259062fecce89a2338c3ab40 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/datasets/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +import sys + +JEPA_ROOT = os.path.dirname(os.path.dirname(__file__)) +sys.path.append(JEPA_ROOT) diff --git a/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_dataloader.py b/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..d0aae23fee6fdc1a2334449230544dbb0bbb0c7a --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_dataloader.py @@ -0,0 +1,34 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +from src.datasets.utils.dataloader import ConcatIndices + + +class TestConcatIndices(unittest.TestCase): + def test_concat_indices(self): + sizes = [10, 20, 30, 40] + total_size = sum(sizes) + concat_indices = ConcatIndices(sizes) + + # -1 is outside the total range + with self.assertRaises(ValueError): + concat_indices[-1] + # 0-9 map to dataset 0 + self.assertEqual(concat_indices[0], (0, 0)) + self.assertEqual(concat_indices[9], (0, 9)) + # 10-29 map to dataset 1 + self.assertEqual(concat_indices[10], (1, 0)) + self.assertEqual(concat_indices[29], (1, 19)) + # 30-59 map to dataset 2 + self.assertEqual(concat_indices[30], (2, 0)) + self.assertEqual(concat_indices[59], (2, 29)) + # 60-99 map to dataset 3 + self.assertEqual(concat_indices[60], (3, 0)) + self.assertEqual(concat_indices[99], (3, 39)) + # 100 is outside the total range + with self.assertRaises(ValueError): + concat_indices[total_size] diff --git a/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_memory_efficient_sampler.py b/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_memory_efficient_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdeab24b999a91c7a3744e2e9fe33b0378ed321 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_memory_efficient_sampler.py @@ -0,0 +1,151 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +from src.datasets.utils.weighted_sampler import ( + MemoryEfficientDistributedWeightedSampler, + MemoryEfficientDistributedWeightedSamplerLessRepeat, +) + + +class MockDataset: + def __init__(self, datasets, dataset_weights): + self.datasets = datasets + self.dataset_weights = dataset_weights + + def __len__(self): + return sum(len(d) for d in self.datasets) + + +class TestMemoryEfficientSampler(unittest.TestCase): + + def test_shuffled_sampling_single(self): + "The specific values returned are a function of the random sampler with the given seed." + datasets = [] + for i in range(3): + datasets.append([f"DS{i}"] * 100 * (i + 1)) + + mock_dataset = MockDataset(datasets, [1, 1, 1]) + sampler = MemoryEfficientDistributedWeightedSampler(mock_dataset, num_replicas=1, rank=0, shuffle=True) + + smplr_it = iter(sampler) + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 202) # Based on previous run + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 26) # Based on previous run + + def test_shuffled_sampling(self): + datasets = [] + for i in range(3): + datasets.append([f"DS{i}"] * 100 * (i + 1)) + + mock_dataset = MockDataset(datasets, [1, 2000, 1]) + sampler = MemoryEfficientDistributedWeightedSampler(mock_dataset, num_replicas=8, rank=3, shuffle=True) + + smplr_it = iter(sampler) + + # Notice how the following samples are drawn from the 2nd dataset, which has a weight of 2000. + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 135) # Based on previous run + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 143) # Based on previous run + + def test_non_shuffled_sampling(self): + datasets = [] + for i in range(3): + datasets.append([f"DS{i}"] * 100 * (i + 1)) + + mock_dataset = MockDataset(datasets, [1, 10, 1]) + sampler = MemoryEfficientDistributedWeightedSampler(mock_dataset, num_replicas=4, rank=2, shuffle=False) + + smplr_it = iter(sampler) + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 102) # Calculated based on the `__next__` function's non shuffled logic. + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 106) # Calculated based on the `__next__` function's non shuffled logic. + + +class TestMemoryEfficientSamplerLessRepeat(unittest.TestCase): + + def test_shuffled_sampling_single(self): + """ + Testing all weights are equal to 1. + The specific values returned are a function of the random sampler with the given seed. + """ + datasets = [] + for i in range(3): + datasets.append([f"DS{i}"] * 100 * (i + 1)) + + mock_dataset = MockDataset(datasets, [1, 1, 1]) + sampler = MemoryEfficientDistributedWeightedSamplerLessRepeat( + mock_dataset, num_replicas=1, rank=0, shuffle=True + ) + + smplr_it = iter(sampler) + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 144) # Based on previous run + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 84) # Based on previous run + + def test_shuffled_sampling(self): + """ + Testing one dominant dataset. + The specific values returned are a function of the random sampler with the given seed. + """ + datasets = [] + for i in range(3): + datasets.append([f"DS{i}"] * 100 * (i + 1)) + + mock_dataset = MockDataset(datasets, [1, 2000, 1]) + sampler = MemoryEfficientDistributedWeightedSamplerLessRepeat( + mock_dataset, num_replicas=8, rank=3, shuffle=True + ) + + smplr_it = iter(sampler) + + # Notice how the following samples are drawn from the 2nd dataset, which has a weight of 2000. + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 255) # Based on previous run + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 231) # Based on previous run + + def test_non_shuffled_sampling(self): + datasets = [] + for i in range(3): + datasets.append([f"DS{i}"] * 100 * (i + 1)) + + mock_dataset = MockDataset(datasets, [1, 10, 1]) + sampler = MemoryEfficientDistributedWeightedSamplerLessRepeat( + mock_dataset, num_replicas=4, rank=2, shuffle=False + ) + + smplr_it = iter(sampler) + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 102) # Calculated based on the `__next__` function's non shuffled logic. + + ex = next(smplr_it) + self.assertIsNotNone(ex) + self.assertEqual(ex, 106) # Calculated based on the `__next__` function's non shuffled logic. diff --git a/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_vjepa_transforms.py b/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_vjepa_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..1340f4769e5cd3913518ec18e1c3995f31f1ea59 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/datasets/test_vjepa_transforms.py @@ -0,0 +1,91 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import numpy as np +import torch + +from app.vjepa import transforms +from src.datasets.utils.video import functional +from src.datasets.utils.video.volume_transforms import ClipToTensor + + +class TestNormalize(unittest.TestCase): + + def setUp(self): + self.g = torch.Generator() + self.g.manual_seed(42) + + def test_approximation_equivalence(self): + T, H, W, C = 16, 224, 224, 3 + shape = (T, H, W, C) + mean = torch.tensor([0.485, 0.456, 0.406]) + std = torch.tensor([0.229, 0.224, 0.225]) + for i in range(10): + X = torch.randint(low=0, high=255, size=shape, generator=self.g, dtype=torch.uint8) + X_clone = X.clone().permute(3, 0, 1, 2) # C, T, H, W + + X_norm = transforms.tensor_normalize(X, mean, std) + X_norm_fast = transforms._tensor_normalize_inplace(X_clone, 255.0 * mean, 255.0 * std) + self.assertTrue(torch.allclose(X_norm, X_norm_fast.permute(1, 2, 3, 0))) + + +class TestVideoTransformFunctionalCrop(unittest.TestCase): + def test_tensor_numpy(self): + T, C, H, W = 16, 3, 280, 320 + shape = (T, C, H, W) + crop_size = (10, 10, 224, 224) + video_tensor = torch.randint(low=0, high=255, size=shape, dtype=torch.uint8) + video_numpy = video_tensor.numpy() + + cropped_tensor = functional.crop_clip(video_tensor, *crop_size) + self.assertIsInstance(cropped_tensor[0], torch.Tensor) + + cropped_np_array = functional.crop_clip(video_numpy, *crop_size) + self.assertIsInstance(cropped_np_array[0], np.ndarray) + + for clip_tensor, clip_np in zip(cropped_tensor, cropped_np_array): + torch.testing.assert_close(clip_tensor, torch.Tensor(clip_np).to(dtype=torch.uint8)) + + +class TestVideoTransformFunctionalResize(unittest.TestCase): + def test_tensor_numpy(self): + T, C, H, W = 16, 3, 280, 320 + shape = (T, C, H, W) + resize_to = 256 + + video_tensor = torch.randint(low=0, high=255, size=shape, dtype=torch.int16) + # We permute the videos because our underlying numpy.array based transforms are expecting + # image in (H, W, C) shape whereas our tensor transforms are mostly in (C, H, W) + video_numpy = video_tensor.permute(0, 2, 3, 1).numpy() # (T, C, H, W) -> (T, H, W, C) + + resized_tensor = functional.resize_clip(video_tensor, resize_to) + self.assertIsInstance(resized_tensor[0], torch.Tensor) + + resized_np_array = functional.resize_clip(video_numpy, resize_to) + self.assertIsInstance(resized_np_array[0], np.ndarray) + + for clip_tensor, clip_np in zip(resized_tensor, resized_np_array): + clip_tensor = clip_tensor.permute(1, 2, 0) + diff = torch.mean((torch.abs(clip_tensor - torch.Tensor(clip_np).to(torch.int16))) / (clip_tensor + 1)) + + # Transformations can not exactly match because of their interpolation functions coming from + # two different sources. Here we check for their relative differences. + # See the discussion here: https://github.com/fairinternal/jepa-internal/pull/65#issuecomment-2101833959 + self.assertLess(diff, 0.05) + + +class TestVideoTransformClipToTensor(unittest.TestCase): + def test_tensor_numpy(self): + T, C, H, W = 16, 3, 280, 320 + shape = (T, C, H, W) + transform = ClipToTensor() + + video_tensor = [clip for clip in torch.randint(low=0, high=255, size=shape, dtype=torch.int16)] + # We permute the videos because our underlying numpy.array based transforms are expecting + # image in (H, W, C) shape whereas our tensor transforms are mostly in (C, H, W) + video_numpy = [clip.permute(1, 2, 0).numpy() for clip in video_tensor] + torch.testing.assert_close(transform(video_tensor), transform(video_numpy)) diff --git a/starVLA/facebookresearch_vjepa2_main/tests/models/__init__.py b/starVLA/facebookresearch_vjepa2_main/tests/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b671f45cb34d1ef1259062fecce89a2338c3ab40 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/models/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +import sys + +JEPA_ROOT = os.path.dirname(os.path.dirname(__file__)) +sys.path.append(JEPA_ROOT) diff --git a/starVLA/facebookresearch_vjepa2_main/tests/models/test_models.py b/starVLA/facebookresearch_vjepa2_main/tests/models/test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a05c99f0543879bfa44428f4b43e88be4dfcb9 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/models/test_models.py @@ -0,0 +1,93 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch + +from src.models.vision_transformer import VIT_EMBED_DIMS, vit_tiny + + +class TestImageViT(unittest.TestCase): + def setUp(self) -> None: + self._vit_tiny = vit_tiny() + self.height, self.width = 224, 224 + self.num_patches = (self.height // self._vit_tiny.patch_size) * (self.width // self._vit_tiny.patch_size) + + def test_model_image_nomask_batchsize_4(self): + BS = 4 + x = torch.rand((BS, 3, self.height, self.width)) + y = self._vit_tiny(x) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"])) + + def test_model_image_nomask_batchsize_1(self): + BS = 1 + x = torch.rand((BS, 3, self.height, self.width)) + y = self._vit_tiny(x) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"])) + + def test_model_image_masked_batchsize_4(self): + BS = 4 + mask_indices = [6, 7, 8] + masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)] + x = torch.rand((BS, 3, self.height, self.width)) + y = self._vit_tiny(x, masks=masks) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"])) + + def test_model_image_masked_batchsize_1(self): + BS = 1 + mask_indices = [6, 7, 8] + masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)] + x = torch.rand((BS, 3, self.height, self.width)) + y = self._vit_tiny(x, masks=masks) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"])) + + +class TestVideoViT(unittest.TestCase): + def setUp(self) -> None: + self.num_frames = 8 + self._vit_tiny = vit_tiny(num_frames=8) + self.height, self.width = 224, 224 + self.num_patches = ( + (self.height // self._vit_tiny.patch_size) + * (self.width // self._vit_tiny.patch_size) + * (self.num_frames // self._vit_tiny.tubelet_size) + ) + + def test_model_video_nomask_batchsize_4(self): + BS = 4 + x = torch.rand((BS, 3, self.num_frames, self.height, self.width)) + y = self._vit_tiny(x) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"])) + + def test_model_video_nomask_batchsize_1(self): + BS = 1 + x = torch.rand((BS, 3, self.num_frames, self.height, self.width)) + y = self._vit_tiny(x) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, self.num_patches, VIT_EMBED_DIMS["vit_tiny"])) + + def test_model_video_masked_batchsize_4(self): + BS = 4 + mask_indices = [6, 7, 8] + masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)] + x = torch.rand((BS, 3, self.num_frames, self.height, self.width)) + y = self._vit_tiny(x, masks=masks) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"])) + + def test_model_video_masked_batchsize_1(self): + BS = 1 + mask_indices = [6, 7, 8] + masks = [torch.tensor(mask_indices, dtype=torch.int64) for _ in range(BS)] + x = torch.rand((BS, 3, self.num_frames, self.height, self.width)) + y = self._vit_tiny(x, masks=masks) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, len(mask_indices), VIT_EMBED_DIMS["vit_tiny"])) diff --git a/starVLA/facebookresearch_vjepa2_main/tests/models/test_predictor.py b/starVLA/facebookresearch_vjepa2_main/tests/models/test_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..8ebc63f9dc4c9608f92efa57c6c80f8817bb0514 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/models/test_predictor.py @@ -0,0 +1,58 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch + +from src.models.predictor import VisionTransformerPredictor + + +class TestImagePredictorMaskTokens(unittest.TestCase): + def setUp(self) -> None: + self._embed_dim = 768 + self._predictor = VisionTransformerPredictor(embed_dim=self._embed_dim, use_mask_tokens=True) + + def test_image_predictor_batchsize_4(self): + BS = 4 + enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)] + target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)] + enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim)) + y = self._predictor(enc, enc_mask_indices, target_mask_indices) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim)) + + def test_image_predictor_batchsize_1(self): + BS = 1 + enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)] + target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)] + enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim)) + y = self._predictor(enc, enc_mask_indices, target_mask_indices) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim)) + + +class TestVideoPredictorMaskTokens(unittest.TestCase): + def setUp(self) -> None: + self._embed_dim = 768 + self._predictor = VisionTransformerPredictor(embed_dim=self._embed_dim, use_mask_tokens=True) + + def test_video_predictor_batchsize_4(self): + BS = 4 + enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)] + target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)] + enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim)) + y = self._predictor(enc, enc_mask_indices, target_mask_indices) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim)) + + def test_video_predictor_batchsize_1(self): + BS = 1 + enc_mask_indices = [torch.tensor(BS * [[6, 7, 8]], dtype=torch.int64)] + target_mask_indices = [torch.tensor(BS * [[16, 17, 18, 19]], dtype=torch.int64)] + enc = torch.rand((BS, len(enc_mask_indices[0][0]), self._embed_dim)) + y = self._predictor(enc, enc_mask_indices, target_mask_indices) + self.assertIsInstance(y, torch.Tensor) + self.assertEqual(y.size(), (BS, target_mask_indices[0].size(1), self._embed_dim)) diff --git a/starVLA/facebookresearch_vjepa2_main/tests/models/test_vision_transformer.py b/starVLA/facebookresearch_vjepa2_main/tests/models/test_vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..af314792311703b69c10b145419cd4b8f45ab872 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/tests/models/test_vision_transformer.py @@ -0,0 +1,63 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import unittest +from copy import deepcopy + +import numpy as np +import pytest +import torch + +from src.models.vision_transformer import vit_giant_xformers_rope + + +# Usage: pytest tests/models/test_vision_transformer.py +@pytest.mark.skipif(not torch.cuda.is_available(), reason="This test requires CUDA") +class TestViTGiant(unittest.TestCase): + def setUp(self) -> None: + self.model_shape_invariant = vit_giant_xformers_rope( + img_size=256, patch_size=16, num_frames=16, handle_nonsquare_inputs=True + ).cuda() + self.model_square = deepcopy(self.model_shape_invariant) + self.model_square.handle_nonsquare_inputs = False + torch.manual_seed(42) + self.total_iters = 10 + + def test_square_inputs(self): + for i in range(self.total_iters): + input = torch.rand(1, 3, 16, 256, 256).cuda() + with torch.cuda.amp.autocast(enabled=True): + with torch.no_grad(): + out1 = self.model_shape_invariant(input) + out2 = self.model_square(input) + torch.testing.assert_close(out1, out2) + + def test_square_inputs_with_mask(self): + for i in range(self.total_iters): + input = torch.rand(1, 3, 16, 256, 256).cuda() + mask = torch.randint(0, 2, (1, 2048)).cuda() + with torch.cuda.amp.autocast(enabled=True): + with torch.no_grad(): + out1 = self.model_shape_invariant(input, masks=mask) + out2 = self.model_square(input, masks=mask) + torch.testing.assert_close(out1, out2) + + def test_nonsquare_inputs(self): + for i in range(self.total_iters): + rand_width = np.random.randint(256, 512) + rand_height = np.random.randint(256, 512) + input = torch.rand(1, 3, 16, rand_height, rand_width).cuda() + # Since input is interpolated, output won't be exactly the same + input_resized_to_square = [ + torch.nn.functional.interpolate(input[:, :, frame_idx], size=256, mode="bicubic") + for frame_idx in range(input.shape[2]) + ] + input_resized_to_square = torch.stack(input_resized_to_square, dim=2) + + with torch.cuda.amp.autocast(enabled=True): + with torch.no_grad(): + out1 = self.model_shape_invariant(input).mean(dim=1) + out2 = self.model_square(input_resized_to_square).mean(dim=1) + self.assertAlmostEqual(torch.nn.functional.cosine_similarity(out2, out1).item(), 1.0, places=3) diff --git a/starVLA/model/framework/DreamZero.py b/starVLA/model/framework/DreamZero.py new file mode 100644 index 0000000000000000000000000000000000000000..6fcca524aee2ff0160acd3bab9b061ee759ede18 --- /dev/null +++ b/starVLA/model/framework/DreamZero.py @@ -0,0 +1,496 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""DreamZero Wan2.2 policy framework for starVLA. + +This is a starVLA-native DreamZero model file. It uses the existing +Wan2.2-TI2V-5B-Diffusers world model in ``starVLA.model.modules.world_model.Wan2`` +and trains joint action/future-image latent flow targets, so it does not depend +on the official DreamZero training stack, Hydra, GrootSimPolicy, or PEFT. +""" + +import math +import os +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class DreamZeroDefaultConfig: + """Wan2.2 DreamZero-style action/video policy defaults.""" + + name: str = "DreamZero" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + "height": 224, + "width": 224, + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 3072, + }) + + action_model: dict = field(default_factory=lambda: { + "action_dim": 32, + "state_dim": 64, + "future_action_window_size": 15, + "action_horizon": 16, + "past_action_window_size": 0, + }) + + policy: dict = field(default_factory=lambda: { + "train_time_distribution": "logitnormal", + "shift": 5.0, + "action_loss_weight": 1.0, + "future_image_loss_weight": 1.0, + "num_inference_steps": 5, + "timestep_scale": 1000.0, + "decode_future_images": True, + "autoregressive": True, + "latent_clip_value": 30.0, + "prediction_clip_value": 30.0, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("DreamZero") +class DreamZero(baseframework): + """Wan2.2 latent action and future-image flow-matching policy.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(DreamZeroDefaultConfig, config) + self.backbone = get_world_model(config=self.config) + self._disable_backbone_feature_hooks() + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.action_dim = self.config.framework.action_model.action_dim + + policy_cfg = self.config.framework.get("policy", {}) + self.train_time_distribution = policy_cfg.get("train_time_distribution", "logitnormal") + self.shift = float(policy_cfg.get("shift", 5.0)) + self.action_loss_weight = float(policy_cfg.get("action_loss_weight", 1.0)) + self.future_image_loss_weight = float(policy_cfg.get("future_image_loss_weight", 1.0)) + self.num_inference_steps = int(policy_cfg.get("num_inference_steps", 5)) + self.timestep_scale = float(policy_cfg.get("timestep_scale", 1000.0)) + self.decode_future_images = self._as_bool(policy_cfg.get("decode_future_images", True)) + self.autoregressive = self._as_bool(policy_cfg.get("autoregressive", True)) + self.latent_clip_value = float(policy_cfg.get("latent_clip_value", 30.0)) + self.prediction_clip_value = float(policy_cfg.get("prediction_clip_value", 30.0)) + self._wm_debug_count = 0 + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _disable_backbone_feature_hooks(self) -> None: + for hook in getattr(self.backbone, "_hooks", []): + hook.remove() + if hasattr(self.backbone, "_hooks"): + self.backbone._hooks.clear() + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + def _begin_wm_debug_trace(self) -> bool: + if os.getenv("STARVLA_WM_DEBUG", "0").lower() not in {"1", "true", "yes", "on"}: + return False + max_traces = int(os.getenv("STARVLA_WM_DEBUG_MAX", "6")) + if self._wm_debug_count >= max_traces: + return False + self._wm_debug_count += 1 + return True + + @staticmethod + def _tensor_stats(name: str, tensor: torch.Tensor) -> str: + tensor = tensor.detach().float() + return ( + f"{name}:shape={tuple(tensor.shape)}," + f"mean={tensor.mean().item():.4g},std={tensor.std(unbiased=False).item():.4g}," + f"min={tensor.min().item():.4g},max={tensor.max().item():.4g}," + f"nan={torch.isnan(tensor).any().item()},inf={torch.isinf(tensor).any().item()}" + ) + + def _log_wm_debug(self, enabled: bool, label: str, **tensors) -> None: + if not enabled: + return + parts = [f"[WM_DEBUG_VERSION=DreamZeroWan2Native] {type(self).__name__} {label}"] + for name, tensor in tensors.items(): + if tensor is not None: + parts.append(self._tensor_stats(name, tensor)) + print(" | ".join(parts), flush=True) + + @staticmethod + def _sanitize_tensor(tensor: torch.Tensor, clip_value: Optional[float] = None) -> torch.Tensor: + tensor = torch.nan_to_num(tensor, nan=0.0, posinf=0.0, neginf=0.0) + if clip_value is not None and clip_value > 0: + tensor = tensor.clamp(min=-clip_value, max=clip_value) + return tensor + + def _select_action_chunk(self, actions) -> torch.Tensor: + actions = torch.tensor(np.array(actions), dtype=torch.float32) + return actions[:, -(self.future_action_window_size + 1):, :] + + @staticmethod + def _latent_slot_count(latents: torch.Tensor) -> int: + _, channels, _, height, width = latents.shape + return channels * height * width + + def _tensor_to_latent_frame(self, values: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + batch_size, channels, _, height, width = latents.shape + flat_values = values.reshape(batch_size, -1).to(device=latents.device, dtype=latents.dtype) + slot_count = self._latent_slot_count(latents) + repeat_factor = math.ceil(slot_count / flat_values.shape[1]) + tiled_values = flat_values.repeat(1, repeat_factor)[:, :slot_count] + return tiled_values.reshape(batch_size, channels, height, width) + + def _actions_to_latent_frame(self, actions: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + return self._tensor_to_latent_frame(actions, latents) + + def _latent_frame_to_actions(self, action_frame: torch.Tensor, action_shape) -> torch.Tensor: + batch_size = action_frame.shape[0] + flat_dim = int(np.prod(action_shape[1:])) + flat_frame = action_frame.reshape(batch_size, -1) + slot_count = flat_frame.shape[1] + action_indices = torch.arange(slot_count, device=flat_frame.device) % flat_dim + + action_sum = flat_frame.new_zeros((batch_size, flat_dim)) + action_count = flat_frame.new_zeros((batch_size, flat_dim)) + expanded_indices = action_indices.expand(batch_size, -1) + action_sum.scatter_add_(1, expanded_indices, flat_frame) + action_count.scatter_add_(1, expanded_indices, torch.ones_like(flat_frame)) + return (action_sum / action_count.clamp_min(1.0)).reshape(batch_size, *action_shape[1:]) + + def _sample_train_times(self, batch_size: int, device: torch.device) -> torch.Tensor: + distribution = str(self.train_time_distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported train_time_distribution={self.train_time_distribution!r}") + + def _shift_time(self, time: torch.Tensor, shift: Optional[float] = None) -> torch.Tensor: + shift = self.shift if shift is None else float(shift) + return shift * time / (1.0 + (shift - 1.0) * time) + + def _flow_inference_schedule(self, num_steps: int, device: torch.device, shift: Optional[float] = None): + base_times = torch.linspace(1.0, 0.0, num_steps + 1, device=device, dtype=torch.float32) + return self._shift_time(base_times, shift=shift) + + def _make_wan_timestep( + self, + hidden_states: torch.Tensor, + target_indices: List[int], + timestep: torch.Tensor, + ) -> torch.Tensor: + batch_size, _, num_latent_frames, height, width = hidden_states.shape + p_t, p_h, p_w = self.backbone.transformer.config.patch_size + frame_token_count = (height // p_h) * (width // p_w) + temporal_token_count = num_latent_frames // p_t + seq_len = temporal_token_count * frame_token_count + rope_max_seq_len = getattr(self.backbone.transformer.config, "rope_max_seq_len", None) + if rope_max_seq_len is not None and seq_len > rope_max_seq_len: + raise ValueError( + f"DreamZero Wan policy seq_len={seq_len} exceeds rope_max_seq_len={rope_max_seq_len}. " + "Reduce observation frames/resolution or disable optional future-image targets." + ) + + timestep_tokens = torch.zeros( + batch_size, + seq_len, + device=hidden_states.device, + dtype=torch.float32, + ) + timestep = timestep.to(device=hidden_states.device, dtype=torch.float32) * self.timestep_scale + for target_idx in target_indices: + temporal_idx = int(target_idx) // p_t + start = temporal_idx * frame_token_count + end = start + frame_token_count + timestep_tokens[:, start:end] = timestep[:, None] + return timestep_tokens + + def _make_policy_inputs( + self, + wm_inputs: dict, + target_frames: List[torch.Tensor], + timestep: torch.Tensor, + context_frames: Optional[List[torch.Tensor]] = None, + ): + condition_latents = wm_inputs["hidden_states"] + context_frames = context_frames or [] + hidden_states = torch.cat( + [ + condition_latents, + *[frame.unsqueeze(2).to(condition_latents.dtype) for frame in context_frames], + *[frame.unsqueeze(2).to(condition_latents.dtype) for frame in target_frames], + ], + dim=2, + ) + condition_t = condition_latents.shape[2] + len(context_frames) + target_indices = list(range(condition_t, condition_t + len(target_frames))) + timestep_tokens = self._make_wan_timestep(hidden_states, target_indices=target_indices, timestep=timestep) + return { + "hidden_states": hidden_states, + "timestep": timestep_tokens, + "encoder_hidden_states": wm_inputs["encoder_hidden_states"], + "target_indices": target_indices, + } + + def _run_transformer(self, policy_inputs: dict) -> torch.Tensor: + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + output = self.backbone.transformer( + hidden_states=policy_inputs["hidden_states"], + timestep=policy_inputs["timestep"], + encoder_hidden_states=policy_inputs["encoder_hidden_states"], + ) + pred = output.sample if hasattr(output, "sample") else output + if isinstance(pred, tuple): + pred = pred[0] + pred = self._sanitize_tensor(pred, clip_value=self.prediction_clip_value) + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + return pred[:, :, policy_inputs["target_indices"]].float() + + def _predict_velocity( + self, + wm_inputs: dict, + target_frames: List[torch.Tensor], + timestep: torch.Tensor, + context_frames: Optional[List[torch.Tensor]] = None, + ) -> torch.Tensor: + policy_inputs = self._make_policy_inputs( + wm_inputs=wm_inputs, + target_frames=target_frames, + timestep=timestep, + context_frames=context_frames, + ) + return self._run_transformer(policy_inputs) + + def _predict_velocity_autoregressive( + self, + wm_inputs: dict, + sample_frames: List[torch.Tensor], + timestep: torch.Tensor, + teacher_context_frames: Optional[List[torch.Tensor]] = None, + ) -> torch.Tensor: + pred_frames = [] + context_frames = list(teacher_context_frames or []) + for frame_idx, sample_frame in enumerate(sample_frames): + pred_frame = self._predict_velocity( + wm_inputs=wm_inputs, + target_frames=[sample_frame], + timestep=timestep, + context_frames=context_frames, + )[:, :, 0] + pred_frames.append(pred_frame) + context_frames.append(sample_frame.detach()) + return torch.stack(pred_frames, dim=2) + + def _encode_future_image_frame(self, future_images: List, like_latents: torch.Tensor) -> Optional[torch.Tensor]: + if future_images is None or self.future_image_loss_weight <= 0: + return None + future_latents = self.backbone._encode_images_vae(future_images, num_frames=1).float() + future_frame = future_latents[:, :, 0].to(device=like_latents.device, dtype=like_latents.dtype) + return self._sanitize_tensor(future_frame, clip_value=self.latent_clip_value) + + def _decode_latent_frames(self, latent_frames: torch.Tensor) -> List[np.ndarray]: + latent_video = latent_frames.to(device=latent_frames.device, dtype=self.backbone.vae.dtype) + + if getattr(self.backbone.vae.config, "latents_mean", None) is not None: + latents_mean = ( + torch.tensor(self.backbone.vae.config.latents_mean) + .view(1, self.backbone.vae.config.z_dim, 1, 1, 1) + .to(device=latent_video.device, dtype=latent_video.dtype) + ) + latents_std = ( + torch.tensor(self.backbone.vae.config.latents_std) + .view(1, self.backbone.vae.config.z_dim, 1, 1, 1) + .to(device=latent_video.device, dtype=latent_video.dtype) + ) + latent_video = latent_video * latents_std + latents_mean + + with torch.no_grad(): + decoded = self.backbone.vae.decode(latent_video).sample + + decoded = decoded.float().clamp(-1, 1) + decoded = ((decoded + 1.0) * 127.5).clamp(0, 255).byte() + decoded = decoded.permute(0, 2, 3, 4, 1).detach().cpu().numpy() + images = [] + for sample in decoded: + frames = [sample[idx] for idx in range(sample.shape[0])] + images.append(frames[0] if len(frames) == 1 else np.concatenate(frames, axis=1)) + return images + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + batch_images = [example["image"] for example in examples] + future_images = [example["future_image"] for example in examples] if "future_image" in examples[0] else None + instructions = [example["lang"] for example in examples] + actions = self._select_action_chunk([example["action"] for example in examples]) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + latents = wm_inputs["hidden_states"] + latents = self._sanitize_tensor(latents, clip_value=self.latent_clip_value) + wm_inputs["hidden_states"] = latents + actions = self._sanitize_tensor(actions.to(device=latents.device, dtype=torch.float32), clip_value=1.0) + target_action_frame = self._actions_to_latent_frame(actions, latents).float() + target_action_frame = self._sanitize_tensor(target_action_frame, clip_value=self.latent_clip_value) + + target_frames = [target_action_frame.to(latents.dtype)] + future_frame = self._encode_future_image_frame(future_images, like_latents=latents) + if future_frame is not None: + target_frames.append(future_frame) + + batch_size = latents.shape[0] + train_time = self._sample_train_times(batch_size, latents.device) + flow_time = self._shift_time(train_time) + time_view = flow_time.view(batch_size, 1, 1, 1).to(device=latents.device, dtype=latents.dtype) + + noises = [torch.randn_like(target_frame).to(latents.dtype) for target_frame in target_frames] + sample_frames = [ + self._sanitize_tensor(noise * time_view + target_frame * (1.0 - time_view), clip_value=self.latent_clip_value) + for target_frame, noise in zip(target_frames, noises) + ] + target_velocities = [ + self._sanitize_tensor(noise.float() - target_frame.float(), clip_value=self.latent_clip_value) + for target_frame, noise in zip(target_frames, noises) + ] + + if self.autoregressive: + pred_frames = self._predict_velocity_autoregressive( + wm_inputs=wm_inputs, + sample_frames=sample_frames, + timestep=flow_time, + ) + else: + pred_frames = self._predict_velocity(wm_inputs=wm_inputs, target_frames=sample_frames, timestep=flow_time) + pred_frames = self._sanitize_tensor(pred_frames, clip_value=self.prediction_clip_value) + pred_action_frame = pred_frames[:, :, 0] + + action_loss = F.mse_loss(pred_action_frame, target_velocities[0], reduction="none") + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + if action_mask is not None: + action_mask = torch.tensor(np.array(action_mask), device=latents.device, dtype=torch.float32) + action_mask = action_mask[:, -(self.future_action_window_size + 1):, :] + latent_mask = self._actions_to_latent_frame(action_mask, latents).float().clamp(0.0, 1.0) + action_loss_scalar = (action_loss * latent_mask).sum() / latent_mask.sum().clamp_min(1.0) + else: + action_loss_scalar = action_loss.mean() + + total_loss = action_loss_scalar * self.action_loss_weight + output = { + "action_loss": total_loss, + "demo_sample_action_mse_loss": action_loss_scalar.detach(), + } + + if future_frame is not None: + pred_future_frame = pred_frames[:, :, 1] + future_loss = F.mse_loss(pred_future_frame, target_velocities[1], reduction="mean") + total_loss = total_loss + future_loss * self.future_image_loss_weight + output["action_loss"] = total_loss + output["future_image_loss"] = future_loss.detach() + + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + latents = wm_inputs["hidden_states"] + latents = self._sanitize_tensor(latents, clip_value=self.latent_clip_value) + wm_inputs["hidden_states"] = latents + batch_size, channels, _, height, width = latents.shape + action_shape = (batch_size, self.future_action_window_size + 1, self.action_dim) + + num_inference_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps)) + num_inference_steps = max(num_inference_steps, 1) + shift = float(kwargs.get("shift", self.shift)) + debug_trace = self._begin_wm_debug_trace() + self._log_wm_debug( + debug_trace, + f"start requested_num_inference_steps={num_inference_steps} parameterization=rectified_flow shift={shift:g}", + obs_latents=latents, + ) + + decode_future_images = self._as_bool(kwargs.get("decode_future_images", self.decode_future_images)) + action_frame = torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype) + future_frame = ( + torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype) + if decode_future_images + else None + ) + + sigmas = self._flow_inference_schedule(num_inference_steps, latents.device, shift=shift) + for step_idx in range(num_inference_steps): + timestep = sigmas[step_idx].expand(batch_size) + sigma = sigmas[step_idx] + next_sigma = sigmas[step_idx + 1] + pred_action = self._predict_velocity( + wm_inputs=wm_inputs, + target_frames=[action_frame], + timestep=timestep, + )[:, :, 0] + pred_action = self._sanitize_tensor(pred_action, clip_value=self.prediction_clip_value) + + pred_future = None + if decode_future_images and future_frame is not None: + pred_future = self._predict_velocity( + wm_inputs=wm_inputs, + target_frames=[future_frame], + timestep=timestep, + context_frames=[action_frame], + )[:, :, 0] + pred_future = self._sanitize_tensor(pred_future, clip_value=self.prediction_clip_value) + + self._log_wm_debug( + debug_trace, + f"step={step_idx} sigma={sigma.item():.4g}->{next_sigma.item():.4g}", + sample_action_before=action_frame, + pred_action_velocity=pred_action, + pred_future_velocity=pred_future, + ) + dt = (next_sigma - sigma).to(device=latents.device, dtype=latents.dtype) + action_frame = self._sanitize_tensor( + action_frame + dt * pred_action.to(dtype=latents.dtype), + clip_value=self.latent_clip_value, + ) + if pred_future is not None and future_frame is not None: + future_frame = self._sanitize_tensor( + future_frame + dt * pred_future.to(dtype=latents.dtype), + clip_value=self.latent_clip_value, + ) + pred_action_frame = action_frame.float() + pred_actions = self._latent_frame_to_actions(pred_action_frame, action_shape) + self._log_wm_debug(debug_trace, "final_action", pred_action_frame=pred_action_frame, pred_actions=pred_actions) + + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + if decode_future_images and future_frame is not None: + output["pred_future_images"] = self._decode_latent_frames(future_frame.float().unsqueeze(2)) + return output diff --git a/starVLA/model/framework/M1.py b/starVLA/model/framework/M1.py new file mode 100644 index 0000000000000000000000000000000000000000..a9df674d447a97384bfadbbf1c420935becd572b --- /dev/null +++ b/starVLA/model/framework/M1.py @@ -0,0 +1,421 @@ +# Copyright 2025 InternVLA-M1. All rights reserved. +# Modified by [Jinhui YE/ HKUST University] in [2025]. +# Modification: [add fake sample and predict_action to match with starVLA]. +""" +InternVLA M1 framework: +Vision-Language-Action diffusion model integrating: + - Qwen2.5 vision-language backbone + - Layer-wise QFormer aggregation + - DINO multi-view visual encoder + - DiT diffusion head for future action sequence prediction +Primary goal: predict continuous future actions conditioned on multi-view images + instruction. +""" + +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import numpy as np +from PIL import Image +from qwen_vl_utils import process_vision_info + + +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.model.tools import FRAMEWORK_REGISTRY + + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.projector.QFormer import get_layerwise_qformer +from starVLA.model.modules.action_model.DiTActionHeader import get_action_model +from starVLA.model.modules.dino_model.dino import get_dino_model +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@FRAMEWORK_REGISTRY.register("InternVLA-M1") +class InternVLA_M1(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + self.layer_qformer = get_layerwise_qformer(config=self.config) + self.action_model = get_action_model(config=self.config) + self.dino_encoder = get_dino_model( + backone_name=getattr(self.config.framework.dino, "dino_backbone", "dinov2_vits14") + ) + self.dino_pro = nn.Linear( + in_features=self.dino_encoder.num_channels, out_features=self.qwen_vl_interface.model.config.hidden_size + ) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + Forward pass for training (diffusion objective). + + Flow: + 1. Build QwenVL inputs (images + instruction tokens) + 2. Extract hidden states from configured layer range + 3. Encode images with DINO, flatten multi-view tokens and project + 4. Concatenate per-layer language tokens with visual tokens + 5. Fuse via layer-wise QFormer -> action condition embeddings + 6. Prepare repeated future action windows (for diffusion efficiency) + 7. Predict noise and compute diffusion loss + + Args: + examples: List[dict], each dict requires: + - image: List[PIL.Image] (multi-view) + - lang: str instruction + - action: np.ndarray or list shaped [T, action_dim] + **kwargs: Reserved. + + Returns: + dict: + action_loss (torch.Tensor): Scalar diffusion noise prediction loss. + """ + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + pass + + # Step 2: DINO Forward + image_tensors = self.dino_encoder.prepare_dino_input(batch_images) # + B = len(batch_images) + dino_features = self.dino_encoder(image_tensors) # DINO output is [B*num_view, token, dim] + dino_encoded_features = dino_features.reshape(B, -1, dino_features.shape[-1]) # [B, num_view * token, dim] + dino_encoded_features = self.dino_pro(dino_encoded_features) # [B, num_view * token, hidden_size] + + # Step 3: aggregation condition for Action expert + start_layer = self.config.framework.layer_qformer.qformer_start_layer + end_layer = self.config.framework.layer_qformer.qformer_end_layer + condition_features = qwenvl_outputs.hidden_states[start_layer:end_layer] + + cat_conditions = [] + for layer_index in range(len(condition_features)): + layer_features = condition_features[layer_index] # [B, n_qformer_token, D] + layer_features = torch.cat( + [layer_features, dino_encoded_features], dim=1 + ) # [B, n_qformer_token + num_view * token, D] + cat_conditions.append(layer_features) + + action_condition = self.layer_qformer(cat_conditions) # [B, 64, D_action] + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + + # here is a tips to accelerate training speed, by repeating each sample for several times @ref to CogACT + actions = torch.tensor(np.array(actions), device=action_condition.device) # [B, chunk, 7] + actions_future = actions[:, -(self.future_action_window_size + 1) :, :] + + # tips: Repeat 'actions' 'repeated_diffusion_steps' times, resulting in [repeated_diffusion_steps*B, T, D] + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_repeated = actions_future.repeat(repeated_diffusion_steps, 1, 1) + action_condition = action_condition.repeat( + repeated_diffusion_steps, 1, 1 + ) # [repeated_diffusion_steps*B, T, D_action] + + # DiT noise add and predict + noise_pred, noise, timestep = self.action_model(actions_repeated, action_condition) + + # perdition loss + action_loss = self.action_model.loss(noise_pred, noise) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( + self, + batch_images: List[List[Image.Image]], # B * List of PIL Image as [view1, view2] + instructions: List[str], + cfg_scale: float = 1.5, + use_ddim: bool = True, + num_ddim_steps: int = 5, + resize_image = [224, 224], + **kwargs: str, + ) -> np.ndarray: + """ + Inference: generate future normalized action sequence via diffusion sampling. + + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 3. Extract DINO tokens and project to vlm hidden size + 4. Build multi-layer fused QwenVL and DINO features via QFormer + 5. Run diffusion sampling (DDIM optional, CFG optional) + 6. Return normalized action trajectory + + Args: + batch_images: List of samples; each sample is List[PIL.Image] (multi-view). + instructions: List[str] natural language task instructions. + cfg_scale: >1 enables classifier-free guidance (scales conditional vs unconditional). + use_ddim: Whether to use DDIM deterministic sampling. + num_ddim_steps: Number of DDIM steps if enabled. + **kwargs: Reserved. + + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + # align obs and lang # is policy's duty to make sure the image size? + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + instructions = [instruction.lower() for instruction in instructions] + + inferface_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + qwen_inputs = inferface_inputs + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_hidden_states=True, + return_dict=True, + ) + + B = len(batch_images) # dino don't have smart resize in processing + image_tensors = self.dino_encoder.prepare_dino_input(batch_images) + dino_features = self.dino_encoder(image_tensors) + + B = len(batch_images) + dino_encoded_features = dino_features.reshape(B, -1, dino_features.shape[-1]) # [B, num_view * token, dim] + dino_encoded_features = self.dino_pro(dino_encoded_features) # [B, 256, D] + + with torch.autocast("cuda", dtype=torch.bfloat16): + + start_layer = self.config.framework.layer_qformer.qformer_start_layer + end_layer = self.config.framework.layer_qformer.qformer_end_layer + condition_features = qwenvl_outputs.hidden_states[start_layer:end_layer] + cat_conditions = [] + for layer_index in range(len(condition_features)): + layer_features = condition_features[layer_index] # [B, n_qformer_token, D] + layer_features = torch.cat( + [layer_features, dino_encoded_features], dim=1 + ) # [B, n_qformer_token + num_view * token, D] + cat_conditions.append(layer_features) + + action_condition_feature = self.layer_qformer(cat_conditions) # [B, 64, D_action] + + using_cfg = cfg_scale > 1.0 + + model_dtype = next(self.action_model.net.parameters()).dtype + B = action_condition_feature.shape[0] + + # Sample random noise + noise = torch.randn( + B, + self.future_action_window_size + 1, + self.action_model.in_channels, + device=action_condition_feature.device, + ).to( + model_dtype + ) # [B, T, D] + + # Setup classifier-free guidance: + if using_cfg: + noise = torch.cat([noise, noise], 0) # [2,16,7] + uncondition = self.action_model.net.z_embedder.uncondition # [64, 768] + uncondition_shape = uncondition.shape + uncondition = uncondition.unsqueeze(0) # [1, 64, D] + uncondition = uncondition.expand( + B, uncondition_shape[0], uncondition_shape[1] + ) # [B, n_qformer_token, D] + z = torch.cat([action_condition_feature, uncondition], 0) # [2, 64, 768] + cfg_scale = cfg_scale + model_kwargs = dict(z=z, cfg_scale=cfg_scale) + sample_fn = self.action_model.net.forward_with_cfg + else: + model_kwargs = dict(z=action_condition_feature) + sample_fn = self.action_model.net.forward + + # DDIM Sampling + if use_ddim and num_ddim_steps is not None: + if self.action_model.ddim_diffusion is None: + self.action_model.create_ddim(ddim_step=num_ddim_steps) + samples = self.action_model.ddim_diffusion.ddim_sample_loop( + sample_fn, + noise.shape, + noise, + clip_denoised=False, + model_kwargs=model_kwargs, + progress=False, + device=action_condition_feature.device, + eta=0.0, + ) + + if using_cfg: + samples, _ = samples.chunk(2, dim=0) # Remove null class samples + normalized_actions = samples.cpu().numpy() + + raw_actions = None + + return {"normalized_actions": normalized_actions} # [B, T, action_dim] + + + @torch.inference_mode() + def chat_with_M1( + self, + image: Image.Image, + text: str, + max_new_tokens: int = 128, + device: Optional[str] = "cuda", + ) -> List[str]: + processor = getattr(self.qwen_vl_interface, "processor", None) + model = getattr(self.qwen_vl_interface, "model", None) + # if processor is None or model is None: + # raise RuntimeError("qwen_vl_interface 缺少 processor 或 model。") + + messages0 = [ + { + "role": "user", + "content": [ + { + "type": "image", + "image": image, + }, + {"type": "text", "text": text}, + ], + } + ] + + messages = [messages0] + # text info + texts = [processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True) for msg in messages] + # visual info + image_inputs, video_inputs = process_vision_info(messages) + + # tokenizer + inputs = processor( + text=texts, + images=image_inputs, + videos=video_inputs, + padding=True, + return_tensors="pt", + ).to(device) + + model.eval() + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] + outputs = processor.batch_decode( + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + return outputs + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + cfg = OmegaConf.load(args.config_yaml) + + # try get model + model = InternVLA_M1(cfg) + print(model) + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image, image], # two views + "lang": "This is a fake instruction for testing.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]]) + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + + + + # model_path = "./results/Checkpoints/1_need/0906_bestvla_retrain_sota2/checkpoints/steps_50000_pytorch_model.pt" + # state_dict = torch.load(model_path, map_location="cpu") + + # model.load_state_dict(state_dict, strict=True) + + # # try forward model + # # can be fake sample, but here get from dataloader for simpler + # from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + + # vla_dataset_cfg = cfg.datasets.vla_data + # dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + # from torch.utils.data import DataLoader + + # train_dataloader = DataLoader( + # dataset, + # batch_size=2, + # num_workers=1, # For Debug + # collate_fn=collate_fn, + # ) + + # for batch in tqdm(train_dataloader, desc="Processing Batches"): + # batch + # break + + # # try get model + # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + # model = model.to(device) + # model(batch) diff --git a/starVLA/model/framework/QwenAdapter.py b/starVLA/model/framework/QwenAdapter.py new file mode 100644 index 0000000000000000000000000000000000000000..72e73f2108e7bb14c7c93d2ca0b99fef9d0c9a53 --- /dev/null +++ b/starVLA/model/framework/QwenAdapter.py @@ -0,0 +1,427 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Junqiu YU / Fudan University] in [2025]. +# Design and Merged by [Jinhui YE / HKUST University] in [2025]. +""" +Qwen-Adapter Framework +A lightweight implementation that Qwen-VL + Adapter Action head to directly predict continuous actions +Action head is copyright from VLA-Adapter, +""" +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.action_model.VLA_AdapterHeader import get_action_model, L1RegressionActionHead +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY + +def get_image_token_counts(batch_inputs): + IMAGE_TOKEN_ID = 151655 + + # input_ids shape: [Batch_Size, Seq_Len] + # result shape: [Batch_Size] + num_tokens_per_sample = torch.sum(batch_inputs['input_ids'] == IMAGE_TOKEN_ID, dim=1) + + return num_tokens_per_sample + + +class ProprioProjector(nn.Module): + """ + Projects proprio state inputs into the LLM's embedding space. + """ + def __init__(self, llm_dim: int, proprio_dim: int) -> None: + super().__init__() + self.llm_dim = llm_dim + self.proprio_dim = proprio_dim + + self.fc1 = nn.Linear(self.proprio_dim, self.llm_dim, bias=True) + self.fc2 = nn.Linear(self.llm_dim, self.llm_dim, bias=True) + self.act_fn1 = nn.GELU() + + def forward(self, proprio: torch.Tensor = None) -> torch.Tensor: + # proprio: (bsz, proprio_dim) + projected_features = self.fc1(proprio) + projected_features = self.act_fn1(projected_features) + projected_features = self.fc2(projected_features) + return projected_features + +# Only support for Qwen2.5 now @ PR 60 +@FRAMEWORK_REGISTRY.register("QwenAdapter") +class Qwen_Adapter(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.use_proprio = self.config.framework.action_model.get("use_proprio", False) + self.proprio_projector = ProprioProjector( + llm_dim=self.qwen_vl_interface.model.config.hidden_size, + proprio_dim=self.config.framework.action_model.get("state_dim", 0), + ) if self.use_proprio else None + self.phase = self.config.framework.action_model.get("phase", "Training") + self.qwen_vl_interface = get_vlm_model(config=self.config) + self.config.framework.qwenvl.vl_hidden_dim = self.qwen_vl_interface.model.config.hidden_size + self.action_query_num = self.config.framework.action_model.get("action_query_num", 64) + self.action_model: L1RegressionActionHead = get_action_model(config=self.config) + self.action_query = nn.Parameter(torch.randn(self.action_query_num, self.qwen_vl_interface.model.config.hidden_size)) + nn.init.normal_(self.action_query, mean=0.0, std=0.02) + + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + + """ + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + gt_actions = [example["action"] for example in examples] # label [B, len, 7] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + num_patches = get_image_token_counts(qwen_inputs) # [B, ] + + batch_size = qwen_inputs['input_ids'].shape[0] + pad_id = self.qwen_vl_interface.model.config.pad_token_id + if pad_id is None: + pad_id = getattr(self.qwen_vl_interface.model.config, "eos_token_id", 0) + if pad_id is None: + pad_id = 0 + device = qwen_inputs['input_ids'].device + + dummy_ids = torch.full( + (batch_size, self.action_query_num),pad_id, device=device, dtype=qwen_inputs['input_ids'].dtype + ) # (B, action_query_num) + dummy_mask = torch.ones( + (batch_size, self.action_query_num), device=device, dtype=qwen_inputs['attention_mask'].dtype + ) # (B, action_query_num) + + qwen_inputs['input_ids'] = torch.cat([qwen_inputs['input_ids'], dummy_ids], dim=1) # (B, L + action_query_num) + qwen_inputs['attention_mask'] = torch.cat([qwen_inputs['attention_mask'], dummy_mask], dim=1) # (B, L + action_query_num) + + def inject_query_hook(module, inputs, output): + query_embed = self.action_query.to(dtype=output.dtype, device=output.device) # (action_query_num, hidden_dim) + batch_query = query_embed.unsqueeze(0).expand(output.shape[0], -1, -1) # (B, action_query_num, hidden_dim) + output[:, -self.action_query_num:, :] = batch_query + return output + + embedding_layer = self.qwen_vl_interface.model.model.get_input_embeddings() + assert isinstance(embedding_layer, nn.Embedding), "Cannot find qwenvl embedding layer" + hook_handle = embedding_layer.register_forward_hook(inject_query_hook) + try: + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + finally: + hook_handle.remove() + + + multi_layer_hidden_states = [] + + for item in qwenvl_outputs.hidden_states[0:]: + batch_size = item.shape[0] + hidden_dim = item.shape[-1] + + max_patch_len = num_patches.max().item() + + batch_vision_states = [] + batch_action_query_states = [] + + for i in range(batch_size): + n_p = num_patches[i].item() + vis_feat = item[i, :n_p, :] # [n_p, D] + if n_p < max_patch_len: + pad_len = max_patch_len - n_p + padding = torch.zeros((pad_len, hidden_dim), device=vis_feat.device, dtype=vis_feat.dtype) + vis_feat = torch.cat([vis_feat, padding], dim=0) # [max_patch_len, D] + + batch_vision_states.append(vis_feat) + + act_query_feat = item[i, -self.action_query_num:, :] # [action_query_num, D] + batch_action_query_states.append(act_query_feat) + + vision_hidden_states = torch.stack(batch_vision_states).unsqueeze(1) # [B, 1, max_patch_len, D] + action_query_hidden_states = torch.stack(batch_action_query_states).unsqueeze(1) # [B, 1, action_query_num, D] + + all_hidden_states = torch.cat([vision_hidden_states, action_query_hidden_states], dim=2) # [B, 1, max_patch_len + action_query_num, D] + multi_layer_hidden_states.append(all_hidden_states) # [num_layers][B, 1, L_total, D] + + multi_layer_hidden_states = torch.cat(multi_layer_hidden_states, dim=1) # [B, num_layers, L_total, D] + + + # Step 3: Action Expert Forward + self.action_model = self.action_model.to(device=multi_layer_hidden_states.device, dtype=multi_layer_hidden_states.dtype) + predicted_actions = self.action_model.predict_action( + multi_layer_hidden_states, + proprio=state if self.use_proprio else None, + proprio_projector=self.proprio_projector if self.use_proprio else None, + phase=self.phase, + ) # (B, chunk_len, action_dim) + + gt_actions = torch.tensor(np.stack(gt_actions)).to( + device=predicted_actions.device, + dtype=predicted_actions.dtype + ) + + loss = torch.nn.L1Loss()(predicted_actions, gt_actions) + + return {"action_loss": loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict] = None, + **kwargs: str, + ) -> np.ndarray: + """ + Inference: Predict future continuous actions aligned with the Forward logic (Hook + Multi-layer states). + """ + from deployment.model_server.tools.image_tools import to_pil_preserve + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + # Step 0: Preprocessing (Resize) + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + # Assuming resize_images is a valid helper function available in context + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + num_patches = get_image_token_counts(qwen_inputs) # [B, ] + + # Step 2: Prepare Dummy Tokens & Hook for Action Query Injection + batch_size = qwen_inputs['input_ids'].shape[0] + pad_id = self.qwen_vl_interface.model.config.pad_token_id + if pad_id is None: + pad_id = getattr(self.qwen_vl_interface.model.config, "eos_token_id", 0) + if pad_id is None: + pad_id = 0 + device = qwen_inputs['input_ids'].device + + # Create dummy placeholders + dummy_ids = torch.full( + (batch_size, self.action_query_num), pad_id, device=device, dtype=qwen_inputs['input_ids'].dtype + ) + dummy_mask = torch.ones( + (batch_size, self.action_query_num), device=device, dtype=qwen_inputs['attention_mask'].dtype + ) + + # Concat to inputs + qwen_inputs['input_ids'] = torch.cat([qwen_inputs['input_ids'], dummy_ids], dim=1) + qwen_inputs['attention_mask'] = torch.cat([qwen_inputs['attention_mask'], dummy_mask], dim=1) + + # Define Hook + def inject_query_hook(module, inputs, output): + query_embed = self.action_query.to(dtype=output.dtype, device=output.device) + batch_query = query_embed.unsqueeze(0).expand(output.shape[0], -1, -1) + output[:, -self.action_query_num:, :] = batch_query + return output + + # Register Hook + embedding_layer = self.qwen_vl_interface.model.model.get_input_embeddings() + hook_handle = embedding_layer.register_forward_hook(inject_query_hook) + + try: + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + finally: + hook_handle.remove() + + # Step 3: Process Multi-layer Hidden States + # Logic copied from forward: Concatenate Vision Tokens + Action Query Tokens across layers + multi_layer_hidden_states = [] + + for item in qwenvl_outputs.hidden_states[0:]: + # item shape: [B, Seq_Len, H] + hidden_dim = item.shape[-1] + max_patch_len = num_patches.max().item() + + batch_vision_states = [] + batch_action_query_states = [] + + for i in range(batch_size): + n_p = num_patches[i].item() + # Extract vision features + vis_feat = item[i, :n_p, :] # [n_p, D] + + # Handle padding for vision tokens if batch has varying aspect ratios + if n_p < max_patch_len: + pad_len = max_patch_len - n_p + padding = torch.zeros((pad_len, hidden_dim), device=vis_feat.device, dtype=vis_feat.dtype) + vis_feat = torch.cat([vis_feat, padding], dim=0) # [max_patch_len, D] + + batch_vision_states.append(vis_feat) + + # Extract action query features (last N tokens) + act_query_feat = item[i, -self.action_query_num:, :] # [action_query_num, D] + batch_action_query_states.append(act_query_feat) + + vision_hidden_states = torch.stack(batch_vision_states).unsqueeze(1) # [B, 1, max_patch_len, D] + action_query_hidden_states = torch.stack(batch_action_query_states).unsqueeze(1) # [B, 1, action_query_num, D] + + all_hidden_states = torch.cat([vision_hidden_states, action_query_hidden_states], dim=2) + multi_layer_hidden_states.append(all_hidden_states) + + # [B, num_layers, L_total, D] + multi_layer_hidden_states = torch.cat(multi_layer_hidden_states, dim=1) + + # Step 4: Proprioception Processing + proprio_tensor = None + if self.use_proprio and state is not None: + # Convert numpy state to tensor, match device/dtype of hidden states + proprio_tensor = torch.from_numpy(np.array(state)).to( + device=multi_layer_hidden_states.device, + dtype=multi_layer_hidden_states.dtype + ) + # Ensure shape is [B, proprio_dim] or [B, 1, proprio_dim] depending on projector expectation + if proprio_tensor.ndim == 1: + proprio_tensor = proprio_tensor.unsqueeze(0) # Batch dim + if proprio_tensor.ndim == 3: + proprio_tensor = proprio_tensor.squeeze(1) # Remove seq dim if present for projector + + # Step 5: Action Expert Prediction + # Handle DDP wrapper if present, otherwise call model directly + action_model_ref = self.action_model.module if hasattr(self.action_model, "module") else self.action_model + + # Ensure model is on correct device/dtype + action_model_ref = action_model_ref.to(device=multi_layer_hidden_states.device, dtype=multi_layer_hidden_states.dtype) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = action_model_ref.predict_action( + multi_layer_hidden_states, + proprio=proprio_tensor, + proprio_projector=self.proprio_projector if self.use_proprio else None, + phase="Inference", # Explicitly set phase for inference logic + ) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_train_adapter.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + cfg = OmegaConf.load(args.config_yaml) + # try get model + cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen2.5-VL-3B-Instruct" + + model: Qwen_Adapter = Qwen_Adapter(cfg) + print(model) + + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 14)).astype(np.float16), # action_chunk, action_dim + "image": [image, image], # two views + "lang": "This is a fake for testing.", + # "state" : np.random.uniform(-1, 1, size=(1, 14)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action(examples=[batch[0]]) + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + # from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + + # vla_dataset_cfg = cfg.datasets.vla_data + # dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + # from torch.utils.data import DataLoader + + # train_dataloader = DataLoader( + # dataset, + # batch_size=2, + # num_workers=1, # For Debug + # collate_fn=collate_fn, + # ) + # # + # for batch in tqdm(train_dataloader, desc="Processing Batches"): + # batch + # break + + # # try get model + # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + # model = model.to(device) + # model(batch) + + # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]]) + + # # fake state + # for ba in batch: + # ba["state"] = ba["action"][0][None] + + # model(batch) + # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]], state=[batch[0]["state"]]) diff --git a/starVLA/model/framework/QwenDual.py b/starVLA/model/framework/QwenDual.py new file mode 100644 index 0000000000000000000000000000000000000000..fcebbffe53b1c92a0e9e2515a177a40cf4d98ebc --- /dev/null +++ b/starVLA/model/framework/QwenDual.py @@ -0,0 +1,288 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Jinhui YE / HKUST University] in [2025]. + +""" +Qwen-Dual Framework +A lightweight implementation that Qwen2.5-vl + dinov2 + Flow-matching head to directly predict continuous actions +Flow-matching header is copyright from GR00T N1.5 +""" +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + +from starVLA.model.modules.dino_model.dino import get_dino_model +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.action_model.GR00T_ActionHeader import get_action_model, FlowmatchingActionHead +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY +from deployment.model_server.tools.image_tools import to_pil_preserve + + +@FRAMEWORK_REGISTRY.register("QwenDual") +class Qwen_Dual(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + # align dims --> we should put them to config or no? + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = self.qwen_vl_interface.model.config.hidden_size + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用 + + self.dino_encoder = get_dino_model( + backone_name=getattr(self.config.framework.dino, "dino_backbone", "dinov2_vits14") + ) + self.dino_pro = nn.Linear( + in_features=self.dino_encoder.num_channels, out_features=self.qwen_vl_interface.model.config.hidden_size + ) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + 训练前向:直接回归未来动作(无扩散)。 + + Flow: + 1. Build QwenVL inputs (images + instruction tokens) + 2. Extract hidden states from configured layer range + 7. Predict action and compute L1 loss + + Args: + examples: List[dict], each dict requires: + - image: List[PIL.Image] (multi-view) + - lang: str instruction + - action: np.ndarray or list shaped [T, action_dim] + **kwargs: Reserved. + + Returns: + dict: + action_loss (torch.Tensor): Scalar diffusion noise prediction loss. + """ + batch_images, wrist_views, instructions, state = self.align_model_input(examples) + last_hidden, state = self.get_action_condition(batch_images, instructions, wrist_views, state) + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + # get action labels + actions = [example["action"] for example in examples] # List of [T_full, action_dim] + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + # repeate for efficient training + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + state_repeated = None + if state is not None: + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated) # (B, chunk_len, action_dim) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict] = None, + **kwargs: str, + ) -> np.ndarray: + """ + 推理:单次前向直接回归未来动作(无扩散采样)。 + + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + batch_images, wrist_views, instructions, state = self.align_model_input(examples) + last_hidden, state = self.get_action_condition(batch_images, instructions, wrist_views, state) + # Step 4: Action Expert Forward + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim) + normalized_actions = pred_actions.detach().cpu().numpy() + + return {"normalized_actions": normalized_actions} + + def align_model_input(self, examples: List[dict]): + + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + wrist_views = [to_pil_preserve(example["wrist_views"]) for example in examples] if "wrist_views" in examples[0] else None # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", [224,224]) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + if train_obs_image_size and wrist_views is not None: + wrist_views = resize_images(wrist_views, target_size=train_obs_image_size) + + return batch_images, wrist_views, instructions, state + + def get_action_condition(self, batch_images, instructions, wrist_views=None, state=None): + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + connect_layer_index = self.config.framework.action_model.get("connect_layer_index", -1) + last_hidden = qwenvl_outputs.hidden_states[connect_layer_index] # [B, L, H] + + # Step 2: DINO Forward + if wrist_views == None: + wrist_views = batch_images + image_tensors = self.dino_encoder.prepare_dino_input(wrist_views) # + B = len(batch_images) + dino_features = self.dino_encoder(image_tensors) # DINO output is [B*num_view, token, dim] + dino_encoded_features = dino_features.reshape(B, -1, dino_features.shape[-1]) # [B, num_view * token, dim] + dino_encoded_features = self.dino_pro(dino_encoded_features) # [B, num_view * token, hidden_size] + + # Step 3: Feature Concatenation + last_hidden = torch.cat( + [last_hidden, dino_encoded_features], dim=1 + ) + state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None + + return last_hidden, state +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + cfg = OmegaConf.load(args.config_yaml) + # try get model + # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen3-VL-4B-Instruct" + # # cfg.framework.action_model.connect_layer_index = 16 + # cfg.framework.action_model.state_dim = 44 + # cfg.datasets.vla_data.include_state = True + + cfg.framework.action_model.action_hidden_dim = 2048 + cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large" + + model: Qwen_Dual = Qwen_Dual(cfg) + print(model) + + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + # "wrist_views": [image, image], + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 44)).astype(np.float16), # chunk, state_dim + } + + sample2 = sample.copy() + sample2["lang"] = "Move the red cup from the table to the kitchen counter next to the sink." + batch = [sample, sample2] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action([sample]) #, state=[batch[0]["state"]] + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + + vla_dataset_cfg = cfg.datasets.vla_data + # vla_dataset_cfg.include_state = True + # vla_dataset_cfg.data_mix = "BEHAVIOR_challenge" + # vla_dataset_cfg.data_mix = "BEHAVIOR_rgp_dual_history" + vla_dataset_cfg.task_id = 40 + vla_dataset_cfg.video_backend = "torchvision_av" + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + from torch.utils.data import DataLoader + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + # + count = 0 + for batch in tqdm(train_dataloader, desc="Processing Batches"): + batch + count += 1 + if count > 1: + break + + # try get model + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + + action = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]] diff --git a/starVLA/model/framework/QwenFast.py b/starVLA/model/framework/QwenFast.py new file mode 100644 index 0000000000000000000000000000000000000000..47451b5e9bc9c7d7a9223c25d43cf762dcce7fe3 --- /dev/null +++ b/starVLA/model/framework/QwenFast.py @@ -0,0 +1,307 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Jinhui YE / HKUST University] in [2025]. + +""" +Qwen-Fast Framework + +A lightweight implementation for autoregressive discrete action prediction conditioned on multi-view images + instruction. +fast tokenizer is copyright from physical-intelligence/fast + +Key Points: + - Qwen2.5 vision-language backbone + - Unified action learning via next-token prediction (fast tokenizer) + - Autoregressive action tokens derived from discretized / symbolized continuous actions + +Note: How to add special tokens to Qwen2.5: + download our model checkpoint with special tokens added: https://huggingface.co/StarVLA/Qwen2.5-VL-3B-Instruct-Action +""" + +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple, Any +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image +from qwen_vl_utils import process_vision_info + + +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.model.tools import FRAMEWORK_REGISTRY +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.action_model.fast_ActionHeader import get_action_model + + +@FRAMEWORK_REGISTRY.register("QwenFast") +class Qwenvl_Fast(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + self.action_model = get_action_model(config=self.config) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + # self.hidden_dim = config.framework.action_model.action_hidden_dim + + self.action_model.fast_tokenizer.time_horizon = self.future_action_window_size + 1 + self.action_model.fast_tokenizer.action_dim = self.config.framework.action_model.action_dim + + + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + Training forward: directly predict future actions via next-token prediction (no diffusion). + + Flow: + 1. Build QwenVL inputs (images + instruction tokens) + 2. Extract hidden states from configured layer range + 7. Predict action and compute L1 loss + + Args: + examples: List[dict], each dict requires: + - image: List[PIL.Image] (multi-view) + - lang: str instruction + - action: np.ndarray or list shaped [T, action_dim] + **kwargs: Reserved. + + Returns: + dict: + action_loss (torch.Tensor): Scalar diffusion noise prediction loss. + """ + batch_images = [example["image"] for example in examples] # [B, [PIL]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + + # step 0: map_raw_action_to_vlm_action + batch_fast_tokens = self.action_model.encoder_action2fastoken(actions) # List[str] + + # batch_fast_tokens = [self.fast_tokenizer(raw_action)[0] for raw_action in raw_actions] + vlm_action_tokens = [self.map_fast_token_to_vlm_action(fast_tokens) for fast_tokens in batch_fast_tokens] + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions, solutions=vlm_action_tokens) + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=False, + return_dict=True, + ) + + vlm_action_loss = qwenvl_outputs.loss + if vlm_action_loss is None or torch.isnan(vlm_action_loss): + vlm_action_loss = torch.tensor(0.0, device=self.qwen_vl_interface.model.device) + + return {"action_loss": vlm_action_loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict] = None, + **kwargs: str, + ) -> np.ndarray: + """ + Inference: single forward pass to obtain future actions (no diffusion sampling). + # can be batch forward + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + # train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + # if train_obs_image_size: + # batch_images = resize_images(batch_images, target_size=train_obs_image_size) + instructions = [instruction for instruction in instructions] + + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + generated_ids = self.qwen_vl_interface.model.generate( + **qwen_inputs, + max_length=2048, + ) + # --- Extract and decoder vlm_action to continue actions --- + # --- extrace token (index based on VLM) --- + batch_vlm_action_token_ids = self._extract_action_token_ids(generated_ids) + # --- map index to fast tokenizer index space --- + batch_fast_action_token_idx = self._decode_action_tokens(batch_vlm_action_token_ids) + # --- decode fast tokenizer index to action semantic --- + normalized_actions = self.action_model.fast_tokenizer.decode(batch_fast_action_token_idx) + + return {"normalized_actions": normalized_actions} + + def _extract_action_token_ids( + self, + generated_ids: torch.LongTensor, + ) -> List[List[int]]: + """ + Extract action tokens (with offset) from the generated token sequence and return a 2D list: + ret[b] = [vlm_action_token_id_0, vlm_action_token_id_1, ...] + Rule: keep all tokens falling within [_ACTION_TOKEN_MIN, _ACTION_TOKEN_MAX] in order of appearance. + You may change it to "take only the first occurrence followed by continuous segment" as needed. + """ + act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN + act_max = self.qwen_vl_interface._ACTION_TOKEN_MAX + mask = (generated_ids >= act_min) & (generated_ids <= act_max) # [B, L] + results = [] + for b in range(generated_ids.size(0)): + idx = mask[b].nonzero(as_tuple=False).flatten() + if idx.numel() == 0: + results.append([]) + continue + # all action tokens + tokens = generated_ids[b, idx].tolist() + results.append(tokens) + return results + + def _decode_action_tokens(self, batch_vlm_tokens: List[List[int]]) -> List[Any]: + """ + Decode the offset VLM action token list back to fast tokenizer semantics. + fast_tokenizer.decode expects the original fast token id sequence (without offset). + """ + act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN + batch_fast_token_ids = [] + for seq in batch_vlm_tokens: + if not seq: + batch_fast_token_ids.append(None) + continue + fast_ids = [t - act_min for t in seq] + + batch_fast_token_ids.append(fast_ids) + + return batch_fast_token_ids + + def map_fast_token_to_vlm_action(self, tokens) -> str: + """Maps fast action tokens to the VLM action format. + Action token 0 is mapped to the string ... and so on + """ + return ''.join([f"" for token in tokens]) # you should add to VLM as special tokens, + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + args.config_yaml = "./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml" + cfg = OmegaConf.load(args.config_yaml) + # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen3-VL-4B-Instruct-Action" + + # try get model + model = Qwenvl_Fast(cfg) + print(model) + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 14)).astype(np.float16), # action_chunk, action_dim + "image": [image, image], # two views + "lang": "This is a fake instruction for testing.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + sample2 = { + "action": np.random.uniform(-1, 1, size=(16, 14)).astype(np.float16), # action_chunk, action_dim + "image": [image, image], # two views + "lang": "The fake instruction for testing.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample2] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action. for new model, it didn't learn to predict action token, so you would meet empty action + predict_output = model.predict_action([sample]) + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + + + + # # test with dataloader + # # can be fake sample, but here get from dataloader for simpler + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + + vla_dataset_cfg = cfg.datasets.vla_data + vla_dataset_cfg.video_backend = "torchvision_av" + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + from torch.utils.data import DataLoader + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + + for batch in tqdm(train_dataloader, desc="Processing Batches"): + batch + break + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + pass + action = model.predict_action(batch[0]) diff --git a/starVLA/model/framework/QwenFastWanPerceiver.py b/starVLA/model/framework/QwenFastWanPerceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..1ceedab8c57b299b7ddbc260a5449e6bbf3dfc6e --- /dev/null +++ b/starVLA/model/framework/QwenFastWanPerceiver.py @@ -0,0 +1,372 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by combining QwenFast + QwenWanPerceiver. +""" +QwenFastWanPerceiver Framework + +VLM 内部通过 next-token prediction 学习 fast action(QwenFast), +同时用纯 VL 条件(图像 + 指令,不含 action token)融合 Wan 特征后, +交给 Perceiver flow-matching head 预测连续动作(QwenWanPerceiver)。 + +因果 LM 下,action token 之前的 hidden state 与仅 VL 输入前向等价, +因此训练时可单次前向(含 teacher-forced action)并截取 VL 段特征。 +""" +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from typing import Any, List, Optional, Tuple + +import numpy as np +import torch +from PIL import Image +from tqdm import tqdm + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.action_model.fast_ActionHeader import Fast_Action_Tokenizer +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.training.trainer_utils.trainer_tools import resize_images + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + + +@FRAMEWORK_REGISTRY.register("QwenFastWanPerceiver") +class QwenFastWanPerceiver(baseframework): + """ + Qwen-VL + Wan + Perceiver,VLM 内部额外学习 fast action token 预测。 + + - Fast action:VLM 对离散 action token 做自回归监督(训练)/ generate(推理) + - Continuous action:仅用 VL hidden(不含 action token 段)+ Wan 特征 → Perceiver head + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + self.wan_interface = get_world_model(config=self.config) + + wm_cfg = config.framework.get("world_model", {}) + self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False)) + wm_hidden = self.wan_interface.model.config.hidden_size + cross_dim = self.qwen_vl_interface.model.config.hidden_size + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = cross_dim + self.wm_projector = torch.nn.Linear(wm_hidden, cross_dim) + self.wm_post_norm = torch.nn.LayerNorm(cross_dim, eps=1e-6) + gain = float(wm_cfg.get("wm_projector_init_gain", 0.02)) + torch.nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain) + torch.nn.init.zeros_(self.wm_projector.bias) + + self.fast_action_model = Fast_Action_Tokenizer() + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + self.fast_action_model.fast_tokenizer.time_horizon = self.future_action_window_size + 1 + self.fast_action_model.fast_tokenizer.action_dim = self.config.framework.action_model.action_dim + + self.fast_loss_weight = float(config.framework.get("fast_loss_weight", 1.0)) + + self.freeze_vlm_for_vla = ( + config.trainer.get("freeze_vlm_for_vla", False) + if config and hasattr(config, "trainer") + else False + ) + + logger.info( + f"QwenFastWanPerceiver: pool_wm_sequence={self._pool_wm_sequence}, " + f"fast_loss_weight={self.fast_loss_weight}" + ) + + @staticmethod + def _wm_images_head_only(batch_images: List) -> List: + wm_images = [] + for imgs in batch_images: + if isinstance(imgs, (list, tuple)): + wm_images.append([imgs[0]] if len(imgs) > 0 else []) + else: + wm_images.append([imgs]) + return wm_images + + def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor: + if self._pool_wm_sequence: + last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True) + proj_dtype = self.wm_projector.weight.dtype + x = last_wm_hidden.to(dtype=proj_dtype) + wm_aligned = self.wm_post_norm(self.wm_projector(x)).to(dtype=last_vlm_hidden.dtype) + return torch.cat([last_vlm_hidden, wm_aligned], dim=1) + + def _first_action_token_index(self, input_ids: torch.Tensor) -> int: + """返回 batch 内第一个 action token 的位置(各样本 VL 段长度应一致)。""" + act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN + act_max = self.qwen_vl_interface._ACTION_TOKEN_MAX + seq = input_ids[0] + is_action = (seq >= act_min) & (seq <= act_max) + nonzero = torch.nonzero(is_action, as_tuple=False) + return nonzero[0].item() if nonzero.numel() > 0 else input_ids.size(1) + + def _extract_vl_only_hidden( + self, + hidden_states: torch.Tensor, + input_ids: torch.Tensor, + ) -> torch.Tensor: + """ + 从含 fast action 的完整序列 hidden 中截取纯 VL 段。 + 因果 LM 下,action token 之前的表示与仅 VL 输入前向一致。 + """ + end_idx = self._first_action_token_index(input_ids) + return hidden_states[:, :end_idx, :] + + def _encode_wan_hidden(self, batch_images: List, instructions: List[str]) -> torch.Tensor: + with torch.no_grad(): + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_inputs = self.wan_interface.build_inputs( + images=self._wm_images_head_only(batch_images), instructions=instructions + ) + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + return wm_outputs.hidden_states[-1] + + def map_fast_token_to_vlm_action(self, tokens) -> str: + return "".join([f"" for token in tokens]) + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> dict: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = ( + [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + ) + + if "action_mask" in examples[0]: + action_mask = [example["action_mask"] for example in examples] + if all(mask is None for mask in action_mask): + action_mask = None + else: + action_mask = None + + batch_fast_tokens = self.fast_action_model.encoder_action2fastoken(actions) + vlm_action_tokens = [self.map_fast_token_to_vlm_action(fast_tokens) for fast_tokens in batch_fast_tokens] + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs( + images=batch_images, instructions=instructions, solutions=vlm_action_tokens + ) + last_wm_hidden = self._encode_wan_hidden(batch_images, instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = self._extract_vl_only_hidden( + qwenvl_outputs.hidden_states[-1], qwen_inputs["input_ids"] + ) + if self.freeze_vlm_for_vla: + last_vlm_hidden = last_vlm_hidden.detach() + + vlm_fast_loss = qwenvl_outputs.loss + if vlm_fast_loss is None or torch.isnan(vlm_fast_loss): + vlm_fast_loss = torch.tensor(0.0, device=last_vlm_hidden.device) + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + with torch.autocast("cuda", dtype=torch.float32): + actions_tensor = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) + actions_target = actions_tensor[:, -(self.future_action_window_size + 1) :, :] + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state_tensor = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + state_repeated = state_tensor.repeat(repeated_diffusion_steps, 1, 1) + + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor( + np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype + ) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1) :, :] + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + if embodiment_tag is not None: + embodiment_tag_tensor = torch.tensor( + np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64 + ) + embodiment_tag_repeated = embodiment_tag_tensor.repeat(repeated_diffusion_steps) + else: + embodiment_tag_repeated = None + + diffusion_action_loss = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + ) + + action_loss = diffusion_action_loss + self.fast_loss_weight * vlm_fast_loss + return { + "action_loss": action_loss, + "vlm_fast_loss": vlm_fast_loss, + "diffusion_action_loss": diffusion_action_loss, + } + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict], + **kwargs: str, + ) -> dict: + if not isinstance(examples, list): + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = ( + [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + ) + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + last_wm_hidden = self._encode_wan_hidden(batch_images, instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwenvl_outputs.hidden_states[-1] + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + state_tensor = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + embodiment_tag_tensor = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + + with torch.autocast("cuda", dtype=torch.float32): + if embodiment_tag_tensor is not None: + pred_actions = self.action_model.predict_action(last_hidden, state_tensor, embodiment_tag_tensor) + else: + pred_actions = self.action_model.predict_action(last_hidden, state_tensor) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + @torch.inference_mode() + def predict_fast_action( + self, + examples: List[dict], + **kwargs, + ) -> dict: + """可选:单独通过 VLM generate 预测 fast 离散 action。""" + if not isinstance(examples, list): + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + generated_ids = self.qwen_vl_interface.model.generate(**qwen_inputs, max_length=2048) + + batch_vlm_action_token_ids = self._extract_action_token_ids(generated_ids) + batch_fast_action_token_idx = self._decode_action_tokens(batch_vlm_action_token_ids) + normalized_actions = self.fast_action_model.fast_tokenizer.decode(batch_fast_action_token_idx) + return {"normalized_actions": normalized_actions} + + def _extract_action_token_ids(self, generated_ids: torch.LongTensor) -> List[List[int]]: + act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN + act_max = self.qwen_vl_interface._ACTION_TOKEN_MAX + mask = (generated_ids >= act_min) & (generated_ids <= act_max) + results = [] + for b in range(generated_ids.size(0)): + idx = mask[b].nonzero(as_tuple=False).flatten() + if idx.numel() == 0: + results.append([]) + continue + results.append(generated_ids[b, idx].tolist()) + return results + + def _decode_action_tokens(self, batch_vlm_tokens: List[List[int]]) -> List[Any]: + act_min = self.qwen_vl_interface._ACTION_TOKEN_MIN + batch_fast_token_ids = [] + for seq in batch_vlm_tokens: + if not seq: + batch_fast_token_ids.append(None) + continue + batch_fast_token_ids.append([t - act_min for t in seq]) + return batch_fast_token_ids + + +if __name__ == "__main__": + from omegaconf import OmegaConf + + cfg = OmegaConf.load("examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml") + model: QwenFastWanPerceiver = QwenFastWanPerceiver(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image], + "lang": "Put all the toys in the child's room.", + } + sample2 = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image], + "lang": "Put all the toys in the child's room.", + } + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + print(f"Action Loss: {forward_output['action_loss'].item()}") + print(f"VLM Fast Loss: {forward_output['vlm_fast_loss'].item()}") + print(f"Diffusion Loss: {forward_output['diffusion_action_loss'].item()}") + + predict_output = model.predict_action(examples=[sample]) + print(f"Predicted Actions: {predict_output['normalized_actions']}") diff --git a/starVLA/model/framework/QwenGR00T.py b/starVLA/model/framework/QwenGR00T.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8684a319250172f884f0307ab55b834c2d3c6c --- /dev/null +++ b/starVLA/model/framework/QwenGR00T.py @@ -0,0 +1,276 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Junqiu YU / Fudan University] in [2025]. +# Design and Merged by [Jinhui YE / HKUST University] in [2025]. +""" +Qwen-GR00T Framework +A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions +Flow-matching header is copyright from GR00T N1.5, +""" +import sys +from pathlib import Path + +# Add workspace root to Python path if not already there +_workspace_root = Path(__file__).parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + + +from starVLA.training.trainer_utils import initialize_overwatch +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.action_model.GR00T_ActionHeader import get_action_model, FlowmatchingActionHead +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY + + +@FRAMEWORK_REGISTRY.register("QwenGR00T") +class Qwen_GR00T(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + # align dims --> we should put them to config or no? + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = self.qwen_vl_interface.model.config.hidden_size + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用 + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + + """ + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + # Extract action_mask if available + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None # [B, len, action_dim] + + + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor( + np.array(state), device=last_hidden.device, dtype=last_hidden.dtype + ) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + # Process action_mask if available + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor( + np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + + action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated, action_mask=action_mask_repeated) # (B, chunk_len, action_dim) + + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict], + **kwargs: str, + ) -> np.ndarray: + """ + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + + # last_hidden_state: [B, seq_len, H] + last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] + + state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None + + # Step 4: Action Expert Forward + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + 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") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10093)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + args.config_yaml = "/mnt/workspace/users/chenzengjue/starVLA2/examples/Robocasa_tabletop/train_files/test.yaml" + cfg = OmegaConf.load(args.config_yaml) + # try get model + # cfg.framework.action_model.action_hidden_dim = 2048 + + # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large" + + + model: Qwen_GR00T = Qwen_GR00T(cfg) + print(model) + + + + # # fake sample + # image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # # Create a sample + # sample = { + # "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + # "image": [image], # three views + # "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.", + # # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + # } + # sample2 = { + # "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + # "image": [image], # three views + # "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.", + # # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + # } + + # batch = [sample, sample2] # batch size 2 + # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + # model = model.to(device) + # forward_output = model(batch) + # action_loss = forward_output['action_loss'] + # print(f"Action Loss: {action_loss.item()}") + + # # test predict action + # predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]] + # normalized_actions = predict_output['normalized_actions'] + # print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + vla_dataset_cfg = cfg.datasets.vla_data + from torch.utils.data import DataLoader + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + cfg.datasets.vla_data.include_state = "False" + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + # forward model with dataloader + for batch in tqdm(train_dataloader, desc="Processing Batches"): + # try get model + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + # break + + action = model.predict_action(examples=batch) + print("Finished") diff --git a/starVLA/model/framework/QwenOFT.py b/starVLA/model/framework/QwenOFT.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc8060ff49c8dc399302e0a8bb37e095fa49cbc --- /dev/null +++ b/starVLA/model/framework/QwenOFT.py @@ -0,0 +1,338 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Jinhui YE / HKUST University] in [2025]. + +""" +Qwen-OFT Framework + +A lightweight implementation that uses an action special token to parallelly predict continuous actions +conditioned on multi-view images plus a language instruction (shares parameters with the VLM). +Inspired by OpenVLA-OFT +Key Points: + - Qwen2.5 vision-language backbone + - Injects an action special token into the VLM + - Continuous action prediction via L1 regression over the action special token hidden states + + +Note: How to add special tokens to Qwen2.5: + download our model checkpoint with special tokens added: https://huggingface.co/StarVLA/Qwen2.5-VL-3B-Instruct-Action + or /starVLA/model/modules/vlm/tools/add_qwen_special_tokens/README.md (adpat a little code) + +""" +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + + +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.model.tools import FRAMEWORK_REGISTRY +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.action_model.MLP_ActionHeader import get_action_model +from starVLA.training.trainer_utils.trainer_tools import resize_images + +@FRAMEWORK_REGISTRY.register("QwenOFT") +class Qwenvl_OFT(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + # align dims --> we should put them to config or no? + config.framework.action_model.action_hidden_dim = self.qwen_vl_interface.model.config.hidden_size + self.action_model = get_action_model(config=self.config) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + # self.hidden_dim = config.framework.action_model.action_hidden_dim + + self.action_token = "🔍" # TODO also can add spacail token to Qwen, but too complex + self.action_token_id = self.qwen_vl_interface.processor.tokenizer("🔍", add_special_tokens=False)["input_ids"][0] + + # L1 损失 + self.l1_loss = nn.L1Loss() + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + 训练前向:直接回归未来动作(无扩散)。 + + Flow: + 1. Build QwenVL inputs (images + instruction tokens) + 2. Extract hidden states from configured layer range + 7. Predict action and compute L1 loss + + Args: + examples: List[dict], each dict requires: + - image: List[PIL.Image] (multi-view) + - lang: str instruction + - action: np.ndarray or list shaped [T, action_dim] + **kwargs: Reserved. + + Returns: + dict: + action_loss (torch.Tensor): Scalar diffusion noise prediction loss. + """ + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + + # step 0: add special action token to instruction + action_tokens = self.action_token* self.chunk_len #can't add " " between two tokens, otherwise will be tokenized to multiple tokens + prompt_suffix = f" Please predict the next {self.chunk_len} robot actions: {action_tokens}." + instructions = [instruction + prompt_suffix for instruction in instructions] + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + # 提取动作 token embedding 作为动作预测查询 + input_ids = qwen_inputs.get("input_ids", None) + action_queries = self._gather_action_token_embeddings(last_hidden, input_ids, action_token_id=self.action_token_id) # [B, chunk_len, H] + pred_actions = self.action_model.predict_action(action_queries) # (B, chunk_len, action_dim) + + # 标签对齐:取最后 chunk_len 段 + actions = torch.tensor( + np.array(actions), device=pred_actions.device, dtype=pred_actions.dtype + ) # [B, T_full, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + # 计算 L1 损失 + action_loss = self.l1_loss(pred_actions, actions_target) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict] = None, + **kwargs: str, + ) -> np.ndarray: + """ + 推理:单次前向直接回归未来动作(无扩散采样)。 + + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # step 0: add special action token to instruction + action_tokens = self.action_token* self.chunk_len #can't add " " between two tokens, otherwise will be tokenized to multiple tokens + prompt_suffix = f" Please predict the next {self.chunk_len} robot actions: {action_tokens}." + instructions = [instruction + prompt_suffix for instruction in instructions] + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + # 提取动作 token embedding 作为动作预测查询 + input_ids = qwen_inputs.get("input_ids", None) + action_queries = self._gather_action_token_embeddings(last_hidden, input_ids, action_token_id=self.action_token_id) # [B, chunk_len, H] + pred_actions = self.action_model.predict_action(action_queries) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + def _gather_action_token_embeddings( + self, + last_hidden: torch.Tensor, # [B, L, H] + input_ids: torch.Tensor, # [B, L] + action_token_id=None, # 可为 int 或 List[int] + ) -> torch.Tensor: + """ + 向量化批量提取动作 token embedding: + - 不再逐样本 for 循环 + - 取每个样本里最靠后的 chunk_len 个动作占位 token + Args: + last_hidden: [B, L, H] + input_ids: [B, L] + action_token_id: int 或 List[int] + Returns: + action_queries: [B, chunk_len, H] + """ + if action_token_id is None: + raise ValueError("action_token_id 不能为空") + + device = input_ids.device + B, L, H = last_hidden.shape + + # 支持多 id(如多个变体) + if isinstance(action_token_id, (list, tuple, set)): + id_list = torch.tensor(list(action_token_id), device=device, dtype=input_ids.dtype) + # torch.isin 需要 PyTorch >=1.10 + mask = torch.isin(input_ids, id_list) + else: + mask = (input_ids == action_token_id) # [B, L] + + counts = mask.sum(dim=1) # [B] + if (counts < self.chunk_len).any(): + insufficient = (counts < self.chunk_len).nonzero(as_tuple=False).flatten().tolist() + raise RuntimeError( + f"以下样本动作 token 数量不足 {self.chunk_len}: {insufficient} | counts={counts.tolist()}" + ) + + # 位置索引 + idx = torch.arange(L, device=device).unsqueeze(0).expand(B, L) # [B, L] + masked_pos = torch.where(mask, idx, torch.full_like(idx, -1)) # 非动作位置置 -1 + + # 取最后 chunk_len 个(索引大的在序列靠后) + # 注意: 已确保数量足够,不会出现 -1 被错误选中的问题 + topk_pos = masked_pos.topk(k=self.chunk_len, dim=-1).values # [B, chunk_len] 未排序 + # 时间顺序排序 + selected_pos = topk_pos.sort(dim=-1).values # [B, chunk_len] + + # Gather + expanded_index = selected_pos.unsqueeze(-1).expand(-1, -1, H) # [B, chunk_len, H] + action_queries = last_hidden.gather(dim=1, index=expanded_index) # [B, chunk_len, H] + return action_queries + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + cfg = OmegaConf.load(args.config_yaml) + cfg.framework.action_model.action_hidden_dim = 2048 + + cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large" + + + # try get model + model = Qwenvl_OFT(cfg) + print(model) + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # two views + "lang": "This is a fake instruction for testing.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + sample2 = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # two views + "lang": "For testing.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample2] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]]) + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + + # try forward model + # can be fake sample, but here get from dataloader for simpler + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + + vla_dataset_cfg = cfg.datasets.vla_data + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + from torch.utils.data import DataLoader + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + # zhe + for batch in tqdm(train_dataloader, desc="Processing Batches"): + batch + break + + # try get model + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + pass + action = model.predict_action(batch) \ No newline at end of file diff --git a/starVLA/model/framework/QwenPI.py b/starVLA/model/framework/QwenPI.py new file mode 100644 index 0000000000000000000000000000000000000000..a5eb2946ab656dc24d37d44777efba55e12f2c56 --- /dev/null +++ b/starVLA/model/framework/QwenPI.py @@ -0,0 +1,275 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by Jinhui YE / HKUST University] in [2025]. +""" +Qwen-GROOT Framework +A lightweight implementation that Qwen2.5-vl + Flow-matching head to directly predict continuous actions +Flow-matching header is copyright from GR00T N1.5, but a sample MoE inspired by PI_0 +""" +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + + +from starVLA.training.trainer_utils import initialize_overwatch +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.action_model.LayerwiseFM_ActionHeader import get_action_model, LayerwiseFlowmatchingActionHead +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY + +#################################################### +# ⚠️ Warning: This framework has been restructured and is NOT compatible with checkpoints created before 2025-10-20. +#################################################### + +@FRAMEWORK_REGISTRY.register("QwenPI") +class Qwen_PI(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise cross DiT diffusion head + + + Focus: Predict future continuous actions conditioned on images + instruction. + """ +# + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + + # dynamic get llm config + num_vl_layers, llm_hidden_size = 36, self.qwen_vl_interface.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = llm_hidden_size + self.config.framework.qwenvl.num_vl_layers = num_vl_layers + + self.action_model: LayerwiseFlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + Args: + examples: List[dict], each dict requires: + - image: List[PIL.Image] (multi-view) + - lang: str instruction + - action: np.ndarray or list shaped [T, action_dim] + Returns: + dict: + action_loss (torch.Tensor): Scalar diffusion noise prediction loss. + """ + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # 取与 DiT 层数匹配的最后 N 层隐藏态,按层喂给 DiT + all_hidden = qwenvl_outputs.hidden_states + expected_layers = len(self.action_model.model.transformer_blocks) + vl_embs_list = list(all_hidden[-expected_layers:]) + base_hidden = vl_embs_list[-1] + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + # 标签对齐:取最后 chunk_len 段 + actions = torch.tensor( + np.array(actions), device=base_hidden.device, dtype=base_hidden.dtype + ) # [B, T_full, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + repeated_diffusion_steps = 2 # NO repeat for big action FM + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + # 对每层特征做 repeat + vl_embs_list_repeated = [h.repeat(repeated_diffusion_steps, 1, 1) for h in vl_embs_list] + + state_repeated = None + if state is not None: + state = torch.tensor( + np.array(state), device=base_hidden.device, dtype=base_hidden.dtype + ) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_loss = self.action_model(vl_embs_list_repeated, actions_target_repeated, state_repeated) # (B, chunk_len, action_dim) + + + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( # TODO align predict_action with forward, make api more flexible + self, + examples: List[dict] = None, + **kwargs: str, + ) -> np.ndarray: + """ + 推理:单次前向直接回归未来动作(无扩散采样)。 + + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + from deployment.model_server.tools.image_tools import to_pil_preserve + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + all_hidden = qwenvl_outputs.hidden_states + expected_layers = len(self.action_model.model.transformer_blocks) + vl_embs_list = list(all_hidden[-expected_layers:]) + base_hidden = vl_embs_list[-1] + + state = torch.from_numpy(np.array(state)).to(base_hidden.device, dtype=base_hidden.dtype) if state is not None else None + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(vl_embs_list, state) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./starVLA/config/training/starvla_cotrain_oxe.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + cfg = OmegaConf.load(args.config_yaml) + # try get model + cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Qwen3-VL-4B-Instruct" + + + model = Qwen_PI(cfg) + # ckpt="/mnt/petrelfs/yejinhui/Projects/llavavla/results/Checkpoints/1011_qwenpi/checkpoints/need_steps_10000_pytorch_model.pt" + # model = Qwen_PI.from_pretrained(ckpt) + print(model) + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image, image], # two views + "lang": "This is a fake instruction for testing.", + "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action([sample]) + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + # from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + + # vla_dataset_cfg = cfg.datasets.vla_data + # dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + # from torch.utils.data import DataLoader + + # train_dataloader = DataLoader( + # dataset, + # batch_size=2, + # num_workers=1, # For Debug + # collate_fn=collate_fn, + # ) + # # + # for batch in tqdm(train_dataloader, desc="Processing Batches"): + # batch + # break + + # # try get model + # device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + # model = model.to(device) + # model(batch) + + # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]]) + + # # fake state + # for ba in batch: + # ba["state"] = ba["action"][0][None] + + # model(batch) + # action = model.predict_action(batch_images=[batch[0]["image"]], instructions=[batch[0]["lang"]], state=[batch[0]["state"]]) diff --git a/starVLA/model/framework/QwenPerceiver.py b/starVLA/model/framework/QwenPerceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..20ff6e79f94012449a98de019cfa493b9df92999 --- /dev/null +++ b/starVLA/model/framework/QwenPerceiver.py @@ -0,0 +1,313 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Junqiu YU / Fudan University] in [2025]. +# Design and Merged by [Jinhui YE / HKUST University] in [2025]. +""" +Qwen-GR00T Framework +A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions +Flow-matching header is copyright from GR00T N1.5, +""" +import sys +from pathlib import Path + +# Add workspace root to Python path if not already there +_workspace_root = Path(__file__).parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + + +from starVLA.training.trainer_utils import initialize_overwatch +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model + +from starVLA.model.modules.action_model.PerceiverHead import get_action_model, FlowmatchingActionHead +from starVLA.model.modules.action_model.time_aware_action_head import TimeAwareActionHead,TimeAwareActionHead_Config +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY + +# from starVLA.model.modules.action_model.flow_matching_action_head import ( +# FlowmatchingActionHead, +# FlowmatchingActionHeadConfig, +# ) + + +@FRAMEWORK_REGISTRY.register("QwenPerceiver") +class Qwen_Perceiver(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + # align dims --> we should put them to config or no? + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = self.qwen_vl_interface.model.config.hidden_size + + self.use_time_aware_action_head = True + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用 + + # if self.use_time_aware_action_head: + # # self.model = TimeAwareActionHead(config=time_aware_action_head_config) + # action_head_cfg = TimeAwareActionHead_Config() + # time_aware_action_head_config = action_head_cfg.convert_to_dict() + # time_aware_action_head_config['action_dim'] = 1536 + # time_aware_action_head_config['layers'] = 16 + # time_aware_action_head_config['heads'] = 16 + # act_config = {} + # act_config['diffusion_model_cfg'] = time_aware_action_head_config + # act_config["tune_projector"] = True + # act_config["tune_diffusion_model"] = True + # act_config["use_time_aware_action_head"] = True + # action_model_params = dict(self.config.framework.action_model) + # # 2. 将这些参数合并到 act_config 中 + # act_config.update(action_model_params) + # action_head_config = FlowmatchingActionHeadConfig(**act_config) + # # import ipdb;ipdb.set_trace() + # self.action_head = FlowmatchingActionHead(action_head_config) + # # self.action_model = TimeAwareActionHead(config=time_aware_action_head_config) + # else: + # self.action_model: TimeAwareActionHead = get_action_model(config=self.config) # 修复后续引用 + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + + def forward( + self, + examples: List[dict] = None, + **kwargs, + ) -> Tuple: + """ + + """ + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1] + + # Extract action_mask if available + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None # [B, len, action_dim] + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor( + np.array(state), device=last_hidden.device, dtype=last_hidden.dtype + ) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + # Process action_mask if available + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor( + np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + if embodiment_tag is not None: + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) # embodiment_tag is index + else: + embodiment_tag_repeated = None + + 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) + + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict], + **kwargs: str, + ) -> np.ndarray: + """ + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1] + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + + # last_hidden_state: [B, seq_len, H] + last_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] + + state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None + embodiment_tag = torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) if embodiment_tag is not None else None + + # Step 4: Action Expert Forward + with torch.autocast("cuda", dtype=torch.float32): + if embodiment_tag is not None: + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) # (B, chunk_len, action_dim) + else: + pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + args.config_yaml = "examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml" + cfg = OmegaConf.load(args.config_yaml) + # try get model + # cfg.framework.action_model.action_hidden_dim = 2048 + + # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large" + + + model: Qwen_Perceiver = Qwen_Perceiver(cfg) + print(model) + + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + sample2 = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample2] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]] + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + vla_dataset_cfg = cfg.datasets.vla_data + from torch.utils.data import DataLoader + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + cfg.datasets.vla_data.include_state = "False" + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + # forward model with dataloader + for batch in tqdm(train_dataloader, desc="Processing Batches"): + # try get model + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + # break + + action = model.predict_action(examples=batch) + print("Finished") diff --git a/starVLA/model/framework/QwenWanPerceiver.py b/starVLA/model/framework/QwenWanPerceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..0893698dbde48f046597c5a29c9044f8cb93c20b --- /dev/null +++ b/starVLA/model/framework/QwenWanPerceiver.py @@ -0,0 +1,373 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Junqiu YU / Fudan University] in [2025]. +# Design and Merged by [Jinhui YE / HKUST University] in [2025]. +""" +Qwen-GR00T Framework +A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions +Flow-matching header is copyright from GR00T N1.5, +""" +import sys +from pathlib import Path + +# Add workspace root to Python path if not already there +_workspace_root = Path(__file__).parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + + +from starVLA.training.trainer_utils import initialize_overwatch +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.world_model import get_world_model + +from starVLA.model.modules.action_model.PerceiverHead_original import get_action_model, FlowmatchingActionHead +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY + +# from starVLA.model.modules.action_model.flow_matching_action_head import ( +# FlowmatchingActionHead, +# FlowmatchingActionHeadConfig, +# ) + + +@FRAMEWORK_REGISTRY.register("QwenWanPerceiver") +class QwenWan_Perceiver(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + self.qwen_vl_interface = get_vlm_model(config=self.config) + self.wan_interface = get_world_model(config=self.config) + + wm_cfg = config.framework.get("world_model", {}) + # 将 Wan 多 token 压成 1 个全局条件,避免 action DiT 的 KV 比 QwenPerceiver 长数倍、稀释 cross-attn + self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False)) + wm_hidden = self.wan_interface.model.config.hidden_size + cross_dim = self.qwen_vl_interface.model.config.hidden_size + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = cross_dim + self.wm_projector = torch.nn.Linear(wm_hidden, cross_dim) + self.wm_post_norm = torch.nn.LayerNorm(cross_dim, eps=1e-6) + gain = float(wm_cfg.get("wm_projector_init_gain", 0.02)) + torch.nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain) + torch.nn.init.zeros_(self.wm_projector.bias) + logger.info( + f"QwenWanPerceiver: pool_wm_sequence={self._pool_wm_sequence}, wm_projector_init_gain={gain}" + ) + + self.use_time_aware_action_head = True + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) # 修复后续引用 + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # Whether to freeze VLM for VLA data (no gradient backprop to VLM) + self.freeze_vlm_for_vla = ( + config.trainer.get("freeze_vlm_for_vla", False) + if config and hasattr(config, "trainer") else False + ) + print("freeze_vlm_for_vla: ",self.freeze_vlm_for_vla) + + @staticmethod + def _wm_images_head_only(batch_images: List) -> List: + """World model 只使用每个样本的第一路相机(例如 [头, 左手, 右手] 中的头部)。""" + wm_images = [] + for imgs in batch_images: + if isinstance(imgs, (list, tuple)): + wm_images.append([imgs[0]] if len(imgs) > 0 else []) + else: + wm_images.append([imgs]) + return wm_images + + def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor: + """Wan 特征与 Qwen 最后一层 hidden 对齐维后沿序列维拼接。""" + if self._pool_wm_sequence: + last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True) + # Wan 在 bf16 autocast 下常为 BF16,Linear/LayerNorm 参数默认 FP32,需对齐后再乘权重 + proj_dtype = self.wm_projector.weight.dtype + x = last_wm_hidden.to(dtype=proj_dtype) + wm_aligned = self.wm_post_norm(self.wm_projector(x)).to(dtype=last_vlm_hidden.dtype) + return torch.cat([last_vlm_hidden, wm_aligned], dim=1) + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1] + + # Extract action_mask if available + if "action_mask" in examples[0]: + action_mask = [example["action_mask"] for example in examples] # [B, len, action_dim] + # Check if all action_mask values are None, if so set to None + if all(mask is None for mask in action_mask): + action_mask = None + else: + action_mask = None + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + + # Step 2–3: Wan 仅作冻结特征提取:no_grad 不保留反传激活;bf16 autocast 降低 Wan 前向峰值显存 + # with torch.no_grad(): + # with torch.autocast("cuda", dtype=torch.bfloat16): + # wm_inputs = self.wan_interface.build_inputs( + # images=self._wm_images_head_only(batch_images), instructions=instructions + # ) + # wm_outputs = self.wan_interface( + # **wm_inputs, + # output_hidden_states=True, + # return_dict=True, + # ) + # last_wm_hidden = wm_outputs.hidden_states[-1] + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_inputs = self.wan_interface.build_inputs( + images=self._wm_images_head_only(batch_images), instructions=instructions + ) + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_wm_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + last_vlm_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] [ 2, 221, 3072 ] + + # Detach hidden states to prevent gradient backprop to VLM for VLA data + if self.freeze_vlm_for_vla: + last_vlm_hidden = last_vlm_hidden.detach() + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + # last_hidden = last_vlm_hidden + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor( + np.array(state), device=last_hidden.device, dtype=last_hidden.dtype + ) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + # Process action_mask if available + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor( + np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + if embodiment_tag is not None: + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) # embodiment_tag is index + else: + embodiment_tag_repeated = None + + 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) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict], + **kwargs: str, + ) -> np.ndarray: + """ + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1] + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # Step 1: QWenVL + Wan(与 forward 一致,否则推理与训练条件分布不一致) + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + with torch.no_grad(): + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_inputs = self.wan_interface.build_inputs( + images=self._wm_images_head_only(batch_images), instructions=instructions + ) + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_wm_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwenvl_outputs.hidden_states[-1] + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None + embodiment_tag = torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) if embodiment_tag is not None else None + + # Step 4: Action Expert Forward + with torch.autocast("cuda", dtype=torch.float32): + if embodiment_tag is not None: + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) # (B, chunk_len, action_dim) + else: + pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + args.config_yaml = "examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml" + cfg = OmegaConf.load(args.config_yaml) + # try get model + # cfg.framework.action_model.action_hidden_dim = 2048 + + # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large" + + + model: QwenWan_Perceiver = QwenWan_Perceiver(cfg) + print(model) + + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + sample2 = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample2] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]] + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + vla_dataset_cfg = cfg.datasets.vla_data + from torch.utils.data import DataLoader + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + cfg.datasets.vla_data.include_state = "False" + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + # forward model with dataloader + for batch in tqdm(train_dataloader, desc="Processing Batches"): + # try get model + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + # break + + action = model.predict_action(examples=batch) + print("Finished") diff --git a/starVLA/model/framework/QwenWanPerceiverACoT.py b/starVLA/model/framework/QwenWanPerceiverACoT.py new file mode 100644 index 0000000000000000000000000000000000000000..3f213dfb4b797f665524236c7f27e94e29989463 --- /dev/null +++ b/starVLA/model/framework/QwenWanPerceiverACoT.py @@ -0,0 +1,595 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Junqiu YU / Fudan University] in [2025]. +# Design and Merged by [Jinhui YE / HKUST University] in [2025]. +""" +Qwen-GR00T Framework +A lightweight implementation that Qwen-VL + Flow-matching head to directly predict continuous actions +Flow-matching header is copyright from GR00T N1.5, +""" +import sys +from pathlib import Path + +# Add workspace root to Python path if not already there +_workspace_root = Path(__file__).parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from typing import List +from tqdm import tqdm +from typing import List, Optional, Tuple +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + + + +from starVLA.training.trainer_utils import initialize_overwatch +from deployment.model_server.tools.image_tools import to_pil_preserve + +logger = initialize_overwatch(__name__) + +# HuggingFace Default / LLaMa-2 IGNORE_INDEX (for labels) +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.world_model import get_world_model + +from starVLA.model.modules.action_model.PerceiverHead import get_action_model, FlowmatchingActionHead +from starVLA.training.trainer_utils.trainer_tools import resize_images +from starVLA.model.tools import FRAMEWORK_REGISTRY + +# from starVLA.model.modules.action_model.flow_matching_action_head import ( +# FlowmatchingActionHead, +# FlowmatchingActionHeadConfig, +# ) + + +@FRAMEWORK_REGISTRY.register("QwenWanPerceiverACoT") +class QwenWan_Perceiver_ACoT(baseframework): + """ + Multimodal vision-language-action model. + + Components: + - Qwen2.5 VL interface for fused language/vision token embeddings + - Layer-wise QFormer for multi-layer feature aggregation + - DINO encoder for dense multi-view spatial tokens + - DiT diffusion head for future action sequence modeling + + Focus: Predict future continuous actions conditioned on images + instruction. + """ + + def __init__( + self, + config: Optional[dict] = None, + **kwargs, + ) -> None: + """ + Construct all submodules and cache key configuration values. + + Args: + config: Hierarchical configuration (OmegaConf/dict) containing framework + trainer sections. + **kwargs: Reserved for future overrides (unused). + """ + super().__init__() + self.config = config + + # 1. 初始化Qwen作为VLM-Backone、初始化Wan作为WAM-Backbone、初始化FlowmatchingActionHead作为ActionHead + self.qwen_vl_interface = get_vlm_model(config=self.config) + self.wan_interface = get_world_model(config=self.config) + + # for p in self.wan_interface.parameters(): + # p.requires_grad = False + # for p in self.qwen_vl_interface.parameters(): + # p.requires_grad = False + + for p in self.wan_interface.text_encoder.parameters(): + p.requires_grad = False + for p in self.wan_interface.vae.parameters(): + p.requires_grad = False + + wm_cfg = config.framework.get("world_model", {}) + # 将 Wan 多 token 压成 1 个全局条件,避免 action DiT 的 KV 比 QwenPerceiver 长数倍、稀释 cross-attn + self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False)) + wm_hidden = self.wan_interface.model.config.hidden_size + cross_dim = self.qwen_vl_interface.model.config.hidden_size + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = cross_dim + self.wm_projector = torch.nn.Linear(wm_hidden, cross_dim) + self.wm_post_norm = torch.nn.LayerNorm(cross_dim, eps=1e-6) + gain = float(wm_cfg.get("wm_projector_init_gain", 0.02)) + torch.nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain) + torch.nn.init.zeros_(self.wm_projector.bias) + logger.info( + f"QwenWanPerceiver: pool_wm_sequence={self._pool_wm_sequence}, wm_projector_init_gain={gain}" + ) + + self.use_time_aware_action_head = True + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = config.framework.action_model.future_action_window_size + self.past_action_window_size = config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # Whether to freeze VLM for VLA data (no gradient backprop to VLM) + self.freeze_vlm_for_vla = ( + config.trainer.get("freeze_vlm_for_vla", False) + if config and hasattr(config, "trainer") else False + ) + print("freeze_vlm_for_vla: ",self.freeze_vlm_for_vla) + + # 2. 加载vjepa_encoder和vjepa_decoder,并将其权重固定为bf16 + vjepa2_ac_cfg = self.config.framework.get("vjepa2_ac") + vjepa2_ac_repo_dir = vjepa2_ac_cfg.get("repo_dir") + vjepa2_ac_pretrained = vjepa2_ac_cfg.get("pretrained") + # print(vjepa2_ac_repo_dir) # /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main + # print(vjepa2_ac_pretrained) # /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt + self.vjepa_encoder, self.vjepa_predictor = torch.hub.load( + vjepa2_ac_repo_dir, + "vjepa2_ac_vit_giant", + source="local", + pretrained=vjepa2_ac_pretrained, + ) + self.vjepa_encoder = self.vjepa_encoder.to(torch.bfloat16).cuda() + self.vjepa_predictor = self.vjepa_predictor.to(torch.bfloat16).cuda() + for p in self.vjepa_encoder.parameters(): + p.requires_grad = False + + # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用, + # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配 + # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None, + # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重 + for p in self.vjepa_predictor.action_encoder.parameters(): + p.requires_grad = False + for p in self.vjepa_predictor.state_encoder.parameters(): + p.requires_grad = False + for p in self.vjepa_predictor.extrinsics_encoder.parameters(): + p.requires_grad = False + + # print(type(self.vjepa_encoder)) # + # print(type(self.vjepa_predictor)) # + + # 初始化VJEPA2-AC的图像预处理transform,与官方energy_landscape_example.ipynb保持一致 + from starVLA.facebookresearch_vjepa2_main.app.vjepa_droid.transforms import make_transforms as vjepa2_make_transforms + self._vjepa2_transform = vjepa2_make_transforms( + random_horizontal_flip=False, + random_resize_aspect_ratio=(1., 1.), + random_resize_scale=(1., 1.), + reprob=0., + auto_augment=False, + motion_shift=False, + crop_size=256, + ) + + self.state_dim = self.config.framework.action_model.get("state_dim", None) + self.state_projector = torch.nn.Linear( + self.state_dim, + self.vjepa_predictor.predictor_embed.out_features, + bias=True + ).to(torch.bfloat16) + # print(self.state_dim) # 64 + # print(self.vjepa_predictor.predictor_embed.out_features) # 1024 + self.action_projector = torch.nn.Linear( + self.action_model.model.config.output_dim, + self.vjepa_predictor.predictor_embed.out_features, + bias=True + ).to(torch.bfloat16) + # print(self.action_model.model.config.output_dim) # 1024 + # print(self.vjepa_predictor.predictor_embed.out_features) # 1024 + + @staticmethod + def _wm_images_head_only(batch_images: List) -> List: + """World model 只使用每个样本的第一路相机(例如 [头, 左手, 右手] 中的头部)。""" + wm_images = [] + for imgs in batch_images: + if isinstance(imgs, (list, tuple)): + wm_images.append([imgs[0]] if len(imgs) > 0 else []) + else: + wm_images.append([imgs]) + return wm_images + + def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor: + """Wan 特征与 Qwen 最后一层 hidden 对齐维后沿序列维拼接。""" + if self._pool_wm_sequence: + last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True) + # Wan 在 bf16 autocast 下常为 BF16,Linear/LayerNorm 参数默认 FP32,需对齐后再乘权重 + proj_dtype = self.wm_projector.weight.dtype + x = last_wm_hidden.to(dtype=proj_dtype) + wm_aligned = self.wm_post_norm(self.wm_projector(x)).to(dtype=last_vlm_hidden.dtype) + return torch.cat([last_vlm_hidden, wm_aligned], dim=1) + + def _as_bool(self, value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _as_sequence(self, images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor: + if state is None or self.state_dim is None: + return state + target_dim = int(self.state_dim) + current_dim = state.shape[-1] + if current_dim == target_dim: + return state + if current_dim > target_dim: + return state[..., :target_dim] + + pad_shape = (*state.shape[:-1], target_dim - current_dim) + padding = state.new_zeros(pad_shape) + return torch.cat([state, padding], dim=-1) + + def _vjepa2ac_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-1') + if "future_image" not in examples[0]: + return None + + # 2. 从examples中取出当前图像和未来图像,并使用VJEPA2-AC官方的transform对图像做预处理 + batch_current_images = [to_pil_preserve(example["image"]) for example in examples] + batch_future_images = [to_pil_preserve(example["future_image"]) for example in examples] + # print(len(examples)) # 8 + clips_list = [] + for current_images, future_images in zip(batch_current_images, batch_future_images): + current_seq = self._as_sequence(current_images) + future_seq = self._as_sequence(future_images) + # print(len(current_seq)) # 1 + # print(len(future_seq)) # 1 + current_np = np.array(current_seq[0]) + future_np = np.array(future_seq[0]) + # print(current_np.shape) # (224, 224, 3) + # print(future_np.shape) # (224, 224, 3) + clip_np = np.stack([current_np, future_np], axis=0) + # print(clip_np.shape) # (2, 224, 224, 3) + clip_tensor = self._vjepa2_transform(clip_np) + # print(clip_tensor.shape) # torch.Size([3, 2, 256, 256]) + clips_list.append(clip_tensor) + clips = torch.stack(clips_list, dim=0).to(self.vjepa_encoder.patch_embed.proj.weight.device) + # print(clips.shape) # torch.Size([8, 3, 2, 256, 256]) + B, C, T, H, W = clips.size() + # print(clips.shape) # torch.Size([8, 3, 2, 256, 256]) + c = clips.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1).to(torch.bfloat16) + # print(c.shape) # torch.Size([16, 3, 2, 256, 256]) + + # 3. self.vjepa_encoder推理时使用b16 + # 这是仿照self._cosmos25_future_image_loss中,当self.backbone作为编码器前向推理时使用bf16 + crop_size = 256 + tokens_per_frame = int((crop_size // self.vjepa_encoder.patch_size) ** 2) + # 仿照原始代码对self.backbone的处理,用bf16 autocast包裹vjepa_encoder + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + # print(type(self.vjepa_encoder)) # + h = self.vjepa_encoder(c) + # print(h.shape) # torch.Size([16, 256, 1408]) + h = h.view(B, T, -1, h.size(-1)).flatten(1, 2) + # print(h.shape) # torch.Size([8, 512, 1408]) + h = F.layer_norm(h, (h.size(-1),)) + # print(h.shape) # torch.Size([8, 512, 1408]) + + # 4. 从h中分离出current_tokens和future_tokens + current_tokens = h[:, :tokens_per_frame] + future_tokens = h[:, tokens_per_frame:] + # print(current_tokens.shape) # torch.Size([8, 256, 1408]) + # print(future_tokens.shape) # torch.Size([8, 256, 1408]) + + # 5. 从examples中取出current_state,参考predict_action()中的实现 + current_state = [example["state"] for example in examples] if "state" in examples[0] else None + # print(len(current_state)) # 8 + # print(current_state[0].shape) # (1, 64) + current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype)) + # print(current_state.shape) # torch.Size([8, 1, 64]) + current_state = self._align_state_dim(current_state) + # print(current_state.shape) # torch.Size([8, 1, 64]) + + # 6. self.vjepa_predictor推理时使用fp32 + # 这是仿照CosmoPredict2Perceiver.forward()中,当self.action_model生成action前向推理时使用fp32 + with torch.autocast("cuda", dtype=torch.float32): + # 通过projector映射维度 + # print(current_state.shape) # torch.Size([8, 1, 64]) + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + current_state_emb = self.state_projector(current_state) + target_emb_proj = self.action_projector(target_emb) + # print(current_state_emb.shape) # torch.Size([8, 1, 1024]) + # print(target_emb_proj.shape) # torch.Size([8, 64, 1024]) + + # 7. 调用self.vjepa_predictor预测future_tokens + future_tokens_pred = self.vjepa_predictor.forward_for_WAM_VJEPA2AC( + x=current_tokens, + target_emb=target_emb_proj, + state_emb=current_state_emb, + ) + # print(type(self.vjepa_predictor)) # + # print(current_tokens.shape) # torch.Size([8, 256, 1408]) + # print(target_emb_proj.shape) # torch.Size([8, 64, 1024]) + # print(current_state_emb.shape) # torch.Size([8, 1, 1024]) + # print(future_tokens_pred.shape) # torch.Size([8, 256, 1408]) + + # 8. 计算future_latent_loss + future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens) + # print(future_latent_loss) # tensor(0.3229, device='cuda:0', grad_fn=) + + # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-2') + return future_latent_loss + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + # ACoT初始化 + output = {} + future_image_cfg = dict(self.config.framework.get("future_image_training", {})) + future_latent_cfg = dict(self.config.framework.get("future_latent_training", {})) + + # 加载数据 + batch_images = [example["image"] for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + actions = [example["action"] for example in examples] # label [B, len, 7] + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1] + + # Extract action_mask if available + if "action_mask" in examples[0]: + action_mask = [example["action_mask"] for example in examples] # [B, len, action_dim] + # Check if all action_mask values are None, if so set to None + if all(mask is None for mask in action_mask): + action_mask = None + else: + action_mask = None + + # Step 1: QWenVL input format + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + + # Step 2–3: Wan 仅作冻结特征提取:no_grad 不保留反传激活;bf16 autocast 降低 Wan 前向峰值显存 + # with torch.no_grad(): + # with torch.autocast("cuda", dtype=torch.bfloat16): + # wm_inputs = self.wan_interface.build_inputs( + # images=self._wm_images_head_only(batch_images), instructions=instructions + # ) + # wm_outputs = self.wan_interface( + # **wm_inputs, + # output_hidden_states=True, + # return_dict=True, + # ) + # last_wm_hidden = wm_outputs.hidden_states[-1] + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_inputs = self.wan_interface.build_inputs( + images=self._wm_images_head_only(batch_images), instructions=instructions + ) + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_wm_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + # last_hidden_state: [B, seq_len, H] + last_vlm_hidden = qwenvl_outputs.hidden_states[-1] # [B, L, H] [ 2, 221, 3072 ] + + # Detach hidden states to prevent gradient backprop to VLM for VLA data + if self.freeze_vlm_for_vla: + last_vlm_hidden = last_vlm_hidden.detach() + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + # last_hidden = last_vlm_hidden + + # Step 4: Action Expert Forward and Loss + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + actions_target = actions[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) if self.config and self.config.trainer else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor( + np.array(state), device=last_hidden.device, dtype=last_hidden.dtype + ) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + # Process action_mask if available + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor( + np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype + ) # [B, T_full, action_dim] + + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size+1):, :] # (B, chunk_len, action_dim) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + if embodiment_tag is not None: + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) # embodiment_tag is index + else: + embodiment_tag_repeated = None + + action_loss, target_emb = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + use_vjepa2ac=True, + repeated_diffusion_steps=repeated_diffusion_steps, + ) + + output = {} + output["perceiver_action_loss"] = action_loss.detach() + total_loss = action_loss + + # Step 5: Calculate the future_latent_loss by VJEPA2-AC + # print(future_latent_cfg.get("enabled")) # True + # print(future_latent_cfg.get("loss_weight")) # 0.02 + if self._as_bool(future_latent_cfg.get("enabled")): + future_latent_loss = self._vjepa2ac_future_latent_loss(examples, target_emb) + if future_latent_loss is not None: + future_latent_loss_weight = float(future_latent_cfg.get("loss_weight")) + output["future_latent_loss"] = future_latent_loss.detach() + total_loss = total_loss + future_latent_loss * future_latent_loss_weight + + output["action_loss"] = total_loss + + return output + + @torch.inference_mode() + def predict_action( + self, + examples: List[dict], + **kwargs: str, + ) -> np.ndarray: + """ + Steps: + 1. Resize images to training resolution (if specified) + 2. Encode with QwenVL (hidden states retained) + 6. Return normalized action trajectory + Returns: + dict: + normalized_actions (np.ndarray): Shape [B, T, action_dim], diffusion-sampled normalized actions. + """ + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] # [B,[PLT]] + instructions = [example["lang"] for example in examples] # [B, str] + + state = [example["state"] for example in examples] if "state" in examples[0] else None # [B, 1, state_dim] + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None # [B, 1] + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # Step 1: QWenVL + Wan(与 forward 一致,否则推理与训练条件分布不一致) + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + # with torch.no_grad(): + # with torch.autocast("cuda", dtype=torch.bfloat16): + # wm_inputs = self.wan_interface.build_inputs( + # images=self._wm_images_head_only(batch_images), instructions=instructions + # ) + # wm_outputs = self.wan_interface( + # **wm_inputs, + # output_hidden_states=True, + # return_dict=True, + # ) + # last_wm_hidden = wm_outputs.hidden_states[-1] + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_inputs = self.wan_interface.build_inputs( + images=self._wm_images_head_only(batch_images), instructions=instructions + ) + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_wm_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.bfloat16): + qwenvl_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwenvl_outputs.hidden_states[-1] + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + state = torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) if state is not None else None + embodiment_tag = torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) if embodiment_tag is not None else None + + # Step 4: Action Expert Forward + with torch.autocast("cuda", dtype=torch.float32): + if embodiment_tag is not None: + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) # (B, chunk_len, action_dim) + else: + pred_actions = self.action_model.predict_action(last_hidden, state) # (B, chunk_len, action_dim) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + +if __name__ == "__main__": + from omegaconf import OmegaConf + import debugpy + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--config_yaml", type=str, default="./examples/Robotwin/train_files/starvla_cotrain_robotwin.yaml", help="Path to YAML config") + args, clipargs = parser.parse_known_args() + + debugpy.listen(("0.0.0.0", 10092)) + print("🔍 Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + args.config_yaml = "examples/MultiRobot/train_files/starvla_cotrain_multiRobot.yaml" + cfg = OmegaConf.load(args.config_yaml) + # try get model + # cfg.framework.action_model.action_hidden_dim = 2048 + + # cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Florence-2-large" + + + model: QwenWan_Perceiver = QwenWan_Perceiver(cfg) + print(model) + + + + # fake sample + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + # Create a sample + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + sample2 = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), # action_chunk, action_dim + "image": [image], # three views + "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.", + # "state" : np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), # chunk, state_dim + } + + batch = [sample, sample2] # batch size 2 + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output['action_loss'] + print(f"Action Loss: {action_loss.item()}") + + # test predict action + predict_output = model.predict_action(examples=[sample]) #, state=[batch[0]["state"]] + normalized_actions = predict_output['normalized_actions'] + print(f"Unnormalized Action: {normalized_actions}") + + # # Advance: try forward model with dataloader + # # can be fake sample, but here get from dataloader for simpler + vla_dataset_cfg = cfg.datasets.vla_data + from torch.utils.data import DataLoader + from starVLA.dataloader.lerobot_datasets import get_vla_dataset, collate_fn + cfg.datasets.vla_data.include_state = "False" + dataset = get_vla_dataset(data_cfg=vla_dataset_cfg) + + train_dataloader = DataLoader( + dataset, + batch_size=2, + num_workers=1, # For Debug + collate_fn=collate_fn, + ) + # forward model with dataloader + for batch in tqdm(train_dataloader, desc="Processing Batches"): + # try get model + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + model(batch) + # break + + action = model.predict_action(examples=batch) + print("Finished") diff --git a/starVLA/model/framework/QwenWanPerceiverMask.py b/starVLA/model/framework/QwenWanPerceiverMask.py new file mode 100644 index 0000000000000000000000000000000000000000..348cf118132d7ff39fbc2f9bf1d02b63ad085d3f --- /dev/null +++ b/starVLA/model/framework/QwenWanPerceiverMask.py @@ -0,0 +1,703 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +QwenWanPerceiver with masked future-image denoising. + +This variant keeps the existing action path and adds a Wan2 future-image +objective with a latent-grid change mask built from the current/future RGB +pair. The mask focuses the loss on changed regions and optionally adds noise +only inside those regions, turning future-image training into an +inpainting-style objective. + +Key adaptation from CosmoPredict25PerceiverMaskedFutureImage: + - Wan2 uses expand_timesteps (per-token timestep) instead of Cosmos's + condition_mask / padding_mask. Condition-frame tokens receive + timestep=0 (clean); target-frame tokens receive flow_time. + - Wan2 VAE has z_dim=48 and temporal_downsample_factor=4. + +================================================================================ +(1) datasets.py 修改说明 +================================================================================ + +为了支持本模型对 future_image 的需求,对 datasets.py 做了两处最小化修改: + +A. 新增 _get_future_images 方法(LeRobotMixtureDataset 类) + + 逻辑: + - 取第一个 action key 的 delta_indices 最大值 +1 作为 future_offset + (即当前 action chunk 最后一步的下一帧) + - 遍历所有 video key,用 dataset.get_video(trajectory_id, video_key, + step + future_offset) 读取未来视频帧 + - 取该视频的最后一帧,转为 PIL Image,返回每路相机的未来帧列表 + +B. 修改 __getitem__ 中的两处 return + + 在 return 之前新增条件化获取和返回 future_image 的逻辑: + future_images = None + if self.data_cfg is not None and self.data_cfg.get("include_future_image", False): + future_images = self._get_future_images(dataset, trajectory_id, step, data) + + 在两处 return 的 dict 中条件化添加: + if future_images is not None: + result["future_image"] = future_images + + 核心原则:只有当 data_cfg.include_future_image=True 时才会获取并返回 + future_image,其他模型的配置中没有该字段(默认 False),完全不受影响。 + +================================================================================ +(2) QwenWanPerceiverMask 与 QwenWanPerceiver 的区别 +================================================================================ + +QwenWan_Perceiver_Mask 继承自 QwenWan_Perceiver,保留了原有的 action 预测 +路径不变,新增了 masked future-image denoising loss。 + +新增方法: + - _build_future_video_sequences(): + 构建视频序列 [current_frame] + [future_frame]*4(5帧 → Wan2 VAE 编码 + → 2个 latent frame:1个条件 + 1个目标) + + - _build_latent_change_masks(): + RGB 差异图下采样到 latent 分辨率,top-k 选择变化最大的 25% 区域, + 生成 binary mask + soft loss weight + + - _wan_future_image_loss(): + 核心方法,计算 masked future-image denoising loss,流程: + 1. 从 example 中取 future_image,若不存在则返回 None(不训练) + 2. 构建 5 帧视频序列,经 Wan2 VAE 编码得到 clean_latents [B,48,2,H,W] + 3. 构建变化 mask:当前帧 vs 未来帧的 RGB 差异 → 下采样到 latent + 分辨率 → top-k 选变化区域 + 4. 采样 flow matching 时间步 t,加噪:x_t = (1-t)*x_0 + t*noise + 5. Masked denoising:只对目标帧中变化区域加噪,静态区域保持干净 + 6. Per-token timestep(关键适配):Wan2 不支持 Cosmos 的 + condition_mask,改用 expand_timesteps——条件帧 token timestep=0 + (干净),目标帧 token timestep=flow_time + 7. Static region conditioning:未变化的目标区域也标记为条件帧 + (timestep=0) + 8. 计算 MSE loss,用 change mask 加权 + + - _future_training_cfg(): + 读取 config.framework.future_image_training 配置 + + - _sample_train_times(): + 采样 flow matching 的时间步(支持 logitnormal / uniform 分布) + + - _shift_time(): + 对时间步施加 shift 偏移(默认 shift=5.0) + + - 辅助方法:_as_sequence(), _pil_rgb_to_tensor(), _as_bool() + +重写的 forward 方法: + + 原始 forward 只返回 {"action_loss": action_loss},新版本: + output = super().forward(examples=examples, **kwargs) # 先走原 action 路径 + action_loss = output["action_loss"] + future_image_loss = self._wan_future_image_loss(examples) + # 总 loss = action_loss + future_image_loss * loss_weight + output["action_loss"] = action_loss + future_image_loss * loss_weight +================================================================================ +""" + +from __future__ import annotations + +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image as PILImage + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.QwenWanPerceiver import QwenWan_Perceiver +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@FRAMEWORK_REGISTRY.register("QwenWanPerceiverMask") +class QwenWan_Perceiver_Mask(QwenWan_Perceiver): + """QwenWanPerceiver with masked future-image denoising.""" + + def __init__(self, config=None, **kwargs): + super().__init__(config=config, **kwargs) + + qwenvl_cfg = self.config.framework.get("qwenvl", {}) if self.config is not None else {} + is_frozen = bool(qwenvl_cfg.get("is_frozen", False)) + + for p in self.wan_interface.text_encoder.parameters(): + p.requires_grad = False + for p in self.wan_interface.vae.parameters(): + p.requires_grad = False + + if is_frozen: + for p in self.qwen_vl_interface.parameters(): + p.requires_grad = False + + @staticmethod + def _as_sequence(images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + @staticmethod + def _pil_rgb_to_tensor(image, size=None) -> torch.Tensor: + from PIL import Image as _Image + image = to_pil_preserve(image).convert("RGB") + if size is not None and image.size != size: + image = image.resize(size) + array = np.asarray(image, dtype=np.float32) / 255.0 + return torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0) + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _future_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_image_training", {})) + + def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor: + distribution = str(distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}") + + @staticmethod + def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor: + return shift * time / (1.0 + (shift - 1.0) * time) + + def _latent_frame_count(self, raw_frame_count: int) -> int: + temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4)) + return (int(raw_frame_count) - 1) // temporal_factor + 1 + + def _maybe_apply_single_frame_condition(self, examples: List[dict], training_cfg: dict) -> tuple[List[dict], float]: + prob = float(training_cfg.get("single_frame_condition_prob", 0.0)) + if prob <= 0.0 or not examples: + return examples, 0.0 + + prob = min(max(prob, 0.0), 1.0) + sampled_examples = [] + single_frame_count = 0 + for example in examples: + image_sequence = self._as_sequence(example.get("image")) + if len(image_sequence) > 1 and torch.rand((), device="cpu").item() < prob: + example = dict(example) + example["image"] = [image_sequence[-1]] + single_frame_count += 1 + sampled_examples.append(example) + + return sampled_examples, single_frame_count / max(1, len(examples)) + + def _build_future_video_sequences(self, batch_images: List, future_images: List): + """Build video sequences for Wan2 VAE encoding. + + Keep all observed frames as condition frames, then append the future frame + repeated by temporal_factor. This mirrors + CosmoPredict25PerceiverFutureImage._build_future_video_sequences, with + only the video model swapped from Cosmos to Wan. + + Returns: + raw_sequences: List of List[PIL Image] + condition_counts: List[int] — latent condition frame count + sample_counts: List[int] — latent total frame count + """ + temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + condition_counts = [] + sample_counts = [] + + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + if not current_sequence or not future_sequence: + raise ValueError("future image training needs both current image and future_image.") + + future_frame = future_sequence[0] + raw_sequence = current_sequence + [future_frame] * temporal_factor + raw_sequences.append(raw_sequence) + condition_counts.append(self._latent_frame_count(len(current_sequence))) + sample_counts.append(self._latent_frame_count(len(raw_sequence))) + + return raw_sequences, condition_counts, sample_counts + + def _build_latent_change_masks( + self, + batch_images: List, + future_images: List, + latent_height: int, + latent_width: int, + training_cfg: dict, + device: torch.device, + ) -> tuple: + """Return binary denoise mask and soft loss weights at latent resolution. + + Adapted from CosmoPredict25PerceiverMaskedFutureImage._build_latent_change_masks. + """ + top_ratio = float(training_cfg.get("change_mask_top_ratio", 0.25)) + top_ratio = min(max(top_ratio, 1e-4), 1.0) + static_weight = float(training_cfg.get("change_mask_static_weight", 0.05)) + static_weight = min(max(static_weight, 0.0), 1.0) + soft_loss = self._as_bool(training_cfg.get("change_mask_soft_loss", True)) + + binary_masks = [] + loss_weights = [] + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + current_frame = current_sequence[-1] + target_frame = future_sequence[0] + + current = self._pil_rgb_to_tensor(current_frame) + target = self._pil_rgb_to_tensor(target_frame, size=to_pil_preserve(current_frame).size) + diff = (target - current).abs().mean(dim=1, keepdim=True) + score = F.interpolate(diff, size=(latent_height, latent_width), mode="area") + flat = score.flatten(1) + max_score = flat.amax(dim=1).view(-1, 1, 1, 1).clamp_min(1e-6) + normalized = (score / max_score).clamp(0.0, 1.0) + + k = max(1, int(flat.shape[1] * top_ratio)) + threshold = flat.topk(k, dim=1).values[:, -1].view(-1, 1, 1, 1) + binary = (score >= threshold).float() + + weight_source = normalized if soft_loss else binary + loss_weight = static_weight + (1.0 - static_weight) * weight_source + binary_masks.append(binary) + loss_weights.append(loss_weight) + + binary_mask = torch.cat(binary_masks, dim=0).to(device=device, dtype=torch.float32) + loss_weight = torch.cat(loss_weights, dim=0).to(device=device, dtype=torch.float32) + return binary_mask, loss_weight + + def _wan_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + """Compute masked future-image denoising loss using Wan2 DiT. + + Adaptation from CosmoPredict25PerceiverMaskedFutureImage for Wan2: + - Uses Wan2 _encode_images_vae instead of Cosmos _encode_images + - Uses per-token expand_timesteps instead of condition_mask / padding_mask + - Condition-frame tokens get timestep=0 (clean), target-frame tokens + get timestep=flow_time + """ + if "future_image" not in examples[0]: + return None + + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if not train_obs_image_size: + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + + # Build video sequences: [current_frame, future_frame * temporal_factor] + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + + # Encode through Wan2 VAE — raw_sequences already contains head-only frames + # (batch_images/future_images were already filtered via _wm_images_head_only earlier, + # so we should NOT apply _wm_images_head_only again on the video sequences) + with torch.no_grad(): + clean_latents = self.wan_interface._encode_images_vae(raw_sequences) + + dtype = self.wan_interface.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + + # Build per-latent-frame masks + # condition_mask: which latent frames are conditions (timestep=0) + # target_mask: which latent frames are targets (to be denoised) + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + # Build change masks at latent spatial resolution + change_binary, change_loss_weight = self._build_latent_change_masks( + batch_images=batch_images, + future_images=future_images, + latent_height=height, + latent_width=width, + training_cfg=training_cfg, + device=device, + ) + change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype) + change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32) + + # Sample training time + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + + # Flow-matching interpolation: x_t = (1-t)*x_0 + t*noise + noise = torch.randn_like(clean_latents) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + + # Masked denoising: only noise changed regions in target frames + use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", True)) + use_static_conditioning = use_masked_denoising and self._as_bool( + training_cfg.get("condition_static_regions", True) + ) + + if use_masked_denoising: + denoise_mask = target_mask.to(dtype=clean_latents.dtype) * change_binary + else: + denoise_mask = target_mask.to(dtype=clean_latents.dtype) + + # hidden_states: condition frames stay clean, target frames are noised + # (within target frames, only changed regions are noised if masked_denoising) + hidden_states = torch.where(denoise_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + target_velocity = noise.float() - clean_latents.float() + + # Static region conditioning: treat unchanged target regions as conditions + if use_static_conditioning: + static_target_mask = target_mask.to(dtype=clean_latents.dtype) * (1.0 - change_binary) + condition_mask = torch.maximum(condition_mask, static_target_mask) + + # Build per-token timestep for Wan2 expand_timesteps mode + # Condition tokens → timestep=0, target tokens → timestep=flow_time + p_t, p_h, p_w = self.wan_interface.transformer.config.patch_size + tokens_per_frame = (height // p_h) * (width // p_w) + + # flow_time is [B], expand to per-token: [B, num_latents * tokens_per_frame] + cond_timestep_val = 0.0 # clean condition + target_timestep_val = flow_time.to(dtype=torch.float32) # [B] + + timestep_per_token = torch.zeros( + batch_size, num_latents * tokens_per_frame, + device=device, dtype=torch.float32, + ) + for batch_idx in range(batch_size): + for latent_idx in range(num_latents): + start = latent_idx * tokens_per_frame + end = (latent_idx + 1) * tokens_per_frame + if target_mask[batch_idx, 0, latent_idx, 0, 0] > 0.5: + timestep_per_token[batch_idx, start:end] = target_timestep_val[batch_idx] + else: + timestep_per_token[batch_idx, start:end] = cond_timestep_val + + # Encode text + with torch.no_grad(): + prompt_embeds = self.wan_interface._encode_text(instructions) + + # DiT forward pass + self.wan_interface._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.wan_interface.transformer( + hidden_states=hidden_states, + timestep=timestep_per_token, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + ) + pred = pred.sample if hasattr(pred, "sample") else pred + if isinstance(pred, tuple): + pred = pred[0] + self.wan_interface._intermediate_features.clear() + + # Compute masked loss + temporal_loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width) + if use_static_conditioning: + change_loss_weight = change_loss_weight * change_binary.float() + spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width) + spatial_loss_weight = spatial_loss_weight.expand(batch_size, channels, num_latents, height, width) + loss_mask = temporal_loss_mask * spatial_loss_weight + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + + return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + + def forward(self, examples: List[dict] = None, **kwargs): + """Forward pass: action loss + masked future-image loss.""" + output = super().forward(examples=examples, **kwargs) + action_loss = output["action_loss"] + + future_image_loss = self._wan_future_image_loss(examples) + if future_image_loss is None: + return output + + loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0)) + output["perceiver_action_loss"] = action_loss.detach() + output["future_image_loss"] = future_image_loss.detach() + output["action_loss"] = action_loss + future_image_loss * loss_weight + return output + + # ------------------------------------------------------------------ + # Future-image generation (eval / inference) + # ------------------------------------------------------------------ + + def _get_future_image_generation_cfg(self, kwargs: dict) -> dict: + """Merge config defaults with runtime kwargs for future-image generation.""" + cfg = dict(self.config.framework.get("future_image_generation", {})) + override = kwargs.get("future_image_generation", None) + if override: + cfg.update(dict(override)) + + if "decode_future_images" in kwargs: + cfg["enabled"] = kwargs["decode_future_images"] + if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs: + cfg["num_inference_steps"] = kwargs["num_ddim_steps"] + + for key in ( + "enabled", + "num_frames", + "num_inference_steps", + "guidance_scale", + "output_type", + "height", + "width", + "max_sequence_length", + "max_samples", + "return_full_video", + "future_frame_index", + "negative_prompt", + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ): + if key in kwargs: + cfg[key] = kwargs[key] + return cfg + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + """Build generation inputs for Wan2 TI2V pipeline. + """ + height = cfg.pop("height", getattr(self.wan_interface, "height", 704)) + width = cfg.pop("width", getattr(self.wan_interface, "width", 1280)) + heights = self._resolve_generation_size_values(batch_images, height, width) + + # Wan2 TI2V: pass conditioning image directly; generate() handles + # VAE encoding + expand_timesteps internally + head_only_images = self._wm_images_head_only(batch_images) + condition_images = [self._as_sequence(imgs)[-1] for imgs in head_only_images] + + generation_inputs = { + "prompt": instructions, + "image": condition_images, + "height": heights[0], + "width": heights[1], + "num_frames": cfg.pop("num_frames", 93), + "num_inference_steps": cfg.pop("num_inference_steps", 36), + "guidance_scale": cfg.pop("guidance_scale", 7.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + } + + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + passthrough_keys = ( + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "num_videos_per_prompt", + "callback_on_step_end", + "callback_on_step_end_tensor_inputs", + ) + for key in passthrough_keys: + if key in cfg and cfg[key] is not None: + generation_inputs[key] = cfg.pop(key) + + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() == "auto" + + @staticmethod + def _round_up_to_multiple(value: int, multiple: int) -> int: + return int(((max(1, value) + multiple - 1) // multiple) * multiple) + + @staticmethod + def _image_size(image) -> tuple[int, int]: + size = getattr(image, "size", None) + if isinstance(size, (list, tuple)) and len(size) >= 2: + return int(size[0]), int(size[1]) + if torch.is_tensor(image): + shape = tuple(image.shape) + if len(shape) >= 3 and shape[0] in (1, 3, 4): + return int(shape[-1]), int(shape[-2]) + if len(shape) >= 2: + return int(shape[1]), int(shape[0]) + array = np.asarray(image) + if array.ndim < 2: + raise ValueError(f"Cannot infer image size from shape {array.shape}") + return int(array.shape[1]), int(array.shape[0]) + + def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple: + if not self._is_auto_size(height) and not self._is_auto_size(width): + return int(height), int(width) + + resolved_heights = [] + resolved_widths = [] + spatial_multiple = int(getattr(self.wan_interface, "vae_scale_factor_spatial", 16)) + patch_size = getattr(getattr(self.wan_interface.transformer, "config", None), "patch_size", None) + if isinstance(patch_size, (list, tuple)) and len(patch_size) >= 3: + spatial_multiple *= max(int(patch_size[-2]), int(patch_size[-1]), 1) + elif isinstance(patch_size, int): + spatial_multiple *= max(int(patch_size), 1) + for images in batch_images: + image_sequence = self._as_sequence(images) + frame_sizes = [self._image_size(image) for image in image_sequence] + if not frame_sizes: + raise ValueError("Cannot infer auto generation size from empty image sequence.") + + sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height) + sample_height = self._round_up_to_multiple(sample_height, spatial_multiple) + if self._is_auto_size(width): + max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes) + sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple) + else: + sample_width = self._round_up_to_multiple(int(width), spatial_multiple) + resolved_heights.append(int(sample_height)) + resolved_widths.append(int(sample_width)) + + height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0] + width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0] + return height_value, width_value + + @staticmethod + def _extract_videos(generation_output): + if hasattr(generation_output, "frames"): + return generation_output.frames + if hasattr(generation_output, "videos"): + return generation_output.videos + if hasattr(generation_output, "images"): + return generation_output.images + if isinstance(generation_output, tuple): + return generation_output[0] + return generation_output + + def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool): + from PIL import Image as _Image + videos = self._extract_videos(generation_output) + if return_full_video: + return videos + + if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], _Image.Image): + return [videos[future_frame_index]] + + future_images = [] + for sample in videos: + if torch.is_tensor(sample): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, np.ndarray): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, (list, tuple)): + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + return future_images + + @staticmethod + def _slice_generation_value(key: str, value, index: int, batch_size: int): + if value is None: + return None + if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if key in {"image", "video", "condition_image"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if torch.is_tensor(value) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, np.ndarray) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, list) and len(value) == batch_size: + return [value[index]] + if isinstance(value, tuple) and len(value) == batch_size: + return (value[index],) + return value + + def _generate_future_images( + self, + generation_inputs: dict, + batch_size: int, + max_samples: int, + future_frame_index: int, + return_full_video: bool, + ): + if max_samples is None or max_samples < 0: + sample_count = batch_size + else: + sample_count = min(batch_size, max(0, int(max_samples))) + + pred_future_images = [] + for sample_idx in range(sample_count): + single_inputs = { + key: self._slice_generation_value(key, value, sample_idx, batch_size) + for key, value in generation_inputs.items() + } + generation_output = self.wan_interface.generate(**single_inputs) + sample_images = self._select_future_images( + generation_output, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + if isinstance(sample_images, (list, tuple)): + pred_future_images.extend(sample_images) + else: + pred_future_images.append(sample_images) + return pred_future_images + + @torch.inference_mode() + def predict_action(self, examples: List[dict], is_run_parallel_eval_mxk: bool = False, **kwargs) -> dict: + """Predict actions and optionally generate future images.""" + output = super().predict_action(examples=examples, **kwargs) + + generation_cfg = self._get_future_image_generation_cfg(kwargs) + if not bool(generation_cfg.pop("enabled", True)): + return output + + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.datasets.vla_data, "image_size", None) + if not train_obs_image_size: + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + return_full_video = bool(generation_cfg.pop("return_full_video", False)) + future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + max_samples = int(generation_cfg.pop("max_samples", 1)) + generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + output["pred_future_images"] = self._generate_future_images( + generation_inputs, + batch_size=len(examples), + max_samples=max_samples, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + + # When called from websocket server, convert PIL Images to numpy arrays + # for msgpack serialization; otherwise keep PIL Image format + if is_run_parallel_eval_mxk and "pred_future_images" in output: + output["pred_future_images"] = [ + np.array(img) if isinstance(img, PILImage.Image) else img + for img in output["pred_future_images"] + ] + + return output \ No newline at end of file diff --git a/starVLA/model/framework/WAM_VJEPA/.ipynb_checkpoints/CosmoPredict25PerceiverVJEPA2AC-checkpoint.py b/starVLA/model/framework/WAM_VJEPA/.ipynb_checkpoints/CosmoPredict25PerceiverVJEPA2AC-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4942f59e1d6efe4a4ab5b1126a33149b2b31f8 --- /dev/null +++ b/starVLA/model/framework/WAM_VJEPA/.ipynb_checkpoints/CosmoPredict25PerceiverVJEPA2AC-checkpoint.py @@ -0,0 +1,895 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver with future-image prediction. + +This framework keeps the existing Cosmos hidden-state -> Perceiver action +path, and additionally runs the Cosmos2.5 generation/decoder path during +inference to return the image predicted after the action chunk horizon. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + +from starVLA.model.framework.WAM_VJEPA.CosmoPredict25Perceiver import ( + CosmoPredict25_Perceiver, + CosmoPredict25PerceiverDefaultConfig, +) + + +@dataclass +class CosmoPredict25PerceiverVJEPA2ACDefaultConfig(CosmoPredict25PerceiverDefaultConfig): + """Cosmos-Predict2.5-Perceiver + VJEPA2-AC defaults.""" + + name: str = "CosmoPredict25PerceiverFutureImage" + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 93, + "num_inference_steps": 36, + "guidance_scale": 7.0, + "output_type": "pil", + "height": 704, + "width": 1280, + "max_sequence_length": 512, + "conditional_frame_timestep": 0.1, + "num_latent_conditional_frames": 2, + "conditioning_mode": "auto", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + }) + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverVJEPA2AC") +class CosmoPredict25_Perceiver_VJEPA2AC(CosmoPredict25_Perceiver): + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + # print('################# CosmoPredict25_Perceiver_VJEPA2AC-1') + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverVJEPA2ACDefaultConfig, config) + + # 1. 加载预训练的CosmoPredictr2.5类作为self.backbone + # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py + self.backbone = get_world_model(config=self.config) + # print(type(self.backbone)) # + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + # print(wm_hidden) # 2048 + + # 2. 初始化FlowmatchingActionHead作为self.action_model + # WM4A/starVLA/model/modules/action_model/PerceiverHead.py + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + # print(type(self.action_model)) # + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + # print(self.future_action_window_size) # 15 + # print(self.past_action_window_size) # 0 + # print(self.chunk_len) # 16 + # print(self.state_dim) # 64 + + # 3. 加载vjepa_encoder和vjepa_decoder,并将其权重固定为bf16 + vjepa2_ac_cfg = self.config.framework.get("vjepa2_ac") + vjepa2_ac_repo_dir = vjepa2_ac_cfg.get("repo_dir") + vjepa2_ac_pretrained = vjepa2_ac_cfg.get("pretrained") + # print(vjepa2_ac_repo_dir) # /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main + # print(vjepa2_ac_pretrained) # /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt + self.vjepa_encoder, self.vjepa_predictor = torch.hub.load( + vjepa2_ac_repo_dir, + "vjepa2_ac_vit_giant", + source="local", + pretrained=vjepa2_ac_pretrained, + ) + self.vjepa_encoder = self.vjepa_encoder.to(torch.bfloat16).cuda() + self.vjepa_predictor = self.vjepa_predictor.to(torch.bfloat16).cuda() + for p in self.vjepa_encoder.parameters(): + p.requires_grad = False + # for p in self.vjepa_predictor.parameters(): + # p.requires_grad = False + + # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用, + # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配 + # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None, + # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重 + for p in self.vjepa_predictor.action_encoder.parameters(): + p.requires_grad = False + for p in self.vjepa_predictor.state_encoder.parameters(): + p.requires_grad = False + for p in self.vjepa_predictor.extrinsics_encoder.parameters(): + p.requires_grad = False + + for name, p in self.vjepa_encoder.named_parameters(): + assert p.dtype == torch.bfloat16, f"vjepa_encoder.{name} dtype={p.dtype}, expected bfloat16" + for name, p in self.vjepa_predictor.named_parameters(): + assert p.dtype == torch.bfloat16, f"vjepa_predictor.{name} dtype={p.dtype}, expected bfloat16" + + # print(type(self.vjepa_encoder)) # + # print(type(self.vjepa_predictor)) # + + # 初始化VJEPA2-AC的图像预处理transform,与官方energy_landscape_example.ipynb保持一致 + from starVLA.facebookresearch_vjepa2_main.app.vjepa_droid.transforms import make_transforms as vjepa2_make_transforms + self._vjepa2_transform = vjepa2_make_transforms( + random_horizontal_flip=False, + random_resize_aspect_ratio=(1., 1.), + random_resize_scale=(1., 1.), + reprob=0., + auto_augment=False, + motion_shift=False, + crop_size=256, + ) + + self.state_projector = torch.nn.Linear( + self.state_dim, + self.vjepa_predictor.predictor_embed.out_features, + bias=True + ).to(torch.bfloat16) + # print(self.state_dim) # 64 + # print(self.vjepa_predictor.predictor_embed.out_features) # 1024 + self.action_projector = torch.nn.Linear( + self.action_model.model.config.output_dim, + self.vjepa_predictor.predictor_embed.out_features, + bias=True + ).to(torch.bfloat16) + # print(self.action_model.model.config.output_dim) # 1024 + # print(self.vjepa_predictor.predictor_embed.out_features) # 1024 + # print('################# CosmoPredict25_Perceiver_FutureImage-2') + + @staticmethod + def _as_sequence(images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor: + if state is None or self.state_dim is None: + return state + target_dim = int(self.state_dim) + current_dim = state.shape[-1] + if current_dim == target_dim: + return state + if current_dim > target_dim: + return state[..., :target_dim] + + pad_shape = (*state.shape[:-1], target_dim - current_dim) + padding = state.new_zeros(pad_shape) + return torch.cat([state, padding], dim=-1) + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _future_image_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_image_training", {})) + + def _future_latent_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_latent_training", {})) + + def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor: + distribution = str(distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}") + + @staticmethod + def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor: + return shift * time / (1.0 + (shift - 1.0) * time) + + def _latent_frame_count(self, raw_frame_count: int) -> int: + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + return (int(raw_frame_count) - 1) // temporal_factor + 1 + + def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]: + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1') + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + condition_counts = [] + sample_counts = [] + # print(temporal_factor) # 4 + # print(len(batch_images)) # 8 + # print(len(future_images)) # 8 + + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + # print(len(current_sequence)) # 1 + # print(len(future_sequence)) # 1 + if not current_sequence or not future_sequence: + raise ValueError("future image training needs both current image and future_image.") + + future_frame = future_sequence[0] + # print(type(future_frame)) # + raw_sequence = current_sequence + [future_frame] * temporal_factor + raw_sequences.append(raw_sequence) + + condition_count = self._latent_frame_count(len(current_sequence)) + sample_count = self._latent_frame_count(len(raw_sequence)) + # print(condition_count) # 1 + # print(sample_count) # 2 + condition_counts.append(condition_count) + sample_counts.append(sample_count) + + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2') + return raw_sequences, condition_counts, sample_counts + + # 训练时 + # future_image支路,self.backbone.transformer() + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1') + if "future_image" not in examples[0]: + return None + training_cfg = self._future_image_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状 + # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt; + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + # print(type(batch_images[0])) # + # print(type(future_images[0])) # + # print(type(instructions[0])) # + + # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs] + # 而raw_sequences也是由8个这样的raw_sequence组成的列表, + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + # print(len(raw_sequences)) # 8 + # print(len(raw_sequences[0])) # 5 + # print(raw_sequences[0][0]) # + # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1] + # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2] + + # 2. 调用CosmosPredict的文本和视觉tokenizer, + # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28), + # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + # print(prompt_embeds.shape) # torch.Size([8, 512, 100352]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(dtype) # torch.bfloat16 + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1]) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪 + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + # print(train_time.shape) # torch.Size([8]) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + # print(flow_time.shape) # torch.Size([8]) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + noise = torch.randn_like(clean_latents) + # print(noise.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity + target_velocity = noise.float() - clean_latents.float() + # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 5. 计算timestep和padding_mask + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + # print(cond_timestep) # 0.1 + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + # print(padding_height) # 224 + # print(padding_width) # 224 + # print(padding_mask.shape) # torch.Size([1, 1, 224, 224]) + + # 7. CosmosPredict前向传播 + # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入, + # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中, + # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息, + # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分, + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + # print(type(self.backbone)) # + # print(pred.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 8. 计算future-image-loss + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width) + # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28]) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28]) + future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=) + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2') + return future_image_loss + + # 训练时 + # future_latent支路,self.vjepa_encoder + self.vjepa_predictor + def _vjepa2ac_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-1') + if "future_image" not in examples[0]: + return None + + # 2. 从examples中取出当前图像和未来图像,并使用VJEPA2-AC官方的transform对图像做预处理 + batch_current_images = [to_pil_preserve(example["image"]) for example in examples] + batch_future_images = [to_pil_preserve(example["future_image"]) for example in examples] + # print(len(examples)) # 8 + clips_list = [] + for current_images, future_images in zip(batch_current_images, batch_future_images): + current_seq = self._as_sequence(current_images) + future_seq = self._as_sequence(future_images) + # print(len(current_seq)) # 1 + # print(len(future_seq)) # 1 + current_np = np.array(current_seq[0]) + future_np = np.array(future_seq[0]) + # print(current_np.shape) # (224, 224, 3) + # print(future_np.shape) # (224, 224, 3) + clip_np = np.stack([current_np, future_np], axis=0) + # print(clip_np.shape) # (2, 224, 224, 3) + clip_tensor = self._vjepa2_transform(clip_np) + # print(clip_tensor.shape) # torch.Size([3, 2, 256, 256]) + clips_list.append(clip_tensor) + clips = torch.stack(clips_list, dim=0).to(self.vjepa_encoder.patch_embed.proj.weight.device) + # print(clips.shape) # torch.Size([8, 3, 2, 256, 256]) + B, C, T, H, W = clips.size() + # print(clips.shape) # torch.Size([8, 3, 2, 256, 256]) + c = clips.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1).to(torch.bfloat16) + # print(c.shape) # torch.Size([16, 3, 2, 256, 256]) + + # 3. self.vjepa_encoder推理时使用b16 + # 这是仿照self._cosmos25_future_image_loss中,当self.backbone作为编码器前向推理时使用bf16 + crop_size = 256 + tokens_per_frame = int((crop_size // self.vjepa_encoder.patch_size) ** 2) + # 仿照原始代码对self.backbone的处理,用bf16 autocast包裹vjepa_encoder + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + # print(type(self.vjepa_encoder)) # + h = self.vjepa_encoder(c) + # print(h.shape) # torch.Size([16, 256, 1408]) + h = h.view(B, T, -1, h.size(-1)).flatten(1, 2) + # print(h.shape) # torch.Size([8, 512, 1408]) + h = F.layer_norm(h, (h.size(-1),)) + # print(h.shape) # torch.Size([8, 512, 1408]) + + # 4. 从h中分离出current_tokens和future_tokens + current_tokens = h[:, :tokens_per_frame] + future_tokens = h[:, tokens_per_frame:] + # print(current_tokens.shape) # torch.Size([8, 256, 1408]) + # print(future_tokens.shape) # torch.Size([8, 256, 1408]) + + # 5. 从examples中取出current_state,参考predict_action()中的实现 + current_state = [example["state"] for example in examples] if "state" in examples[0] else None + # print(len(current_state)) # 8 + # print(current_state[0].shape) # (1, 64) + current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype)) + # print(current_state.shape) # torch.Size([8, 1, 64]) + current_state = self._align_state_dim(current_state) + # print(current_state.shape) # torch.Size([8, 1, 64]) + + # 6. self.vjepa_predictor推理时使用fp32 + # 这是仿照CosmoPredict2Perceiver.forward()中,当self.action_model生成action前向推理时使用fp32 + with torch.autocast("cuda", dtype=torch.float32): + # 通过projector映射维度 + # print(current_state.shape) # torch.Size([8, 1, 64]) + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + current_state_emb = self.state_projector(current_state) + target_emb_proj = self.action_projector(target_emb) + # print(current_state_emb.shape) # torch.Size([8, 1, 1024]) + # print(target_emb_proj.shape) # torch.Size([8, 64, 1024]) + + # 7. 调用self.vjepa_predictor预测future_tokens + future_tokens_pred = self.vjepa_predictor.forward_for_WAM_VJEPA2AC( + x=current_tokens, + target_emb=target_emb_proj, + state_emb=current_state_emb, + ) + # print(type(self.vjepa_predictor)) # + # print(current_tokens.shape) # torch.Size([8, 256, 1408]) + # print(target_emb_proj.shape) # torch.Size([8, 64, 1024]) + # print(current_state_emb.shape) # torch.Size([8, 1, 1024]) + # print(future_tokens_pred.shape) # torch.Size([8, 256, 1408]) + + # 8. 计算future_latent_loss + future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens) + # print(future_latent_loss) # tensor(0.3229, device='cuda:0', grad_fn=) + + # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-2') + return future_latent_loss + + # 训练时 + # 生成future_image、future_latent和action + # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight+future_latent_loss*loss_weight + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1') + output = {} + future_image_cfg = self._future_image_training_cfg() + future_latent_cfg = self._future_latent_training_cfg() + + # 1. action支路(必定执行) + perceiver_action_loss, target_emb = super().forward(examples=examples, **kwargs) + output["perceiver_action_loss"] = perceiver_action_loss.detach() + total_loss = perceiver_action_loss + # 仿照原始代码对action_model输出target_emb的处理,不强制转换精度 + # target_emb在float32 autocast内产生,后续_vjepa2ac_future_latent_loss也在float32 autocast内使用 + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + + # 2. future_image支路(根据enabled配置决定是否执行) + # print(future_image_cfg.get("enabled")) # False + # print(future_image_cfg.get("loss_weight")) # 1.0 + if self._as_bool(future_image_cfg.get("enabled")): + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is not None: + future_image_loss_weight = float(future_image_cfg.get("loss_weight")) + output["future_image_loss"] = future_image_loss.detach() + total_loss = total_loss + future_image_loss * future_image_loss_weight + + # 3. future_latent支路(根据enabled配置决定是否执行) + # print(future_latent_cfg.get("enabled")) # True + # print(future_latent_cfg.get("loss_weight")) # 1.0 + if self._as_bool(future_latent_cfg.get("enabled")): + future_latent_loss = self._vjepa2ac_future_latent_loss(examples, target_emb) + if future_latent_loss is not None: + future_latent_loss_weight = float(future_latent_cfg.get("loss_weight")) + output["future_latent_loss"] = future_latent_loss.detach() + total_loss = total_loss + future_latent_loss * future_latent_loss_weight + + output["action_loss"] = total_loss + + # print(output) + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2') + return output + + def _get_future_image_generation_cfg(self, kwargs: dict) -> dict: + cfg = dict(self.config.framework.get("future_image_generation", {})) + override = kwargs.get("future_image_generation", None) + if override: + cfg.update(dict(override)) + + if "decode_future_images" in kwargs: + cfg["enabled"] = kwargs["decode_future_images"] + if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs: + cfg["num_inference_steps"] = kwargs["num_ddim_steps"] + + for key in ( + "enabled", + "num_frames", + "num_inference_steps", + "guidance_scale", + "output_type", + "height", + "width", + "max_sequence_length", + "conditional_frame_timestep", + "num_latent_conditional_frames", + "conditioning_mode", + "max_samples", + "return_full_video", + "future_frame_index", + "negative_prompt", + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ): + if key in kwargs: + cfg[key] = kwargs[key] + return cfg + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + mode = str(cfg.pop("conditioning_mode", "auto")).lower() + height = cfg.pop("height", getattr(self.backbone, "_height", 704)) + width = cfg.pop("width", getattr(self.backbone, "_width", 1280)) + heights = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "prompt": instructions, + "height": heights[0], + "width": heights[1], + "num_frames": cfg.pop("num_frames", 93), + "num_inference_steps": cfg.pop("num_inference_steps", 36), + "guidance_scale": cfg.pop("guidance_scale", 7.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1), + "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2), + } + + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + if mode == "image": + generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images] + elif mode == "video": + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + elif mode == "auto": + if any(len(self._as_sequence(images)) > 1 for images in batch_images): + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + else: + generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images] + else: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + passthrough_keys = ( + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "num_videos_per_prompt", + "callback_on_step_end", + "callback_on_step_end_tensor_inputs", + ) + for key in passthrough_keys: + if key in cfg and cfg[key] is not None: + generation_inputs[key] = cfg.pop(key) + + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() == "auto" + + @staticmethod + def _round_up_to_multiple(value: int, multiple: int) -> int: + return int(((max(1, value) + multiple - 1) // multiple) * multiple) + + @staticmethod + def _image_size(image) -> tuple[int, int]: + size = getattr(image, "size", None) + if isinstance(size, (list, tuple)) and len(size) >= 2: + return int(size[0]), int(size[1]) + if torch.is_tensor(image): + shape = tuple(image.shape) + if len(shape) >= 3 and shape[0] in (1, 3, 4): + return int(shape[-1]), int(shape[-2]) + if len(shape) >= 2: + return int(shape[1]), int(shape[0]) + array = np.asarray(image) + if array.ndim < 2: + raise ValueError(f"Cannot infer image size from shape {array.shape}") + return int(array.shape[1]), int(array.shape[0]) + + def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple: + if not self._is_auto_size(height) and not self._is_auto_size(width): + return int(height), int(width) + + resolved_heights = [] + resolved_widths = [] + spatial_multiple = int(getattr(self.backbone, "vae_scale_factor_spatial", 16)) + for images in batch_images: + image_sequence = self._as_sequence(images) + frame_sizes = [self._image_size(image) for image in image_sequence] + if not frame_sizes: + raise ValueError("Cannot infer auto generation size from empty image sequence.") + + sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height) + if self._is_auto_size(width): + max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes) + sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple) + else: + sample_width = int(width) + resolved_heights.append(int(sample_height)) + resolved_widths.append(int(sample_width)) + + height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0] + width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0] + return height_value, width_value + + @staticmethod + def _extract_videos(generation_output): + if hasattr(generation_output, "frames"): + return generation_output.frames + if hasattr(generation_output, "videos"): + return generation_output.videos + if hasattr(generation_output, "images"): + return generation_output.images + if isinstance(generation_output, tuple): + return generation_output[0] + return generation_output + + def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool): + videos = self._extract_videos(generation_output) + if return_full_video: + return videos + + if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image): + return [videos[future_frame_index]] + + future_images = [] + for sample in videos: + if torch.is_tensor(sample): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, np.ndarray): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, (list, tuple)): + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + return future_images + + @staticmethod + def _slice_generation_value(key: str, value, index: int, batch_size: int): + if value is None: + return None + if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if torch.is_tensor(value) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, np.ndarray) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, list) and len(value) == batch_size: + return [value[index]] + if isinstance(value, tuple) and len(value) == batch_size: + return (value[index],) + return value + + # 推理时 + # future_image支路,self.backbone.generate() + def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool): + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1') + if max_samples is None or max_samples < 0: + sample_count = batch_size + else: + sample_count = min(batch_size, max(0, int(max_samples))) + # print(sample_count) # 1 + + # print(generation_inputs) + """ + { + 'prompt': [ + 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.', + 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.', + 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.', + 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.' + ], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': [ + , + , + , + , + , + , + , + + ] + } + """ + pred_future_images = [] + for sample_idx in range(sample_count): + + # 1. CosmosPredict:构建输入 + # print(sample_idx) # 0 + single_inputs = { + key: self._slice_generation_value(key, value, sample_idx, batch_size) + for key, value in generation_inputs.items() + } + # print(single_inputs) + """ + { + 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': + } + """ + + # 2. CosmosPredict:前向推理 + generation_output = self.backbone.generate(**single_inputs) + # print(type(self.backbone)) # + # print(type(generation_output)) # + # print(future_frame_index) # -1 + # print(return_full_video) # False + sample_images = self._select_future_images( + generation_output, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # print(sample_images) # [] + if isinstance(sample_images, (list, tuple)): + pred_future_images.extend(sample_images) + else: + pred_future_images.append(sample_images) + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2') + return pred_future_images + + # 推理时 + # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action() + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1') + if type(examples) is not list: + examples = [examples] + + # 1. CosmosPredict:构建输入 + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + state = [example["state"] for example in examples] if "state" in examples[0] else None + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + # print(state.shape) # torch.Size([8, 1, 64]) + state = self._align_state_dim(state) + # print(state.shape) # torch.Size([8, 1, 64]) + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + # print(embodiment_tag.shape) # torch.Size([8]) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + + # 4. ActionHead:前向推理 + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + # print(type(self.action_model)) # + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + # print(state.shape) # torch.Size([8, 1, 64]) + # print(embodiment_tag.shape) # torch.Size([8]) + # print(pred_actions.shape) # torch.Size([8, 16, 32]) + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + # # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要 + # generation_cfg = self._get_future_image_generation_cfg(kwargs) + # is_enabled = generation_cfg.pop("enabled", True) + # # print(is_enabled) # True + # if not bool(is_enabled): + # # print('is_enabled is False') + # # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + # return output + + # return_full_video = bool(generation_cfg.pop("return_full_video", False)) + # future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + # max_samples = int(generation_cfg.pop("max_samples", 1)) + # generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + # output["pred_future_images"] = self._generate_future_images( + # generation_inputs, + # batch_size=len(examples), + # max_samples=max_samples, + # future_frame_index=future_frame_index, + # return_full_video=return_full_video, + # ) + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output diff --git a/starVLA/model/framework/WAM_VJEPA/CosmoPredict25Perceiver.py b/starVLA/model/framework/WAM_VJEPA/CosmoPredict25Perceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..fc9c052fb6c6bd0bbc2d3e10f70c5603f553f98b --- /dev/null +++ b/starVLA/model/framework/WAM_VJEPA/CosmoPredict25Perceiver.py @@ -0,0 +1,92 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver Framework. + +This keeps Predict2.5 separate from the existing Cosmos-Predict2 framework +while reusing the same Perceiver action-head training/inference logic. +""" + +from dataclasses import dataclass, field +from typing import Optional + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY + +from starVLA.model.framework.WAM_VJEPA.CosmoPredict2Perceiver import CosmoPredict2_Perceiver + + +@dataclass +class CosmoPredict25PerceiverDefaultConfig: + """Cosmos-Predict2.5-Perceiver default parameters.""" + + name: str = "CosmoPredict25Perceiver" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "nvidia/Cosmos-Predict2.5-2B", + "revision": "diffusers/base/post-trained", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "nvidia/Cosmos-Predict2.5-2B", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "max_num_embodiments": 32, + "use_category_specific": False, + "diffusion_model_cfg": { + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25Perceiver") +class CosmoPredict25_Perceiver(CosmoPredict2_Perceiver): + """World-model-for-action framework using Cosmos-Predict2.5 + Perceiver.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size diff --git a/starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverDINO.py b/starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverDINO.py new file mode 100644 index 0000000000000000000000000000000000000000..6974e4132eec38be860a6142c2009884e5f05ef1 --- /dev/null +++ b/starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverDINO.py @@ -0,0 +1,709 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver with DINOv3 future-latent prediction. + +This framework keeps the existing Cosmos hidden-state -> Perceiver action +path, and additionally uses DINOv3 encoder + kaiming-initialized predictor +to compute future-latent loss during training. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from torchvision.transforms import v2 + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + +from starVLA.model.framework.WAM_VJEPA.CosmoPredict25Perceiver import ( + CosmoPredict25_Perceiver, + CosmoPredict25PerceiverDefaultConfig, +) + + + +@dataclass +class CosmoPredict25PerceiverDINODefaultConfig(CosmoPredict25PerceiverDefaultConfig): + """Cosmos-Predict2.5-Perceiver + DINOv3 defaults.""" + + name: str = "CosmoPredict25PerceiverFutureImage" + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 93, + "num_inference_steps": 36, + "guidance_scale": 7.0, + "output_type": "pil", + "height": 704, + "width": 1280, + "max_sequence_length": 512, + "conditional_frame_timestep": 0.1, + "num_latent_conditional_frames": 2, + "conditioning_mode": "auto", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + }) + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverDINO") +class CosmoPredict25_Perceiver_DINO(CosmoPredict25_Perceiver): + + # DINOv3 ViT-H+/16 常量 + DINO_EMBED_DIM = 1280 + DINO_PATCH_SIZE = 16 + DINO_IMG_SIZE = 224 + DINO_PREDICTOR_EMBED_DIM = 1024 + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverDINODefaultConfig, config) + + # 1. 加载预训练的CosmoPredictr2.5类作为self.backbone + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + # 2. 初始化FlowmatchingActionHead作为self.action_model + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + + # 3. 加载DINOv3编码器 + dino_cfg = self.config.framework.get("dinov3") + dino_repo_dir = dino_cfg.get("repo_dir") + dino_pretrained = dino_cfg.get("pretrained") + # 直接从dinov3代码构建模型,绕过torch.hub.load()。 + # 原因:torch.hub.load()内部dinov3_vith16plus会强制从远程URL下载.pth权重, + # 而本地权重是safetensors格式且网络不可达,导致URLError。 + import sys as _sys + import os as _os + # 将dinov3 repo根目录加入sys.path,使 `from dinov3.hub.backbones import ...` 可用 + # 注意:dinov3仓库结构为 repo_root/dinov3/hub/backbones.py, + # 需要将repo_root加入sys.path,Python才能找到内部的dinov3包(有__init__.py)。 + # 若加入repo_root的父目录,Python会找到没有__init__.py的repo_root目录作为命名空间包,导致dinov3.hub找不到。 + _dino_repo_root = _os.path.abspath(dino_repo_dir) + if _dino_repo_root not in _sys.path: + _sys.path.insert(0, _dino_repo_root) + # mock torchmetrics,dinov3的hubconf.py顶层import链依赖它 + if "torchmetrics" not in _sys.modules: + import types as _types + _tm = _types.ModuleType("torchmetrics") + _tm.Metric = type("Metric", (), {}) + _sys.modules["torchmetrics"] = _tm + _sys.modules["torchmetrics.utilities"] = _types.ModuleType("torchmetrics.utilities") + _sys.modules["torchmetrics.utilities.distributed"] = _types.ModuleType("torchmetrics.utilities.distributed") + _sys.modules["torchmetrics.utilities.distributed.gather"] = type("gather", (), {}) + _sys.modules["torchmetrics.utilities.prints"] = _types.ModuleType("torchmetrics.utilities.prints") + from dinov3.hub.backbones import dinov3_vith16plus as _dinov3_vith16plus + # pretrained=False:只构建模型结构,不下载权重 + self.dino_encoder = _dinov3_vith16plus(pretrained=False) + # 手动加载本地safetensors权重 + _weight_file = _os.path.join(dino_pretrained, "model.safetensors") + if not _os.path.isfile(_weight_file): + raise FileNotFoundError(f"DINOv3 weight file not found: {_weight_file}") + from safetensors.torch import load_file as _load_safetensors + _state_dict = _load_safetensors(_weight_file) + self.dino_encoder.load_state_dict(_state_dict, strict=False) + self.dino_encoder = self.dino_encoder.to(torch.bfloat16).cuda() + # 冻结dino_encoder全部参数 + for p in self.dino_encoder.parameters(): + p.requires_grad = False + + # 4. 初始化DINO Predictor(同结构kaiming随机初始化) + # 延迟导入VisionTransformerPredictorAC,避免模块级导入时因src不在sys.path而报错 + # (VJEPA2AC版本通过torch.hub.load触发导入,此处仿照其思路在__init__内导入) + from starVLA.facebookresearch_vjepa2_main.src.models.ac_predictor import VisionTransformerPredictorAC + # num_frames=4, tubelet_size=2 → grid_depth=2 → attn_mask足够大 + # forward_for_WAM_VJEPA2AC中实际序列长度=cond_tokens(65)+196=261, + # attn_mask大小=grid_depth*(add_tokens+H*W)=2*(2+196)=396>261 ✓ + # 注意:若num_frames太小(如默认1),grid_depth=0会导致attn_mask=[0,0]崩溃 + self.dino_predictor = VisionTransformerPredictorAC( + img_size=self.DINO_IMG_SIZE, + patch_size=self.DINO_PATCH_SIZE, + in_chans=3, + num_frames=4, + tubelet_size=2, + embed_dim=self.DINO_EMBED_DIM, + predictor_embed_dim=self.DINO_PREDICTOR_EMBED_DIM, + depth=24, + num_heads=16, + mlp_ratio=4.0, + qkv_bias=True, + action_embed_dim=self.state_dim, + ) + # kaiming随机初始化 + def _kaiming_init(m): + if isinstance(m, torch.nn.Linear): + torch.nn.init.kaiming_normal_(m.weight) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + self.dino_predictor.apply(_kaiming_init) + self.dino_predictor = self.dino_predictor.to(torch.bfloat16).cuda() + + # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用, + # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配 + # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None, + # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重 + for p in self.dino_predictor.action_encoder.parameters(): + p.requires_grad = False + for p in self.dino_predictor.state_encoder.parameters(): + p.requires_grad = False + for p in self.dino_predictor.extrinsics_encoder.parameters(): + p.requires_grad = False + + for name, p in self.dino_encoder.named_parameters(): + assert p.dtype == torch.bfloat16, f"dino_encoder.{name} dtype={p.dtype}, expected bfloat16" + for name, p in self.dino_predictor.named_parameters(): + assert p.dtype == torch.bfloat16, f"dino_predictor.{name} dtype={p.dtype}, expected bfloat16" + + # 初始化DINOv3的图像预处理transform(ImageNet标准) + self._dino_transform = v2.Compose([ + v2.ToImage(), + v2.Resize((self.DINO_IMG_SIZE, self.DINO_IMG_SIZE), antialias=True), + v2.ToDtype(torch.float32, scale=True), + v2.Normalize( + mean=(0.485, 0.456, 0.406), + std=(0.229, 0.224, 0.225), + ), + ]) + + self.state_projector = torch.nn.Linear( + self.state_dim, + self.DINO_PREDICTOR_EMBED_DIM, + bias=True + ).to(torch.bfloat16) + self.action_projector = torch.nn.Linear( + self.action_model.model.config.output_dim, + self.DINO_PREDICTOR_EMBED_DIM, + bias=True + ).to(torch.bfloat16) + + @staticmethod + def _as_sequence(images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor: + if state is None or self.state_dim is None: + return state + target_dim = int(self.state_dim) + current_dim = state.shape[-1] + if current_dim == target_dim: + return state + if current_dim > target_dim: + return state[..., :target_dim] + + pad_shape = (*state.shape[:-1], target_dim - current_dim) + padding = state.new_zeros(pad_shape) + return torch.cat([state, padding], dim=-1) + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _future_image_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_image_training", {})) + + def _future_latent_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_latent_training", {})) + + def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor: + distribution = str(distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}") + + @staticmethod + def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor: + return shift * time / (1.0 + (shift - 1.0) * time) + + def _latent_frame_count(self, raw_frame_count: int) -> int: + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + return (int(raw_frame_count) - 1) // temporal_factor + 1 + + def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]: + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + condition_counts = [] + sample_counts = [] + + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + if not current_sequence or not future_sequence: + raise ValueError("future image training needs both current image and future_image.") + + future_frame = future_sequence[0] + raw_sequence = current_sequence + [future_frame] * temporal_factor + raw_sequences.append(raw_sequence) + + condition_count = self._latent_frame_count(len(current_sequence)) + sample_count = self._latent_frame_count(len(raw_sequence)) + condition_counts.append(condition_count) + sample_counts.append(sample_count) + + return raw_sequences, condition_counts, sample_counts + + # 训练时 + # future_image支路,self.backbone.transformer() + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + if "future_image" not in examples[0]: + return None + training_cfg = self._future_image_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + noise = torch.randn_like(clean_latents) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + + target_velocity = noise.float() - clean_latents.float() + + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + return future_image_loss + + # 训练时 + # future_latent支路,self.dino_encoder + self.dino_predictor + def _dino_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]: + if "future_image" not in examples[0]: + return None + + # 2. 从examples中取出当前图像和未来图像,并使用DINOv3的ImageNet标准transform做预处理 + # to_pil_preserve可能返回PIL.Image或list[PIL.Image],需要统一取单帧 + batch_current_images = [self._as_sequence(to_pil_preserve(example["image"]))[0] for example in examples] + batch_future_images = [self._as_sequence(to_pil_preserve(example["future_image"]))[0] for example in examples] + + # DINOv3是2D图像编码器,需要分别处理当前图像和未来图像 + current_tensors = torch.stack([ + self._dino_transform(img) for img in batch_current_images + ]).to(self.dino_encoder.patch_embed.proj.weight.device) + + future_tensors = torch.stack([ + self._dino_transform(img) for img in batch_future_images + ]).to(self.dino_encoder.patch_embed.proj.weight.device) + + # 3. DINOv3编码,分别获取当前图像和未来图像的patch tokens + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + current_tokens = self.dino_encoder.forward_features(current_tensors)["x_norm_patchtokens"] + future_tokens = self.dino_encoder.forward_features(future_tensors)["x_norm_patchtokens"] + # current_tokens: [B, 196, 1280], future_tokens: [B, 196, 1280] + + # 4. 从examples中取出current_state + current_state = [example["state"] for example in examples] if "state" in examples[0] else None + current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype)) + current_state = self._align_state_dim(current_state) + + # 5. dino_predictor推理时使用fp32 + with torch.autocast("cuda", dtype=torch.float32): + # 通过projector映射维度 + current_state_emb = self.state_projector(current_state) + target_emb_proj = self.action_projector(target_emb) + + # 6. 调用dino_predictor预测future_tokens + future_tokens_pred = self.dino_predictor.forward_for_WAM_VJEPA2AC( + x=current_tokens, + target_emb=target_emb_proj, + state_emb=current_state_emb, + ) + + # 7. 计算future_latent_loss + future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens) + + return future_latent_loss + + # 训练时 + # 生成future_image、future_latent和action + # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight+future_latent_loss*loss_weight + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + output = {} + future_image_cfg = self._future_image_training_cfg() + future_latent_cfg = self._future_latent_training_cfg() + + # 1. action支路(必定执行) + perceiver_action_loss, target_emb = super().forward(examples=examples, **kwargs) + output["perceiver_action_loss"] = perceiver_action_loss.detach() + total_loss = perceiver_action_loss + + # 2. future_image支路(根据enabled配置决定是否执行) + if self._as_bool(future_image_cfg.get("enabled")): + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is not None: + future_image_loss_weight = float(future_image_cfg.get("loss_weight")) + output["future_image_loss"] = future_image_loss.detach() + total_loss = total_loss + future_image_loss * future_image_loss_weight + + # 3. future_latent支路(根据enabled配置决定是否执行) + if self._as_bool(future_latent_cfg.get("enabled")): + future_latent_loss = self._dino_future_latent_loss(examples, target_emb) + if future_latent_loss is not None: + future_latent_loss_weight = float(future_latent_cfg.get("loss_weight")) + output["future_latent_loss"] = future_latent_loss.detach() + total_loss = total_loss + future_latent_loss * future_latent_loss_weight + + output["action_loss"] = total_loss + + return output + + def _get_future_image_generation_cfg(self, kwargs: dict) -> dict: + cfg = dict(self.config.framework.get("future_image_generation", {})) + override = kwargs.get("future_image_generation", None) + if override: + cfg.update(dict(override)) + + if "decode_future_images" in kwargs: + cfg["enabled"] = kwargs["decode_future_images"] + if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs: + cfg["num_inference_steps"] = kwargs["num_ddim_steps"] + + for key in ( + "enabled", + "num_frames", + "num_inference_steps", + "guidance_scale", + "output_type", + "height", + "width", + "max_sequence_length", + "conditional_frame_timestep", + "num_latent_conditional_frames", + "conditioning_mode", + "max_samples", + "return_full_video", + "future_frame_index", + "negative_prompt", + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ): + if key in kwargs: + cfg[key] = kwargs[key] + return cfg + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + mode = str(cfg.pop("conditioning_mode", "auto")).lower() + height = cfg.pop("height", getattr(self.backbone, "_height", 704)) + width = cfg.pop("width", getattr(self.backbone, "_width", 1280)) + heights = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "prompt": instructions, + "height": heights[0], + "width": heights[1], + "num_frames": cfg.pop("num_frames", 93), + "num_inference_steps": cfg.pop("num_inference_steps", 36), + "guidance_scale": cfg.pop("guidance_scale", 7.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1), + "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2), + } + + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + if mode == "image": + generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images] + elif mode == "video": + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + elif mode == "auto": + if any(len(self._as_sequence(images)) > 1 for images in batch_images): + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + else: + generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images] + else: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + passthrough_keys = ( + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "num_videos_per_prompt", + "callback_on_step_end", + "callback_on_step_end_tensor_inputs", + ) + for key in passthrough_keys: + if key in cfg and cfg[key] is not None: + generation_inputs[key] = cfg.pop(key) + + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() == "auto" + + @staticmethod + def _round_up_to_multiple(value: int, multiple: int) -> int: + return int(((max(1, value) + multiple - 1) // multiple) * multiple) + + @staticmethod + def _image_size(image) -> tuple[int, int]: + size = getattr(image, "size", None) + if isinstance(size, (list, tuple)) and len(size) >= 2: + return int(size[0]), int(size[1]) + if torch.is_tensor(image): + shape = tuple(image.shape) + if len(shape) >= 3 and shape[0] in (1, 3, 4): + return int(shape[-1]), int(shape[-2]) + if len(shape) >= 2: + return int(shape[1]), int(shape[0]) + array = np.asarray(image) + if array.ndim < 2: + raise ValueError(f"Cannot infer image size from shape {array.shape}") + return int(array.shape[1]), int(array.shape[0]) + + def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple: + if not self._is_auto_size(height) and not self._is_auto_size(width): + return int(height), int(width) + + resolved_heights = [] + resolved_widths = [] + spatial_multiple = int(getattr(self.backbone, "vae_scale_factor_spatial", 16)) + for images in batch_images: + image_sequence = self._as_sequence(images) + frame_sizes = [self._image_size(image) for image in image_sequence] + if not frame_sizes: + raise ValueError("Cannot infer auto generation size from empty image sequence.") + + sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height) + if self._is_auto_size(width): + max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes) + sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple) + else: + sample_width = int(width) + resolved_heights.append(int(sample_height)) + resolved_widths.append(int(sample_width)) + + height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0] + width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0] + return height_value, width_value + + @staticmethod + def _extract_videos(generation_output): + if hasattr(generation_output, "frames"): + return generation_output.frames + if hasattr(generation_output, "videos"): + return generation_output.videos + if hasattr(generation_output, "images"): + return generation_output.images + if isinstance(generation_output, tuple): + return generation_output[0] + return generation_output + + def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool): + videos = self._extract_videos(generation_output) + if return_full_video: + return videos + + if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image): + return [videos[future_frame_index]] + + future_images = [] + for sample in videos: + if torch.is_tensor(sample): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, np.ndarray): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, (list, tuple)): + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + return future_images + + @staticmethod + def _slice_generation_value(key: str, value, index: int, batch_size: int): + if value is None: + return None + if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if torch.is_tensor(value) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, np.ndarray) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, list) and len(value) == batch_size: + return [value[index]] + if isinstance(value, tuple) and len(value) == batch_size: + return (value[index],) + return value + + # 推理时 + # future_image支路,self.backbone.generate() + def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool): + if max_samples is None or max_samples < 0: + sample_count = batch_size + else: + sample_count = min(batch_size, max(0, int(max_samples))) + + pred_future_images = [] + for sample_idx in range(sample_count): + single_inputs = { + key: self._slice_generation_value(key, value, sample_idx, batch_size) + for key, value in generation_inputs.items() + } + + generation_output = self.backbone.generate(**single_inputs) + sample_images = self._select_future_images( + generation_output, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + if isinstance(sample_images, (list, tuple)): + pred_future_images.extend(sample_images) + else: + pred_future_images.append(sample_images) + return pred_future_images + + # 推理时 + # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action() + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + # 1. CosmosPredict:构建输入 + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + # 2. CosmosPredict:前向推理 + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + # 3. ActionHead:构建输入 + state = [example["state"] for example in examples] if "state" in examples[0] else None + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + state = self._align_state_dim(state) + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + + # 4. ActionHead:前向推理 + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + return output \ No newline at end of file diff --git a/starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverVJEPA2AC.py b/starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverVJEPA2AC.py new file mode 100644 index 0000000000000000000000000000000000000000..bda8cda53af57f5373974ccca56c820ff2c26022 --- /dev/null +++ b/starVLA/model/framework/WAM_VJEPA/CosmoPredict25PerceiverVJEPA2AC.py @@ -0,0 +1,893 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver with future-image prediction. + +This framework keeps the existing Cosmos hidden-state -> Perceiver action +path, and additionally runs the Cosmos2.5 generation/decoder path during +inference to return the image predicted after the action chunk horizon. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + +from starVLA.model.framework.WAM_VJEPA.CosmoPredict25Perceiver import ( + CosmoPredict25_Perceiver, + CosmoPredict25PerceiverDefaultConfig, +) + + +@dataclass +class CosmoPredict25PerceiverVJEPA2ACDefaultConfig(CosmoPredict25PerceiverDefaultConfig): + """Cosmos-Predict2.5-Perceiver + VJEPA2-AC defaults.""" + + name: str = "CosmoPredict25PerceiverFutureImage" + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 93, + "num_inference_steps": 36, + "guidance_scale": 7.0, + "output_type": "pil", + "height": 704, + "width": 1280, + "max_sequence_length": 512, + "conditional_frame_timestep": 0.1, + "num_latent_conditional_frames": 2, + "conditioning_mode": "auto", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + }) + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverVJEPA2AC") +class CosmoPredict25_Perceiver_VJEPA2AC(CosmoPredict25_Perceiver): + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + # print('################# CosmoPredict25_Perceiver_VJEPA2AC-1') + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverVJEPA2ACDefaultConfig, config) + + # 1. 加载预训练的CosmoPredictr2.5类作为self.backbone + # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py + self.backbone = get_world_model(config=self.config) + # print(type(self.backbone)) # + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + # print(wm_hidden) # 2048 + + # 2. 初始化FlowmatchingActionHead作为self.action_model + # WM4A/starVLA/model/modules/action_model/PerceiverHead.py + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + # print(type(self.action_model)) # + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + # print(self.future_action_window_size) # 15 + # print(self.past_action_window_size) # 0 + # print(self.chunk_len) # 16 + # print(self.state_dim) # 64 + + # 3. 加载vjepa_encoder和vjepa_decoder,并将其权重固定为bf16 + vjepa2_ac_cfg = self.config.framework.get("vjepa2_ac") + vjepa2_ac_repo_dir = vjepa2_ac_cfg.get("repo_dir") + vjepa2_ac_pretrained = vjepa2_ac_cfg.get("pretrained") + # print(vjepa2_ac_repo_dir) # /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/facebookresearch_vjepa2_main + # print(vjepa2_ac_pretrained) # /mnt/workspace/users/maxiangkai/models/VJEPA2-AC/vjepa2-ac-vitg.pt + self.vjepa_encoder, self.vjepa_predictor = torch.hub.load( + vjepa2_ac_repo_dir, + "vjepa2_ac_vit_giant", + source="local", + pretrained=vjepa2_ac_pretrained, + ) + self.vjepa_encoder = self.vjepa_encoder.to(torch.bfloat16).cuda() + self.vjepa_predictor = self.vjepa_predictor.to(torch.bfloat16).cuda() + for p in self.vjepa_encoder.parameters(): + p.requires_grad = False + + # 冻结predictor内部不再使用的encoder——它们在forward_for_WAM_VJEPA2AC中从未被调用, + # 但作为nn.Linear子模块仍被注册为可训练参数,DeepSpeed ZeRO-2会为它们分配 + # fp32 master weight和优化器状态,由于它们永远不参与前向计算,梯度始终为None, + # 在optimizer.step()或fp32 master同步时可能产生异常值,最终污染backbone权重 + for p in self.vjepa_predictor.action_encoder.parameters(): + p.requires_grad = False + for p in self.vjepa_predictor.state_encoder.parameters(): + p.requires_grad = False + for p in self.vjepa_predictor.extrinsics_encoder.parameters(): + p.requires_grad = False + + for name, p in self.vjepa_encoder.named_parameters(): + assert p.dtype == torch.bfloat16, f"vjepa_encoder.{name} dtype={p.dtype}, expected bfloat16" + for name, p in self.vjepa_predictor.named_parameters(): + assert p.dtype == torch.bfloat16, f"vjepa_predictor.{name} dtype={p.dtype}, expected bfloat16" + + # print(type(self.vjepa_encoder)) # + # print(type(self.vjepa_predictor)) # + + # 初始化VJEPA2-AC的图像预处理transform,与官方energy_landscape_example.ipynb保持一致 + from starVLA.facebookresearch_vjepa2_main.app.vjepa_droid.transforms import make_transforms as vjepa2_make_transforms + self._vjepa2_transform = vjepa2_make_transforms( + random_horizontal_flip=False, + random_resize_aspect_ratio=(1., 1.), + random_resize_scale=(1., 1.), + reprob=0., + auto_augment=False, + motion_shift=False, + crop_size=256, + ) + + self.state_projector = torch.nn.Linear( + self.state_dim, + self.vjepa_predictor.predictor_embed.out_features, + bias=True + ).to(torch.bfloat16) + # print(self.state_dim) # 64 + # print(self.vjepa_predictor.predictor_embed.out_features) # 1024 + self.action_projector = torch.nn.Linear( + self.action_model.model.config.output_dim, + self.vjepa_predictor.predictor_embed.out_features, + bias=True + ).to(torch.bfloat16) + # print(self.action_model.model.config.output_dim) # 1024 + # print(self.vjepa_predictor.predictor_embed.out_features) # 1024 + # print('################# CosmoPredict25_Perceiver_FutureImage-2') + + @staticmethod + def _as_sequence(images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor: + if state is None or self.state_dim is None: + return state + target_dim = int(self.state_dim) + current_dim = state.shape[-1] + if current_dim == target_dim: + return state + if current_dim > target_dim: + return state[..., :target_dim] + + pad_shape = (*state.shape[:-1], target_dim - current_dim) + padding = state.new_zeros(pad_shape) + return torch.cat([state, padding], dim=-1) + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _future_image_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_image_training", {})) + + def _future_latent_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_latent_training", {})) + + def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor: + distribution = str(distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}") + + @staticmethod + def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor: + return shift * time / (1.0 + (shift - 1.0) * time) + + def _latent_frame_count(self, raw_frame_count: int) -> int: + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + return (int(raw_frame_count) - 1) // temporal_factor + 1 + + def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]: + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1') + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + condition_counts = [] + sample_counts = [] + # print(temporal_factor) # 4 + # print(len(batch_images)) # 8 + # print(len(future_images)) # 8 + + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + # print(len(current_sequence)) # 1 + # print(len(future_sequence)) # 1 + if not current_sequence or not future_sequence: + raise ValueError("future image training needs both current image and future_image.") + + future_frame = future_sequence[0] + # print(type(future_frame)) # + raw_sequence = current_sequence + [future_frame] * temporal_factor + raw_sequences.append(raw_sequence) + + condition_count = self._latent_frame_count(len(current_sequence)) + sample_count = self._latent_frame_count(len(raw_sequence)) + # print(condition_count) # 1 + # print(sample_count) # 2 + condition_counts.append(condition_count) + sample_counts.append(sample_count) + + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2') + return raw_sequences, condition_counts, sample_counts + + # 训练时 + # future_image支路,self.backbone.transformer() + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1') + if "future_image" not in examples[0]: + return None + training_cfg = self._future_image_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状 + # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt; + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + # print(type(batch_images[0])) # + # print(type(future_images[0])) # + # print(type(instructions[0])) # + + # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs] + # 而raw_sequences也是由8个这样的raw_sequence组成的列表, + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + # print(len(raw_sequences)) # 8 + # print(len(raw_sequences[0])) # 5 + # print(raw_sequences[0][0]) # + # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1] + # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2] + + # 2. 调用CosmosPredict的文本和视觉tokenizer, + # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28), + # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + # print(prompt_embeds.shape) # torch.Size([8, 512, 100352]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(dtype) # torch.bfloat16 + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1]) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪 + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + # print(train_time.shape) # torch.Size([8]) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + # print(flow_time.shape) # torch.Size([8]) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + noise = torch.randn_like(clean_latents) + # print(noise.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity + target_velocity = noise.float() - clean_latents.float() + # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 5. 计算timestep和padding_mask + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + # print(cond_timestep) # 0.1 + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + # print(padding_height) # 224 + # print(padding_width) # 224 + # print(padding_mask.shape) # torch.Size([1, 1, 224, 224]) + + # 7. CosmosPredict前向传播 + # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入, + # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中, + # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息, + # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分, + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + # print(type(self.backbone)) # + # print(pred.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 8. 计算future-image-loss + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width) + # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28]) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28]) + future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=) + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2') + return future_image_loss + + # 训练时 + # future_latent支路,self.vjepa_encoder + self.vjepa_predictor + def _vjepa2ac_future_latent_loss(self, examples: List[dict], target_emb: torch.Tensor) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-1') + if "future_image" not in examples[0]: + return None + + # 2. 从examples中取出当前图像和未来图像,并使用VJEPA2-AC官方的transform对图像做预处理 + batch_current_images = [to_pil_preserve(example["image"]) for example in examples] + batch_future_images = [to_pil_preserve(example["future_image"]) for example in examples] + # print(len(examples)) # 8 + clips_list = [] + for current_images, future_images in zip(batch_current_images, batch_future_images): + current_seq = self._as_sequence(current_images) + future_seq = self._as_sequence(future_images) + # print(len(current_seq)) # 1 + # print(len(future_seq)) # 1 + current_np = np.array(current_seq[0]) + future_np = np.array(future_seq[0]) + # print(current_np.shape) # (224, 224, 3) + # print(future_np.shape) # (224, 224, 3) + clip_np = np.stack([current_np, future_np], axis=0) + # print(clip_np.shape) # (2, 224, 224, 3) + clip_tensor = self._vjepa2_transform(clip_np) + # print(clip_tensor.shape) # torch.Size([3, 2, 256, 256]) + clips_list.append(clip_tensor) + clips = torch.stack(clips_list, dim=0).to(self.vjepa_encoder.patch_embed.proj.weight.device) + # print(clips.shape) # torch.Size([8, 3, 2, 256, 256]) + B, C, T, H, W = clips.size() + # print(clips.shape) # torch.Size([8, 3, 2, 256, 256]) + c = clips.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1).to(torch.bfloat16) + # print(c.shape) # torch.Size([16, 3, 2, 256, 256]) + + # 3. self.vjepa_encoder推理时使用b16 + # 这是仿照self._cosmos25_future_image_loss中,当self.backbone作为编码器前向推理时使用bf16 + crop_size = 256 + tokens_per_frame = int((crop_size // self.vjepa_encoder.patch_size) ** 2) + # 仿照原始代码对self.backbone的处理,用bf16 autocast包裹vjepa_encoder + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + # print(type(self.vjepa_encoder)) # + h = self.vjepa_encoder(c) + # print(h.shape) # torch.Size([16, 256, 1408]) + h = h.view(B, T, -1, h.size(-1)).flatten(1, 2) + # print(h.shape) # torch.Size([8, 512, 1408]) + h = F.layer_norm(h, (h.size(-1),)) + # print(h.shape) # torch.Size([8, 512, 1408]) + + # 4. 从h中分离出current_tokens和future_tokens + current_tokens = h[:, :tokens_per_frame] + future_tokens = h[:, tokens_per_frame:] + # print(current_tokens.shape) # torch.Size([8, 256, 1408]) + # print(future_tokens.shape) # torch.Size([8, 256, 1408]) + + # 5. 从examples中取出current_state,参考predict_action()中的实现 + current_state = [example["state"] for example in examples] if "state" in examples[0] else None + # print(len(current_state)) # 8 + # print(current_state[0].shape) # (1, 64) + current_state = (torch.from_numpy(np.array(current_state)).to(current_tokens.device, dtype=current_tokens.dtype)) + # print(current_state.shape) # torch.Size([8, 1, 64]) + current_state = self._align_state_dim(current_state) + # print(current_state.shape) # torch.Size([8, 1, 64]) + + # 6. self.vjepa_predictor推理时使用fp32 + # 这是仿照CosmoPredict2Perceiver.forward()中,当self.action_model生成action前向推理时使用fp32 + with torch.autocast("cuda", dtype=torch.float32): + # 通过projector映射维度 + # print(current_state.shape) # torch.Size([8, 1, 64]) + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + current_state_emb = self.state_projector(current_state) + target_emb_proj = self.action_projector(target_emb) + # print(current_state_emb.shape) # torch.Size([8, 1, 1024]) + # print(target_emb_proj.shape) # torch.Size([8, 64, 1024]) + + # 7. 调用self.vjepa_predictor预测future_tokens + future_tokens_pred = self.vjepa_predictor.forward_for_WAM_VJEPA2AC( + x=current_tokens, + target_emb=target_emb_proj, + state_emb=current_state_emb, + ) + # print(type(self.vjepa_predictor)) # + # print(current_tokens.shape) # torch.Size([8, 256, 1408]) + # print(target_emb_proj.shape) # torch.Size([8, 64, 1024]) + # print(current_state_emb.shape) # torch.Size([8, 1, 1024]) + # print(future_tokens_pred.shape) # torch.Size([8, 256, 1408]) + + # 8. 计算future_latent_loss + future_latent_loss = F.smooth_l1_loss(future_tokens_pred, future_tokens) + # print(future_latent_loss) # tensor(0.3229, device='cuda:0', grad_fn=) + + # print('################# CosmoPredict25_Perceiver_FutureImage._vjepa2ac_future_latent_loss-2') + return future_latent_loss + + # 训练时 + # 生成future_image、future_latent和action + # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight+future_latent_loss*loss_weight + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1') + output = {} + future_image_cfg = self._future_image_training_cfg() + future_latent_cfg = self._future_latent_training_cfg() + + # 1. action支路(必定执行) + perceiver_action_loss, target_emb = super().forward(examples=examples, **kwargs) + output["perceiver_action_loss"] = perceiver_action_loss.detach() + total_loss = perceiver_action_loss + # 仿照原始代码对action_model输出target_emb的处理,不强制转换精度 + # target_emb在float32 autocast内产生,后续_vjepa2ac_future_latent_loss也在float32 autocast内使用 + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + + # 2. future_image支路(根据enabled配置决定是否执行) + # print(future_image_cfg.get("enabled")) # False + # print(future_image_cfg.get("loss_weight")) # 1.0 + if self._as_bool(future_image_cfg.get("enabled")): + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is not None: + future_image_loss_weight = float(future_image_cfg.get("loss_weight")) + output["future_image_loss"] = future_image_loss.detach() + total_loss = total_loss + future_image_loss * future_image_loss_weight + + # 3. future_latent支路(根据enabled配置决定是否执行) + # print(future_latent_cfg.get("enabled")) # True + # print(future_latent_cfg.get("loss_weight")) # 1.0 + if self._as_bool(future_latent_cfg.get("enabled")): + future_latent_loss = self._vjepa2ac_future_latent_loss(examples, target_emb) + if future_latent_loss is not None: + future_latent_loss_weight = float(future_latent_cfg.get("loss_weight")) + output["future_latent_loss"] = future_latent_loss.detach() + total_loss = total_loss + future_latent_loss * future_latent_loss_weight + + output["action_loss"] = total_loss + + # print(output) + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2') + return output + + def _get_future_image_generation_cfg(self, kwargs: dict) -> dict: + cfg = dict(self.config.framework.get("future_image_generation", {})) + override = kwargs.get("future_image_generation", None) + if override: + cfg.update(dict(override)) + + if "decode_future_images" in kwargs: + cfg["enabled"] = kwargs["decode_future_images"] + if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs: + cfg["num_inference_steps"] = kwargs["num_ddim_steps"] + + for key in ( + "enabled", + "num_frames", + "num_inference_steps", + "guidance_scale", + "output_type", + "height", + "width", + "max_sequence_length", + "conditional_frame_timestep", + "num_latent_conditional_frames", + "conditioning_mode", + "max_samples", + "return_full_video", + "future_frame_index", + "negative_prompt", + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ): + if key in kwargs: + cfg[key] = kwargs[key] + return cfg + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + mode = str(cfg.pop("conditioning_mode", "auto")).lower() + height = cfg.pop("height", getattr(self.backbone, "_height", 704)) + width = cfg.pop("width", getattr(self.backbone, "_width", 1280)) + heights = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "prompt": instructions, + "height": heights[0], + "width": heights[1], + "num_frames": cfg.pop("num_frames", 93), + "num_inference_steps": cfg.pop("num_inference_steps", 36), + "guidance_scale": cfg.pop("guidance_scale", 7.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1), + "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2), + } + + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + if mode == "image": + generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images] + elif mode == "video": + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + elif mode == "auto": + if any(len(self._as_sequence(images)) > 1 for images in batch_images): + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + else: + generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images] + else: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + passthrough_keys = ( + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "num_videos_per_prompt", + "callback_on_step_end", + "callback_on_step_end_tensor_inputs", + ) + for key in passthrough_keys: + if key in cfg and cfg[key] is not None: + generation_inputs[key] = cfg.pop(key) + + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() == "auto" + + @staticmethod + def _round_up_to_multiple(value: int, multiple: int) -> int: + return int(((max(1, value) + multiple - 1) // multiple) * multiple) + + @staticmethod + def _image_size(image) -> tuple[int, int]: + size = getattr(image, "size", None) + if isinstance(size, (list, tuple)) and len(size) >= 2: + return int(size[0]), int(size[1]) + if torch.is_tensor(image): + shape = tuple(image.shape) + if len(shape) >= 3 and shape[0] in (1, 3, 4): + return int(shape[-1]), int(shape[-2]) + if len(shape) >= 2: + return int(shape[1]), int(shape[0]) + array = np.asarray(image) + if array.ndim < 2: + raise ValueError(f"Cannot infer image size from shape {array.shape}") + return int(array.shape[1]), int(array.shape[0]) + + def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple: + if not self._is_auto_size(height) and not self._is_auto_size(width): + return int(height), int(width) + + resolved_heights = [] + resolved_widths = [] + spatial_multiple = int(getattr(self.backbone, "vae_scale_factor_spatial", 16)) + for images in batch_images: + image_sequence = self._as_sequence(images) + frame_sizes = [self._image_size(image) for image in image_sequence] + if not frame_sizes: + raise ValueError("Cannot infer auto generation size from empty image sequence.") + + sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height) + if self._is_auto_size(width): + max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes) + sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple) + else: + sample_width = int(width) + resolved_heights.append(int(sample_height)) + resolved_widths.append(int(sample_width)) + + height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0] + width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0] + return height_value, width_value + + @staticmethod + def _extract_videos(generation_output): + if hasattr(generation_output, "frames"): + return generation_output.frames + if hasattr(generation_output, "videos"): + return generation_output.videos + if hasattr(generation_output, "images"): + return generation_output.images + if isinstance(generation_output, tuple): + return generation_output[0] + return generation_output + + def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool): + videos = self._extract_videos(generation_output) + if return_full_video: + return videos + + if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image): + return [videos[future_frame_index]] + + future_images = [] + for sample in videos: + if torch.is_tensor(sample): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, np.ndarray): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, (list, tuple)): + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + return future_images + + @staticmethod + def _slice_generation_value(key: str, value, index: int, batch_size: int): + if value is None: + return None + if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if torch.is_tensor(value) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, np.ndarray) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, list) and len(value) == batch_size: + return [value[index]] + if isinstance(value, tuple) and len(value) == batch_size: + return (value[index],) + return value + + # 推理时 + # future_image支路,self.backbone.generate() + def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool): + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1') + if max_samples is None or max_samples < 0: + sample_count = batch_size + else: + sample_count = min(batch_size, max(0, int(max_samples))) + # print(sample_count) # 1 + + # print(generation_inputs) + """ + { + 'prompt': [ + 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.', + 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.', + 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.', + 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.' + ], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': [ + , + , + , + , + , + , + , + + ] + } + """ + pred_future_images = [] + for sample_idx in range(sample_count): + + # 1. CosmosPredict:构建输入 + # print(sample_idx) # 0 + single_inputs = { + key: self._slice_generation_value(key, value, sample_idx, batch_size) + for key, value in generation_inputs.items() + } + # print(single_inputs) + """ + { + 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': + } + """ + + # 2. CosmosPredict:前向推理 + generation_output = self.backbone.generate(**single_inputs) + # print(type(self.backbone)) # + # print(type(generation_output)) # + # print(future_frame_index) # -1 + # print(return_full_video) # False + sample_images = self._select_future_images( + generation_output, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # print(sample_images) # [] + if isinstance(sample_images, (list, tuple)): + pred_future_images.extend(sample_images) + else: + pred_future_images.append(sample_images) + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2') + return pred_future_images + + # 推理时 + # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action() + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1') + if type(examples) is not list: + examples = [examples] + + # 1. CosmosPredict:构建输入 + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + state = [example["state"] for example in examples] if "state" in examples[0] else None + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + # print(state.shape) # torch.Size([8, 1, 64]) + state = self._align_state_dim(state) + # print(state.shape) # torch.Size([8, 1, 64]) + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + # print(embodiment_tag.shape) # torch.Size([8]) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + + # 4. ActionHead:前向推理 + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + # print(type(self.action_model)) # + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + # print(state.shape) # torch.Size([8, 1, 64]) + # print(embodiment_tag.shape) # torch.Size([8]) + # print(pred_actions.shape) # torch.Size([8, 16, 32]) + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要 + generation_cfg = self._get_future_image_generation_cfg(kwargs) + is_enabled = generation_cfg.pop("enabled", True) + # print(is_enabled) # True + if not bool(is_enabled): + # print('is_enabled is False') + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output + + return_full_video = bool(generation_cfg.pop("return_full_video", False)) + future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + max_samples = int(generation_cfg.pop("max_samples", 1)) + generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + output["pred_future_images"] = self._generate_future_images( + generation_inputs, + batch_size=len(examples), + max_samples=max_samples, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output diff --git a/starVLA/model/framework/WAM_VJEPA/CosmoPredict2Perceiver.py b/starVLA/model/framework/WAM_VJEPA/CosmoPredict2Perceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..6cc14655f043d3863b50afa658b32de016142f49 --- /dev/null +++ b/starVLA/model/framework/WAM_VJEPA/CosmoPredict2Perceiver.py @@ -0,0 +1,258 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +CosmoPredict2-Perceiver Framework. + +Uses Cosmos-Predict2 as the world-model backbone and the Perceiver-style +flow-matching action head for continuous action prediction. +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.training.trainer_utils.trainer_tools import resize_images + +logger = initialize_overwatch(__name__) + + +@dataclass +class CosmoPredict2PerceiverDefaultConfig: + """CosmoPredict2-Perceiver default parameters.""" + + name: str = "CosmoPredict2Perceiver" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + # Kept for compatibility with shared utilities and action-head configs. + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "max_num_embodiments": 32, + "use_category_specific": False, + "diffusion_model_cfg": { + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2Perceiver") +class CosmoPredict2_Perceiver(baseframework): + """World-model-for-action framework using Cosmos-Predict2 + Perceiver head.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2PerceiverDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # 训练时 + # action支路,self.backbone.build_inputs、self.backbone.forward()、self.action_model.forward() + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + # print('################# CosmoPredict2_Perceiver.forward-1') + + # 1. CosmosPredict:构建输入 + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + with torch.autocast("cuda", dtype=torch.float32): + + # 3.1 初始化action + actions = [example["action"] for example in examples] + actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype) + # print(actions.shape) # torch.Size([8, 16, 32]) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + # print(self.future_action_window_size) # 15 + # print(actions_target.shape) # torch.Size([8, 16, 32]) + + # 3.2 重复降噪 + # 将action和vl-tokens复制多次,重复多次降噪 + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "trainer") + else self.config.framework.action_model.get("repeated_diffusion_steps", 4) + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + # print(actions_target_repeated.shape) # torch.Size([32, 16, 32]) + # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048]) + + # 3.3 准备state、action_mask和embodiment_tag + state = [example["state"] for example in examples] if "state" in examples[0] else None + if state is not None: + # print('state is not None') + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + # print(state.shape) # torch.Size([8, 1, 64]) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + # print(state_repeated.shape) # torch.Size([32, 1, 64]) + else: + state_repeated = None + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + if action_mask is not None: + # print('action_mask is not None') + action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype) + # print(action_mask_tensor.shape) # torch.Size([8, 16, 32]) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :] + # print(action_mask_target.shape) # torch.Size([8, 16, 32]) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + # print(action_mask_repeated.shape) # torch.Size([32, 16, 32]) + else: + action_mask_repeated = None + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + if embodiment_tag is not None: + # print('embodiment_tag is not None') + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64) + # print(embodiment_tag.shape) # torch.Size([8]) + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) + # print(embodiment_tag_repeated.shape) # torch.Size([32]) + else: + embodiment_tag_repeated = None + + action_loss, target_emb = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + use_vjepa2ac=True, + repeated_diffusion_steps=repeated_diffusion_steps, + ) + # print(type(self.action_model)) # + # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048]) + # print(actions_target_repeated.shape) # torch.Size([32, 16, 32]) + # print(state_repeated.shape) # torch.Size([32, 1, 64]) + # print(embodiment_tag_repeated.shape) # torch.Size([32]) + # print(action_mask_repeated.shape) # torch.Size([32, 16, 32]) + # print(action_loss) # tensor(1.5625, device='cuda:0', grad_fn=) + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + + # print('################# CosmoPredict2_Perceiver.forward-2') + return action_loss, target_emb + + # @torch.inference_mode() + # def predict_action(self, examples: List[dict], **kwargs) -> dict: + # if type(examples) is not list: + # examples = [examples] + + # batch_images = [to_pil_preserve(example["image"]) for example in examples] + # instructions = [example["lang"] for example in examples] + # state = [example["state"] for example in examples] if "state" in examples[0] else None + # embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + + # train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # if train_obs_image_size: + # batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # with torch.autocast("cuda", dtype=torch.bfloat16): + # wm_outputs = self.backbone( + # **wm_inputs, + # output_hidden_states=True, + # return_dict=True, + # ) + # last_hidden = wm_outputs.hidden_states[-1] + + # state = ( + # torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + # if state is not None + # else None + # ) + # embodiment_tag = ( + # torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + # if embodiment_tag is not None + # else None + # ) + # if embodiment_tag is not None: + # embodiment_tag = embodiment_tag.view(-1) + + # with torch.autocast("cuda", dtype=torch.float32): + # pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + + # normalized_actions = pred_actions.detach().cpu().numpy() + # return {"normalized_actions": normalized_actions} diff --git a/starVLA/model/framework/WAM_VJEPA/__init__.py b/starVLA/model/framework/WAM_VJEPA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/starVLA/model/framework/WAM_VJEPA/__init__.py @@ -0,0 +1 @@ + diff --git a/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25Perceiver-checkpoint.py b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25Perceiver-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8824c91271a4fceef4f399952af196ada96bb0 --- /dev/null +++ b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25Perceiver-checkpoint.py @@ -0,0 +1,91 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver Framework. + +This keeps Predict2.5 separate from the existing Cosmos-Predict2 framework +while reusing the same Perceiver action-head training/inference logic. +""" + +from dataclasses import dataclass, field +from typing import Optional + +from starVLA.model.framework.WM4A.CosmoPredict2Perceiver import CosmoPredict2_Perceiver +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY + + +@dataclass +class CosmoPredict25PerceiverDefaultConfig: + """Cosmos-Predict2.5-Perceiver default parameters.""" + + name: str = "CosmoPredict25Perceiver" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "nvidia/Cosmos-Predict2.5-2B", + "revision": "diffusers/base/post-trained", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "nvidia/Cosmos-Predict2.5-2B", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "max_num_embodiments": 32, + "use_category_specific": False, + "diffusion_model_cfg": { + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25Perceiver") +class CosmoPredict25_Perceiver(CosmoPredict2_Perceiver): + """World-model-for-action framework using Cosmos-Predict2.5 + Perceiver.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size diff --git a/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverFutureImage-checkpoint.py b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverFutureImage-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..449228c6487adf755c6cc968d6ba75294d09e8e1 --- /dev/null +++ b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverFutureImage-checkpoint.py @@ -0,0 +1,727 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver with future-image prediction. + +This framework keeps the existing Cosmos hidden-state -> Perceiver action +path, and additionally runs the Cosmos2.5 generation/decoder path during +inference to return the image predicted after the action chunk horizon. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25Perceiver import ( + CosmoPredict25_Perceiver, + CosmoPredict25PerceiverDefaultConfig, +) +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict25PerceiverFutureImageDefaultConfig(CosmoPredict25PerceiverDefaultConfig): + """Cosmos-Predict2.5-Perceiver + future-image defaults.""" + + name: str = "CosmoPredict25PerceiverFutureImage" + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 93, + "num_inference_steps": 36, + "guidance_scale": 7.0, + "output_type": "pil", + "height": 704, + "width": 1280, + "max_sequence_length": 512, + "conditional_frame_timestep": 0.1, + "num_latent_conditional_frames": 2, + "conditioning_mode": "auto", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + }) + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverFutureImage") +class CosmoPredict25_Perceiver_FutureImage(CosmoPredict25_Perceiver): + """Cosmos-Predict2.5 hidden-state action head plus generated future images.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + print('################# CosmoPredict25_Perceiver_FutureImage-1') + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverFutureImageDefaultConfig, config) + + # 1. 初始化CosmosPredictr2.5类作为backbone + # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py + self.backbone = get_world_model(config=self.config) + # print(type(self.backbone)) # + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + # print(wm_hidden) # 2048 + + # 2. 初始化FlowmatchingActionHead作为action-head + # WM4A/starVLA/model/modules/action_model/PerceiverHead.py + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + # print(type(self.action_model)) # + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + # print(self.future_action_window_size) # 15 + # print(self.past_action_window_size) # 0 + # print(self.chunk_len) # 16 + # print(self.state_dim) # 64 + print('################# CosmoPredict25_Perceiver_FutureImage-2') + + @staticmethod + def _as_sequence(images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor: + if state is None or self.state_dim is None: + return state + target_dim = int(self.state_dim) + current_dim = state.shape[-1] + if current_dim == target_dim: + return state + if current_dim > target_dim: + return state[..., :target_dim] + + pad_shape = (*state.shape[:-1], target_dim - current_dim) + padding = state.new_zeros(pad_shape) + return torch.cat([state, padding], dim=-1) + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _future_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_image_training", {})) + + def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor: + distribution = str(distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}") + + @staticmethod + def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor: + return shift * time / (1.0 + (shift - 1.0) * time) + + def _latent_frame_count(self, raw_frame_count: int) -> int: + if hasattr(self, 'backbone'): + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + else: + temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4)) + return (int(raw_frame_count) - 1) // temporal_factor + 1 + + def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]: + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1') + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + condition_counts = [] + sample_counts = [] + # print(temporal_factor) # 4 + # print(len(batch_images)) # 8 + # print(len(future_images)) # 8 + + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + # print(len(current_sequence)) # 1 + # print(len(future_sequence)) # 1 + if not current_sequence or not future_sequence: + raise ValueError("future image training needs both current image and future_image.") + + future_frame = future_sequence[0] + # print(type(future_frame)) # + raw_sequence = current_sequence + [future_frame] * temporal_factor + raw_sequences.append(raw_sequence) + + condition_count = self._latent_frame_count(len(current_sequence)) + sample_count = self._latent_frame_count(len(raw_sequence)) + # print(condition_count) # 1 + # print(sample_count) # 2 + condition_counts.append(condition_count) + sample_counts.append(sample_count) + + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2') + return raw_sequences, condition_counts, sample_counts + + # 训练时 + # future_image支路,self.backbone.transformer() + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1') + if "future_image" not in examples[0]: + return None + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状 + # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt; + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + # print(type(batch_images[0])) # + # print(type(future_images[0])) # + # print(type(instructions[0])) # + + # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs] + # 而raw_sequences也是由8个这样的raw_sequence组成的列表, + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + # print(len(raw_sequences)) # 8 + # print(len(raw_sequences[0])) # 5 + # print(raw_sequences[0][0]) # + # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1] + # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2] + + # 2. 调用CosmosPredict的文本和视觉tokenizer, + # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28), + # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + # print(prompt_embeds.shape) # torch.Size([8, 512, 100352]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(dtype) # torch.bfloat16 + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1]) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪 + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + # print(train_time.shape) # torch.Size([8]) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + # print(flow_time.shape) # torch.Size([8]) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + noise = torch.randn_like(clean_latents) + # print(noise.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity + target_velocity = noise.float() - clean_latents.float() + # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 5. 计算timestep和padding_mask + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + # print(cond_timestep) # 0.1 + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + # print(padding_height) # 224 + # print(padding_width) # 224 + # print(padding_mask.shape) # torch.Size([1, 1, 224, 224]) + + # 7. CosmosPredict前向传播 + # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入, + # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中, + # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息, + # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分, + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + # print(type(self.backbone)) # + # print(pred.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 8. 计算future-image-loss + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width) + # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28]) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28]) + future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=) + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2') + return future_image_loss + + # 训练时 + # 生成future_image和action + # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1') + # 1. 调用CosmosPredict+ActionHead生成action_loss,这个函数定义在父类中 + output = super().forward(examples=examples, **kwargs) + action_loss = output["action_loss"] + + # 2. 调用CosmosPredict生成future_image_loss + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is None: + return output + + # 3. 最终返回的是total_loss=action_loss+future_image_loss*loss_weight + loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0)) + # print(loss_weight) # 1.0 + output["perceiver_action_loss"] = action_loss.detach() + output["future_image_loss"] = future_image_loss.detach() + output["action_loss"] = action_loss + future_image_loss * loss_weight + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2') + return output + + def _get_future_image_generation_cfg(self, kwargs: dict) -> dict: + cfg = dict(self.config.framework.get("future_image_generation", {})) + override = kwargs.get("future_image_generation", None) + if override: + cfg.update(dict(override)) + + if "decode_future_images" in kwargs: + cfg["enabled"] = kwargs["decode_future_images"] + if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs: + cfg["num_inference_steps"] = kwargs["num_ddim_steps"] + + for key in ( + "enabled", + "num_frames", + "num_inference_steps", + "guidance_scale", + "output_type", + "height", + "width", + "max_sequence_length", + "conditional_frame_timestep", + "num_latent_conditional_frames", + "conditioning_mode", + "max_samples", + "return_full_video", + "future_frame_index", + "negative_prompt", + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ): + if key in kwargs: + cfg[key] = kwargs[key] + return cfg + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + mode = str(cfg.pop("conditioning_mode", "auto")).lower() + _wm = self.backbone if hasattr(self, "backbone") else self.wan_interface + height = cfg.pop("height", getattr(_wm, "_height", 704)) + width = cfg.pop("width", getattr(_wm, "_width", 1280)) + heights = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "prompt": instructions, + "height": heights[0], + "width": heights[1], + "num_frames": cfg.pop("num_frames", 93), + "num_inference_steps": cfg.pop("num_inference_steps", 36), + "guidance_scale": cfg.pop("guidance_scale", 7.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1), + "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2), + } + + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + if mode == "image": + generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images] + elif mode == "video": + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + elif mode == "auto": + if any(len(self._as_sequence(images)) > 1 for images in batch_images): + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + else: + generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images] + else: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + passthrough_keys = ( + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "num_videos_per_prompt", + "callback_on_step_end", + "callback_on_step_end_tensor_inputs", + ) + for key in passthrough_keys: + if key in cfg and cfg[key] is not None: + generation_inputs[key] = cfg.pop(key) + + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() == "auto" + + @staticmethod + def _round_up_to_multiple(value: int, multiple: int) -> int: + return int(((max(1, value) + multiple - 1) // multiple) * multiple) + + @staticmethod + def _image_size(image) -> tuple[int, int]: + size = getattr(image, "size", None) + if isinstance(size, (list, tuple)) and len(size) >= 2: + return int(size[0]), int(size[1]) + if torch.is_tensor(image): + shape = tuple(image.shape) + if len(shape) >= 3 and shape[0] in (1, 3, 4): + return int(shape[-1]), int(shape[-2]) + if len(shape) >= 2: + return int(shape[1]), int(shape[0]) + array = np.asarray(image) + if array.ndim < 2: + raise ValueError(f"Cannot infer image size from shape {array.shape}") + return int(array.shape[1]), int(array.shape[0]) + + def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple: + if not self._is_auto_size(height) and not self._is_auto_size(width): + return int(height), int(width) + + resolved_heights = [] + resolved_widths = [] + _wm = self.backbone if hasattr(self, "backbone") else self.wan_interface + spatial_multiple = int(getattr(_wm, "vae_scale_factor_spatial", 16)) + for images in batch_images: + image_sequence = self._as_sequence(images) + frame_sizes = [self._image_size(image) for image in image_sequence] + if not frame_sizes: + raise ValueError("Cannot infer auto generation size from empty image sequence.") + + sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height) + if self._is_auto_size(width): + max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes) + sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple) + else: + sample_width = int(width) + resolved_heights.append(int(sample_height)) + resolved_widths.append(int(sample_width)) + + height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0] + width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0] + return height_value, width_value + + @staticmethod + def _extract_videos(generation_output): + if hasattr(generation_output, "frames"): + return generation_output.frames + if hasattr(generation_output, "videos"): + return generation_output.videos + if hasattr(generation_output, "images"): + return generation_output.images + if isinstance(generation_output, tuple): + return generation_output[0] + return generation_output + + def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool): + videos = self._extract_videos(generation_output) + if return_full_video: + return videos + + if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image): + return [videos[future_frame_index]] + + future_images = [] + for sample in videos: + if torch.is_tensor(sample): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, np.ndarray): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, (list, tuple)): + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + return future_images + + @staticmethod + def _slice_generation_value(key: str, value, index: int, batch_size: int): + if value is None: + return None + if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if torch.is_tensor(value) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, np.ndarray) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, list) and len(value) == batch_size: + return [value[index]] + if isinstance(value, tuple) and len(value) == batch_size: + return (value[index],) + return value + + # 推理时 + # future_image支路,self.backbone.generate() + def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool): + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1') + if max_samples is None or max_samples < 0: + sample_count = batch_size + else: + sample_count = min(batch_size, max(0, int(max_samples))) + # print(sample_count) # 1 + + # print(generation_inputs) + """ + { + 'prompt': [ + 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.', + 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.', + 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.', + 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.' + ], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': [ + , + , + , + , + , + , + , + + ] + } + """ + pred_future_images = [] + for sample_idx in range(sample_count): + + # 1. CosmosPredict:构建输入 + # print(sample_idx) # 0 + single_inputs = { + key: self._slice_generation_value(key, value, sample_idx, batch_size) + for key, value in generation_inputs.items() + } + # print(single_inputs) + """ + { + 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': + } + """ + + # 2. CosmosPredict:前向推理 + generation_output = self.backbone.generate(**single_inputs) if hasattr(self, "backbone") else self.wan_interface.generate(**single_inputs) + # print(type(self.backbone)) # + # print(type(generation_output)) # + # print(future_frame_index) # -1 + # print(return_full_video) # False + sample_images = self._select_future_images( + generation_output, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # print(sample_images) # [] + if isinstance(sample_images, (list, tuple)): + pred_future_images.extend(sample_images) + else: + pred_future_images.append(sample_images) + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2') + return pred_future_images + + # 推理时 + # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action() + @torch.inference_mode() + def predict_action(self, examples: List[dict], is_run_parallel_eval_mxk: bool = False, **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1') + if type(examples) is not list: + examples = [examples] + + # 1. CosmosPredict:构建输入 + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + state = [example["state"] for example in examples] if "state" in examples[0] else None + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + # print(state.shape) # torch.Size([8, 1, 64]) + state = self._align_state_dim(state) + # print(state.shape) # torch.Size([8, 1, 64]) + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + # print(embodiment_tag.shape) # torch.Size([8]) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + + # 4. ActionHead:前向推理 + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + # print(type(self.action_model)) # + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + # print(state.shape) # torch.Size([8, 1, 64]) + # print(embodiment_tag.shape) # torch.Size([8]) + # print(pred_actions.shape) # torch.Size([8, 16, 32]) + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要 + generation_cfg = self._get_future_image_generation_cfg(kwargs) + is_enabled = generation_cfg.pop("enabled", True) + # print(is_enabled) # True + if not bool(is_enabled): + # print('is_enabled is False') + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output + + return_full_video = bool(generation_cfg.pop("return_full_video", False)) + future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + max_samples = int(generation_cfg.pop("max_samples", 1)) + generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + output["pred_future_images"] = self._generate_future_images( + generation_inputs, + batch_size=len(examples), + max_samples=max_samples, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # When called from websocket server, convert PIL Images to numpy arrays + # for msgpack serialization; otherwise keep PIL Image format + if is_run_parallel_eval_mxk and "pred_future_images" in output: + output["pred_future_images"] = [ + np.array(img) if isinstance(img, Image.Image) else img + for img in output["pred_future_images"] + ] + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output diff --git a/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverMaskedFutureImage-checkpoint.py b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverMaskedFutureImage-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..fc125d5b196b82e0e9ec42e8587ce1461a794d98 --- /dev/null +++ b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PerceiverMaskedFutureImage-checkpoint.py @@ -0,0 +1,196 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""Cosmos-Predict2.5 Perceiver with masked future-image denoising. + +This variant keeps the existing action path and Cosmos future-image objective, +but builds a latent-grid change mask from the current/future RGB pair. The mask +can focus the loss on changed regions and optionally add noise only inside those +regions, turning future-image training into an inpainting-style objective. +""" + +from __future__ import annotations + +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import ( + CosmoPredict25_Perceiver_FutureImage, +) +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverMaskedFutureImage") +class CosmoPredict25_Perceiver_MaskedFutureImage(CosmoPredict25_Perceiver_FutureImage): + """Future-image training that denoises mostly/only changed regions.""" + + @staticmethod + def _pil_rgb_to_tensor(image, size: tuple[int, int] | None = None) -> torch.Tensor: + image = to_pil_preserve(image).convert("RGB") + if size is not None and image.size != size: + image = image.resize(size) + array = np.asarray(image, dtype=np.float32) / 255.0 + return torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0) + + def _build_latent_change_masks( + self, + batch_images: List, + future_images: List, + latent_height: int, + latent_width: int, + training_cfg: dict, + device: torch.device, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Return binary denoise mask and soft loss weights at latent resolution.""" + top_ratio = float(training_cfg.get("change_mask_top_ratio", 0.25)) + top_ratio = min(max(top_ratio, 1e-4), 1.0) + static_weight = float(training_cfg.get("change_mask_static_weight", 0.05)) + static_weight = min(max(static_weight, 0.0), 1.0) + soft_loss = self._as_bool(training_cfg.get("change_mask_soft_loss", True)) + + binary_masks = [] + loss_weights = [] + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + current_frame = current_sequence[-1] + target_frame = future_sequence[0] + + current = self._pil_rgb_to_tensor(current_frame) + target = self._pil_rgb_to_tensor(target_frame, size=to_pil_preserve(current_frame).size) + diff = (target - current).abs().mean(dim=1, keepdim=True) + score = F.interpolate(diff, size=(latent_height, latent_width), mode="area") + flat = score.flatten(1) + max_score = flat.amax(dim=1).view(-1, 1, 1, 1).clamp_min(1e-6) + normalized = (score / max_score).clamp(0.0, 1.0) + + k = max(1, int(flat.shape[1] * top_ratio)) + threshold = flat.topk(k, dim=1).values[:, -1].view(-1, 1, 1, 1) + binary = (score >= threshold).float() + + weight_source = normalized if soft_loss else binary + loss_weight = static_weight + (1.0 - static_weight) * weight_source + binary_masks.append(binary) + loss_weights.append(loss_weight) + + binary_mask = torch.cat(binary_masks, dim=0).to(device=device, dtype=torch.float32) + loss_weight = torch.cat(loss_weights, dim=0).to(device=device, dtype=torch.float32) + return binary_mask, loss_weight + + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + if "future_image" not in examples[0]: + return None + + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + if not self._as_bool(training_cfg.get("change_mask_enabled", True)): + return super()._cosmos25_future_image_loss(examples) + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + change_binary, change_loss_weight = self._build_latent_change_masks( + batch_images=batch_images, + future_images=future_images, + latent_height=height, + latent_width=width, + training_cfg=training_cfg, + device=device, + ) + change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype) + change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32) + + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + + noise = torch.randn_like(clean_latents) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width) + + use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", True)) + use_static_conditioning = use_masked_denoising and self._as_bool( + training_cfg.get("condition_static_regions", True) + ) + + if use_masked_denoising: + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) * change_binary + else: + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) + hidden_states = torch.where(denoise_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + target_velocity = noise.float() - clean_latents.float() + + if use_static_conditioning: + static_target_mask = target_spatial_mask.to(dtype=clean_latents.dtype) * (1.0 - change_binary) + condition_mask = torch.maximum(condition_mask, static_target_mask) + + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + temporal_loss_mask = target_spatial_mask.expand(batch_size, channels, num_latents, height, width) + if use_static_conditioning: + change_loss_weight = change_loss_weight * change_binary.float() + spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width) + spatial_loss_weight = spatial_loss_weight.expand(batch_size, channels, num_latents, height, width) + loss_mask = temporal_loss_mask * spatial_loss_weight + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) diff --git a/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PolicyNative-checkpoint.py b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PolicyNative-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..0af33d8b20056dfee9dcfcfed1abf5e91c768af4 --- /dev/null +++ b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict25PolicyNative-checkpoint.py @@ -0,0 +1,756 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Native Cosmos-Predict2.5 Policy backend. + +This wrapper intentionally does not use the diffusers Cosmos pipeline. It +loads NVIDIA's native Cosmos Policy implementation and adapts starVLA batches +to the official ``CosmosPolicyVideo2WorldModelRectifiedFlow`` data_batch +format. The policy model, scheduler, tokenizer/VAE, latent injection, and +loss computation are therefore owned by the official code. +""" + +from __future__ import annotations + +import os +import pickle +import sys +import traceback +import types +import importlib +import importlib.metadata +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +import numpy as np +import torch +from PIL import Image + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.tools import FRAMEWORK_REGISTRY + + +@dataclass +class CosmoPredict25PolicyNativeDefaultConfig: + name: str = "CosmoPredict25PolicyNative" + + world_model: dict = field(default_factory=lambda: { + # Native checkpoint path, not a diffusers folder. + "base_wm": "", + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 15, + "action_horizon": 16, + "past_action_window_size": 0, + }) + + policy: dict = field(default_factory=lambda: { + "native_repo_path": "", + "config_file": "cosmos_predict2/_src/predict2/cosmos_policy/config/config.py", + "experiment": "cosmos_predict2p5_2b_480p_robocasa_50_demos_per_task_no_s3", + "text_embeddings_path": "", + "text_embeddings_kind": "reason1", + "use_online_text_encoder": True, + "text_encoder_ckpt_path": "", + "height": 224, + "width": 224, + "shift": 5.0, + "num_inference_steps": 5, + # starVLA currently trains demos, so only supervise action + future + # primary image instead of blank unused future/value slots. + "mask_policy_loss": True, + "action_loss_multiplier": 16, + "load_ema_to_reg": True, + "instantiate_ema": False, + "skip_native_package_init": True, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PolicyNative") +class CosmoPredict25_Policy_Native(baseframework): + """Adapter around NVIDIA's native Cosmos-Predict2.5 policy model.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict25PolicyNativeDefaultConfig, config) + self.policy_cfg = self.config.framework.get("policy", {}) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.action_dim = self.config.framework.action_model.action_dim + self.state_dim = self.config.framework.action_model.get("state_dim", self.action_dim) + + self.height = int(self.policy_cfg.get("height", 224)) + self.width = int(self.policy_cfg.get("width", 224)) + self.shift = float(self.policy_cfg.get("shift", 5.0)) + self.num_inference_steps = int(self.policy_cfg.get("num_inference_steps", 5)) + + self._add_native_repo_to_path() + self.native_model, self.native_config = self._load_native_model() + self._configure_native_policy_loss() + self._freeze_native_non_policy_modules() + self._use_online_text_encoder = bool(self.policy_cfg.get("use_online_text_encoder", True)) + self._text_embedding_cache = {} if self._use_online_text_encoder else self._load_text_embedding_cache() + self._iteration = 0 + + def _add_native_repo_to_path(self) -> None: + repo_path = self.policy_cfg.get("native_repo_path") or os.getenv("COSMOS_PREDICT25_REPO", "") + if repo_path: + repo_path = os.path.abspath(os.path.expanduser(repo_path)) + if bool(self.policy_cfg.get("skip_native_package_init", True)): + self._install_cosmos_predict2_package_shim(repo_path) + self._install_optional_dependency_shims() + packages_root = os.path.join(repo_path, "packages") + package_paths = [] + if os.path.isdir(packages_root): + package_paths = [ + os.path.join(packages_root, name) + for name in sorted(os.listdir(packages_root)) + if os.path.isdir(os.path.join(packages_root, name)) + ] + extra_paths = [repo_path, *package_paths] + for extra_path in reversed(extra_paths): + if os.path.isdir(extra_path) and extra_path not in sys.path: + sys.path.insert(0, extra_path) + + @staticmethod + def _install_cosmos_predict2_package_shim(repo_path: str) -> None: + """Expose cosmos_predict2 submodules without running its top-level check.""" + package_root = os.path.join(repo_path, "cosmos_predict2") + if not os.path.isdir(package_root): + return + existing = sys.modules.get("cosmos_predict2") + if existing is not None and getattr(existing, "__file__", None): + return + + module = types.ModuleType("cosmos_predict2") + module.__path__ = [package_root] + module.__package__ = "cosmos_predict2" + module.__file__ = os.path.join(package_root, "__init__.py") + module.__version__ = "1.5.0" + + about_path = os.path.join(package_root, "__about__.py") + if os.path.exists(about_path): + namespace = {} + with open(about_path, "r", encoding="utf-8") as f: + exec(compile(f.read(), about_path, "exec"), namespace) + module.__version__ = namespace.get("__version__", module.__version__) + + sys.modules["cosmos_predict2"] = module + + @staticmethod + def _install_optional_dependency_shims() -> None: + """Let local-only official config imports pass without S3 packages.""" + if "boto3" not in sys.modules: + boto3_module = types.ModuleType("boto3") + + def _missing_boto3(*args, **kwargs): + raise RuntimeError("boto3 is not installed; S3 access is disabled in CosmoPredict25PolicyNative.") + + boto3_module.client = _missing_boto3 + boto3_module.Session = _missing_boto3 + sys.modules["boto3"] = boto3_module + + if "botocore" not in sys.modules: + botocore_module = types.ModuleType("botocore") + sys.modules["botocore"] = botocore_module + + if "botocore.config" not in sys.modules: + config_module = types.ModuleType("botocore.config") + + class Config: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + config_module.Config = Config + sys.modules["botocore.config"] = config_module + + if "botocore.exceptions" not in sys.modules: + exceptions_module = types.ModuleType("botocore.exceptions") + + class ClientError(Exception): + pass + + exceptions_module.ClientError = ClientError + sys.modules["botocore.exceptions"] = exceptions_module + + if "multistorageclient" not in sys.modules: + msc_module = types.ModuleType("multistorageclient") + + class StorageClient: + def __init__(self, *args, **kwargs): + raise RuntimeError( + "multistorageclient is not installed; MSC/S3 access is disabled in " + "CosmoPredict25PolicyNative." + ) + + class StorageClientConfig: + @staticmethod + def read_msc_config(*args, **kwargs): + raise RuntimeError( + "multistorageclient is not installed; MSC/S3 access is disabled in " + "CosmoPredict25PolicyNative." + ) + + @staticmethod + def from_dict(*args, **kwargs): + return None + + msc_module.StorageClient = StorageClient + msc_module.StorageClientConfig = StorageClientConfig + sys.modules["multistorageclient"] = msc_module + + if "multistorageclient.types" not in sys.modules: + msc_types_module = types.ModuleType("multistorageclient.types") + + class Range: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + msc_types_module.Range = Range + sys.modules["multistorageclient.types"] = msc_types_module + + if "transformer_engine" not in sys.modules: + te_module = types.ModuleType("transformer_engine") + te_pytorch_module = types.ModuleType("transformer_engine.pytorch") + te_attention_module = types.ModuleType("transformer_engine.pytorch.attention") + te_rope_module = types.ModuleType("transformer_engine.pytorch.attention.rope") + te_optimizers_module = types.ModuleType("transformer_engine.pytorch.optimizers") + + class RMSNorm(torch.nn.Module): + def __init__(self, hidden_size, eps=1e-5, **kwargs): + super().__init__() + self.eps = eps + self.weight = torch.nn.Parameter(torch.ones(hidden_size)) + + def reset_parameters(self): + torch.nn.init.ones_(self.weight) + + def forward(self, x): + out = x.float() * torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) + self.eps) + return out.to(dtype=x.dtype) * self.weight + + def _rotate_half(x): + x1, x2 = x.chunk(2, dim=-1) + return torch.cat((-x2, x1), dim=-1) + + def apply_rotary_pos_emb(x, rope_emb, tensor_format="bshd", fused=True): + del tensor_format, fused + if rope_emb is None: + return x + cos = rope_emb.cos().to(device=x.device, dtype=x.dtype) + sin = rope_emb.sin().to(device=x.device, dtype=x.dtype) + while cos.dim() < x.dim(): + cos = cos.unsqueeze(0) + sin = sin.unsqueeze(0) + return (x * cos) + (_rotate_half(x) * sin) + + class DotProductAttention(torch.nn.Module): + def __init__(self, *args, **kwargs): + super().__init__() + + def set_context_parallel_group(self, *args, **kwargs): + return None + + def forward(self, q, k, v, *args, **kwargs): + del args, kwargs + q_bhsd = q.permute(0, 2, 1, 3) + k_bhsd = k.permute(0, 2, 1, 3) + v_bhsd = v.permute(0, 2, 1, 3) + out = torch.nn.functional.scaled_dot_product_attention(q_bhsd, k_bhsd, v_bhsd) + out = out.permute(0, 2, 1, 3).contiguous() + return out.flatten(start_dim=2) + + def _missing_multi_tensor_applier(*args, **kwargs): + raise RuntimeError( + "transformer_engine is not installed; official FusedAdam is unavailable. " + "Use the starVLA optimizer path instead." + ) + + te_pytorch_module.RMSNorm = RMSNorm + te_attention_module.DotProductAttention = DotProductAttention + te_attention_module.apply_rotary_pos_emb = apply_rotary_pos_emb + te_rope_module.apply_rotary_pos_emb = apply_rotary_pos_emb + te_optimizers_module.multi_tensor_applier = _missing_multi_tensor_applier + te_pytorch_module.attention = te_attention_module + te_pytorch_module.optimizers = te_optimizers_module + te_module.pytorch = te_pytorch_module + sys.modules["transformer_engine"] = te_module + sys.modules["transformer_engine.pytorch"] = te_pytorch_module + sys.modules["transformer_engine.pytorch.attention"] = te_attention_module + sys.modules["transformer_engine.pytorch.attention.rope"] = te_rope_module + sys.modules["transformer_engine.pytorch.optimizers"] = te_optimizers_module + + if "transformer_engine_torch" not in sys.modules: + tex_module = types.ModuleType("transformer_engine_torch") + + def _missing_transformer_engine_torch(*args, **kwargs): + raise RuntimeError( + "transformer_engine_torch is not installed; official FusedAdam is unavailable." + ) + + tex_module.multi_tensor_adam = _missing_transformer_engine_torch + tex_module.multi_tensor_adam_capturable = _missing_transformer_engine_torch + tex_module.multi_tensor_adam_capturable_master = _missing_transformer_engine_torch + sys.modules["transformer_engine_torch"] = tex_module + + try: + from transformers import cache_utils as transformers_cache_utils + + if not hasattr(transformers_cache_utils, "SlidingWindowCache"): + class SlidingWindowCache(transformers_cache_utils.DynamicCache): + pass + + transformers_cache_utils.SlidingWindowCache = SlidingWindowCache + except Exception: + pass + + if "megatron" not in sys.modules: + sys.modules["megatron"] = types.ModuleType("megatron") + if "megatron.core" not in sys.modules: + core_module = types.ModuleType("megatron.core") + sys.modules["megatron.core"] = core_module + else: + core_module = sys.modules["megatron.core"] + sys.modules["megatron"].core = core_module + + if not hasattr(core_module, "ModelParallelConfig"): + try: + import attrs as _attrs + + @_attrs.define(slots=False) + class ModelParallelConfig: + tensor_model_parallel_size: int = 1 + pipeline_model_parallel_size: int = 1 + context_parallel_size: int = 1 + expert_model_parallel_size: int = 1 + sequence_parallel: bool = False + + except Exception: + @dataclass + class ModelParallelConfig: + tensor_model_parallel_size: int = 1 + pipeline_model_parallel_size: int = 1 + context_parallel_size: int = 1 + expert_model_parallel_size: int = 1 + sequence_parallel: bool = False + + core_module.ModelParallelConfig = ModelParallelConfig + + if "megatron.core.parallel_state" not in sys.modules: + parallel_state_module = types.ModuleType("megatron.core.parallel_state") + + class _SingleProcessGroup: + def size(self): + return 1 + + def rank(self): + return 0 + + _group = _SingleProcessGroup() + parallel_state_module.sequence_parallel = False + parallel_state_module.cp_size_t = 1 + parallel_state_module.is_initialized = lambda: False + parallel_state_module.initialize_model_parallel = lambda *args, **kwargs: None + parallel_state_module.destroy_model_parallel = lambda *args, **kwargs: None + parallel_state_module.get_data_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_data_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_context_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_context_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_context_parallel_group = lambda *args, **kwargs: None + parallel_state_module.get_tensor_model_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_tensor_model_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_pipeline_model_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_pipeline_model_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_expert_model_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_model_parallel_group = lambda *args, **kwargs: _group + parallel_state_module.get_data_parallel_group = lambda *args, **kwargs: None + sys.modules["megatron.core.parallel_state"] = parallel_state_module + core_module.parallel_state = parallel_state_module + else: + core_module.parallel_state = sys.modules["megatron.core.parallel_state"] + + def _load_native_model(self): + try: + from cosmos_predict2._src.imaginaire.lazy_config import instantiate + from cosmos_predict2._src.imaginaire.utils.config_helper import get_config_module, override + except ImportError as exc: + raise ImportError( + "Failed to import the minimal NVIDIA cosmos-predict2.5 config/model helpers. " + "This can mean framework.policy.native_repo_path is wrong, or one of the native repo " + "dependencies is missing from the current Python environment. " + f"native_repo_path={self.policy_cfg.get('native_repo_path')!r}, " + f"COSMOS_PREDICT25_REPO={os.getenv('COSMOS_PREDICT25_REPO')!r}. " + f"Original ImportError: {exc!r}\n{traceback.format_exc()}" + ) from exc + + checkpoint_path = ( + self.policy_cfg.get("checkpoint_path") + or self.config.framework.world_model.get("base_wm") + or self.config.framework.qwenvl.get("base_vlm") + ) + if not checkpoint_path: + raise ValueError( + "CosmoPredict25PolicyNative needs a native Cosmos checkpoint path in " + "framework.world_model.base_wm or framework.policy.checkpoint_path." + ) + + use_online_text_encoder = bool(self.policy_cfg.get("use_online_text_encoder", True)) + if use_online_text_encoder: + transformers_version = importlib.metadata.version("transformers") + if transformers_version != "4.51.3": + raise ValueError( + "Online Reason1 must run with transformers==4.51.3 to match the official " + f"cosmos-predict2.5 lockfile, but the current environment has transformers=={transformers_version}. " + "Please switch/pin the training environment before online Reason1 training." + ) + text_encoder_ckpt_path = self.policy_cfg.get("text_encoder_ckpt_path", "") + if not text_encoder_ckpt_path: + raise ValueError( + "Online Reason1 requires framework.policy.text_encoder_ckpt_path to point to a local " + "Reason1 checkpoint. The official default is an internal S3 path, which this wrapper " + "does not use." + ) + if not os.path.exists(os.path.abspath(os.path.expanduser(text_encoder_ckpt_path))): + raise FileNotFoundError( + "framework.policy.text_encoder_ckpt_path does not exist: " + f"{text_encoder_ckpt_path!r}" + ) + + experiment_opts = list(self.policy_cfg.get("experiment_opts", [])) + experiment_opts.extend([ + "model.config.fsdp_shard_size=1", + "model.config.ema.enabled=false", + "model.config.net.atten_backend=torch", + f"model.config.action_loss_multiplier={int(self.policy_cfg.get('action_loss_multiplier', 16))}", + ]) + if bool(self.policy_cfg.get("mask_policy_loss", True)): + experiment_opts.append("model.config.mask_value_prediction_loss_for_policy_prediction=true") + + config_module = get_config_module(self.policy_cfg.get("config_file")) + native_config = importlib.import_module(config_module).make_config() + native_config = override( + native_config, + ["--", f"experiment={self.policy_cfg.get('experiment')}", *experiment_opts], + ) + if use_online_text_encoder: + text_encoder_ckpt_path = self.policy_cfg.get("text_encoder_ckpt_path", "") + from cosmos_predict2._src.predict2.text_encoders.text_encoder import TextEncoderConfig + + text_encoder_config = TextEncoderConfig( + compute_online=True, + ckpt_path=os.path.abspath(os.path.expanduser(text_encoder_ckpt_path)), + ) + native_config.model.config.text_encoder_class = "reason1p1_7B" + native_config.model.config.text_encoder_config = text_encoder_config + + model = instantiate(native_config.model) + if hasattr(model, "on_train_start"): + model.on_train_start() + if torch.cuda.is_available(): + model = model.cuda() + self._load_local_checkpoint(model, checkpoint_path) + return model, native_config + + @staticmethod + def _candidate_checkpoint_files(checkpoint_path: str) -> List[str]: + if os.path.isfile(checkpoint_path): + return [checkpoint_path] + candidates = [ + os.path.join(checkpoint_path, "model.pt"), + os.path.join(checkpoint_path, "model.pth"), + os.path.join(checkpoint_path, "pytorch_model.pt"), + os.path.join(checkpoint_path, "pytorch_model.bin"), + ] + base_dir = os.path.join(checkpoint_path, "base", "pre-trained") + candidates.extend([ + os.path.join(base_dir, "model.pt"), + os.path.join(base_dir, "model.pth"), + os.path.join(base_dir, "pytorch_model.pt"), + ]) + return [path for path in candidates if os.path.isfile(path)] + + def _load_local_checkpoint(self, model, checkpoint_path: str) -> None: + checkpoint_files = self._candidate_checkpoint_files(os.path.expanduser(checkpoint_path)) + if not checkpoint_files: + raise FileNotFoundError( + "CosmoPredict25PolicyNative now uses a minimal local torch.load checkpoint path " + "and does not import NVIDIA model_loader/easy_io/boto3. Please point " + "framework.policy.checkpoint_path or framework.world_model.base_wm to a local .pt/.pth file. " + f"No supported checkpoint file found under: {checkpoint_path}" + ) + + state = torch.load(checkpoint_files[0], map_location="cpu") + if isinstance(state, dict) and "model" in state: + state = state["model"] + elif isinstance(state, dict) and "state_dict" in state: + state = state["state_dict"] + load_info = model.load_state_dict(state, strict=False) + if load_info is not None and (load_info.missing_keys or load_info.unexpected_keys): + print( + "[CosmoPredict25PolicyNative] checkpoint loaded with " + f"{len(load_info.missing_keys)} missing keys and " + f"{len(load_info.unexpected_keys)} unexpected keys. " + f"First missing={load_info.missing_keys[:5]}, " + f"first unexpected={load_info.unexpected_keys[:5]}", + flush=True, + ) + + def _configure_native_policy_loss(self) -> None: + if bool(self.policy_cfg.get("mask_policy_loss", True)): + self.native_model.config.mask_value_prediction_loss_for_policy_prediction = True + self.native_model.config.action_loss_multiplier = int(self.policy_cfg.get("action_loss_multiplier", 16)) + + def _freeze_native_non_policy_modules(self) -> None: + for module_name in ("tokenizer", "text_encoder"): + module = getattr(self.native_model, module_name, None) + if module is not None and hasattr(module, "requires_grad_"): + module.requires_grad_(False) + + def _load_text_embedding_cache(self) -> Dict[str, torch.Tensor]: + path = self.policy_cfg.get("text_embeddings_path", "") + if not path: + return {} + path = os.path.abspath(os.path.expanduser(path)) + with open(path, "rb") as f: + return pickle.load(f) + + @staticmethod + def _as_image_list(images) -> List: + return list(images) if isinstance(images, (list, tuple)) else [images] + + @staticmethod + def _blank_like(image): + if isinstance(image, Image.Image): + return Image.new(image.mode, image.size) + image_array = np.asarray(image) + return np.zeros_like(image_array) + + @staticmethod + def _to_uint8_array(image) -> np.ndarray: + if isinstance(image, Image.Image): + return np.asarray(image.convert("RGB")) + if torch.is_tensor(image): + array = image.detach().cpu().numpy() + else: + array = np.asarray(image) + if array.ndim == 3 and array.shape[0] in (1, 3) and array.shape[-1] not in (1, 3): + array = np.transpose(array, (1, 2, 0)) + if array.dtype != np.uint8: + if array.max() <= 1.0 and array.min() >= 0.0: + array = array * 255.0 + elif array.min() >= -1.0 and array.max() <= 1.0: + array = (array + 1.0) * 127.5 + array = np.clip(array, 0, 255).astype(np.uint8) + if array.ndim == 2: + array = np.repeat(array[..., None], 3, axis=-1) + if array.shape[-1] == 1: + array = np.repeat(array, 3, axis=-1) + return array[..., :3] + + def _resize_uint8(self, image) -> np.ndarray: + array = self._to_uint8_array(image) + pil = Image.fromarray(array) + pil = pil.resize((self.width, self.height), Image.BILINEAR) + return np.asarray(pil, dtype=np.uint8) + + def _split_policy_views(self, images: List, blank_image): + primary = images[0] if images else blank_image + wrist = images[1] if len(images) > 1 else blank_image + secondary = images[2] if len(images) > 2 else blank_image + return wrist, primary, secondary + + def _build_video_frames(self, example: dict, include_future: bool) -> List[np.ndarray]: + temporal_factor = 4 + current_images = self._as_image_list(example["image"]) + future_images = self._as_image_list(example.get("future_image", current_images)) if include_future else [] + blank_image = self._blank_like(current_images[0]) + + wrist, primary, secondary = self._split_policy_views(current_images, blank_image) + if future_images: + future_wrist, future_primary, future_secondary = self._split_policy_views(future_images, blank_image) + else: + future_wrist, future_primary, future_secondary = blank_image, blank_image, blank_image + + slot_images = [ + blank_image, # 0: special blank, not repeated + blank_image, # 1: current proprio placeholder + wrist, # 2: current wrist + primary, # 3: current primary + secondary, # 4: current secondary + blank_image, # 5: action placeholder + blank_image, # 6: future proprio placeholder + future_wrist, # 7: future wrist + future_primary, # 8: future primary + future_secondary, # 9: future secondary + blank_image, # 10: value placeholder + ] + + frames = [self._resize_uint8(slot_images[0])] + for slot_image in slot_images[1:]: + resized = self._resize_uint8(slot_image) + frames.extend([resized] * temporal_factor) + return frames + + def _stack_video(self, examples: List[dict], include_future: bool) -> torch.Tensor: + videos = [] + for example in examples: + frames = np.stack(self._build_video_frames(example, include_future=include_future), axis=0) + videos.append(torch.from_numpy(frames).permute(3, 0, 1, 2).contiguous()) + return torch.stack(videos, dim=0).to(dtype=torch.uint8) + + def _select_action_chunk(self, actions) -> torch.Tensor: + actions = torch.tensor(np.array(actions), dtype=torch.float32) + return actions[:, -(self.future_action_window_size + 1):, :] + + def _stack_state(self, examples: List[dict], key: str, device: torch.device) -> torch.Tensor: + if key in examples[0]: + return torch.tensor(np.array([example[key] for example in examples]), device=device, dtype=torch.float32) + return torch.zeros((len(examples), self.state_dim), device=device, dtype=torch.float32) + + def _stack_text_embeddings(self, examples: List[dict], device: torch.device) -> torch.Tensor: + if self._use_online_text_encoder: + raise RuntimeError("_stack_text_embeddings should not be called when use_online_text_encoder=true.") + if "t5_text_embeddings" in examples[0]: + embeddings = [example["t5_text_embeddings"] for example in examples] + else: + embeddings = [] + missing = [] + for example in examples: + instruction = example.get("lang") or example.get("instruction") or example.get("ai_caption") + if instruction in self._text_embedding_cache: + embeddings.append(self._text_embedding_cache[instruction]) + else: + missing.append(instruction) + if missing: + raise KeyError( + "CosmoPredict25PolicyNative needs official text embeddings. " + "Provide example['t5_text_embeddings'] or set framework.policy.text_embeddings_path. " + f"Missing instruction example: {missing[0]!r}" + ) + + tensors = [] + for embedding in embeddings: + tensor = embedding if torch.is_tensor(embedding) else torch.as_tensor(embedding) + tensor = tensor.squeeze(0).to(device=device, dtype=torch.bfloat16) + tensors.append(tensor) + return torch.stack(tensors, dim=0) + + def _make_native_batch(self, examples: List[dict], include_future: bool = True) -> dict: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + batch_size = len(examples) + + actions = self._select_action_chunk([example["action"] for example in examples]).to(device=device) + video = self._stack_video(examples, include_future=include_future) + proprio = self._stack_state(examples, "state", device=device) + future_proprio = self._stack_state(examples, "future_state", device=device) + + captions = [ + example.get("ai_caption") or example.get("lang") or example.get("instruction") or "" + for example in examples + ] + if self._use_online_text_encoder: + text_embeddings = None + text_mask = None + else: + text_embeddings = self._stack_text_embeddings(examples, device=device) + text_mask = torch.ones( + (batch_size, text_embeddings.shape[1]), + device=device, + dtype=torch.int64, + ) + + def full_idx(value: int) -> torch.Tensor: + return torch.full((batch_size,), value, device=device, dtype=torch.int64) + + zeros = torch.zeros((batch_size,), device=device, dtype=torch.int64) + data_batch = { + "video": video, + "actions": actions, + "proprio": proprio, + "future_proprio": future_proprio, + "ai_caption": captions, + "num_conditional_frames": torch.tensor(5, device=device, dtype=torch.int64), + "current_proprio_latent_idx": full_idx(1) if "state" in examples[0] else full_idx(-1), + "action_latent_idx": full_idx(5), + "future_proprio_latent_idx": full_idx(-1), + "future_wrist_image_latent_idx": full_idx(-1), + "future_wrist_image2_latent_idx": full_idx(-1), + "future_image_latent_idx": full_idx(8) if include_future else full_idx(-1), + "future_image2_latent_idx": full_idx(-1), + "value_latent_idx": full_idx(10), + "rollout_data_mask": zeros.clone(), + "world_model_sample_mask": zeros.clone(), + "value_function_sample_mask": zeros.clone(), + "value_function_return": torch.zeros((batch_size,), device=device, dtype=torch.float32), + } + if not self._use_online_text_encoder: + data_batch["t5_text_embeddings"] = text_embeddings + data_batch["t5_text_mask"] = text_mask + return data_batch + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + data_batch = self._make_native_batch(examples, include_future=True) + output_batch, loss = self.native_model.training_step(data_batch, self._iteration) + self._iteration += 1 + + metrics = {"action_loss": loss} + for key in ( + "demo_sample_action_mse_loss", + "demo_sample_action_l1_loss", + "demo_sample_future_image_mse_loss", + "demo_sample_future_image_l1_loss", + "velocity_mse_loss", + "edm_loss", + ): + value = output_batch.get(key) + if torch.is_tensor(value): + metrics[key] = value.detach() + return metrics + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + from cosmos_predict2._src.predict2.cosmos_policy.experiments.robot.cosmos_utils import ( + extract_action_chunk_from_latent_sequence, + ) + + data_batch = self._make_native_batch(examples, include_future=True) + batch_size = len(examples) + num_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps)) + generated_latent = self.native_model.generate_samples_from_batch( + data_batch, + n_sample=batch_size, + num_steps=num_steps, + seed=int(kwargs.get("seed", 0)), + is_negative_prompt=False, + use_variance_scale=False, + return_orig_clean_latent_frames=False, + shift=float(kwargs.get("shift", self.shift)), + guidance=0, + ) + action_indices = torch.full( + (batch_size,), + 5, + dtype=torch.int64, + device=generated_latent.device, + ) + actions = extract_action_chunk_from_latent_sequence( + generated_latent, + action_shape=(self.future_action_window_size + 1, self.action_dim), + action_indices=action_indices, + ) + return {"normalized_actions": actions.detach().float().cpu().numpy()} diff --git a/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict2Perceiver-checkpoint.py b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict2Perceiver-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ac74f201b07040c60301bc705fb46a1b62e12d --- /dev/null +++ b/starVLA/model/framework/WM4A/.ipynb_checkpoints/CosmoPredict2Perceiver-checkpoint.py @@ -0,0 +1,256 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +CosmoPredict2-Perceiver Framework. + +Uses Cosmos-Predict2 as the world-model backbone and the Perceiver-style +flow-matching action head for continuous action prediction. +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.training.trainer_utils.trainer_tools import resize_images + +logger = initialize_overwatch(__name__) + + +@dataclass +class CosmoPredict2PerceiverDefaultConfig: + """CosmoPredict2-Perceiver default parameters.""" + + name: str = "CosmoPredict2Perceiver" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + # Kept for compatibility with shared utilities and action-head configs. + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "max_num_embodiments": 32, + "use_category_specific": False, + "diffusion_model_cfg": { + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2Perceiver") +class CosmoPredict2_Perceiver(baseframework): + """World-model-for-action framework using Cosmos-Predict2 + Perceiver head.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2PerceiverDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # 训练时 + # action支路,self.backbone.build_inputs、self.backbone.forward()、self.action_model.forward() + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + # print('################# CosmoPredict2_Perceiver.forward-1') + + # 1. CosmosPredict:构建输入 + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + with torch.autocast("cuda", dtype=torch.float32): + + # 3.1 初始化action + actions = [example["action"] for example in examples] + actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype) + # print(actions.shape) # torch.Size([8, 16, 32]) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + # print(self.future_action_window_size) # 15 + # print(actions_target.shape) # torch.Size([8, 16, 32]) + + # 3.2 重复降噪 + # 将action和vl-tokens复制多次,重复多次降噪 + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "trainer") + else self.config.framework.action_model.get("repeated_diffusion_steps", 4) + ) + # print(repeated_diffusion_steps) # 4 + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + # print(actions_target_repeated.shape) # torch.Size([32, 16, 32]) + # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048]) + + # 3.3 准备state、action_mask和embodiment_tag + state = [example["state"] for example in examples] if "state" in examples[0] else None + if state is not None: + # print('state is not None') + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + # print(state.shape) # torch.Size([8, 1, 64]) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + # print(state_repeated.shape) # torch.Size([32, 1, 64]) + else: + state_repeated = None + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + if action_mask is not None: + # print('action_mask is not None') + action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype) + # print(action_mask_tensor.shape) # torch.Size([8, 16, 32]) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :] + # print(action_mask_target.shape) # torch.Size([8, 16, 32]) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + # print(action_mask_repeated.shape) # torch.Size([32, 16, 32]) + else: + action_mask_repeated = None + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + if embodiment_tag is not None: + # print('embodiment_tag is not None') + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64) + # print(embodiment_tag.shape) # torch.Size([8]) + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) + # print(embodiment_tag_repeated.shape) # torch.Size([32]) + else: + embodiment_tag_repeated = None + + action_loss = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + ) + # print(type(self.action_model)) # + # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048]) + # print(actions_target_repeated.shape) # torch.Size([32, 16, 32]) + # print(state_repeated.shape) # torch.Size([32, 1, 64]) + # print(embodiment_tag_repeated.shape) # torch.Size([32]) + # print(action_mask_repeated.shape) # torch.Size([32, 16, 32]) + # print(action_loss) # tensor(1.5625, device='cuda:0', grad_fn=) + + # print('################# CosmoPredict2_Perceiver.forward-2') + return {"action_loss": action_loss} + + # @torch.inference_mode() + # def predict_action(self, examples: List[dict], **kwargs) -> dict: + # if type(examples) is not list: + # examples = [examples] + + # batch_images = [to_pil_preserve(example["image"]) for example in examples] + # instructions = [example["lang"] for example in examples] + # state = [example["state"] for example in examples] if "state" in examples[0] else None + # embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + + # train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # if train_obs_image_size: + # batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # with torch.autocast("cuda", dtype=torch.bfloat16): + # wm_outputs = self.backbone( + # **wm_inputs, + # output_hidden_states=True, + # return_dict=True, + # ) + # last_hidden = wm_outputs.hidden_states[-1] + + # state = ( + # torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + # if state is not None + # else None + # ) + # embodiment_tag = ( + # torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + # if embodiment_tag is not None + # else None + # ) + # if embodiment_tag is not None: + # embodiment_tag = embodiment_tag.view(-1) + + # with torch.autocast("cuda", dtype=torch.float32): + # pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + + # normalized_actions = pred_actions.detach().cpu().numpy() + # return {"normalized_actions": normalized_actions} diff --git a/starVLA/model/framework/WM4A/.ipynb_checkpoints/JoyRA05MaskFutureImage-checkpoint.py b/starVLA/model/framework/WM4A/.ipynb_checkpoints/JoyRA05MaskFutureImage-checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..953569de48f07aae9c6e0cec36ce6145fdb742f9 --- /dev/null +++ b/starVLA/model/framework/WM4A/.ipynb_checkpoints/JoyRA05MaskFutureImage-checkpoint.py @@ -0,0 +1,452 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""Wan2.2-TI2V Perceiver with masked future-image denoising.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import ( + CosmoPredict25PerceiverFutureImageDefaultConfig, +) +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverMaskedFutureImage import ( + CosmoPredict25_Perceiver_MaskedFutureImage, +) +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class JoyRA05MaskFutureImageDefaultConfig(CosmoPredict25PerceiverFutureImageDefaultConfig): + """Wan2.2-TI2V Perceiver + masked future-image defaults.""" + + name: str = "JoyRA05MaskFutureImage" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + "height": 224, + "width": 224, + "freeze_text_encoder": True, + "freeze_vae": True, + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 3072, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + "timestep_scale": 1000.0, + "single_frame_condition_prob": 0.0, + "change_mask_enabled": True, + "change_mask_top_ratio": 0.25, + "change_mask_static_weight": 0.05, + "change_mask_soft_loss": True, + "masked_denoising": False, + "condition_static_regions": False, + }) + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 81, + "num_inference_steps": 50, + "guidance_scale": 5.0, + "output_type": "pil", + "height": 224, + "width": 224, + "max_sequence_length": 512, + "conditioning_mode": "image", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + +@FRAMEWORK_REGISTRY.register("JoyRA05MaskFutureImage") +class JoyRA05_MaskedFutureImage(CosmoPredict25_Perceiver_MaskedFutureImage): + """Perceiver action head plus Wan2.2 per-token masked flow matching.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(JoyRA05MaskFutureImageDefaultConfig, config) + + self.qwen_vl_interface = get_vlm_model(config=self.config) + # 保持与历史 checkpoint 键名一致:主模块名使用 wan_interface.* + self.wan_interface = get_world_model(config=self.config) + + qwen_hidden = self.qwen_vl_interface.model.config.hidden_size + wm_hidden = self.wan_interface.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = qwen_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = qwen_hidden + + wm_cfg = self.config.framework.get("world_model", {}) if self.config is not None else {} + self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False)) + self.wm_projector = nn.Linear(wm_hidden, qwen_hidden) + self.wm_post_norm = nn.LayerNorm(qwen_hidden, eps=1e-6) + gain = float(wm_cfg.get("wm_projector_init_gain", 0.02)) + nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain) + nn.init.zeros_(self.wm_projector.bias) + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + + qwenvl_cfg = self.config.framework.get("qwenvl", {}) if self.config is not None else {} + if self._as_bool(wm_cfg.get("freeze_text_encoder", True)) and hasattr(self.wan_interface, "text_encoder"): + for p in self.wan_interface.text_encoder.parameters(): + p.requires_grad = False + if self._as_bool(wm_cfg.get("freeze_vae", True)) and hasattr(self.wan_interface, "vae"): + for p in self.wan_interface.vae.parameters(): + p.requires_grad = False + if self._as_bool(qwenvl_cfg.get("is_frozen", True)): + for p in self.qwen_vl_interface.parameters(): + p.requires_grad = False + + + def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor: + if self._pool_wm_sequence: + last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True) + wm_input = last_wm_hidden.to(dtype=self.wm_projector.weight.dtype) + wm_aligned = self.wm_post_norm(self.wm_projector(wm_input)).to(dtype=last_vlm_hidden.dtype) + return torch.cat([last_vlm_hidden, wm_aligned], dim=1) + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + training_cfg = self._future_training_cfg() + examples, single_frame_ratio = self._maybe_apply_single_frame_condition(examples, training_cfg) + + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + wm_inputs = self.wan_interface.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.wan_interface(**wm_inputs, output_hidden_states=True, return_dict=True) + last_wm_hidden = wm_outputs.hidden_states[-1] + qwen_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwen_outputs.hidden_states[-1] + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "trainer") + else self.config.framework.action_model.get("repeated_diffusion_steps", 4) + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + state = self._align_state_dim(state) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :] + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + embodiment_tag_repeated = None + if embodiment_tag is not None: + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64).view(-1) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) + + action_loss = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + ) + + output = {"action_loss": action_loss} + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is None: + if single_frame_ratio > 0.0: + output["single_frame_condition_ratio"] = single_frame_ratio + return output + + loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0)) + output["perceiver_action_loss"] = action_loss.detach() + output["future_image_loss"] = future_image_loss.detach() + if single_frame_ratio > 0.0: + output["single_frame_condition_ratio"] = single_frame_ratio + output["action_loss"] = action_loss + future_image_loss * loss_weight + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + wm_inputs = self.wan_interface.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_wm_hidden = wm_outputs.hidden_states[-1] + + qwen_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwen_outputs.hidden_states[-1] + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + state = self._align_state_dim(state) + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + generation_cfg = self._get_future_image_generation_cfg(kwargs) + if not bool(generation_cfg.pop("enabled", True)): + return output + + return_full_video = bool(generation_cfg.pop("return_full_video", False)) + future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + max_samples = int(generation_cfg.pop("max_samples", 1)) + generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + output["pred_future_images"] = self._generate_future_images( + generation_inputs, + batch_size=len(examples), + max_samples=max_samples, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + + return output + + def _make_wan_timestep( + self, + hidden_states: torch.Tensor, + denoise_mask: torch.Tensor, + flow_time: torch.Tensor, + timestep_scale: float, + ) -> torch.Tensor: + """Convert the latent denoise mask into Wan's per-patch timestep tokens.""" + batch_size, _, num_frames, height, width = hidden_states.shape + p_t, p_h, p_w = self.wan_interface.transformer.config.patch_size + if num_frames % p_t or height % p_h or width % p_w: + raise ValueError( + "Wan latent shape must be divisible by transformer.patch_size; " + f"got {(num_frames, height, width)} and {(p_t, p_h, p_w)}." + ) + + patch_mask = F.max_pool3d( + denoise_mask.float(), + kernel_size=(p_t, p_h, p_w), + stride=(p_t, p_h, p_w), + ) + patch_mask = patch_mask[:, 0].flatten(1) + seq_len = patch_mask.shape[1] + rope_max_seq_len = getattr(self.wan_interface.transformer.config, "rope_max_seq_len", None) + if rope_max_seq_len is not None and seq_len > int(rope_max_seq_len): + raise ValueError( + f"Wan future-image seq_len={seq_len} exceeds rope_max_seq_len={rope_max_seq_len}. " + "Reduce observation frames or image resolution." + ) + + scaled_time = flow_time.to(device=hidden_states.device, dtype=torch.float32) * float(timestep_scale) + return patch_mask * scaled_time[:, None] + + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + """Compute masked Wan flow loss (method name retained for parent forward compatibility).""" + if "future_image" not in examples[0]: + return None + + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + prompt_embeds = self.wan_interface._encode_text(instructions) + clean_latents = self.wan_interface._encode_images_vae(raw_sequences) + dtype = self.wan_interface.transformer.dtype + clean_latents = clean_latents.to(dtype=dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width) + + use_change_mask = self._as_bool(training_cfg.get("change_mask_enabled", True)) + if use_change_mask: + change_binary, change_loss_weight = self._build_latent_change_masks( + batch_images=batch_images, + future_images=future_images, + latent_height=height, + latent_width=width, + training_cfg=training_cfg, + device=device, + ) + change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype) + change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32) + else: + change_binary = clean_latents.new_ones((batch_size, 1, 1, height, width)) + change_loss_weight = clean_latents.new_ones( + (batch_size, 1, 1, height, width), dtype=torch.float32 + ) + + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + time_view = flow_time.view(batch_size, 1, 1, 1, 1).to(dtype=clean_latents.dtype) + + noise = torch.randn_like(clean_latents) + noisy_latents = clean_latents * (1.0 - time_view) + noise * time_view + use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", False)) + use_static_conditioning = use_masked_denoising and self._as_bool( + training_cfg.get("condition_static_regions", False) + ) + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) + if use_masked_denoising: + denoise_mask = denoise_mask * change_binary + hidden_states = torch.where(denoise_mask.bool(), noisy_latents, clean_latents) + target_velocity = noise.float() - clean_latents.float() + + timestep_mask = denoise_mask if use_static_conditioning else target_spatial_mask + timestep = self._make_wan_timestep( + hidden_states=hidden_states, + denoise_mask=timestep_mask, + flow_time=flow_time, + timestep_scale=float(training_cfg.get("timestep_scale", 1000.0)), + ) + + if hasattr(self.wan_interface, "_intermediate_features"): + self.wan_interface._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.wan_interface.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.wan_interface, "_intermediate_features"): + self.wan_interface._intermediate_features.clear() + + if use_static_conditioning: + change_loss_weight = change_loss_weight * change_binary.float() + spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width) + loss_mask = target_spatial_mask * spatial_loss_weight + loss_mask = loss_mask.expand(batch_size, channels, num_latents, height, width) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + """Build arguments accepted by Diffusers WanImageToVideoPipeline.""" + mode = str(cfg.pop("conditioning_mode", "image")).lower() + if mode not in {"auto", "image", "video"}: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + height = cfg.pop("height", getattr(self.wan_interface, "height", 480)) + width = cfg.pop("width", getattr(self.wan_interface, "width", 832)) + resolved_height, resolved_width = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "image": [self._as_sequence(images)[-1] for images in batch_images], + "prompt": instructions, + "height": resolved_height, + "width": resolved_width, + "num_frames": cfg.pop("num_frames", 81), + "num_inference_steps": cfg.pop("num_inference_steps", 50), + "guidance_scale": cfg.pop("guidance_scale", 5.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + } + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + # Cosmos-only knobs may still be present in a shared YAML. + cfg.pop("conditional_frame_timestep", None) + cfg.pop("num_latent_conditional_frames", None) + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs diff --git a/starVLA/model/framework/WM4A/CosmoPredict25Perceiver.py b/starVLA/model/framework/WM4A/CosmoPredict25Perceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8824c91271a4fceef4f399952af196ada96bb0 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict25Perceiver.py @@ -0,0 +1,91 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver Framework. + +This keeps Predict2.5 separate from the existing Cosmos-Predict2 framework +while reusing the same Perceiver action-head training/inference logic. +""" + +from dataclasses import dataclass, field +from typing import Optional + +from starVLA.model.framework.WM4A.CosmoPredict2Perceiver import CosmoPredict2_Perceiver +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY + + +@dataclass +class CosmoPredict25PerceiverDefaultConfig: + """Cosmos-Predict2.5-Perceiver default parameters.""" + + name: str = "CosmoPredict25Perceiver" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "nvidia/Cosmos-Predict2.5-2B", + "revision": "diffusers/base/post-trained", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "nvidia/Cosmos-Predict2.5-2B", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "max_num_embodiments": 32, + "use_category_specific": False, + "diffusion_model_cfg": { + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25Perceiver") +class CosmoPredict25_Perceiver(CosmoPredict2_Perceiver): + """World-model-for-action framework using Cosmos-Predict2.5 + Perceiver.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size diff --git a/starVLA/model/framework/WM4A/CosmoPredict25PerceiverDiT4DiT.py b/starVLA/model/framework/WM4A/CosmoPredict25PerceiverDiT4DiT.py new file mode 100644 index 0000000000000000000000000000000000000000..80b072f795fbe8a0db175fd6380b40b0e8c3376a --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict25PerceiverDiT4DiT.py @@ -0,0 +1,639 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver with DiT4DiT-style video dynamics fusion. + +This keeps starVLA's Perceiver action head, but aligns the Cosmos path with +DiT4DiT: the action head consumes the hidden state captured from the first +Cosmos denoising call, and the optional future-video loss supervises the same +condition/future latent layout with rectified-flow targets. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import ( + CosmoPredict25_Perceiver_FutureImage, + CosmoPredict25PerceiverFutureImageDefaultConfig, +) +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.DiT4DiTPerceiverHead import get_action_model as get_dit4dit_action_model +from starVLA.model.modules.action_model.PerceiverHead import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict25PerceiverDiT4DiTDefaultConfig(CosmoPredict25PerceiverFutureImageDefaultConfig): + """Cosmos-Predict2.5-Perceiver defaults for DiT4DiT-style fusion.""" + + name: str = "CosmoPredict25PerceiverDiT4DiT" + + dit4dit_video: dict = field(default_factory=lambda: { + "enabled": True, + "training": "joint", # joint | action | video + "future_loss_type": "flow_matching", + "future_loss_weight": 1.0, + "future_num_inference_steps": 1, + "conditional_frame_timestep": 0.0001, + "tri_timestep": { + "video_time_distribution": "uniform", + "feature_timestep": 1.0, + "action_time_distribution": "beta_action_head", + }, + "return_pred_future_video": False, + }) + + dit4dit_action_head: dict = field(default_factory=lambda: { + "enabled": False, + }) + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverDiT4DiT") +class CosmoPredict25_Perceiver_DiT4DiT(CosmoPredict25_Perceiver_FutureImage): + """Cosmos first-denoising hidden + starVLA Perceiver action head.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverDiT4DiTDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + action_head_cfg = dict(self.config.framework.get("dit4dit_action_head", {})) + if bool(action_head_cfg.get("enabled", False)): + self.action_model: FlowmatchingActionHead = get_dit4dit_action_model(config=self.config) + else: + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + + def _video_cfg(self) -> dict: + return dict(self.config.framework.get("dit4dit_video", {})) + + @staticmethod + def _flatten_hidden(hidden: torch.Tensor) -> torch.Tensor: + if hidden.dim() == 3: + return hidden + if hidden.dim() == 5: + batch, channels, frames, height, width = hidden.shape + return hidden.permute(0, 2, 3, 4, 1).reshape(batch, frames * height * width, channels) + raise ValueError(f"Unsupported Cosmos hidden shape: {tuple(hidden.shape)}") + + def _preprocess_video_sequence(self, sequences: List[List], height: int, width: int) -> torch.Tensor: + videos = [] + for sequence in sequences: + video = self.backbone.video_processor.preprocess_video(sequence, height=height, width=width) + videos.append(video.squeeze(0)) + dtype = self.backbone.vae.dtype + device = next(self.backbone.vae.parameters()).device + return torch.stack(videos, dim=0).to(device=device, dtype=dtype) + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() in {"auto", "infer"} + + def _resolve_video_size(self, cfg: dict, condition_sequences: List[List], future_sequences: Optional[List[List]] = None): + height_cfg = cfg.get("height", getattr(self.backbone, "_height", 704)) + width_cfg = cfg.get("width", getattr(self.backbone, "_width", 1280)) + + height = None if self._is_auto_size(height_cfg) else int(height_cfg) + width = None if self._is_auto_size(width_cfg) else int(width_cfg) + if height is not None and width is not None: + return height, width + + images = [] + for sequence in condition_sequences: + images.extend(sequence) + if future_sequences is not None: + for sequence in future_sequences: + images.extend(sequence) + if not images: + raise ValueError("Cannot infer video size from empty image sequences.") + + if height is None: + height = max(int(image.height) for image in images) + if width is None: + width = max(int(image.width) for image in images) + return height, width + + def _split_condition_future(self, examples: List[dict]) -> tuple[List[List], Optional[List[List]], List[str]]: + condition_sequences = [] + future_sequences = [] + has_future = False + + for example in examples: + image_sequence = self._as_sequence(to_pil_preserve(example["image"])) + if not image_sequence: + raise ValueError("Each example must contain at least one image.") + + condition_sequences.append([image_sequence[0]]) + if "future_image" in example: + future = self._as_sequence(to_pil_preserve(example["future_image"])) + elif len(image_sequence) > 1: + future = image_sequence[1:] + else: + future = [] + + if future: + has_future = True + future_sequences.append(future) + + if not has_future: + return condition_sequences, None, [example["lang"] for example in examples] + + max_future = max(len(future) for future in future_sequences) + padded_future = [] + for cond, future in zip(condition_sequences, future_sequences): + if not future: + future = [cond[-1]] + if len(future) < max_future: + future = future + [future[-1]] * (max_future - len(future)) + padded_future.append(future) + + return condition_sequences, padded_future, [example["lang"] for example in examples] + + def _prepare_dit4dit_latents( + self, + condition_video: torch.Tensor, + num_frames_out: int, + height: int, + width: int, + dtype: torch.dtype, + ): + batch_size = condition_video.shape[0] + num_channels = int(self.backbone.transformer.config.in_channels) - 1 + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + spatial_factor = int(getattr(self.backbone, "vae_scale_factor_spatial", 16)) + t_lat = (int(num_frames_out) - 1) // temporal_factor + 1 + h_lat = height // spatial_factor + w_lat = width // spatial_factor + + if condition_video.shape[2] < num_frames_out: + pad = condition_video.new_zeros( + batch_size, + condition_video.shape[1], + num_frames_out - condition_video.shape[2], + condition_video.shape[3], + condition_video.shape[4], + ) + padded_video = torch.cat([condition_video, pad], dim=2) + else: + padded_video = condition_video[:, :, :num_frames_out] + + with torch.no_grad(): + cond_latents = self.backbone.vae.encode(padded_video).latent_dist.sample() + + latents_mean = self.backbone.latents_mean.to(device=cond_latents.device, dtype=cond_latents.dtype) + latents_std = self.backbone.latents_std.to(device=cond_latents.device, dtype=cond_latents.dtype) + cond_latents = ((cond_latents - latents_mean) / latents_std).to(dtype) + + target_shape = (batch_size, num_channels, t_lat, h_lat, w_lat) + if cond_latents.shape != target_shape: + adjusted = cond_latents.new_zeros(target_shape) + t_copy = min(cond_latents.shape[2], t_lat) + adjusted[:, :, :t_copy] = cond_latents[:, :, :t_copy] + cond_latents = adjusted + + latents = torch.randn(target_shape, device=condition_video.device, dtype=dtype) + cond_count = min(t_lat, (condition_video.shape[2] - 1) // temporal_factor + 1) + cond_indicator = latents.new_zeros(batch_size, 1, t_lat, 1, 1) + cond_indicator[:, :, :cond_count] = 1.0 + cond_mask = cond_indicator.expand(batch_size, 1, t_lat, h_lat, w_lat) + return latents, cond_latents, cond_mask, cond_indicator, cond_count + + def _encode_video_latents_mean(self, video: torch.Tensor) -> torch.Tensor: + with torch.no_grad(): + encoded = self.backbone.vae.encode(video.to(dtype=self.backbone.vae.dtype)) + latents = encoded.latent_dist.mean if hasattr(encoded, "latent_dist") else encoded + latents = latents.float() + mean = self.backbone.latents_mean.to(device=latents.device, dtype=latents.dtype) + std = self.backbone.latents_std.to(device=latents.device, dtype=latents.dtype) + if mean.ndim == 5 and mean.shape[2] >= latents.shape[2]: + mean = mean[:, :, :latents.shape[2]] + if std.ndim == 5 and std.shape[2] >= latents.shape[2]: + std = std[:, :, :latents.shape[2]] + return (latents - mean) / std + + def _decode_latents_to_video(self, latents: torch.Tensor) -> torch.Tensor: + mean = self.backbone.latents_mean.to(device=latents.device, dtype=latents.dtype) + std = self.backbone.latents_std.to(device=latents.device, dtype=latents.dtype) + if mean.ndim == 5 and mean.shape[2] >= latents.shape[2]: + mean = mean[:, :, :latents.shape[2]] + if std.ndim == 5 and std.shape[2] >= latents.shape[2]: + std = std[:, :, :latents.shape[2]] + decoded = self.backbone.vae.decode((latents * std + mean).to(dtype=self.backbone.vae.dtype), return_dict=False)[0] + if decoded.ndim == 5 and decoded.shape[1] == 3: + decoded = decoded.permute(0, 2, 1, 3, 4).contiguous() + elif decoded.ndim == 4 and decoded.shape[1] == 3: + decoded = decoded.unsqueeze(1) + decoded = decoded.float() + if decoded.min() < -0.5: + decoded = (decoded + 1.0) / 2.0 + return decoded.clamp(0.0, 1.0) + + def _tri_timestep_cfg(self, cfg: Optional[dict] = None) -> dict: + cfg = self._video_cfg() if cfg is None else cfg + tri_cfg = dict(cfg.get("tri_timestep", {})) + tri_cfg.setdefault("video_time_distribution", cfg.get("time_distribution", "uniform")) + tri_cfg.setdefault("feature_timestep", cfg.get("feature_timestep", 1.0)) + tri_cfg.setdefault("action_time_distribution", "beta_action_head") + return tri_cfg + + def _sample_video_flow_time(self, batch_size: int, device: torch.device, cfg: dict) -> torch.Tensor: + tri_cfg = self._tri_timestep_cfg(cfg) + distribution = str(tri_cfg.get("video_time_distribution", "uniform")).lower() + if distribution in {"logit_normal", "logitnormal"}: + time = torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + elif distribution == "uniform": + time = torch.rand(batch_size, device=device, dtype=torch.float32) + elif distribution in {"fixed", "constant"}: + time = torch.full( + (batch_size,), + fill_value=float(tri_cfg.get("video_timestep", 0.5)), + device=device, + dtype=torch.float32, + ) + else: + raise ValueError(f"Unsupported dit4dit_video.tri_timestep.video_time_distribution={distribution!r}") + + high_sigma_ratio = tri_cfg.get("high_sigma_ratio", cfg.get("high_sigma_ratio", None)) + if high_sigma_ratio is not None and float(high_sigma_ratio) > 0: + high_sigma_min = float(tri_cfg.get("high_sigma_min", cfg.get("high_sigma_min", 0.98))) + high_mask = torch.rand(batch_size, device=device) < float(high_sigma_ratio) + high_time = torch.rand(batch_size, device=device, dtype=torch.float32) * (1.0 - high_sigma_min) + high_sigma_min + time = torch.where(high_mask, high_time, time) + return time + + def _dit4dit_cosmos_forward( + self, + condition_sequences: List[List], + instructions: List[str], + future_sequences: Optional[List[List]] = None, + return_pred_future_video: bool = False, + ): + cfg = self._video_cfg() + height, width = self._resolve_video_size(cfg, condition_sequences, future_sequences) + condition_video = self._preprocess_video_sequence(condition_sequences, height, width) + + future_video = None + num_frames_out = condition_video.shape[2] + if future_sequences is not None: + future_video = self._preprocess_video_sequence(future_sequences, height, width) + num_frames_out += future_video.shape[2] + num_frames_out = max(num_frames_out, 1 + int(getattr(self.backbone, "vae_scale_factor_temporal", 4))) + + dtype = self.backbone.transformer.dtype + prompt_embeds = self.backbone._encode_text(instructions).to(device=condition_video.device, dtype=dtype) + latents, cond_latents, cond_mask, cond_indicator, cond_count = self._prepare_dit4dit_latents( + condition_video=condition_video, + num_frames_out=num_frames_out, + height=height, + width=width, + dtype=dtype, + ) + + num_steps = max(1, int(cfg.get("future_num_inference_steps", 1))) + self.backbone.scheduler.set_timesteps(num_steps, device=condition_video.device) + timesteps = self.backbone.scheduler.timesteps + sigma = getattr(self.backbone.scheduler, "sigmas", None) + tri_cfg = self._tri_timestep_cfg(cfg) + feature_timestep = float(tri_cfg.get("feature_timestep", 1.0)) + feature_timestep_tensor = torch.full((1,), feature_timestep, device=condition_video.device, dtype=dtype) + + cond_timestep = torch.ones_like(cond_indicator, dtype=dtype) * float( + cfg.get("conditional_frame_timestep", getattr(self.backbone, "_conditional_frame_timestep", 0.0001)) + ) + in_timestep = ( + cond_indicator.to(dtype) * cond_timestep + + (1.0 - cond_indicator.to(dtype)) * feature_timestep_tensor + ) + padding_mask = latents.new_zeros((1, 1, height, width), dtype=dtype) + cond_mask = cond_mask.to(dtype) + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + in_latents = cond_mask * cond_latents + (1.0 - cond_mask) * latents + model_out = self.backbone.transformer( + hidden_states=in_latents, + timestep=in_timestep, + encoder_hidden_states=prompt_embeds, + condition_mask=cond_mask, + padding_mask=padding_mask, + return_dict=False, + )[0] + + if not getattr(self.backbone, "_intermediate_features", None): + hidden = model_out + else: + hidden = self.backbone._intermediate_features[-1] + hidden = self._flatten_hidden(hidden) + + future_loss = None + pred_future_video = None + if future_video is not None and str(cfg.get("future_loss_type", "flow_matching")).lower() in { + "flow_matching", + "latent_flow_matching", + "rectified_flow", + "rf", + }: + full_video = torch.cat([condition_video, future_video], dim=2) + min_full_frames = 1 + int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + if full_video.shape[2] < min_full_frames: + pad = full_video[:, :, -1:].repeat(1, 1, min_full_frames - full_video.shape[2], 1, 1) + full_video = torch.cat([full_video, pad], dim=2) + + gt_latents = self._encode_video_latents_mean(full_video) + pred_future_len = latents.shape[2] - cond_count + gt_future = gt_latents[:, :, cond_count:cond_count + pred_future_len].to( + device=latents.device, dtype=torch.float32 + ) + + if pred_future_len > 0 and gt_future.numel() > 0: + t_sup = min(pred_future_len, gt_future.shape[2]) + x0_future = gt_future[:, :, :t_sup] + flow_time = self._sample_video_flow_time(latents.shape[0], latents.device, cfg).view(-1, 1, 1, 1, 1) + noise_future = torch.randn_like(x0_future) + xt_future = (1.0 - flow_time) * x0_future + flow_time * noise_future + + xt_full = torch.randn_like(latents.float()) + xt_full[:, :, cond_count:cond_count + t_sup] = xt_future + t_full = latents.new_zeros(cond_indicator.shape, dtype=torch.float32) + t_full[:, :, cond_count:cond_count + t_sup] = flow_time + + v_pred = self.backbone.transformer( + hidden_states=cond_mask * cond_latents + (1.0 - cond_mask) * xt_full.to(dtype), + timestep=cond_indicator.to(dtype) * cond_timestep + (1.0 - cond_indicator.to(dtype)) * t_full.to(dtype), + encoder_hidden_states=prompt_embeds, + condition_mask=cond_mask, + padding_mask=padding_mask, + return_dict=False, + )[0] + v_target = (noise_future - x0_future).to(device=v_pred.device, dtype=v_pred.dtype) + future_loss = F.mse_loss(v_pred[:, :, cond_count:cond_count + t_sup].float(), v_target.float()) + else: + future_loss = latents.new_tensor(0.0) + + if return_pred_future_video: + scheduler_cfg = getattr(self.backbone.scheduler, "config", None) + prediction_type = str(getattr(scheduler_cfg, "prediction_type", "")).lower() + step_model_out = model_out + if prediction_type == "flow_prediction": + gt_velocity = (latents - cond_latents).to(dtype=dtype) * cond_mask + step_model_out = gt_velocity + model_out * (1.0 - cond_mask) + + denoised_latents = self.backbone.scheduler.step(step_model_out, timesteps[0], latents, return_dict=False)[0] + for step_idx, timestep in enumerate(timesteps[1:], start=1): + sigma_t = ( + torch.tensor(sigma[step_idx].item(), device=condition_video.device, dtype=dtype).view(1) + if sigma is not None + else torch.ones(1, device=condition_video.device, dtype=dtype) + ) + in_latents = cond_mask * cond_latents + (1.0 - cond_mask) * denoised_latents + in_timestep = cond_indicator.to(dtype) * cond_timestep + (1.0 - cond_indicator.to(dtype)) * sigma_t + model_out_i = self.backbone.transformer( + hidden_states=in_latents, + timestep=in_timestep, + encoder_hidden_states=prompt_embeds, + condition_mask=cond_mask, + padding_mask=padding_mask, + return_dict=False, + )[0] + if prediction_type == "flow_prediction": + gt_velocity = (denoised_latents - cond_latents).to(dtype=dtype) * cond_mask + model_out_i = gt_velocity + model_out_i * (1.0 - cond_mask) + denoised_latents = self.backbone.scheduler.step( + model_out_i, + timestep, + denoised_latents, + return_dict=False, + )[0] + pred_future_video = self._decode_latents_to_video(denoised_latents) + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + return hidden, future_loss, pred_future_video + + def _sample_dit4dit_future_video( + self, + condition_sequences: List[List], + instructions: List[str], + generation_cfg: dict, + ) -> torch.Tensor: + video_cfg = self._video_cfg() + size_cfg = { + "height": generation_cfg.get("height", video_cfg.get("height", getattr(self.backbone, "_height", 704))), + "width": generation_cfg.get("width", video_cfg.get("width", getattr(self.backbone, "_width", 1280))), + } + height, width = self._resolve_video_size(size_cfg, condition_sequences) + condition_video = self._preprocess_video_sequence(condition_sequences, height, width) + + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + num_frames_out = int(generation_cfg.get("num_frames", 1 + temporal_factor)) + num_frames_out = max(num_frames_out, condition_video.shape[2], 1 + temporal_factor) + + dtype = self.backbone.transformer.dtype + prompt_embeds = self.backbone._encode_text(instructions).to(device=condition_video.device, dtype=dtype) + latents, cond_latents, cond_mask, cond_indicator, _ = self._prepare_dit4dit_latents( + condition_video=condition_video, + num_frames_out=num_frames_out, + height=height, + width=width, + dtype=dtype, + ) + + num_steps = int(generation_cfg.get("num_inference_steps", video_cfg.get("future_num_inference_steps", 1))) + num_steps = max(1, num_steps) + self.backbone.scheduler.set_timesteps(num_steps, device=condition_video.device) + timesteps = self.backbone.scheduler.timesteps + sigmas = getattr(self.backbone.scheduler, "sigmas", None) + + cond_timestep = torch.ones_like(cond_indicator, dtype=dtype) * float( + generation_cfg.get( + "conditional_frame_timestep", + video_cfg.get( + "conditional_frame_timestep", + getattr(self.backbone, "_conditional_frame_timestep", 0.0001), + ), + ) + ) + padding_mask = latents.new_zeros((1, 1, height, width), dtype=dtype) + cond_mask = cond_mask.to(dtype) + + scheduler_cfg = getattr(self.backbone.scheduler, "config", None) + prediction_type = str(getattr(scheduler_cfg, "prediction_type", "")).lower() + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + sample_latents = latents + for step_idx, timestep in enumerate(timesteps): + sigma_t = ( + torch.tensor(sigmas[step_idx].item(), device=condition_video.device, dtype=dtype).view(1) + if sigmas is not None + else torch.ones(1, device=condition_video.device, dtype=dtype) + ) + in_latents = cond_mask * cond_latents + (1.0 - cond_mask) * sample_latents + in_timestep = cond_indicator.to(dtype) * cond_timestep + (1.0 - cond_indicator.to(dtype)) * sigma_t + model_out = self.backbone.transformer( + hidden_states=in_latents, + timestep=in_timestep, + encoder_hidden_states=prompt_embeds, + condition_mask=cond_mask, + padding_mask=padding_mask, + return_dict=False, + )[0] + if prediction_type == "flow_prediction": + gt_velocity = (sample_latents - cond_latents).to(dtype=dtype) * cond_mask + model_out = gt_velocity + model_out * (1.0 - cond_mask) + sample_latents = self.backbone.scheduler.step(model_out, timestep, sample_latents, return_dict=False)[0] + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + return self._decode_latents_to_video(sample_latents) + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + condition_sequences, future_sequences, instructions = self._split_condition_future(examples) + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + condition_sequences = [resize_images(seq, target_size=train_obs_image_size) for seq in condition_sequences] + if future_sequences is not None: + future_sequences = [resize_images(seq, target_size=train_obs_image_size) for seq in future_sequences] + + video_cfg = self._video_cfg() + training_mode = str(video_cfg.get("training", "joint")).lower() + use_video_loss = bool(video_cfg.get("enabled", True)) and training_mode in {"joint", "video"} + + with torch.autocast("cuda", dtype=torch.bfloat16): + last_hidden, future_video_loss, _ = self._dit4dit_cosmos_forward( + condition_sequences=condition_sequences, + instructions=instructions, + future_sequences=future_sequences if use_video_loss else None, + return_pred_future_video=False, + ) + + if training_mode == "video": + if future_video_loss is None: + raise ValueError("dit4dit_video.training='video' requires future frames in image or future_image.") + return {"action_loss": future_video_loss, "future_video_loss": future_video_loss.detach()} + + actions = [example["action"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "trainer") + else self.config.framework.action_model.get("repeated_diffusion_steps", 4) + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + state = self._align_state_dim(state) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :] + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + embodiment_tag_repeated = None + if embodiment_tag is not None: + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64).view(-1) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) + + action_loss = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + ) + + output = {"action_loss": action_loss} + if future_video_loss is not None: + future_video_loss_scaled = future_video_loss * float(video_cfg.get("future_loss_weight", 1.0)) + output["perceiver_action_loss"] = action_loss.detach() + output["future_video_loss"] = future_video_loss.detach() + output["future_video_loss_scaled"] = future_video_loss_scaled.detach() + output["action_loss"] = action_loss + future_video_loss_scaled + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + condition_sequences, _, instructions = self._split_condition_future(examples) + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + condition_sequences = [resize_images(seq, target_size=train_obs_image_size) for seq in condition_sequences] + + generation_cfg = self._get_future_image_generation_cfg(kwargs) + return_pred_future_video = bool(generation_cfg.get("enabled", True)) + + with torch.autocast("cuda", dtype=torch.bfloat16): + last_hidden, _, _ = self._dit4dit_cosmos_forward( + condition_sequences=condition_sequences, + instructions=instructions, + future_sequences=None, + return_pred_future_video=False, + ) + + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + state = self._align_state_dim(state) + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + if return_pred_future_video: + with torch.autocast("cuda", dtype=torch.bfloat16): + pred_video = self._sample_dit4dit_future_video( + condition_sequences=condition_sequences, + instructions=instructions, + generation_cfg=generation_cfg, + ) + if bool(generation_cfg.get("return_full_video", False)): + output["pred_future_images"] = [sample.detach().cpu() for sample in pred_video] + else: + frame_idx = int(generation_cfg.get("future_frame_index", -1)) + output["pred_future_images"] = pred_video[:, frame_idx].detach().cpu() + return output diff --git a/starVLA/model/framework/WM4A/CosmoPredict25PerceiverFutureImage.py b/starVLA/model/framework/WM4A/CosmoPredict25PerceiverFutureImage.py new file mode 100644 index 0000000000000000000000000000000000000000..449228c6487adf755c6cc968d6ba75294d09e8e1 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict25PerceiverFutureImage.py @@ -0,0 +1,727 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5-Perceiver with future-image prediction. + +This framework keeps the existing Cosmos hidden-state -> Perceiver action +path, and additionally runs the Cosmos2.5 generation/decoder path during +inference to return the image predicted after the action chunk horizon. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25Perceiver import ( + CosmoPredict25_Perceiver, + CosmoPredict25PerceiverDefaultConfig, +) +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict25PerceiverFutureImageDefaultConfig(CosmoPredict25PerceiverDefaultConfig): + """Cosmos-Predict2.5-Perceiver + future-image defaults.""" + + name: str = "CosmoPredict25PerceiverFutureImage" + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 93, + "num_inference_steps": 36, + "guidance_scale": 7.0, + "output_type": "pil", + "height": 704, + "width": 1280, + "max_sequence_length": 512, + "conditional_frame_timestep": 0.1, + "num_latent_conditional_frames": 2, + "conditioning_mode": "auto", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + }) + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverFutureImage") +class CosmoPredict25_Perceiver_FutureImage(CosmoPredict25_Perceiver): + """Cosmos-Predict2.5 hidden-state action head plus generated future images.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + print('################# CosmoPredict25_Perceiver_FutureImage-1') + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict25PerceiverFutureImageDefaultConfig, config) + + # 1. 初始化CosmosPredictr2.5类作为backbone + # WM4A/starVLA/model/modules/world_model/CosmoPredict25.py + self.backbone = get_world_model(config=self.config) + # print(type(self.backbone)) # + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + # print(wm_hidden) # 2048 + + # 2. 初始化FlowmatchingActionHead作为action-head + # WM4A/starVLA/model/modules/action_model/PerceiverHead.py + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + # print(type(self.action_model)) # + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + # print(self.future_action_window_size) # 15 + # print(self.past_action_window_size) # 0 + # print(self.chunk_len) # 16 + # print(self.state_dim) # 64 + print('################# CosmoPredict25_Perceiver_FutureImage-2') + + @staticmethod + def _as_sequence(images): + return list(images) if isinstance(images, (list, tuple)) else [images] + + def _align_state_dim(self, state: torch.Tensor) -> torch.Tensor: + if state is None or self.state_dim is None: + return state + target_dim = int(self.state_dim) + current_dim = state.shape[-1] + if current_dim == target_dim: + return state + if current_dim > target_dim: + return state[..., :target_dim] + + pad_shape = (*state.shape[:-1], target_dim - current_dim) + padding = state.new_zeros(pad_shape) + return torch.cat([state, padding], dim=-1) + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.lower() in {"1", "true", "yes", "on"} + return bool(value) + + def _future_training_cfg(self) -> dict: + return dict(self.config.framework.get("future_image_training", {})) + + def _sample_train_times(self, batch_size: int, device: torch.device, distribution: str) -> torch.Tensor: + distribution = str(distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported future_image_training.train_time_distribution={distribution!r}") + + @staticmethod + def _shift_time(time: torch.Tensor, shift: float) -> torch.Tensor: + return shift * time / (1.0 + (shift - 1.0) * time) + + def _latent_frame_count(self, raw_frame_count: int) -> int: + if hasattr(self, 'backbone'): + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + else: + temporal_factor = int(getattr(self.wan_interface, "vae_scale_factor_temporal", 4)) + return (int(raw_frame_count) - 1) // temporal_factor + 1 + + def _build_future_video_sequences(self, batch_images: List, future_images: List) -> tuple[List[List], List[int], List[int]]: + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-1') + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + condition_counts = [] + sample_counts = [] + # print(temporal_factor) # 4 + # print(len(batch_images)) # 8 + # print(len(future_images)) # 8 + + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + # print(len(current_sequence)) # 1 + # print(len(future_sequence)) # 1 + if not current_sequence or not future_sequence: + raise ValueError("future image training needs both current image and future_image.") + + future_frame = future_sequence[0] + # print(type(future_frame)) # + raw_sequence = current_sequence + [future_frame] * temporal_factor + raw_sequences.append(raw_sequence) + + condition_count = self._latent_frame_count(len(current_sequence)) + sample_count = self._latent_frame_count(len(raw_sequence)) + # print(condition_count) # 1 + # print(sample_count) # 2 + condition_counts.append(condition_count) + sample_counts.append(sample_count) + + # print('################# CosmoPredict25_Perceiver_FutureImage._build_future_video_sequences-2') + return raw_sequences, condition_counts, sample_counts + + # 训练时 + # future_image支路,self.backbone.transformer() + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-1') + if "future_image" not in examples[0]: + return None + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + # 1. 将输入数据【当前观测】和【未来观测】预处理为可以被CosmosPredict接受的形状 + # batch_size=8时,batch_images、future_images和instructions都是长度为8的列表,分别包含当前观测图像、未来观测图像和文本prompt; + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + # print(type(batch_images[0])) # + # print(type(future_images[0])) # + # print(type(instructions[0])) # + + # 我们将每个样本对应的当前和未来图像组装为raw_sequence=concat[obs,future_obs,future_obs,future_obs,future_obs] + # 而raw_sequences也是由8个这样的raw_sequence组成的列表, + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + # print(len(raw_sequences)) # 8 + # print(len(raw_sequences[0])) # 5 + # print(raw_sequences[0][0]) # + # print(condition_counts) # [1, 1, 1, 1, 1, 1, 1, 1] + # print(sample_counts) # [2, 2, 2, 2, 2, 2, 2, 2] + + # 2. 调用CosmosPredict的文本和视觉tokenizer, + # 将每个样本的prompt编码为prompt_emb(512,100352),将raw_sequence编码为clean_latents(16,2,28,28), + # 从mask上来看,1个image和4个future_image分别被编码为了两个(16,28,28),分别记为obs_tokens和future_obs_tokens,二者拼起来就是clean_latents + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + # print(prompt_embeds.shape) # torch.Size([8, 512, 100352]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(dtype) # torch.bfloat16 + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(condition_mask.shape) # torch.Size([8, 1, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + # print(cond_indicator.shape) # torch.Size([8, 1, 2, 1, 1]) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + # 3. 在clean_latents中,对obs_tokens部分保持不变、对future_obs_tokens部分加噪 + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + # print(train_time.shape) # torch.Size([8]) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + # print(flow_time.shape) # torch.Size([8]) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + # print(clean_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + noise = torch.randn_like(clean_latents) + # print(noise.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_time.shape) # torch.Size([8, 1, 1, 1, 1]) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + # print(noisy_latents.shape) # torch.Size([8, 16, 2, 28, 28]) + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + hidden_states = torch.where(target_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + # print(hidden_states.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 4. 对future_obs_tokens部分,计算其去噪目标target_velocity + target_velocity = noise.float() - clean_latents.float() + # print(target_velocity.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 5. 计算timestep和padding_mask + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + # print(cond_timestep) # 0.1 + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + # print(timestep.shape) # torch.Size([8, 1, 2, 1, 1]) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + # print(padding_height) # 224 + # print(padding_width) # 224 + # print(padding_mask.shape) # torch.Size([1, 1, 224, 224]) + + # 7. CosmosPredict前向传播 + # 以prompt_emb(8,512,100352)和clean_latents(8,16,2,28,28)作为输入, + # 其中clean_latents包含【当前观测的tokens1】和【未来观测加噪后的tokens2】这两部分,CosmosPredict采用了一个经典的DiT架构,其中, + # self-attn使得tokens2能够看到tokens1中真实的当前观测中是视觉信息、cross-attn使得tokens2能够理解prompt_emb中的人类指令信息, + # 这两部分信息一起作为tokens2部分的降噪条件,得益于loss_mask,最终参与计算future_image_loss的只有tokens2部分, + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + # print(type(self.backbone)) # + # print(pred.shape) # torch.Size([8, 16, 2, 28, 28]) + + # 8. 计算future-image-loss + # print(target_mask.shape) # torch.Size([8, 1, 2, 1, 1]) + loss_mask = target_mask.expand(batch_size, channels, num_latents, height, width) + # print(loss_mask.shape) # torch.Size([8, 16, 2, 28, 28]) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + # print(future_loss.shape) # torch.Size([8, 16, 2, 28, 28]) + future_image_loss = (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + # print(future_image_loss) # tensor(0.3386, device='cuda:0', grad_fn=) + # print('################# CosmoPredict25_Perceiver_FutureImage._cosmos25_future_image_loss-2') + return future_image_loss + + # 训练时 + # 生成future_image和action + # 最终返回的是total_loss=action_loss+future_image_loss*loss_weight + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-1') + # 1. 调用CosmosPredict+ActionHead生成action_loss,这个函数定义在父类中 + output = super().forward(examples=examples, **kwargs) + action_loss = output["action_loss"] + + # 2. 调用CosmosPredict生成future_image_loss + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is None: + return output + + # 3. 最终返回的是total_loss=action_loss+future_image_loss*loss_weight + loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0)) + # print(loss_weight) # 1.0 + output["perceiver_action_loss"] = action_loss.detach() + output["future_image_loss"] = future_image_loss.detach() + output["action_loss"] = action_loss + future_image_loss * loss_weight + # print('################# CosmoPredict25_Perceiver_FutureImage.forward-2') + return output + + def _get_future_image_generation_cfg(self, kwargs: dict) -> dict: + cfg = dict(self.config.framework.get("future_image_generation", {})) + override = kwargs.get("future_image_generation", None) + if override: + cfg.update(dict(override)) + + if "decode_future_images" in kwargs: + cfg["enabled"] = kwargs["decode_future_images"] + if "num_ddim_steps" in kwargs and "num_inference_steps" not in kwargs: + cfg["num_inference_steps"] = kwargs["num_ddim_steps"] + + for key in ( + "enabled", + "num_frames", + "num_inference_steps", + "guidance_scale", + "output_type", + "height", + "width", + "max_sequence_length", + "conditional_frame_timestep", + "num_latent_conditional_frames", + "conditioning_mode", + "max_samples", + "return_full_video", + "future_frame_index", + "negative_prompt", + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + ): + if key in kwargs: + cfg[key] = kwargs[key] + return cfg + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + mode = str(cfg.pop("conditioning_mode", "auto")).lower() + _wm = self.backbone if hasattr(self, "backbone") else self.wan_interface + height = cfg.pop("height", getattr(_wm, "_height", 704)) + width = cfg.pop("width", getattr(_wm, "_width", 1280)) + heights = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "prompt": instructions, + "height": heights[0], + "width": heights[1], + "num_frames": cfg.pop("num_frames", 93), + "num_inference_steps": cfg.pop("num_inference_steps", 36), + "guidance_scale": cfg.pop("guidance_scale", 7.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + "conditional_frame_timestep": cfg.pop("conditional_frame_timestep", 0.1), + "num_latent_conditional_frames": cfg.pop("num_latent_conditional_frames", 2), + } + + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + if mode == "image": + generation_inputs["image"] = [self._as_sequence(images)[-1] for images in batch_images] + elif mode == "video": + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + elif mode == "auto": + if any(len(self._as_sequence(images)) > 1 for images in batch_images): + generation_inputs["video"] = [self._as_sequence(images) for images in batch_images] + else: + generation_inputs["image"] = [self._as_sequence(images)[0] for images in batch_images] + else: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + passthrough_keys = ( + "generator", + "latents", + "prompt_embeds", + "negative_prompt_embeds", + "num_videos_per_prompt", + "callback_on_step_end", + "callback_on_step_end_tensor_inputs", + ) + for key in passthrough_keys: + if key in cfg and cfg[key] is not None: + generation_inputs[key] = cfg.pop(key) + + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs + + @staticmethod + def _is_auto_size(value) -> bool: + return isinstance(value, str) and value.lower() == "auto" + + @staticmethod + def _round_up_to_multiple(value: int, multiple: int) -> int: + return int(((max(1, value) + multiple - 1) // multiple) * multiple) + + @staticmethod + def _image_size(image) -> tuple[int, int]: + size = getattr(image, "size", None) + if isinstance(size, (list, tuple)) and len(size) >= 2: + return int(size[0]), int(size[1]) + if torch.is_tensor(image): + shape = tuple(image.shape) + if len(shape) >= 3 and shape[0] in (1, 3, 4): + return int(shape[-1]), int(shape[-2]) + if len(shape) >= 2: + return int(shape[1]), int(shape[0]) + array = np.asarray(image) + if array.ndim < 2: + raise ValueError(f"Cannot infer image size from shape {array.shape}") + return int(array.shape[1]), int(array.shape[0]) + + def _resolve_generation_size_values(self, batch_images: List, height, width) -> tuple: + if not self._is_auto_size(height) and not self._is_auto_size(width): + return int(height), int(width) + + resolved_heights = [] + resolved_widths = [] + _wm = self.backbone if hasattr(self, "backbone") else self.wan_interface + spatial_multiple = int(getattr(_wm, "vae_scale_factor_spatial", 16)) + for images in batch_images: + image_sequence = self._as_sequence(images) + frame_sizes = [self._image_size(image) for image in image_sequence] + if not frame_sizes: + raise ValueError("Cannot infer auto generation size from empty image sequence.") + + sample_height = max(frame_height for _, frame_height in frame_sizes) if self._is_auto_size(height) else int(height) + if self._is_auto_size(width): + max_aspect = max(frame_width / max(1, frame_height) for frame_width, frame_height in frame_sizes) + sample_width = self._round_up_to_multiple(round(sample_height * max_aspect), spatial_multiple) + else: + sample_width = int(width) + resolved_heights.append(int(sample_height)) + resolved_widths.append(int(sample_width)) + + height_value = resolved_heights if len(set(resolved_heights)) > 1 else resolved_heights[0] + width_value = resolved_widths if len(set(resolved_widths)) > 1 else resolved_widths[0] + return height_value, width_value + + @staticmethod + def _extract_videos(generation_output): + if hasattr(generation_output, "frames"): + return generation_output.frames + if hasattr(generation_output, "videos"): + return generation_output.videos + if hasattr(generation_output, "images"): + return generation_output.images + if isinstance(generation_output, tuple): + return generation_output[0] + return generation_output + + def _select_future_images(self, generation_output, future_frame_index: int, return_full_video: bool): + videos = self._extract_videos(generation_output) + if return_full_video: + return videos + + if isinstance(videos, (list, tuple)) and videos and isinstance(videos[0], Image.Image): + return [videos[future_frame_index]] + + future_images = [] + for sample in videos: + if torch.is_tensor(sample): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, np.ndarray): + if sample.ndim >= 4: + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + elif isinstance(sample, (list, tuple)): + future_images.append(sample[future_frame_index]) + else: + future_images.append(sample) + return future_images + + @staticmethod + def _slice_generation_value(key: str, value, index: int, batch_size: int): + if value is None: + return None + if key in {"height", "width"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if key in {"image", "video"} and isinstance(value, (list, tuple)) and len(value) == batch_size: + return value[index] + if torch.is_tensor(value) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, np.ndarray) and value.shape[0] == batch_size: + return value[index:index + 1] + if isinstance(value, list) and len(value) == batch_size: + return [value[index]] + if isinstance(value, tuple) and len(value) == batch_size: + return (value[index],) + return value + + # 推理时 + # future_image支路,self.backbone.generate() + def _generate_future_images(self, generation_inputs: dict, batch_size: int, max_samples: int, future_frame_index: int, return_full_video: bool): + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-1') + if max_samples is None or max_samples < 0: + sample_count = batch_size + else: + sample_count = min(batch_size, max(0, int(max_samples))) + # print(sample_count) # 1 + + # print(generation_inputs) + """ + { + 'prompt': [ + 'Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick the tomato from the tray and place it in the cardboard box.', + 'Subtask: unlocked_waist: pick up the milk, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the bell pepper from the cutting board and place it in the pot.', + 'Subtask: unlocked_waist: pick up the potato, place it into the microwave and close the microwave.', + 'Subtask: unlocked_waist: pick the tomato from the placemat and place it in the tiered shelf.', + 'Subtask: unlocked_waist: pick the can from the cutting board and place it in the basket.', + 'Subtask: unlocked_waist: pick up the wine, place it into the cabinet and close the cabinet.' + ], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': [ + , + , + , + , + , + , + , + + ] + } + """ + pred_future_images = [] + for sample_idx in range(sample_count): + + # 1. CosmosPredict:构建输入 + # print(sample_idx) # 0 + single_inputs = { + key: self._slice_generation_value(key, value, sample_idx, batch_size) + for key, value in generation_inputs.items() + } + # print(single_inputs) + """ + { + 'prompt': ['Subtask: unlocked_waist: pick the bell pepper from the plate and place it in the cardboard box.'], + 'height': 224, + 'width': 224, + 'num_frames': 93, + 'num_inference_steps': 20, + 'guidance_scale': 7.0, + 'output_type': 'pil', + 'return_dict': True, + 'max_sequence_length': 512, + 'conditional_frame_timestep': 0.1, + 'num_latent_conditional_frames': 2, + 'image': + } + """ + + # 2. CosmosPredict:前向推理 + generation_output = self.backbone.generate(**single_inputs) if hasattr(self, "backbone") else self.wan_interface.generate(**single_inputs) + # print(type(self.backbone)) # + # print(type(generation_output)) # + # print(future_frame_index) # -1 + # print(return_full_video) # False + sample_images = self._select_future_images( + generation_output, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # print(sample_images) # [] + if isinstance(sample_images, (list, tuple)): + pred_future_images.extend(sample_images) + else: + pred_future_images.append(sample_images) + # print('################# CosmoPredict25_Perceiver_FutureImage._generate_future_images-2') + return pred_future_images + + # 推理时 + # action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action() + @torch.inference_mode() + def predict_action(self, examples: List[dict], is_run_parallel_eval_mxk: bool = False, **kwargs) -> dict: + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-1') + if type(examples) is not list: + examples = [examples] + + # 1. CosmosPredict:构建输入 + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # print(train_obs_image_size) # None + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + state = [example["state"] for example in examples] if "state" in examples[0] else None + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + # print(state.shape) # torch.Size([8, 1, 64]) + state = self._align_state_dim(state) + # print(state.shape) # torch.Size([8, 1, 64]) + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + # print(embodiment_tag.shape) # torch.Size([8]) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + + # 4. ActionHead:前向推理 + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + # print(type(self.action_model)) # + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + # print(state.shape) # torch.Size([8, 1, 64]) + # print(embodiment_tag.shape) # torch.Size([8]) + # print(pred_actions.shape) # torch.Size([8, 16, 32]) + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + # 5. 若enabled为True,只生成action即可返回;若enabled为False,则需要 + generation_cfg = self._get_future_image_generation_cfg(kwargs) + is_enabled = generation_cfg.pop("enabled", True) + # print(is_enabled) # True + if not bool(is_enabled): + # print('is_enabled is False') + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output + + return_full_video = bool(generation_cfg.pop("return_full_video", False)) + future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + max_samples = int(generation_cfg.pop("max_samples", 1)) + generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + output["pred_future_images"] = self._generate_future_images( + generation_inputs, + batch_size=len(examples), + max_samples=max_samples, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + # When called from websocket server, convert PIL Images to numpy arrays + # for msgpack serialization; otherwise keep PIL Image format + if is_run_parallel_eval_mxk and "pred_future_images" in output: + output["pred_future_images"] = [ + np.array(img) if isinstance(img, Image.Image) else img + for img in output["pred_future_images"] + ] + # print('################# CosmoPredict25_Perceiver_FutureImage.predict_action-2') + return output diff --git a/starVLA/model/framework/WM4A/CosmoPredict25PerceiverMaskedFutureImage.py b/starVLA/model/framework/WM4A/CosmoPredict25PerceiverMaskedFutureImage.py new file mode 100644 index 0000000000000000000000000000000000000000..fc125d5b196b82e0e9ec42e8587ce1461a794d98 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict25PerceiverMaskedFutureImage.py @@ -0,0 +1,196 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""Cosmos-Predict2.5 Perceiver with masked future-image denoising. + +This variant keeps the existing action path and Cosmos future-image objective, +but builds a latent-grid change mask from the current/future RGB pair. The mask +can focus the loss on changed regions and optionally add noise only inside those +regions, turning future-image training into an inpainting-style objective. +""" + +from __future__ import annotations + +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import ( + CosmoPredict25_Perceiver_FutureImage, +) +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PerceiverMaskedFutureImage") +class CosmoPredict25_Perceiver_MaskedFutureImage(CosmoPredict25_Perceiver_FutureImage): + """Future-image training that denoises mostly/only changed regions.""" + + @staticmethod + def _pil_rgb_to_tensor(image, size: tuple[int, int] | None = None) -> torch.Tensor: + image = to_pil_preserve(image).convert("RGB") + if size is not None and image.size != size: + image = image.resize(size) + array = np.asarray(image, dtype=np.float32) / 255.0 + return torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0) + + def _build_latent_change_masks( + self, + batch_images: List, + future_images: List, + latent_height: int, + latent_width: int, + training_cfg: dict, + device: torch.device, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Return binary denoise mask and soft loss weights at latent resolution.""" + top_ratio = float(training_cfg.get("change_mask_top_ratio", 0.25)) + top_ratio = min(max(top_ratio, 1e-4), 1.0) + static_weight = float(training_cfg.get("change_mask_static_weight", 0.05)) + static_weight = min(max(static_weight, 0.0), 1.0) + soft_loss = self._as_bool(training_cfg.get("change_mask_soft_loss", True)) + + binary_masks = [] + loss_weights = [] + for images, future_image in zip(batch_images, future_images): + current_sequence = self._as_sequence(images) + future_sequence = self._as_sequence(future_image) + current_frame = current_sequence[-1] + target_frame = future_sequence[0] + + current = self._pil_rgb_to_tensor(current_frame) + target = self._pil_rgb_to_tensor(target_frame, size=to_pil_preserve(current_frame).size) + diff = (target - current).abs().mean(dim=1, keepdim=True) + score = F.interpolate(diff, size=(latent_height, latent_width), mode="area") + flat = score.flatten(1) + max_score = flat.amax(dim=1).view(-1, 1, 1, 1).clamp_min(1e-6) + normalized = (score / max_score).clamp(0.0, 1.0) + + k = max(1, int(flat.shape[1] * top_ratio)) + threshold = flat.topk(k, dim=1).values[:, -1].view(-1, 1, 1, 1) + binary = (score >= threshold).float() + + weight_source = normalized if soft_loss else binary + loss_weight = static_weight + (1.0 - static_weight) * weight_source + binary_masks.append(binary) + loss_weights.append(loss_weight) + + binary_mask = torch.cat(binary_masks, dim=0).to(device=device, dtype=torch.float32) + loss_weight = torch.cat(loss_weights, dim=0).to(device=device, dtype=torch.float32) + return binary_mask, loss_weight + + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + if "future_image" not in examples[0]: + return None + + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + if not self._as_bool(training_cfg.get("change_mask_enabled", True)): + return super()._cosmos25_future_image_loss(examples) + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents, _, _ = self.backbone._encode_images(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + + condition_mask = clean_latents.new_zeros((batch_size, 1, num_latents, height, width)) + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + cond_indicator = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + condition_mask[batch_idx, :, :condition_count] = 1.0 + cond_indicator[batch_idx, :, :condition_count] = 1.0 + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + + change_binary, change_loss_weight = self._build_latent_change_masks( + batch_images=batch_images, + future_images=future_images, + latent_height=height, + latent_width=width, + training_cfg=training_cfg, + device=device, + ) + change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype) + change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32) + + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + target_time = flow_time.view(batch_size, 1, 1, 1, 1).to(device=device, dtype=clean_latents.dtype) + + noise = torch.randn_like(clean_latents) + noisy_latents = clean_latents * (1.0 - target_time) + noise * target_time + target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width) + + use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", True)) + use_static_conditioning = use_masked_denoising and self._as_bool( + training_cfg.get("condition_static_regions", True) + ) + + if use_masked_denoising: + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) * change_binary + else: + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) + hidden_states = torch.where(denoise_mask.to(dtype=torch.bool), noisy_latents, clean_latents) + target_velocity = noise.float() - clean_latents.float() + + if use_static_conditioning: + static_target_mask = target_spatial_mask.to(dtype=clean_latents.dtype) * (1.0 - change_binary) + condition_mask = torch.maximum(condition_mask, static_target_mask) + + cond_timestep = float(getattr(self.backbone, "_conditional_frame_timestep", 0.1)) + timestep = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1)) + timestep = timestep + cond_indicator.to(dtype=clean_latents.dtype) * cond_timestep + timestep = torch.where(target_mask.to(dtype=torch.bool), target_time.expand_as(timestep), timestep) + + padding_height = int(height * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_width = int(width * getattr(self.backbone, "vae_scale_factor_spatial", 16)) + padding_mask = clean_latents.new_zeros((1, 1, padding_height, padding_width), dtype=dtype) + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + condition_mask=condition_mask.to(dtype), + padding_mask=padding_mask, + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + temporal_loss_mask = target_spatial_mask.expand(batch_size, channels, num_latents, height, width) + if use_static_conditioning: + change_loss_weight = change_loss_weight * change_binary.float() + spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width) + spatial_loss_weight = spatial_loss_weight.expand(batch_size, channels, num_latents, height, width) + loss_mask = temporal_loss_mask * spatial_loss_weight + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) diff --git a/starVLA/model/framework/WM4A/CosmoPredict25Policy.py b/starVLA/model/framework/WM4A/CosmoPredict25Policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8d4c9aa2375d9b442e3473dd68e3349577390771 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict25Policy.py @@ -0,0 +1,719 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2.5 Policy Framework. + +This follows the Cosmos-Predict2.5 policy recipe: actions are injected into +the Cosmos latent video sequence as an extra latent frame, and the Cosmos DiT +is trained with rectified flow / flow matching to predict latent velocity. + +Scope: + - blank/proprio/current observation image/video + language -> condition latents + - action chunk -> one injected latent frame + - optional future image latent frames + - RF target velocity is noise - clean_latent + +It keeps the official Cosmos Policy RF/FM training target and denoising loop, +while adapting the frame layout to the fields available in starVLA batches. +""" + +import math +import os +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict25PolicyDefaultConfig: + """Cosmos-Predict2.5 latent-action policy defaults.""" + + name: str = "CosmoPredict25Policy" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "nvidia/Cosmos-Predict2.5-2B", + "revision": "diffusers/base/post-trained", + "height": 704, + "width": 1280, + "conditional_frame_timestep": 0.0, + }) + + # Kept for shared config compatibility. + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "nvidia/Cosmos-Predict2.5-2B", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + }) + + policy: dict = field(default_factory=lambda: { + "train_time_distribution": "logitnormal", + "train_time_weight": "uniform", + "shift": 5.0, + "action_loss_weight": 16.0, + "future_image_loss_weight": 1.0, + "num_inference_steps": 5, + "action_inference_mode": "euler", + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25Policy") +class CosmoPredict25_Policy(baseframework): + """Cosmos-Predict2.5 with latent-frame action injection.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict25PolicyDefaultConfig, config) + self.backbone = get_world_model(config=self.config) + self._disable_backbone_feature_hooks() + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.action_dim = self.config.framework.action_model.action_dim + + policy_cfg = self.config.framework.get("policy", {}) + self.train_time_distribution = policy_cfg.get("train_time_distribution", "logitnormal") + self.train_time_weight = policy_cfg.get("train_time_weight", "uniform") + self.shift = float(policy_cfg.get("shift", 5.0)) + self.action_loss_weight = float(policy_cfg.get("action_loss_weight", 16.0)) + self.future_image_loss_weight = float(policy_cfg.get("future_image_loss_weight", 1.0)) + self.num_inference_steps = int(policy_cfg.get("num_inference_steps", 5)) + self.action_inference_mode = str(policy_cfg.get("action_inference_mode", "euler")) + self._wm_debug_count = 0 + + def _disable_backbone_feature_hooks(self) -> None: + for hook in getattr(self.backbone, "_hooks", []): + hook.remove() + if hasattr(self.backbone, "_hooks"): + self.backbone._hooks.clear() + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + def _begin_wm_debug_trace(self) -> bool: + if os.getenv("STARVLA_WM_DEBUG", "0").lower() not in {"1", "true", "yes", "on"}: + return False + max_traces = int(os.getenv("STARVLA_WM_DEBUG_MAX", "6")) + if self._wm_debug_count >= max_traces: + return False + self._wm_debug_count += 1 + return True + + @staticmethod + def _tensor_stats(name: str, tensor: torch.Tensor) -> str: + tensor = tensor.detach().float() + return ( + f"{name}:shape={tuple(tensor.shape)}," + f"mean={tensor.mean().item():.4g},std={tensor.std(unbiased=False).item():.4g}," + f"min={tensor.min().item():.4g},max={tensor.max().item():.4g}," + f"nan={torch.isnan(tensor).any().item()},inf={torch.isinf(tensor).any().item()}" + ) + + def _log_wm_debug(self, enabled: bool, label: str, **tensors) -> None: + if not enabled: + return + parts = [f"[WM_DEBUG_VERSION=20260506_step_trace] {type(self).__name__} {label}"] + for name, tensor in tensors.items(): + if tensor is not None: + parts.append(self._tensor_stats(name, tensor)) + print(" | ".join(parts), flush=True) + + def _select_action_chunk(self, actions) -> torch.Tensor: + actions = torch.tensor(np.array(actions), dtype=torch.float32) + return actions[:, -(self.future_action_window_size + 1):, :] + + @staticmethod + def _latent_slot_count(latents: torch.Tensor) -> int: + _, channels, _, height, width = latents.shape + return channels * height * width + + def _tensor_to_latent_frame(self, values: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + batch_size, channels, _, height, width = latents.shape + flat_values = values.reshape(batch_size, -1).to(device=latents.device, dtype=latents.dtype) + slot_count = self._latent_slot_count(latents) + repeat_factor = math.ceil(slot_count / flat_values.shape[1]) + tiled_values = flat_values.repeat(1, repeat_factor)[:, :slot_count] + return tiled_values.reshape(batch_size, channels, height, width) + + def _actions_to_latent_frame(self, actions: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + return self._tensor_to_latent_frame(actions, latents) + + def _state_to_latent_frame(self, states: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + return self._tensor_to_latent_frame(states, latents) + + def _latent_frame_to_actions(self, action_frame: torch.Tensor, action_shape) -> torch.Tensor: + batch_size = action_frame.shape[0] + flat_dim = int(np.prod(action_shape[1:])) + flat_frame = action_frame.reshape(batch_size, -1) + slot_count = flat_frame.shape[1] + action_indices = torch.arange(slot_count, device=flat_frame.device) % flat_dim + + action_sum = flat_frame.new_zeros((batch_size, flat_dim)) + action_count = flat_frame.new_zeros((batch_size, flat_dim)) + action_sum.scatter_add_(1, action_indices.expand(batch_size, -1), flat_frame) + action_count.scatter_add_(1, action_indices.expand(batch_size, -1), torch.ones_like(flat_frame)) + return (action_sum / action_count.clamp_min(1.0)).reshape(batch_size, *action_shape[1:]) + + def _project_action_frame_to_action_manifold(self, action_frame: torch.Tensor, latents: torch.Tensor, action_shape) -> torch.Tensor: + actions = self._latent_frame_to_actions(action_frame.float(), action_shape) + return self._actions_to_latent_frame(actions, latents).to(dtype=action_frame.dtype) + + def _sample_train_times(self, batch_size: int, device: torch.device) -> torch.Tensor: + distribution = str(self.train_time_distribution).lower() + if distribution == "logitnormal": + return torch.sigmoid(torch.randn(batch_size, device=device, dtype=torch.float32)) + if distribution == "uniform": + return torch.rand(batch_size, device=device, dtype=torch.float32) + raise ValueError(f"Unsupported train_time_distribution={self.train_time_distribution!r}") + + def _shift_time(self, time: torch.Tensor, shift: Optional[float] = None) -> torch.Tensor: + shift = self.shift if shift is None else float(shift) + return shift * time / (1.0 + (shift - 1.0) * time) + + def _time_to_timestep(self, time: torch.Tensor, shift: Optional[float] = None) -> torch.Tensor: + return self._shift_time(time, shift=shift) + + @staticmethod + def _sigma_to_timestep(sigma: torch.Tensor) -> torch.Tensor: + return sigma + + def _flow_inference_schedule(self, num_steps: int, device: torch.device, shift: Optional[float] = None): + base_times = torch.linspace(1.0, 0.0, num_steps + 1, device=device, dtype=torch.float32) + sigmas = self._shift_time(base_times, shift=shift) + return sigmas + + @staticmethod + def _stack_optional_tensor(values, device: torch.device, dtype: torch.dtype) -> Optional[torch.Tensor]: + if values is None: + return None + return torch.tensor(np.array(values), device=device, dtype=dtype) + + @staticmethod + def _as_image_list(images) -> List: + return list(images) if isinstance(images, (list, tuple)) else [images] + + @staticmethod + def _blank_like(image): + if isinstance(image, Image.Image): + return Image.new(image.mode, image.size) + image_array = np.asarray(image) + return np.zeros_like(image_array) + + @staticmethod + def _duplicate_frame(image, count: int) -> List: + return [image] * count + + def _split_policy_views(self, images: List, blank_image): + # LeRobot loader returns primary views first and wrist views after them. + primary = images[0] if images else blank_image + wrist = images[1] if len(images) > 1 else blank_image + secondary = images[2] if len(images) > 2 else blank_image + return wrist, primary, secondary + + def _build_raw_policy_sequences( + self, + batch_images: List, + future_images: Optional[List] = None, + include_state: bool = False, + include_future: bool = True, + ) -> tuple[List[List], dict]: + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_sequences = [] + slot_info = None + + for batch_idx, images in enumerate(batch_images): + current_images = self._as_image_list(images) + future_image_list = ( + self._as_image_list(future_images[batch_idx]) + if future_images is not None + else current_images + ) + if not include_future: + future_image_list = [] + + blank_image = self._blank_like(current_images[0]) + _, current_primary, _ = self._split_policy_views(current_images, blank_image) + if future_image_list: + _, future_primary, _ = self._split_policy_views(future_image_list, blank_image) + else: + future_primary = blank_image + + # Match the official RoboCasa Cosmos Policy latent role layout: + # [blank, proprio, wrist, primary, secondary, action, + # future_proprio, future_wrist, future_primary, future_secondary, value]. + # When starVLA only provides a primary camera, the missing views keep + # their official temporal slots as blank placeholders. + sequence = [blank_image] + slot_images = [ + blank_image, # current proprio placeholder + blank_image, # current wrist placeholder + current_primary, + blank_image, # current secondary placeholder + blank_image, # action placeholder + blank_image, # future proprio placeholder + blank_image, # future wrist placeholder + future_primary, + blank_image, # future secondary placeholder + blank_image, # value placeholder + ] + for slot_image in slot_images: + sequence.extend(self._duplicate_frame(slot_image, temporal_factor)) + + blank_idx = 0 + state_idx = 1 + current_wrist_idx = 2 + current_primary_idx = 3 + current_secondary_idx = 4 + action_idx = 5 + future_state_idx = 6 + future_wrist_idx = 7 + future_primary_idx = 8 + future_secondary_idx = 9 + value_idx = 10 + condition_indices = [ + blank_idx, + state_idx, + current_wrist_idx, + current_primary_idx, + current_secondary_idx, + ] + future_indices = [future_primary_idx] + target_indices = [ + action_idx, + future_state_idx, + future_wrist_idx, + future_primary_idx, + future_secondary_idx, + value_idx, + ] + + sample_slot_info = { + "condition_indices": condition_indices, + "state_idx": state_idx, + "current_wrist_idx": current_wrist_idx, + "current_image_indices": [current_primary_idx], + "current_secondary_idx": current_secondary_idx, + "action_idx": action_idx, + "future_state_idx": future_state_idx, + "future_wrist_idx": future_wrist_idx, + "future_indices": future_indices, + "future_secondary_idx": future_secondary_idx, + "value_idx": value_idx, + "target_indices": target_indices, + } + if slot_info is None: + slot_info = sample_slot_info + elif sample_slot_info != slot_info: + raise ValueError( + "CosmoPredict25Policy requires the same policy frame layout for every sample in a batch." + ) + raw_sequences.append(sequence) + + return raw_sequences, slot_info + + def _make_policy_inputs( + self, + wm_inputs: dict, + clean_latents: torch.Tensor, + condition_indices: List[int], + target_indices: List[int], + sample_frames: List[torch.Tensor], + timestep: torch.Tensor, + ): + batch_size, _, t_lat, h_lat, w_lat = clean_latents.shape + dtype = clean_latents.dtype + num_target_frames = len(sample_frames) + + hidden_states = clean_latents.clone() + for frame_idx, target_idx in enumerate(target_indices): + hidden_states[:, :, target_idx] = sample_frames[frame_idx].to(dtype=dtype) + + condition_mask = clean_latents.new_zeros((batch_size, 1, t_lat, h_lat, w_lat)) + condition_mask[:, :, condition_indices] = 1.0 + + timestep_tensor = clean_latents.new_zeros((batch_size, 1, t_lat, 1, 1)) + target_timestep = timestep.view(batch_size, 1, 1, 1, 1).to(device=clean_latents.device, dtype=dtype) + timestep_tensor[:, :, target_indices] = target_timestep.expand(batch_size, 1, num_target_frames, 1, 1) + + return { + "hidden_states": hidden_states.to(dtype), + "timestep": timestep_tensor, + "encoder_hidden_states": wm_inputs["encoder_hidden_states"], + "condition_mask": condition_mask.to(dtype), + "padding_mask": wm_inputs.get("padding_mask", None), + } + + def _predict_velocity( + self, + wm_inputs: dict, + clean_latents: torch.Tensor, + condition_indices: List[int], + target_indices: List[int], + sample_frames: List[torch.Tensor], + timestep: torch.Tensor, + ) -> torch.Tensor: + policy_inputs = self._make_policy_inputs( + wm_inputs=wm_inputs, + clean_latents=clean_latents, + condition_indices=condition_indices, + target_indices=target_indices, + sample_frames=sample_frames, + timestep=timestep, + ) + return self._run_transformer(policy_inputs, target_indices=target_indices) + + def _run_transformer(self, policy_inputs: dict, target_indices: List[int]) -> torch.Tensor: + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + output = self.backbone.transformer( + hidden_states=policy_inputs["hidden_states"], + timestep=policy_inputs["timestep"], + encoder_hidden_states=policy_inputs["encoder_hidden_states"], + condition_mask=policy_inputs.get("condition_mask", None), + padding_mask=policy_inputs.get("padding_mask", None), + return_dict=False, + ) + + pred = output[0] if isinstance(output, tuple) else output + pred_frames = pred[:, :, target_indices].float() + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + return pred_frames + + def _encode_future_image_frames(self, future_images: List) -> tuple[torch.Tensor, List[int]]: + future_latents, frame_counts, counts_are_latent_frames = self.backbone._encode_images(future_images) + if not counts_are_latent_frames: + frame_counts = [ + (frame_count - 1) // self.backbone.vae_scale_factor_temporal + 1 + for frame_count in frame_counts + ] + return future_latents.float(), frame_counts + + def _decode_latent_frames(self, latent_frames: torch.Tensor, frame_counts: Optional[List[int]] = None) -> List[np.ndarray]: + batch_size, channels, num_frames, height, width = latent_frames.shape + latent_video = ( + latent_frames.permute(0, 2, 1, 3, 4) + .reshape(batch_size * num_frames, channels, 1, height, width) + .to(device=latent_frames.device, dtype=self.backbone.vae.dtype) + ) + + latents_mean = self.backbone.latents_mean.to(device=latent_video.device, dtype=latent_video.dtype) + latents_std = self.backbone.latents_std.to(device=latent_video.device, dtype=latent_video.dtype) + latent_video = latent_video * latents_std + latents_mean + + with torch.no_grad(): + decoded = self.backbone.vae.decode(latent_video).sample + + decoded = decoded[:, :, 0].float().clamp(-1, 1) + decoded = ((decoded + 1.0) * 127.5).clamp(0, 255).byte() + decoded = decoded.permute(0, 2, 3, 1) + decoded = decoded.reshape(batch_size, num_frames, decoded.shape[1], decoded.shape[2], decoded.shape[3]) + decoded = decoded.detach().cpu().numpy() + + images = [] + if frame_counts is None: + frame_counts = [num_frames] * batch_size + for sample, frame_count in zip(decoded, frame_counts): + frame_count = max(1, min(int(frame_count), sample.shape[0])) + sample = sample[:frame_count] + if frame_count == 1: + images.append(sample[0]) + else: + images.append(np.concatenate([frame for frame in sample], axis=1)) + return images + + def _decode_policy_future_images( + self, + latent_sequence: torch.Tensor, + future_indices: List[int], + ) -> List[np.ndarray]: + latent_video = latent_sequence.to(device=latent_sequence.device, dtype=self.backbone.vae.dtype) + latents_mean = self.backbone.latents_mean.to(device=latent_video.device, dtype=latent_video.dtype) + latents_std = self.backbone.latents_std.to(device=latent_video.device, dtype=latent_video.dtype) + latent_video = latent_video * latents_std + latents_mean + + with torch.no_grad(): + decoded = self.backbone.vae.decode(latent_video).sample + + decoded = decoded.float().clamp(-1, 1) + decoded = ((decoded + 1.0) * 127.5).clamp(0, 255).byte() + decoded = decoded.permute(0, 2, 3, 4, 1).detach().cpu().numpy() + + temporal_factor = int(getattr(self.backbone, "vae_scale_factor_temporal", 4)) + raw_indices = [ + 0 if latent_idx == 0 else (int(latent_idx) - 1) * temporal_factor + 1 + for latent_idx in future_indices + ] + + images = [] + for sample in decoded: + frames = [sample[min(raw_idx, sample.shape[0] - 1)] for raw_idx in raw_indices] + if len(frames) == 1: + images.append(frames[0]) + else: + images.append(np.concatenate(frames, axis=1)) + return images + + @staticmethod + def _image_frame_counts(images) -> List[int]: + frame_counts = [len(sample) if isinstance(sample, (list, tuple)) else 1 for sample in images] + return [max(1, int(frame_count)) for frame_count in frame_counts] + + @staticmethod + def _latent_frame_mask(frame_counts: List[int], num_frames: int, like: torch.Tensor) -> torch.Tensor: + mask = like.new_zeros((len(frame_counts), 1, num_frames, 1, 1), dtype=torch.float32) + for batch_idx, frame_count in enumerate(frame_counts): + mask[batch_idx, :, : max(1, min(int(frame_count), num_frames))] = 1.0 + return mask + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + batch_images = [example["image"] for example in examples] + future_images = [example["future_image"] for example in examples] if "future_image" in examples[0] else None + instructions = [example["lang"] for example in examples] + actions = self._select_action_chunk([example["action"] for example in examples]) + states = [example["state"] for example in examples] if "state" in examples[0] else None + + raw_sequences, slot_info = self._build_raw_policy_sequences( + batch_images=batch_images, + future_images=future_images, + include_state=states is not None, + include_future=True, + ) + wm_inputs = self.backbone.build_inputs(images=raw_sequences, instructions=instructions) + latents = wm_inputs["hidden_states"] + clean_latents = latents.clone() + actions = actions.to(device=latents.device, dtype=torch.float32) + states = self._stack_optional_tensor(states, latents.device, torch.float32) + if states is not None and slot_info["state_idx"] is not None: + clean_latents[:, :, slot_info["state_idx"]] = self._state_to_latent_frame(states, clean_latents) + target_action_frame = self._actions_to_latent_frame(actions, clean_latents).float() + clean_latents[:, :, slot_info["action_idx"]] = target_action_frame.to(clean_latents.dtype) + target_indices = slot_info["target_indices"] + target_frames = [clean_latents[:, :, target_idx].to(latents.dtype) for target_idx in target_indices] + + batch_size = target_action_frame.shape[0] + train_time = self._sample_train_times(batch_size, latents.device) + flow_time = self._shift_time(train_time) + timestep = self._sigma_to_timestep(flow_time) + time_view = flow_time.view(batch_size, 1, 1, 1).to(device=latents.device, dtype=latents.dtype) + + noises = [torch.randn_like(target_frame).to(latents.dtype) for target_frame in target_frames] + sample_frames = [ + noise * time_view + target_frame * (1.0 - time_view) + for target_frame, noise in zip(target_frames, noises) + ] + target_velocities = [ + (noise.float() - target_frame.float()) + for target_frame, noise in zip(target_frames, noises) + ] + + pred_frames = self._predict_velocity( + wm_inputs=wm_inputs, + clean_latents=clean_latents, + condition_indices=slot_info["condition_indices"], + target_indices=target_indices, + sample_frames=sample_frames, + timestep=timestep, + ) + pred_action_frame = pred_frames[:, :, 0] + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + action_loss = F.mse_loss(pred_action_frame, target_velocities[0], reduction="none") + if action_mask is not None: + action_mask = torch.tensor(np.array(action_mask), device=latents.device, dtype=torch.float32) + action_mask = action_mask[:, -(self.future_action_window_size + 1):, :] + latent_mask = self._actions_to_latent_frame(action_mask, latents).float().clamp(0.0, 1.0) + action_loss_scalar = (action_loss * latent_mask).sum() / latent_mask.sum().clamp_min(1.0) + else: + action_loss_scalar = action_loss.mean() + + future_positions = [target_indices.index(idx) for idx in slot_info["future_indices"]] + pred_future_frame = pred_frames[:, :, future_positions] + future_target = torch.stack([target_velocities[pos] for pos in future_positions], dim=2).float() + future_diff = future_target - pred_future_frame + future_image_loss = (future_diff**2).mean() + + # Official Cosmos Policy multiplies selected frame losses and then + # averages over the full latent time axis, including conditioned frames + # whose loss is zero because they are replaced by GT velocity. + total_loss = ( + action_loss_scalar * self.action_loss_weight + + future_image_loss * self.future_image_loss_weight * len(future_positions) + ) / clean_latents.shape[2] + + action_diff = target_velocities[0] - pred_action_frame + output = { + "action_loss": total_loss, + "demo_sample_action_mse_loss": (action_diff**2).mean().detach(), + "demo_sample_action_l1_loss": torch.abs(action_diff).mean().detach(), + "demo_sample_future_image_mse_loss": future_image_loss.detach(), + "demo_sample_future_image_l1_loss": torch.abs(future_diff).mean().detach(), + } + output["future_image_loss"] = future_image_loss.detach() + + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + states = [example["state"] for example in examples] if "state" in examples[0] else None + raw_sequences, slot_info = self._build_raw_policy_sequences( + batch_images=batch_images, + future_images=None, + include_state=states is not None, + include_future=True, + ) + wm_inputs = self.backbone.build_inputs(images=raw_sequences, instructions=instructions) + latents = wm_inputs["hidden_states"] + clean_latents = latents.clone() + states = self._stack_optional_tensor(states, latents.device, torch.float32) + if states is not None and slot_info["state_idx"] is not None: + clean_latents[:, :, slot_info["state_idx"]] = self._state_to_latent_frame(states, clean_latents) + batch_size, channels, _, height, width = latents.shape + action_shape = (batch_size, self.future_action_window_size + 1, self.action_dim) + future_frame_counts = [len(slot_info["future_indices"])] * batch_size + target_indices = slot_info["target_indices"] + action_target_indices = [slot_info["action_idx"]] + + num_inference_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps)) + num_inference_steps = max(num_inference_steps, 1) + shift = float(kwargs.get("shift", self.shift)) + debug_trace = self._begin_wm_debug_trace() + self._log_wm_debug( + debug_trace, + ( + f"start requested_num_inference_steps={num_inference_steps} " + f"parameterization=rectified_flow shift={shift:g}" + ), + obs_latents=latents, + ) + + target_frames = [ + torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype) + for _ in target_indices + ] + + sigmas = self._flow_inference_schedule(num_inference_steps, latents.device, shift=shift) + if self.action_inference_mode == "one_step_x0": + timestep = torch.ones((batch_size,), device=latents.device, dtype=torch.float32) + pred_frames = self._predict_velocity( + wm_inputs=wm_inputs, + clean_latents=clean_latents, + condition_indices=slot_info["condition_indices"], + target_indices=target_indices, + sample_frames=target_frames, + timestep=timestep, + ) + self._log_wm_debug( + debug_trace, + "one_step_x0", + sample_action_before=target_frames[0], + pred_action_velocity=pred_frames[:, :, 0], + pred_future=pred_frames[:, :, 1:] if pred_frames.shape[2] > 1 else None, + ) + target_frames = [ + target_frames[frame_idx] - pred_frames[:, :, frame_idx].to(dtype=latents.dtype) + for frame_idx in range(len(target_frames)) + ] + else: + for step_idx in range(num_inference_steps): + timestep = self._sigma_to_timestep(sigmas[step_idx]).expand(batch_size) + next_sigma = sigmas[step_idx + 1] + sigma = sigmas[step_idx] + pred_frames = self._predict_velocity( + wm_inputs=wm_inputs, + clean_latents=clean_latents, + condition_indices=slot_info["condition_indices"], + target_indices=target_indices, + sample_frames=target_frames, + timestep=timestep, + ) + self._log_wm_debug( + debug_trace, + ( + f"step={step_idx} sigma={sigma.item():.4g}->{next_sigma.item():.4g} " + f"timestep={timestep[0].item():.4g}" + ), + sample_action_before=target_frames[0], + pred_action_velocity=pred_frames[:, :, 0], + pred_future=pred_frames[:, :, 1:] if pred_frames.shape[2] > 1 else None, + ) + dt = (next_sigma - sigma).to(device=latents.device, dtype=latents.dtype) + target_frames = [ + target_frames[frame_idx] + dt * pred_frames[:, :, frame_idx].to(dtype=latents.dtype) + for frame_idx in range(len(target_frames)) + ] + self._log_wm_debug( + debug_trace, + f"step={step_idx} after_update", + sample_action_after=target_frames[0], + ) + + pred_action_frame = target_frames[0].float() + pred_actions = self._latent_frame_to_actions(pred_action_frame, action_shape) + self._log_wm_debug( + debug_trace, + "final_action", + pred_action_frame=pred_action_frame, + pred_actions=pred_actions, + ) + + generated_latents = clean_latents.clone() + for frame_idx, target_idx in enumerate(target_indices): + generated_latents[:, :, target_idx] = target_frames[frame_idx].to(dtype=generated_latents.dtype) + pred_future_frames = generated_latents[:, :, slot_info["future_indices"]].float() + self._log_wm_debug(debug_trace, "final_future", pred_future_frames=pred_future_frames) + + decode_latents = generated_latents.clone() + replace_indices = [ + slot_info["state_idx"], + slot_info["current_wrist_idx"], + *slot_info["current_image_indices"], + slot_info["current_secondary_idx"], + slot_info["action_idx"], + slot_info["future_state_idx"], + slot_info["future_wrist_idx"], + slot_info["future_secondary_idx"], + slot_info["value_idx"], + ] + for replace_idx in replace_indices: + if replace_idx is not None: + decode_latents[:, :, replace_idx] = latents[:, :, replace_idx] + pred_future_images = self._decode_policy_future_images( + decode_latents.float(), + future_indices=slot_info["future_indices"], + ) + + return { + "normalized_actions": pred_actions.detach().cpu().numpy(), + "pred_future_images": pred_future_images, + } diff --git a/starVLA/model/framework/WM4A/CosmoPredict25PolicyNative.py b/starVLA/model/framework/WM4A/CosmoPredict25PolicyNative.py new file mode 100644 index 0000000000000000000000000000000000000000..0af33d8b20056dfee9dcfcfed1abf5e91c768af4 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict25PolicyNative.py @@ -0,0 +1,756 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Native Cosmos-Predict2.5 Policy backend. + +This wrapper intentionally does not use the diffusers Cosmos pipeline. It +loads NVIDIA's native Cosmos Policy implementation and adapts starVLA batches +to the official ``CosmosPolicyVideo2WorldModelRectifiedFlow`` data_batch +format. The policy model, scheduler, tokenizer/VAE, latent injection, and +loss computation are therefore owned by the official code. +""" + +from __future__ import annotations + +import os +import pickle +import sys +import traceback +import types +import importlib +import importlib.metadata +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +import numpy as np +import torch +from PIL import Image + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.tools import FRAMEWORK_REGISTRY + + +@dataclass +class CosmoPredict25PolicyNativeDefaultConfig: + name: str = "CosmoPredict25PolicyNative" + + world_model: dict = field(default_factory=lambda: { + # Native checkpoint path, not a diffusers folder. + "base_wm": "", + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 15, + "action_horizon": 16, + "past_action_window_size": 0, + }) + + policy: dict = field(default_factory=lambda: { + "native_repo_path": "", + "config_file": "cosmos_predict2/_src/predict2/cosmos_policy/config/config.py", + "experiment": "cosmos_predict2p5_2b_480p_robocasa_50_demos_per_task_no_s3", + "text_embeddings_path": "", + "text_embeddings_kind": "reason1", + "use_online_text_encoder": True, + "text_encoder_ckpt_path": "", + "height": 224, + "width": 224, + "shift": 5.0, + "num_inference_steps": 5, + # starVLA currently trains demos, so only supervise action + future + # primary image instead of blank unused future/value slots. + "mask_policy_loss": True, + "action_loss_multiplier": 16, + "load_ema_to_reg": True, + "instantiate_ema": False, + "skip_native_package_init": True, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict25PolicyNative") +class CosmoPredict25_Policy_Native(baseframework): + """Adapter around NVIDIA's native Cosmos-Predict2.5 policy model.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict25PolicyNativeDefaultConfig, config) + self.policy_cfg = self.config.framework.get("policy", {}) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.action_dim = self.config.framework.action_model.action_dim + self.state_dim = self.config.framework.action_model.get("state_dim", self.action_dim) + + self.height = int(self.policy_cfg.get("height", 224)) + self.width = int(self.policy_cfg.get("width", 224)) + self.shift = float(self.policy_cfg.get("shift", 5.0)) + self.num_inference_steps = int(self.policy_cfg.get("num_inference_steps", 5)) + + self._add_native_repo_to_path() + self.native_model, self.native_config = self._load_native_model() + self._configure_native_policy_loss() + self._freeze_native_non_policy_modules() + self._use_online_text_encoder = bool(self.policy_cfg.get("use_online_text_encoder", True)) + self._text_embedding_cache = {} if self._use_online_text_encoder else self._load_text_embedding_cache() + self._iteration = 0 + + def _add_native_repo_to_path(self) -> None: + repo_path = self.policy_cfg.get("native_repo_path") or os.getenv("COSMOS_PREDICT25_REPO", "") + if repo_path: + repo_path = os.path.abspath(os.path.expanduser(repo_path)) + if bool(self.policy_cfg.get("skip_native_package_init", True)): + self._install_cosmos_predict2_package_shim(repo_path) + self._install_optional_dependency_shims() + packages_root = os.path.join(repo_path, "packages") + package_paths = [] + if os.path.isdir(packages_root): + package_paths = [ + os.path.join(packages_root, name) + for name in sorted(os.listdir(packages_root)) + if os.path.isdir(os.path.join(packages_root, name)) + ] + extra_paths = [repo_path, *package_paths] + for extra_path in reversed(extra_paths): + if os.path.isdir(extra_path) and extra_path not in sys.path: + sys.path.insert(0, extra_path) + + @staticmethod + def _install_cosmos_predict2_package_shim(repo_path: str) -> None: + """Expose cosmos_predict2 submodules without running its top-level check.""" + package_root = os.path.join(repo_path, "cosmos_predict2") + if not os.path.isdir(package_root): + return + existing = sys.modules.get("cosmos_predict2") + if existing is not None and getattr(existing, "__file__", None): + return + + module = types.ModuleType("cosmos_predict2") + module.__path__ = [package_root] + module.__package__ = "cosmos_predict2" + module.__file__ = os.path.join(package_root, "__init__.py") + module.__version__ = "1.5.0" + + about_path = os.path.join(package_root, "__about__.py") + if os.path.exists(about_path): + namespace = {} + with open(about_path, "r", encoding="utf-8") as f: + exec(compile(f.read(), about_path, "exec"), namespace) + module.__version__ = namespace.get("__version__", module.__version__) + + sys.modules["cosmos_predict2"] = module + + @staticmethod + def _install_optional_dependency_shims() -> None: + """Let local-only official config imports pass without S3 packages.""" + if "boto3" not in sys.modules: + boto3_module = types.ModuleType("boto3") + + def _missing_boto3(*args, **kwargs): + raise RuntimeError("boto3 is not installed; S3 access is disabled in CosmoPredict25PolicyNative.") + + boto3_module.client = _missing_boto3 + boto3_module.Session = _missing_boto3 + sys.modules["boto3"] = boto3_module + + if "botocore" not in sys.modules: + botocore_module = types.ModuleType("botocore") + sys.modules["botocore"] = botocore_module + + if "botocore.config" not in sys.modules: + config_module = types.ModuleType("botocore.config") + + class Config: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + config_module.Config = Config + sys.modules["botocore.config"] = config_module + + if "botocore.exceptions" not in sys.modules: + exceptions_module = types.ModuleType("botocore.exceptions") + + class ClientError(Exception): + pass + + exceptions_module.ClientError = ClientError + sys.modules["botocore.exceptions"] = exceptions_module + + if "multistorageclient" not in sys.modules: + msc_module = types.ModuleType("multistorageclient") + + class StorageClient: + def __init__(self, *args, **kwargs): + raise RuntimeError( + "multistorageclient is not installed; MSC/S3 access is disabled in " + "CosmoPredict25PolicyNative." + ) + + class StorageClientConfig: + @staticmethod + def read_msc_config(*args, **kwargs): + raise RuntimeError( + "multistorageclient is not installed; MSC/S3 access is disabled in " + "CosmoPredict25PolicyNative." + ) + + @staticmethod + def from_dict(*args, **kwargs): + return None + + msc_module.StorageClient = StorageClient + msc_module.StorageClientConfig = StorageClientConfig + sys.modules["multistorageclient"] = msc_module + + if "multistorageclient.types" not in sys.modules: + msc_types_module = types.ModuleType("multistorageclient.types") + + class Range: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + msc_types_module.Range = Range + sys.modules["multistorageclient.types"] = msc_types_module + + if "transformer_engine" not in sys.modules: + te_module = types.ModuleType("transformer_engine") + te_pytorch_module = types.ModuleType("transformer_engine.pytorch") + te_attention_module = types.ModuleType("transformer_engine.pytorch.attention") + te_rope_module = types.ModuleType("transformer_engine.pytorch.attention.rope") + te_optimizers_module = types.ModuleType("transformer_engine.pytorch.optimizers") + + class RMSNorm(torch.nn.Module): + def __init__(self, hidden_size, eps=1e-5, **kwargs): + super().__init__() + self.eps = eps + self.weight = torch.nn.Parameter(torch.ones(hidden_size)) + + def reset_parameters(self): + torch.nn.init.ones_(self.weight) + + def forward(self, x): + out = x.float() * torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) + self.eps) + return out.to(dtype=x.dtype) * self.weight + + def _rotate_half(x): + x1, x2 = x.chunk(2, dim=-1) + return torch.cat((-x2, x1), dim=-1) + + def apply_rotary_pos_emb(x, rope_emb, tensor_format="bshd", fused=True): + del tensor_format, fused + if rope_emb is None: + return x + cos = rope_emb.cos().to(device=x.device, dtype=x.dtype) + sin = rope_emb.sin().to(device=x.device, dtype=x.dtype) + while cos.dim() < x.dim(): + cos = cos.unsqueeze(0) + sin = sin.unsqueeze(0) + return (x * cos) + (_rotate_half(x) * sin) + + class DotProductAttention(torch.nn.Module): + def __init__(self, *args, **kwargs): + super().__init__() + + def set_context_parallel_group(self, *args, **kwargs): + return None + + def forward(self, q, k, v, *args, **kwargs): + del args, kwargs + q_bhsd = q.permute(0, 2, 1, 3) + k_bhsd = k.permute(0, 2, 1, 3) + v_bhsd = v.permute(0, 2, 1, 3) + out = torch.nn.functional.scaled_dot_product_attention(q_bhsd, k_bhsd, v_bhsd) + out = out.permute(0, 2, 1, 3).contiguous() + return out.flatten(start_dim=2) + + def _missing_multi_tensor_applier(*args, **kwargs): + raise RuntimeError( + "transformer_engine is not installed; official FusedAdam is unavailable. " + "Use the starVLA optimizer path instead." + ) + + te_pytorch_module.RMSNorm = RMSNorm + te_attention_module.DotProductAttention = DotProductAttention + te_attention_module.apply_rotary_pos_emb = apply_rotary_pos_emb + te_rope_module.apply_rotary_pos_emb = apply_rotary_pos_emb + te_optimizers_module.multi_tensor_applier = _missing_multi_tensor_applier + te_pytorch_module.attention = te_attention_module + te_pytorch_module.optimizers = te_optimizers_module + te_module.pytorch = te_pytorch_module + sys.modules["transformer_engine"] = te_module + sys.modules["transformer_engine.pytorch"] = te_pytorch_module + sys.modules["transformer_engine.pytorch.attention"] = te_attention_module + sys.modules["transformer_engine.pytorch.attention.rope"] = te_rope_module + sys.modules["transformer_engine.pytorch.optimizers"] = te_optimizers_module + + if "transformer_engine_torch" not in sys.modules: + tex_module = types.ModuleType("transformer_engine_torch") + + def _missing_transformer_engine_torch(*args, **kwargs): + raise RuntimeError( + "transformer_engine_torch is not installed; official FusedAdam is unavailable." + ) + + tex_module.multi_tensor_adam = _missing_transformer_engine_torch + tex_module.multi_tensor_adam_capturable = _missing_transformer_engine_torch + tex_module.multi_tensor_adam_capturable_master = _missing_transformer_engine_torch + sys.modules["transformer_engine_torch"] = tex_module + + try: + from transformers import cache_utils as transformers_cache_utils + + if not hasattr(transformers_cache_utils, "SlidingWindowCache"): + class SlidingWindowCache(transformers_cache_utils.DynamicCache): + pass + + transformers_cache_utils.SlidingWindowCache = SlidingWindowCache + except Exception: + pass + + if "megatron" not in sys.modules: + sys.modules["megatron"] = types.ModuleType("megatron") + if "megatron.core" not in sys.modules: + core_module = types.ModuleType("megatron.core") + sys.modules["megatron.core"] = core_module + else: + core_module = sys.modules["megatron.core"] + sys.modules["megatron"].core = core_module + + if not hasattr(core_module, "ModelParallelConfig"): + try: + import attrs as _attrs + + @_attrs.define(slots=False) + class ModelParallelConfig: + tensor_model_parallel_size: int = 1 + pipeline_model_parallel_size: int = 1 + context_parallel_size: int = 1 + expert_model_parallel_size: int = 1 + sequence_parallel: bool = False + + except Exception: + @dataclass + class ModelParallelConfig: + tensor_model_parallel_size: int = 1 + pipeline_model_parallel_size: int = 1 + context_parallel_size: int = 1 + expert_model_parallel_size: int = 1 + sequence_parallel: bool = False + + core_module.ModelParallelConfig = ModelParallelConfig + + if "megatron.core.parallel_state" not in sys.modules: + parallel_state_module = types.ModuleType("megatron.core.parallel_state") + + class _SingleProcessGroup: + def size(self): + return 1 + + def rank(self): + return 0 + + _group = _SingleProcessGroup() + parallel_state_module.sequence_parallel = False + parallel_state_module.cp_size_t = 1 + parallel_state_module.is_initialized = lambda: False + parallel_state_module.initialize_model_parallel = lambda *args, **kwargs: None + parallel_state_module.destroy_model_parallel = lambda *args, **kwargs: None + parallel_state_module.get_data_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_data_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_context_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_context_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_context_parallel_group = lambda *args, **kwargs: None + parallel_state_module.get_tensor_model_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_tensor_model_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_pipeline_model_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_pipeline_model_parallel_rank = lambda *args, **kwargs: 0 + parallel_state_module.get_expert_model_parallel_world_size = lambda *args, **kwargs: 1 + parallel_state_module.get_model_parallel_group = lambda *args, **kwargs: _group + parallel_state_module.get_data_parallel_group = lambda *args, **kwargs: None + sys.modules["megatron.core.parallel_state"] = parallel_state_module + core_module.parallel_state = parallel_state_module + else: + core_module.parallel_state = sys.modules["megatron.core.parallel_state"] + + def _load_native_model(self): + try: + from cosmos_predict2._src.imaginaire.lazy_config import instantiate + from cosmos_predict2._src.imaginaire.utils.config_helper import get_config_module, override + except ImportError as exc: + raise ImportError( + "Failed to import the minimal NVIDIA cosmos-predict2.5 config/model helpers. " + "This can mean framework.policy.native_repo_path is wrong, or one of the native repo " + "dependencies is missing from the current Python environment. " + f"native_repo_path={self.policy_cfg.get('native_repo_path')!r}, " + f"COSMOS_PREDICT25_REPO={os.getenv('COSMOS_PREDICT25_REPO')!r}. " + f"Original ImportError: {exc!r}\n{traceback.format_exc()}" + ) from exc + + checkpoint_path = ( + self.policy_cfg.get("checkpoint_path") + or self.config.framework.world_model.get("base_wm") + or self.config.framework.qwenvl.get("base_vlm") + ) + if not checkpoint_path: + raise ValueError( + "CosmoPredict25PolicyNative needs a native Cosmos checkpoint path in " + "framework.world_model.base_wm or framework.policy.checkpoint_path." + ) + + use_online_text_encoder = bool(self.policy_cfg.get("use_online_text_encoder", True)) + if use_online_text_encoder: + transformers_version = importlib.metadata.version("transformers") + if transformers_version != "4.51.3": + raise ValueError( + "Online Reason1 must run with transformers==4.51.3 to match the official " + f"cosmos-predict2.5 lockfile, but the current environment has transformers=={transformers_version}. " + "Please switch/pin the training environment before online Reason1 training." + ) + text_encoder_ckpt_path = self.policy_cfg.get("text_encoder_ckpt_path", "") + if not text_encoder_ckpt_path: + raise ValueError( + "Online Reason1 requires framework.policy.text_encoder_ckpt_path to point to a local " + "Reason1 checkpoint. The official default is an internal S3 path, which this wrapper " + "does not use." + ) + if not os.path.exists(os.path.abspath(os.path.expanduser(text_encoder_ckpt_path))): + raise FileNotFoundError( + "framework.policy.text_encoder_ckpt_path does not exist: " + f"{text_encoder_ckpt_path!r}" + ) + + experiment_opts = list(self.policy_cfg.get("experiment_opts", [])) + experiment_opts.extend([ + "model.config.fsdp_shard_size=1", + "model.config.ema.enabled=false", + "model.config.net.atten_backend=torch", + f"model.config.action_loss_multiplier={int(self.policy_cfg.get('action_loss_multiplier', 16))}", + ]) + if bool(self.policy_cfg.get("mask_policy_loss", True)): + experiment_opts.append("model.config.mask_value_prediction_loss_for_policy_prediction=true") + + config_module = get_config_module(self.policy_cfg.get("config_file")) + native_config = importlib.import_module(config_module).make_config() + native_config = override( + native_config, + ["--", f"experiment={self.policy_cfg.get('experiment')}", *experiment_opts], + ) + if use_online_text_encoder: + text_encoder_ckpt_path = self.policy_cfg.get("text_encoder_ckpt_path", "") + from cosmos_predict2._src.predict2.text_encoders.text_encoder import TextEncoderConfig + + text_encoder_config = TextEncoderConfig( + compute_online=True, + ckpt_path=os.path.abspath(os.path.expanduser(text_encoder_ckpt_path)), + ) + native_config.model.config.text_encoder_class = "reason1p1_7B" + native_config.model.config.text_encoder_config = text_encoder_config + + model = instantiate(native_config.model) + if hasattr(model, "on_train_start"): + model.on_train_start() + if torch.cuda.is_available(): + model = model.cuda() + self._load_local_checkpoint(model, checkpoint_path) + return model, native_config + + @staticmethod + def _candidate_checkpoint_files(checkpoint_path: str) -> List[str]: + if os.path.isfile(checkpoint_path): + return [checkpoint_path] + candidates = [ + os.path.join(checkpoint_path, "model.pt"), + os.path.join(checkpoint_path, "model.pth"), + os.path.join(checkpoint_path, "pytorch_model.pt"), + os.path.join(checkpoint_path, "pytorch_model.bin"), + ] + base_dir = os.path.join(checkpoint_path, "base", "pre-trained") + candidates.extend([ + os.path.join(base_dir, "model.pt"), + os.path.join(base_dir, "model.pth"), + os.path.join(base_dir, "pytorch_model.pt"), + ]) + return [path for path in candidates if os.path.isfile(path)] + + def _load_local_checkpoint(self, model, checkpoint_path: str) -> None: + checkpoint_files = self._candidate_checkpoint_files(os.path.expanduser(checkpoint_path)) + if not checkpoint_files: + raise FileNotFoundError( + "CosmoPredict25PolicyNative now uses a minimal local torch.load checkpoint path " + "and does not import NVIDIA model_loader/easy_io/boto3. Please point " + "framework.policy.checkpoint_path or framework.world_model.base_wm to a local .pt/.pth file. " + f"No supported checkpoint file found under: {checkpoint_path}" + ) + + state = torch.load(checkpoint_files[0], map_location="cpu") + if isinstance(state, dict) and "model" in state: + state = state["model"] + elif isinstance(state, dict) and "state_dict" in state: + state = state["state_dict"] + load_info = model.load_state_dict(state, strict=False) + if load_info is not None and (load_info.missing_keys or load_info.unexpected_keys): + print( + "[CosmoPredict25PolicyNative] checkpoint loaded with " + f"{len(load_info.missing_keys)} missing keys and " + f"{len(load_info.unexpected_keys)} unexpected keys. " + f"First missing={load_info.missing_keys[:5]}, " + f"first unexpected={load_info.unexpected_keys[:5]}", + flush=True, + ) + + def _configure_native_policy_loss(self) -> None: + if bool(self.policy_cfg.get("mask_policy_loss", True)): + self.native_model.config.mask_value_prediction_loss_for_policy_prediction = True + self.native_model.config.action_loss_multiplier = int(self.policy_cfg.get("action_loss_multiplier", 16)) + + def _freeze_native_non_policy_modules(self) -> None: + for module_name in ("tokenizer", "text_encoder"): + module = getattr(self.native_model, module_name, None) + if module is not None and hasattr(module, "requires_grad_"): + module.requires_grad_(False) + + def _load_text_embedding_cache(self) -> Dict[str, torch.Tensor]: + path = self.policy_cfg.get("text_embeddings_path", "") + if not path: + return {} + path = os.path.abspath(os.path.expanduser(path)) + with open(path, "rb") as f: + return pickle.load(f) + + @staticmethod + def _as_image_list(images) -> List: + return list(images) if isinstance(images, (list, tuple)) else [images] + + @staticmethod + def _blank_like(image): + if isinstance(image, Image.Image): + return Image.new(image.mode, image.size) + image_array = np.asarray(image) + return np.zeros_like(image_array) + + @staticmethod + def _to_uint8_array(image) -> np.ndarray: + if isinstance(image, Image.Image): + return np.asarray(image.convert("RGB")) + if torch.is_tensor(image): + array = image.detach().cpu().numpy() + else: + array = np.asarray(image) + if array.ndim == 3 and array.shape[0] in (1, 3) and array.shape[-1] not in (1, 3): + array = np.transpose(array, (1, 2, 0)) + if array.dtype != np.uint8: + if array.max() <= 1.0 and array.min() >= 0.0: + array = array * 255.0 + elif array.min() >= -1.0 and array.max() <= 1.0: + array = (array + 1.0) * 127.5 + array = np.clip(array, 0, 255).astype(np.uint8) + if array.ndim == 2: + array = np.repeat(array[..., None], 3, axis=-1) + if array.shape[-1] == 1: + array = np.repeat(array, 3, axis=-1) + return array[..., :3] + + def _resize_uint8(self, image) -> np.ndarray: + array = self._to_uint8_array(image) + pil = Image.fromarray(array) + pil = pil.resize((self.width, self.height), Image.BILINEAR) + return np.asarray(pil, dtype=np.uint8) + + def _split_policy_views(self, images: List, blank_image): + primary = images[0] if images else blank_image + wrist = images[1] if len(images) > 1 else blank_image + secondary = images[2] if len(images) > 2 else blank_image + return wrist, primary, secondary + + def _build_video_frames(self, example: dict, include_future: bool) -> List[np.ndarray]: + temporal_factor = 4 + current_images = self._as_image_list(example["image"]) + future_images = self._as_image_list(example.get("future_image", current_images)) if include_future else [] + blank_image = self._blank_like(current_images[0]) + + wrist, primary, secondary = self._split_policy_views(current_images, blank_image) + if future_images: + future_wrist, future_primary, future_secondary = self._split_policy_views(future_images, blank_image) + else: + future_wrist, future_primary, future_secondary = blank_image, blank_image, blank_image + + slot_images = [ + blank_image, # 0: special blank, not repeated + blank_image, # 1: current proprio placeholder + wrist, # 2: current wrist + primary, # 3: current primary + secondary, # 4: current secondary + blank_image, # 5: action placeholder + blank_image, # 6: future proprio placeholder + future_wrist, # 7: future wrist + future_primary, # 8: future primary + future_secondary, # 9: future secondary + blank_image, # 10: value placeholder + ] + + frames = [self._resize_uint8(slot_images[0])] + for slot_image in slot_images[1:]: + resized = self._resize_uint8(slot_image) + frames.extend([resized] * temporal_factor) + return frames + + def _stack_video(self, examples: List[dict], include_future: bool) -> torch.Tensor: + videos = [] + for example in examples: + frames = np.stack(self._build_video_frames(example, include_future=include_future), axis=0) + videos.append(torch.from_numpy(frames).permute(3, 0, 1, 2).contiguous()) + return torch.stack(videos, dim=0).to(dtype=torch.uint8) + + def _select_action_chunk(self, actions) -> torch.Tensor: + actions = torch.tensor(np.array(actions), dtype=torch.float32) + return actions[:, -(self.future_action_window_size + 1):, :] + + def _stack_state(self, examples: List[dict], key: str, device: torch.device) -> torch.Tensor: + if key in examples[0]: + return torch.tensor(np.array([example[key] for example in examples]), device=device, dtype=torch.float32) + return torch.zeros((len(examples), self.state_dim), device=device, dtype=torch.float32) + + def _stack_text_embeddings(self, examples: List[dict], device: torch.device) -> torch.Tensor: + if self._use_online_text_encoder: + raise RuntimeError("_stack_text_embeddings should not be called when use_online_text_encoder=true.") + if "t5_text_embeddings" in examples[0]: + embeddings = [example["t5_text_embeddings"] for example in examples] + else: + embeddings = [] + missing = [] + for example in examples: + instruction = example.get("lang") or example.get("instruction") or example.get("ai_caption") + if instruction in self._text_embedding_cache: + embeddings.append(self._text_embedding_cache[instruction]) + else: + missing.append(instruction) + if missing: + raise KeyError( + "CosmoPredict25PolicyNative needs official text embeddings. " + "Provide example['t5_text_embeddings'] or set framework.policy.text_embeddings_path. " + f"Missing instruction example: {missing[0]!r}" + ) + + tensors = [] + for embedding in embeddings: + tensor = embedding if torch.is_tensor(embedding) else torch.as_tensor(embedding) + tensor = tensor.squeeze(0).to(device=device, dtype=torch.bfloat16) + tensors.append(tensor) + return torch.stack(tensors, dim=0) + + def _make_native_batch(self, examples: List[dict], include_future: bool = True) -> dict: + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + batch_size = len(examples) + + actions = self._select_action_chunk([example["action"] for example in examples]).to(device=device) + video = self._stack_video(examples, include_future=include_future) + proprio = self._stack_state(examples, "state", device=device) + future_proprio = self._stack_state(examples, "future_state", device=device) + + captions = [ + example.get("ai_caption") or example.get("lang") or example.get("instruction") or "" + for example in examples + ] + if self._use_online_text_encoder: + text_embeddings = None + text_mask = None + else: + text_embeddings = self._stack_text_embeddings(examples, device=device) + text_mask = torch.ones( + (batch_size, text_embeddings.shape[1]), + device=device, + dtype=torch.int64, + ) + + def full_idx(value: int) -> torch.Tensor: + return torch.full((batch_size,), value, device=device, dtype=torch.int64) + + zeros = torch.zeros((batch_size,), device=device, dtype=torch.int64) + data_batch = { + "video": video, + "actions": actions, + "proprio": proprio, + "future_proprio": future_proprio, + "ai_caption": captions, + "num_conditional_frames": torch.tensor(5, device=device, dtype=torch.int64), + "current_proprio_latent_idx": full_idx(1) if "state" in examples[0] else full_idx(-1), + "action_latent_idx": full_idx(5), + "future_proprio_latent_idx": full_idx(-1), + "future_wrist_image_latent_idx": full_idx(-1), + "future_wrist_image2_latent_idx": full_idx(-1), + "future_image_latent_idx": full_idx(8) if include_future else full_idx(-1), + "future_image2_latent_idx": full_idx(-1), + "value_latent_idx": full_idx(10), + "rollout_data_mask": zeros.clone(), + "world_model_sample_mask": zeros.clone(), + "value_function_sample_mask": zeros.clone(), + "value_function_return": torch.zeros((batch_size,), device=device, dtype=torch.float32), + } + if not self._use_online_text_encoder: + data_batch["t5_text_embeddings"] = text_embeddings + data_batch["t5_text_mask"] = text_mask + return data_batch + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + data_batch = self._make_native_batch(examples, include_future=True) + output_batch, loss = self.native_model.training_step(data_batch, self._iteration) + self._iteration += 1 + + metrics = {"action_loss": loss} + for key in ( + "demo_sample_action_mse_loss", + "demo_sample_action_l1_loss", + "demo_sample_future_image_mse_loss", + "demo_sample_future_image_l1_loss", + "velocity_mse_loss", + "edm_loss", + ): + value = output_batch.get(key) + if torch.is_tensor(value): + metrics[key] = value.detach() + return metrics + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + from cosmos_predict2._src.predict2.cosmos_policy.experiments.robot.cosmos_utils import ( + extract_action_chunk_from_latent_sequence, + ) + + data_batch = self._make_native_batch(examples, include_future=True) + batch_size = len(examples) + num_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps)) + generated_latent = self.native_model.generate_samples_from_batch( + data_batch, + n_sample=batch_size, + num_steps=num_steps, + seed=int(kwargs.get("seed", 0)), + is_negative_prompt=False, + use_variance_scale=False, + return_orig_clean_latent_frames=False, + shift=float(kwargs.get("shift", self.shift)), + guidance=0, + ) + action_indices = torch.full( + (batch_size,), + 5, + dtype=torch.int64, + device=generated_latent.device, + ) + actions = extract_action_chunk_from_latent_sequence( + generated_latent, + action_shape=(self.future_action_window_size + 1, self.action_dim), + action_indices=action_indices, + ) + return {"normalized_actions": actions.detach().float().cpu().numpy()} diff --git a/starVLA/model/framework/WM4A/CosmoPredict2GR00T.py b/starVLA/model/framework/WM4A/CosmoPredict2GR00T.py new file mode 100644 index 0000000000000000000000000000000000000000..5b4750390cdd3815e7b42e2def8a4c1e9b9cba8b --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict2GR00T.py @@ -0,0 +1,271 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +CosmoPredict2-GR00T Framework — Diffusion World Model for Action Prediction. + +Uses Cosmos-Predict2 (DiT-based video world model) as the perception backbone +instead of a VLM. The DiT's intermediate representations encode rich +spatiotemporal and physical dynamics, which are projected to the action head +for continuous action prediction via flow-matching. + +Architecture: + T5 (text) + VAE (image) → DiT Transformer → hidden_states [B, N, 2048] + → Linear projection [B, N, action_hidden_dim] + → FlowmatchingActionHead → action predictions + +Key differences from VLM4A frameworks: + - Vision encoding: VAE latent (not pixel tokens) + - Text encoding: T5 (not Qwen tokenizer) + - Feature dim: 2048 (DiT) vs 2048 (Qwen-VL) + - Features are spatiotemporal patches, not sequential tokens +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.GR00T_ActionHeader import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict2GR00TDefaultConfig: + """CosmoPredict2-GR00T default parameters.""" + + name: str = "CosmoPredict2GR00T" + + # === World Model backbone (Cosmos-Predict2) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + # Which DiT layers to extract features from (-1 = last block) + "extract_layers": [-1], + }) + + # Legacy compat: factory functions (vlm/__init__, world_model/__init__) + # fall back to qwenvl.base_vlm when world_model.base_wm is absent. + # vl_hidden_dim is read by some action heads (VLA_AdapterHeader, LayerwiseFM). + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + }) + + # === Action head (Flow-matching / DiT diffusion) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "diffusion_model_cfg": { + # Will be set at runtime to match world model hidden_size (2048) + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2GR00T") +class CosmoPredict2_GR00T(baseframework): + """ + World-Model-for-Action framework using Cosmos-Predict2 backbone. + + Components: + - Cosmos-Predict2 DiT (T5 + VAE + Transformer) for spatiotemporal features + - Flow-matching (DiT) diffusion head for continuous action prediction + + The Cosmos-Predict2 world model provides physics-aware spatiotemporal + representations learned from large-scale video generation pretraining. + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2GR00TDefaultConfig, config) + + # Load world model backbone + self.backbone = get_world_model(config=self.config) + + # Align cross-attention dim to world model hidden size (4096) + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + state = [example["state"] for example in examples] if "state" in examples[0] else None + + # Step 1: World model input encoding (VAE + T5) + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + # Step 2: DiT forward to extract spatiotemporal features + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + # hidden_states[-1]: [B, N_tokens, hidden_dim=4096] + last_hidden = wm_outputs.hidden_states[-1] + + # Step 3: Action head forward and loss + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + repeated_diffusion_steps = ( + self.config.framework.action_model.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "framework") + else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> np.ndarray: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + + + +if __name__ == "__main__": + import argparse + import os + + from PIL import Image + from omegaconf import OmegaConf + + if os.getenv("DEBUGPY_ENABLE", "0") == "1": + import debugpy + debugpy.listen(("0.0.0.0", 10092)) + print("Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + parser = argparse.ArgumentParser() + parser.add_argument( + "--config_yaml", + type=str, + default="./starVLA/config/training/starvla_cotrain_libero.yaml", + help="Path to YAML config", + ) + args, clipargs = parser.parse_known_args() + + cfg = OmegaConf.load(args.config_yaml) + + cfg.framework.name = "CosmoPredict2GR00T" + cfg.framework.world_model = { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + } + + model: CosmoPredict2_GR00T = CosmoPredict2_GR00T(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image, image], + "lang": "This is a fake instruction for testing.", + } + sample2 = sample.copy() + sample2["lang"] = "Another fake instruction for testing." + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output["action_loss"] + print(f"Action Loss: {action_loss.item()}") + + predict_output = model.predict_action(examples=[sample]) + normalized_actions = predict_output["normalized_actions"] + print(f"Unnormalized Action: {normalized_actions}") + + print("Finished") diff --git a/starVLA/model/framework/WM4A/CosmoPredict2OFT.py b/starVLA/model/framework/WM4A/CosmoPredict2OFT.py new file mode 100644 index 0000000000000000000000000000000000000000..462c980fd584ce38f3ec7edfbff5d2ab622530bc --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict2OFT.py @@ -0,0 +1,222 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +CosmoPredict2-OFT Framework — World Model + MLP Regression for Action Prediction. + +Uses Cosmos-Predict2 DiT as the perception backbone with a lightweight MLP +action head (L1 regression), inspired by OpenVLA-OFT. + +Architecture: + T5 (text) + VAE (image) → DiT Transformer → hidden_states [B, N, 2048] + → Global avg pool → [B, 2048] + → Linear projection → [B, chunk_len, 2048] + → MLP (L1 regression) → action predictions [B, chunk_len, action_dim] + +Key differences from CosmoPredict2GR00T: + - Action head: MLP L1 regression (not flow-matching diffusion) + - No repeated_diffusion_steps (single forward pass) + - Faster training & inference +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch +import torch.nn as nn + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.MLP_ActionHeader import get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict2OFTDefaultConfig: + """CosmoPredict2-OFT default parameters.""" + + name: str = "CosmoPredict2OFT" + + # === World Model backbone (Cosmos-Predict2) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + }) + + # === Action head (MLP L1 regression) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "MLP", + "action_dim": 7, + "action_hidden_dim": 2048, + "future_action_window_size": 8, + "past_action_window_size": 0, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2OFT") +class CosmoPredict2_OFT(baseframework): + """ + World-Model-for-Action framework using Cosmos-Predict2 + MLP regression. + + Components: + - Cosmos-Predict2 DiT (T5 + VAE + Transformer) for spatiotemporal features + - Adaptive pooling + MLP regression head (L1 loss) + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2OFTDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.action_model.action_hidden_dim = wm_hidden + + self.action_model = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + self.action_query_proj = nn.Linear(wm_hidden, self.chunk_len * wm_hidden) # Project into a two-layer MLP + + self.l1_loss = nn.L1Loss() + + def _pool_to_action_queries(self, hidden_states: torch.Tensor) -> torch.Tensor: + B, N, H = hidden_states.shape + pooled = hidden_states.mean(dim=1) + queries = self.action_query_proj(pooled) + action_queries = queries.view(B, self.chunk_len, H) + return action_queries + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.float32): + action_queries = self._pool_to_action_queries(last_hidden) # B, chunk_len, hidden_dim + pred_actions = self.action_model.predict_action(action_queries) + + actions = torch.tensor( + np.array(actions), device=pred_actions.device, dtype=pred_actions.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + action_loss = self.l1_loss(pred_actions, actions_target) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> np.ndarray: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.float32): + action_queries = self._pool_to_action_queries(last_hidden) + pred_actions = self.action_model.predict_action(action_queries) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + +if __name__ == "__main__": + import argparse + import os + + from PIL import Image + from omegaconf import OmegaConf + + if os.getenv("DEBUGPY_ENABLE", "0") == "1": + import debugpy + debugpy.listen(("0.0.0.0", 10092)) + print("Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + parser = argparse.ArgumentParser() + parser.add_argument( + "--config_yaml", + type=str, + default="./starVLA/config/training/starvla_cotrain_libero.yaml", + help="Path to YAML config", + ) + args, clipargs = parser.parse_known_args() + + cfg = OmegaConf.load(args.config_yaml) + + cfg.framework.name = "CosmoPredict2OFT" + cfg.framework.world_model = { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + } + + model: CosmoPredict2_OFT = CosmoPredict2_OFT(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image, image], + "lang": "This is a fake instruction for testing.", + } + sample2 = sample.copy() + sample2["lang"] = "Another fake instruction for testing." + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output["action_loss"] + print(f"Action Loss: {action_loss.item()}") + + predict_output = model.predict_action(examples=[sample]) + normalized_actions = predict_output["normalized_actions"] + print(f"Predicted Action: {normalized_actions}") + print("Finished") diff --git a/starVLA/model/framework/WM4A/CosmoPredict2PI.py b/starVLA/model/framework/WM4A/CosmoPredict2PI.py new file mode 100644 index 0000000000000000000000000000000000000000..890f016a0383f453057c7ee1acf00638679d6e15 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict2PI.py @@ -0,0 +1,286 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +CosmoPredict2-PI Framework — World Model + Layer-wise Cross-DiT Flow-Matching. + +Uses Cosmos-Predict2 DiT as the perception backbone with a layer-wise +cross-DiT flow-matching action head, inspired by π₀ (Physical Intelligence). + +Architecture: + T5 (text) + VAE (image) → DiT Transformer (28 blocks) + → Multi-layer hidden_states [28 × (B, N, 2048)] + → LayerwiseFlowmatchingActionHead (cross-DiT) + → action predictions [B, chunk_len, action_dim] + +Key differences from CosmoPredict2GR00T: + - Action head: Layer-wise cross-DiT (not single-layer flow-matching) + - Uses ALL transformer layers (not just last hidden state) + - More expressive multi-scale feature fusion +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.LayerwiseFM_ActionHeader import LayerwiseFlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict2PIDefaultConfig: + """CosmoPredict2-PI default parameters.""" + + name: str = "CosmoPredict2PI" + + # === World Model backbone (Cosmos-Predict2) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + # LayerwiseFM reads qwenvl.vl_hidden_dim and qwenvl.num_vl_layers + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + "num_vl_layers": 28, + }) + + # === Action head (Layer-wise Flow-matching / cross-DiT) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "LayerwiseFM", + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 15, + "past_action_window_size": 0, + "repeated_diffusion_steps": 2, + "num_inference_timesteps": 4, + "add_pos_embed": True, + "max_seq_len": 1024, + "num_target_vision_tokens": 32, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "diffusion_model_cfg": {}, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2PI") +class CosmoPredict2_PI(baseframework): + """ + World-Model-for-Action framework using Cosmos-Predict2 + Layer-wise cross-DiT. + + Components: + - Cosmos-Predict2 DiT (T5 + VAE + Transformer) for spatiotemporal features + - Layer-wise cross-DiT flow-matching head fed by all transformer layers + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2PIDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + # Auto-detect hidden size and num layers from world model + wm_hidden = self.backbone.model.config.hidden_size + # Cosmos uses transformer_blocks, Wan uses blocks + if hasattr(self.backbone.transformer, 'transformer_blocks'): + num_blocks = len(self.backbone.transformer.transformer_blocks) + else: + num_blocks = len(self.backbone.transformer.blocks) + + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.qwenvl.num_vl_layers = num_blocks + + self.action_model: LayerwiseFlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # Register hooks for ALL transformer blocks (not just extract_layers) + self._all_hidden_states = [] + self._all_hooks = [] + self._register_all_hooks() + + def _register_all_hooks(self): + """Register forward hooks on ALL transformer blocks for layerwise features.""" + for hook in self._all_hooks: + hook.remove() + self._all_hooks.clear() + + if hasattr(self.backbone.transformer, 'transformer_blocks'): + blocks = self.backbone.transformer.transformer_blocks + else: + blocks = self.backbone.transformer.blocks + for block in blocks: + hook = block.register_forward_hook(self._capture_all_hook) + self._all_hooks.append(hook) + + def _capture_all_hook(self, module, input, output): + if isinstance(output, tuple): + self._all_hidden_states.append(output[0]) + else: + self._all_hidden_states.append(output) + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + state = [example["state"] for example in examples] if "state" in examples[0] else None + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + self._all_hidden_states.clear() + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + # Collect all layer hidden states + vl_embs_list = list(self._all_hidden_states) + base_hidden = vl_embs_list[-1] + + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=base_hidden.device, dtype=base_hidden.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + repeated_diffusion_steps = ( + self.config.framework.action_model.get("repeated_diffusion_steps", 2) + if self.config and hasattr(self.config, "framework") + else 2 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + vl_embs_list_repeated = [h.repeat(repeated_diffusion_steps, 1, 1) for h in vl_embs_list] + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=base_hidden.device, dtype=base_hidden.dtype) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_loss = self.action_model( + vl_embs_list_repeated, actions_target_repeated, state_repeated + ) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> np.ndarray: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + self._all_hidden_states.clear() + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + vl_embs_list = list(self._all_hidden_states) + + state = ( + torch.from_numpy(np.array(state)).to(vl_embs_list[-1].device, dtype=vl_embs_list[-1].dtype) + if state is not None + else None + ) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(vl_embs_list, state) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + +if __name__ == "__main__": + import argparse + import os + + from PIL import Image + from omegaconf import OmegaConf + + if os.getenv("DEBUGPY_ENABLE", "0") == "1": + import debugpy + debugpy.listen(("0.0.0.0", 10092)) + print("Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + parser = argparse.ArgumentParser() + parser.add_argument( + "--config_yaml", + type=str, + default="./starVLA/config/training/starvla_cotrain_libero.yaml", + help="Path to YAML config", + ) + args, clipargs = parser.parse_known_args() + + cfg = OmegaConf.load(args.config_yaml) + + cfg.framework.name = "CosmoPredict2PI" + cfg.framework.world_model = { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + } + cfg.framework.qwenvl = { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + "num_vl_layers": 28, + } + + model: CosmoPredict2_PI = CosmoPredict2_PI(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image, image], + "lang": "This is a fake instruction for testing.", + "state": np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), + } + sample2 = sample.copy() + sample2["lang"] = "Another fake instruction for testing." + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output["action_loss"] + print(f"Action Loss: {action_loss.item()}") + + predict_output = model.predict_action(examples=[sample]) + normalized_actions = predict_output["normalized_actions"] + print(f"Predicted Action: {normalized_actions}") + print("Finished") diff --git a/starVLA/model/framework/WM4A/CosmoPredict2Perceiver.py b/starVLA/model/framework/WM4A/CosmoPredict2Perceiver.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ac74f201b07040c60301bc705fb46a1b62e12d --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict2Perceiver.py @@ -0,0 +1,256 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +CosmoPredict2-Perceiver Framework. + +Uses Cosmos-Predict2 as the world-model backbone and the Perceiver-style +flow-matching action head for continuous action prediction. +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.training.trainer_utils.trainer_tools import resize_images + +logger = initialize_overwatch(__name__) + + +@dataclass +class CosmoPredict2PerceiverDefaultConfig: + """CosmoPredict2-Perceiver default parameters.""" + + name: str = "CosmoPredict2Perceiver" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + # Kept for compatibility with shared utilities and action-head configs. + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "max_num_embodiments": 32, + "use_category_specific": False, + "diffusion_model_cfg": { + "cross_attention_dim": 2048, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2Perceiver") +class CosmoPredict2_Perceiver(baseframework): + """World-model-for-action framework using Cosmos-Predict2 + Perceiver head.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2PerceiverDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # 训练时 + # action支路,self.backbone.build_inputs、self.backbone.forward()、self.action_model.forward() + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + # print('################# CosmoPredict2_Perceiver.forward-1') + + # 1. CosmosPredict:构建输入 + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + # print(len(examples)) # 8 + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # print(type(self.backbone)) # + # print(wm_inputs.keys()) # dict_keys(['hidden_states', 'timestep', 'encoder_hidden_states', 'condition_mask', 'padding_mask', '_is_wm_input']) + # print(wm_inputs['hidden_states'].shape) # torch.Size([8, 16, 1, 28, 28]) + # print(wm_inputs['timestep'].shape) # torch.Size([8, 1, 1, 1, 1]) + # print(wm_inputs['encoder_hidden_states'].shape) # torch.Size([8, 512, 100352]) + # print(wm_inputs['condition_mask'].shape) # torch.Size([8, 1, 1, 28, 28]) + # print(wm_inputs['padding_mask'].shape) # torch.Size([1, 1, 224, 224]) + # print(wm_inputs['_is_wm_input']) # True + + # 2. CosmosPredict:前向推理 + # 这里的CosmosPredict起到了一个编码器的作用,将输入的当前观测和prompt编码为vl-tokens + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + # print(type(wm_outputs)) # ._WMOutput'> + # print(last_hidden.shape) # torch.Size([8, 196, 2048]) + + # 3. ActionHead:构建输入 + with torch.autocast("cuda", dtype=torch.float32): + + # 3.1 初始化action + actions = [example["action"] for example in examples] + actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype) + # print(actions.shape) # torch.Size([8, 16, 32]) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + # print(self.future_action_window_size) # 15 + # print(actions_target.shape) # torch.Size([8, 16, 32]) + + # 3.2 重复降噪 + # 将action和vl-tokens复制多次,重复多次降噪 + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "trainer") + else self.config.framework.action_model.get("repeated_diffusion_steps", 4) + ) + # print(repeated_diffusion_steps) # 4 + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + # print(actions_target_repeated.shape) # torch.Size([32, 16, 32]) + # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048]) + + # 3.3 准备state、action_mask和embodiment_tag + state = [example["state"] for example in examples] if "state" in examples[0] else None + if state is not None: + # print('state is not None') + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + # print(state.shape) # torch.Size([8, 1, 64]) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + # print(state_repeated.shape) # torch.Size([32, 1, 64]) + else: + state_repeated = None + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + if action_mask is not None: + # print('action_mask is not None') + action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype) + # print(action_mask_tensor.shape) # torch.Size([8, 16, 32]) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :] + # print(action_mask_target.shape) # torch.Size([8, 16, 32]) + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + # print(action_mask_repeated.shape) # torch.Size([32, 16, 32]) + else: + action_mask_repeated = None + + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + if embodiment_tag is not None: + # print('embodiment_tag is not None') + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64) + # print(embodiment_tag.shape) # torch.Size([8]) + embodiment_tag = embodiment_tag.view(-1) + # print(embodiment_tag.shape) # torch.Size([8]) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) + # print(embodiment_tag_repeated.shape) # torch.Size([32]) + else: + embodiment_tag_repeated = None + + action_loss = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + ) + # print(type(self.action_model)) # + # print(last_hidden_repeated.shape) # torch.Size([32, 196, 2048]) + # print(actions_target_repeated.shape) # torch.Size([32, 16, 32]) + # print(state_repeated.shape) # torch.Size([32, 1, 64]) + # print(embodiment_tag_repeated.shape) # torch.Size([32]) + # print(action_mask_repeated.shape) # torch.Size([32, 16, 32]) + # print(action_loss) # tensor(1.5625, device='cuda:0', grad_fn=) + + # print('################# CosmoPredict2_Perceiver.forward-2') + return {"action_loss": action_loss} + + # @torch.inference_mode() + # def predict_action(self, examples: List[dict], **kwargs) -> dict: + # if type(examples) is not list: + # examples = [examples] + + # batch_images = [to_pil_preserve(example["image"]) for example in examples] + # instructions = [example["lang"] for example in examples] + # state = [example["state"] for example in examples] if "state" in examples[0] else None + # embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + + # train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + # if train_obs_image_size: + # batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + # wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + # with torch.autocast("cuda", dtype=torch.bfloat16): + # wm_outputs = self.backbone( + # **wm_inputs, + # output_hidden_states=True, + # return_dict=True, + # ) + # last_hidden = wm_outputs.hidden_states[-1] + + # state = ( + # torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + # if state is not None + # else None + # ) + # embodiment_tag = ( + # torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + # if embodiment_tag is not None + # else None + # ) + # if embodiment_tag is not None: + # embodiment_tag = embodiment_tag.view(-1) + + # with torch.autocast("cuda", dtype=torch.float32): + # pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + + # normalized_actions = pred_actions.detach().cpu().numpy() + # return {"normalized_actions": normalized_actions} diff --git a/starVLA/model/framework/WM4A/CosmoPredict2Policy.py b/starVLA/model/framework/WM4A/CosmoPredict2Policy.py new file mode 100644 index 0000000000000000000000000000000000000000..472332a91719fbeea911bbbb5cc565eb827cf957 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict2Policy.py @@ -0,0 +1,500 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2 Policy Framework. + +Minimal Cosmos-Policy-style implementation on top of the existing +Cosmos-Predict2 diffusers backbone. The action chunk is injected as one +extra latent frame, and the Cosmos DiT is trained to denoise that frame. +""" + +import math +import os +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict2PolicyDefaultConfig: + """Cosmos-Predict2 latent-action policy defaults.""" + + name: str = "CosmoPredict2Policy" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + }) + + policy: dict = field(default_factory=lambda: { + "min_timestep": 0.02, + "max_timestep": 1.0, + "noise_offset": 0.02, + "action_loss_weight": 1.0, + "future_image_loss_weight": 1.0, + "prediction_type": "x0", + # Keep the default sampler at one denoise step. The hand-written + # multi-step path below is not the official Cosmos Policy sampler and + # can drift badly for future-image decoding. + "num_inference_steps": 1, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2Policy") +class CosmoPredict2_Policy(baseframework): + """Cosmos-Predict2 with latent-frame action injection.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(CosmoPredict2PolicyDefaultConfig, config) + self.backbone = get_world_model(config=self.config) + self._disable_backbone_feature_hooks() + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.action_dim = self.config.framework.action_model.action_dim + + policy_cfg = self.config.framework.get("policy", {}) + self.min_timestep = float(policy_cfg.get("min_timestep", 0.02)) + self.max_timestep = float(policy_cfg.get("max_timestep", 1.0)) + self.noise_offset = float(policy_cfg.get("noise_offset", 0.02)) + self.action_loss_weight = float(policy_cfg.get("action_loss_weight", 1.0)) + self.future_image_loss_weight = float(policy_cfg.get("future_image_loss_weight", 1.0)) + self.prediction_type = policy_cfg.get("prediction_type", "x0") + self.num_inference_steps = int(policy_cfg.get("num_inference_steps", 1)) + self._warned_experimental_multistep = False + self._wm_debug_count = 0 + + def _disable_backbone_feature_hooks(self) -> None: + """Policy training does not use DiT feature hooks. + + The Cosmos2 backbone registers hooks for Perceiver/GR00T-style hidden + state extraction. In policy mode we call ``backbone.transformer`` + directly; leaving those hooks attached would append every step's DiT + activations to ``_intermediate_features`` and keep the autograd graph + alive, causing a linear GPU memory leak. + """ + for hook in getattr(self.backbone, "_hooks", []): + hook.remove() + if hasattr(self.backbone, "_hooks"): + self.backbone._hooks.clear() + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + def _begin_wm_debug_trace(self) -> bool: + if os.getenv("STARVLA_WM_DEBUG", "0").lower() not in {"1", "true", "yes", "on"}: + return False + max_traces = int(os.getenv("STARVLA_WM_DEBUG_MAX", "6")) + if self._wm_debug_count >= max_traces: + return False + self._wm_debug_count += 1 + return True + + @staticmethod + def _tensor_stats(name: str, tensor: torch.Tensor) -> str: + tensor = tensor.detach().float() + return ( + f"{name}:shape={tuple(tensor.shape)}," + f"mean={tensor.mean().item():.4g},std={tensor.std(unbiased=False).item():.4g}," + f"min={tensor.min().item():.4g},max={tensor.max().item():.4g}," + f"nan={torch.isnan(tensor).any().item()},inf={torch.isinf(tensor).any().item()}" + ) + + def _log_wm_debug(self, enabled: bool, label: str, **tensors) -> None: + if not enabled: + return + parts = [f"[WM_DEBUG_VERSION=20260506_step_trace] {type(self).__name__} {label}"] + for name, tensor in tensors.items(): + if tensor is not None: + parts.append(self._tensor_stats(name, tensor)) + print(" | ".join(parts), flush=True) + + def _select_action_chunk(self, actions) -> torch.Tensor: + actions = torch.tensor(np.array(actions), dtype=torch.float32) + return actions[:, -(self.future_action_window_size + 1):, :] + + @staticmethod + def _latent_slot_count(latents: torch.Tensor) -> int: + _, channels, _, height, width = latents.shape + return channels * height * width + + def _actions_to_latent_frame(self, actions: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + batch_size, channels, _, height, width = latents.shape + flat_actions = actions.reshape(batch_size, -1).to(device=latents.device, dtype=latents.dtype) + slot_count = self._latent_slot_count(latents) + repeat_factor = math.ceil(slot_count / flat_actions.shape[1]) + tiled_actions = flat_actions.repeat(1, repeat_factor)[:, :slot_count] + return tiled_actions.reshape(batch_size, channels, height, width) + + def _latent_frame_to_actions(self, action_frame: torch.Tensor, action_shape) -> torch.Tensor: + batch_size = action_frame.shape[0] + flat_frame = action_frame.reshape(batch_size, -1) + action_dim = int(np.prod(action_shape[1:])) + num_chunks = flat_frame.shape[1] // action_dim + action_chunks = flat_frame[:, : num_chunks * action_dim].reshape(batch_size, num_chunks, action_dim) + return action_chunks.mean(dim=1).reshape(batch_size, *action_shape[1:]) + + def _make_policy_inputs( + self, + wm_inputs: dict, + target_frames: List[torch.Tensor], + noises: List[torch.Tensor], + timestep: torch.Tensor, + add_noise_offset: bool = True, + ): + latents = wm_inputs["hidden_states"] + batch_size, _, t_lat, h_lat, w_lat = latents.shape + dtype = latents.dtype + + timestep_view = timestep.view(batch_size, 1, 1, 1) + noised_frames = [] + for target_frame, noise in zip(target_frames, noises): + noised_frame = (1.0 - timestep_view) * target_frame + timestep_view * noise + if add_noise_offset and self.noise_offset > 0: + noised_frame = noised_frame + self.noise_offset * torch.randn_like(noised_frame) + noised_frames.append(noised_frame.unsqueeze(2)) + + num_target_frames = len(noised_frames) + hidden_states = torch.cat([latents, *noised_frames], dim=2) + condition_mask = latents.new_zeros((batch_size, 1, t_lat + num_target_frames, h_lat, w_lat)) + obs_condition_mask = wm_inputs.get("condition_mask", None) + if obs_condition_mask is not None: + condition_mask[:, :, :t_lat] = obs_condition_mask.to(device=latents.device, dtype=latents.dtype) + else: + condition_mask[:, :, :t_lat] = 1.0 + + return { + "hidden_states": hidden_states.to(dtype), + "timestep": timestep.to(device=latents.device, dtype=torch.float32), + "encoder_hidden_states": wm_inputs["encoder_hidden_states"], + "condition_mask": condition_mask.to(dtype), + "padding_mask": wm_inputs.get("padding_mask", None), + } + + def _run_transformer(self, policy_inputs: dict, num_target_frames: int) -> torch.Tensor: + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + output = self.backbone.transformer( + hidden_states=policy_inputs["hidden_states"], + timestep=policy_inputs["timestep"], + encoder_hidden_states=policy_inputs["encoder_hidden_states"], + condition_mask=policy_inputs.get("condition_mask", None), + padding_mask=policy_inputs.get("padding_mask", None), + ) + + pred = output.sample if hasattr(output, "sample") else output + if isinstance(pred, tuple): + pred = pred[0] + pred_frames = pred[:, :, -num_target_frames:].float() + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + return pred_frames + + def _encode_future_image_frames(self, future_images: List) -> tuple[torch.Tensor, List[int]]: + future_latents, frame_counts, counts_are_latent_frames = self.backbone._encode_images(future_images) + if not counts_are_latent_frames: + frame_counts = [ + (frame_count - 1) // self.backbone.vae_scale_factor_temporal + 1 + for frame_count in frame_counts + ] + return future_latents.float(), frame_counts + + def _encode_future_image_frame(self, future_images: List) -> torch.Tensor: + future_latents, _ = self._encode_future_image_frames(future_images) + return future_latents[:, :, 0] + + def _decode_latent_frame(self, latent_frame: torch.Tensor) -> List[np.ndarray]: + return self._decode_latent_frames(latent_frame.unsqueeze(2)) + + def _decode_latent_frames(self, latent_frames: torch.Tensor, frame_counts: Optional[List[int]] = None) -> List[np.ndarray]: + batch_size, channels, num_frames, height, width = latent_frames.shape + latent_video = ( + latent_frames.permute(0, 2, 1, 3, 4) + .reshape(batch_size * num_frames, channels, 1, height, width) + .to(device=latent_frames.device, dtype=self.backbone.vae.dtype) + ) + + if self.backbone.vae.config.latents_mean is not None: + z_dim = self.backbone.vae.config.z_dim + latents_mean = ( + torch.tensor(self.backbone.vae.config.latents_mean) + .view(1, z_dim, 1, 1, 1) + .to(device=latent_video.device, dtype=latent_video.dtype) + ) + latents_std = ( + torch.tensor(self.backbone.vae.config.latents_std) + .view(1, z_dim, 1, 1, 1) + .to(device=latent_video.device, dtype=latent_video.dtype) + ) + sigma_data = self.backbone.scheduler.config.sigma_data + latent_video = latent_video / sigma_data * latents_std + latents_mean + + with torch.no_grad(): + decoded = self.backbone.vae.decode(latent_video).sample + + decoded = decoded[:, :, 0].float().clamp(-1, 1) + decoded = ((decoded + 1.0) * 127.5).clamp(0, 255).byte() + decoded = decoded.permute(0, 2, 3, 1) + decoded = decoded.reshape(batch_size, num_frames, decoded.shape[1], decoded.shape[2], decoded.shape[3]) + decoded = decoded.detach().cpu().numpy() + images = [] + if frame_counts is None: + frame_counts = [num_frames] * batch_size + for sample, frame_count in zip(decoded, frame_counts): + frame_count = max(1, min(int(frame_count), sample.shape[0])) + sample = sample[:frame_count] + if frame_count == 1: + images.append(sample[0]) + else: + images.append(np.concatenate([frame for frame in sample], axis=1)) + return images + + @staticmethod + def _image_frame_counts(images) -> List[int]: + frame_counts = [len(sample) if isinstance(sample, (list, tuple)) else 1 for sample in images] + return [max(1, int(frame_count)) for frame_count in frame_counts] + + def _num_image_frames(self, images) -> int: + frame_counts = self._image_frame_counts(images) + return max(frame_counts) if frame_counts else 1 + + @staticmethod + def _latent_frame_mask(frame_counts: List[int], num_frames: int, like: torch.Tensor) -> torch.Tensor: + mask = like.new_zeros((len(frame_counts), 1, num_frames, 1, 1), dtype=torch.float32) + for batch_idx, frame_count in enumerate(frame_counts): + mask[batch_idx, :, : max(1, min(int(frame_count), num_frames))] = 1.0 + return mask + + def _denoise_step(self, sample: torch.Tensor, pred: torch.Tensor, timestep: torch.Tensor, next_timestep: torch.Tensor): + timestep = timestep.view(-1, 1, 1, 1).to(device=sample.device, dtype=sample.dtype).clamp_min(1e-6) + next_timestep = next_timestep.view(-1, 1, 1, 1).to(device=sample.device, dtype=sample.dtype) + + if self.prediction_type == "noise": + pred_noise = pred.to(dtype=sample.dtype) + if torch.all(timestep >= 1.0 - 1e-6): + return sample + (next_timestep - timestep) * pred_noise + pred_x0 = (sample - timestep * pred_noise) / (1.0 - timestep).clamp_min(1e-6) + else: + pred_x0 = pred.to(dtype=sample.dtype) + pred_noise = (sample - (1.0 - timestep) * pred_x0) / timestep + + return (1.0 - next_timestep) * pred_x0 + next_timestep * pred_noise + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + batch_images = [example["image"] for example in examples] + future_images = [example["future_image"] for example in examples] if "future_image" in examples[0] else None + instructions = [example["lang"] for example in examples] + actions = self._select_action_chunk([example["action"] for example in examples]) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + latents = wm_inputs["hidden_states"] + actions = actions.to(device=latents.device, dtype=torch.float32) + target_action_frame = self._actions_to_latent_frame(actions, latents).float() + target_frames = [target_action_frame.to(latents.dtype)] + target_names = ["action"] + target_future_frames = None + future_frame_counts = None + future_start_index = None + + if future_images is not None and self.future_image_loss_weight > 0: + target_future_frames, future_frame_counts = self._encode_future_image_frames(future_images) + future_start_index = len(target_frames) + for frame_idx in range(target_future_frames.shape[2]): + target_frames.append(target_future_frames[:, :, frame_idx].to(latents.dtype)) + target_names.append("future_image") + + batch_size = target_action_frame.shape[0] + timestep = torch.empty(batch_size, device=latents.device).uniform_(self.min_timestep, self.max_timestep) + noises = [torch.randn_like(target_frame).to(latents.dtype) for target_frame in target_frames] + + policy_inputs = self._make_policy_inputs( + wm_inputs=wm_inputs, + target_frames=target_frames, + noises=noises, + timestep=timestep, + ) + pred_frames = self._run_transformer(policy_inputs, num_target_frames=len(target_frames)) + pred_action_frame = pred_frames[:, :, 0] + + action_target = noises[0].float() if self.prediction_type == "noise" else target_action_frame + action_loss = F.mse_loss(pred_action_frame, action_target, reduction="none") + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + if action_mask is not None: + action_mask = torch.tensor(np.array(action_mask), device=latents.device, dtype=torch.float32) + action_mask = action_mask[:, -(self.future_action_window_size + 1):, :] + latent_mask = self._actions_to_latent_frame(action_mask, latents).float().clamp(0.0, 1.0) + action_loss = action_loss * latent_mask + action_loss = action_loss.sum() / latent_mask.sum().clamp_min(1.0) + else: + action_loss = action_loss.mean() + + total_loss = action_loss * self.action_loss_weight + output = {"action_loss": total_loss, "action_latent_loss": action_loss.detach()} + + if target_future_frames is not None and future_frame_counts is not None and future_start_index is not None: + future_end_index = future_start_index + target_future_frames.shape[2] + pred_future_frame = pred_frames[:, :, future_start_index:future_end_index] + if self.prediction_type == "noise": + future_target = torch.stack(noises[future_start_index:future_end_index], dim=2).float() + else: + future_target = target_future_frames + future_mask = self._latent_frame_mask( + future_frame_counts, + target_future_frames.shape[2], + pred_future_frame, + ) + future_loss = F.mse_loss(pred_future_frame, future_target.float(), reduction="none") * future_mask + future_denom = future_mask.sum().clamp_min(1.0) * pred_future_frame.shape[1] * pred_future_frame.shape[3] * pred_future_frame.shape[4] + future_image_loss = future_loss.sum() / future_denom + total_loss = total_loss + future_image_loss * self.future_image_loss_weight + output["action_loss"] = total_loss + output["future_image_loss"] = future_image_loss.detach() + + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + latents = wm_inputs["hidden_states"] + batch_size, channels, _, height, width = latents.shape + action_shape = (batch_size, self.future_action_window_size + 1, self.action_dim) + future_frame_counts = self._image_frame_counts(batch_images) + num_future_frames = max(future_frame_counts) + + num_inference_steps = int(kwargs.get("num_inference_steps", self.num_inference_steps)) + num_inference_steps = max(num_inference_steps, 1) + action_inference_steps = num_inference_steps + if self.prediction_type == "x0": + action_inference_steps = 1 + debug_trace = self._begin_wm_debug_trace() + self._log_wm_debug( + debug_trace, + ( + f"start requested_num_inference_steps={num_inference_steps} " + f"action_inference_steps={action_inference_steps} prediction_type={self.prediction_type}" + ), + obs_latents=latents, + ) + if action_inference_steps != num_inference_steps and not self._warned_experimental_multistep: + print( + "Warning: CosmoPredict2Policy prediction_type=x0 is a one-step x0 predictor; " + "using one action denoise step and ignoring requested multi-step action sampling." + ) + self._warned_experimental_multistep = True + elif num_inference_steps > 1 and not self._warned_experimental_multistep: + print( + "Warning: CosmoPredict2Policy num_inference_steps > 1 uses an experimental " + "linear denoise loop, not the official Cosmos Policy sampler." + ) + self._warned_experimental_multistep = True + + target_frames = [torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype)] + if action_inference_steps == 1: + target_frames.extend( + torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype) + for _ in range(num_future_frames) + ) + timesteps = torch.linspace(1.0, 0.0, action_inference_steps + 1, device=latents.device, dtype=torch.float32) + + for step_idx in range(action_inference_steps): + timestep = timesteps[step_idx].expand(batch_size) + next_timestep = timesteps[step_idx + 1].expand(batch_size) + policy_inputs = self._make_policy_inputs( + wm_inputs=wm_inputs, + target_frames=target_frames, + noises=target_frames, + timestep=timestep, + add_noise_offset=False, + ) + pred_frames = self._run_transformer(policy_inputs, num_target_frames=len(target_frames)) + self._log_wm_debug( + debug_trace, + f"step={step_idx} t={timesteps[step_idx].item():.4g}->next={timesteps[step_idx + 1].item():.4g}", + sample_action_before=target_frames[0], + pred_action=pred_frames[:, :, 0], + pred_future=pred_frames[:, :, 1:] if pred_frames.shape[2] > 1 else None, + ) + target_frames = [ + self._denoise_step(target_frames[frame_idx], pred_frames[:, :, frame_idx], timestep, next_timestep) + for frame_idx in range(len(target_frames)) + ] + self._log_wm_debug( + debug_trace, + f"step={step_idx} after_update", + sample_action_after=target_frames[0], + ) + + pred_action_frame = target_frames[0].float() + pred_actions = self._latent_frame_to_actions(pred_action_frame, action_shape) + self._log_wm_debug( + debug_trace, + "final_action", + pred_action_frame=pred_action_frame, + pred_actions=pred_actions, + ) + + if action_inference_steps == 1: + pred_future_frames = torch.stack([frame.float() for frame in target_frames[1:]], dim=2) + else: + future_frames = [ + torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype) + for _ in range(num_future_frames) + ] + visual_frames = [ + torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype), + *future_frames, + ] + timestep = torch.ones(batch_size, device=latents.device, dtype=torch.float32) + policy_inputs = self._make_policy_inputs( + wm_inputs=wm_inputs, + target_frames=visual_frames, + noises=visual_frames, + timestep=timestep, + add_noise_offset=False, + ) + pred_frames = self._run_transformer(policy_inputs, num_target_frames=len(visual_frames)) + pred_future_frames = pred_frames[:, :, 1:].float() + self._log_wm_debug(debug_trace, "final_future", pred_future_frames=pred_future_frames) + pred_future_images = self._decode_latent_frames(pred_future_frames, frame_counts=future_frame_counts) + + return { + "normalized_actions": pred_actions.detach().cpu().numpy(), + "pred_future_images": pred_future_images, + } diff --git a/starVLA/model/framework/WM4A/CosmoPredict2PolicyEDM.py b/starVLA/model/framework/WM4A/CosmoPredict2PolicyEDM.py new file mode 100644 index 0000000000000000000000000000000000000000..3e42291e684d6981c0ad90c5a57025db5c5c10f0 --- /dev/null +++ b/starVLA/model/framework/WM4A/CosmoPredict2PolicyEDM.py @@ -0,0 +1,549 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +Cosmos-Predict2 EDM Policy Framework. + +This is an EDM/SDE variant of ``CosmoPredict2Policy`` following the sampling +semantics used by NVLabs Cosmos Policy: + + train: x_sigma = x0 + sigma * epsilon + denoise: model(c_in * x_sigma, c_noise) -> raw output, then EDM x0 head + inference: randn * sigma_max -> Karras sigma solver -> clean denoise + +It intentionally lives in a separate file so the existing policy route remains +available for A/B runs. +""" + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict2Policy import CosmoPredict2_Policy +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class CosmoPredict2PolicyEDMDefaultConfig: + """Cosmos-Predict2 latent-action policy defaults with EDM sigma-space.""" + + name: str = "CosmoPredict2PolicyEDM" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "nvidia/Cosmos-Predict2-2B-Video2World", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "nvidia/Cosmos-Predict2-2B-Video2World", + "vl_hidden_dim": 2048, + }) + + action_model: dict = field(default_factory=lambda: { + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + }) + + policy: dict = field(default_factory=lambda: { + "sigma_data": 1.0, + "sigma_min": 0.0002, + "sigma_max": 80.0, + "sigma_p_mean": -1.2, + "sigma_p_std": 1.2, + "hybrid_sigma_distribution": True, + "hybrid_sigma_lognormal_prob": 0.7, + "uniform_lower": 1.0, + "uniform_upper": 85.0, + "rho": 7.0, + "action_loss_weight": 1.0, + "future_image_loss_weight": 1.0, + "loss_weighting": "edm", + "max_loss_weight": 100.0, + "num_inference_steps": 1, + # Cosmos Policy Predict2 uses a truncated inference schedule for action + # prediction; keep training sigma_min separate from the sampling floor. + "inference_sigma_min": 4.0, + "inference_sigma_max": 80.0, + "sampler": "2ab", + "preconditioning": True, + "conditional_sigma": 0.002, + # Diffusers' Cosmos transformer does not expose the official + # PolicyVideo2World wrapper, so we provide the same c_noise values here. + "timestep_mapping": "c_noise", + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("CosmoPredict2PolicyEDM") +class CosmoPredict2_Policy_EDM(CosmoPredict2_Policy): + """Cosmos-Predict2 policy trained and sampled in EDM sigma-space.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(CosmoPredict2PolicyEDMDefaultConfig, config) + self.backbone = get_world_model(config=self.config) + self._disable_backbone_feature_hooks() + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.action_dim = self.config.framework.action_model.action_dim + + policy_cfg = self.config.framework.get("policy", {}) + self.sigma_data = float(policy_cfg.get("sigma_data", 1.0)) + self.sigma_min = float(policy_cfg.get("sigma_min", 0.002)) + self.sigma_max = float(policy_cfg.get("sigma_max", 80.0)) + self.sigma_p_mean = float(policy_cfg.get("sigma_p_mean", -1.2)) + self.sigma_p_std = float(policy_cfg.get("sigma_p_std", 1.2)) + self.hybrid_sigma_distribution = self._as_bool(policy_cfg.get("hybrid_sigma_distribution", True)) + self.hybrid_sigma_lognormal_prob = float(policy_cfg.get("hybrid_sigma_lognormal_prob", 0.7)) + self.uniform_lower = float(policy_cfg.get("uniform_lower", 1.0)) + self.uniform_upper = float(policy_cfg.get("uniform_upper", 85.0)) + self.rho = float(policy_cfg.get("rho", 7.0)) + self.action_loss_weight = float(policy_cfg.get("action_loss_weight", 1.0)) + self.future_image_loss_weight = float(policy_cfg.get("future_image_loss_weight", 1.0)) + self.loss_weighting = policy_cfg.get("loss_weighting", "edm") + self.max_loss_weight = float(policy_cfg.get("max_loss_weight", 100.0)) + self.num_inference_steps = int(policy_cfg.get("num_inference_steps", 1)) + self.inference_sigma_min = float(policy_cfg.get("inference_sigma_min", 4.0)) + self.inference_sigma_max = float(policy_cfg.get("inference_sigma_max", self.sigma_max)) + self.sampler = policy_cfg.get("sampler", "2ab").lower() + if self.sampler not in {"euler", "heun", "2ab"}: + raise ValueError(f"Unsupported sampler: {self.sampler}. Expected one of: euler, heun, 2ab.") + self.preconditioning = self._as_bool(policy_cfg.get("preconditioning", True)) + self.conditional_sigma = float(policy_cfg.get("conditional_sigma", self.sigma_min)) + self.timestep_mapping = policy_cfg.get("timestep_mapping", "c_noise") + self._wm_debug_count = 0 + + @staticmethod + def _as_bool(value) -> bool: + if isinstance(value, str): + return value.strip().lower() in {"1", "true", "yes", "y", "on"} + return bool(value) + + def _latent_frame_to_actions(self, action_frame: torch.Tensor, action_shape) -> torch.Tensor: + batch_size = action_frame.shape[0] + flat_dim = int(np.prod(action_shape[1:])) + flat_frame = action_frame.reshape(batch_size, -1) + slot_count = flat_frame.shape[1] + action_indices = torch.arange(slot_count, device=flat_frame.device) % flat_dim + + action_sum = flat_frame.new_zeros((batch_size, flat_dim)) + action_count = flat_frame.new_zeros((batch_size, flat_dim)) + action_sum.scatter_add_(1, action_indices.expand(batch_size, -1), flat_frame) + action_count.scatter_add_(1, action_indices.expand(batch_size, -1), torch.ones_like(flat_frame)) + return (action_sum / action_count.clamp_min(1.0)).reshape(batch_size, *action_shape[1:]) + + def _project_action_frame_to_action_manifold( + self, + action_frame: torch.Tensor, + action_shape, + latents: torch.Tensor, + ) -> torch.Tensor: + actions = self._latent_frame_to_actions(action_frame.float(), action_shape) + return self._actions_to_latent_frame(actions, latents).to(dtype=action_frame.dtype) + + def _sample_sigmas(self, batch_size: int, device: torch.device) -> torch.Tensor: + log_sigma = torch.randn(batch_size, device=device, dtype=torch.float32) + sigmas = torch.exp(log_sigma * self.sigma_p_std + self.sigma_p_mean) + if self.hybrid_sigma_distribution: + use_lognormal = torch.rand(batch_size, device=device) < self.hybrid_sigma_lognormal_prob + uniform_sigmas = torch.empty(batch_size, device=device, dtype=torch.float32).uniform_( + self.uniform_lower, + self.uniform_upper, + ) + sigmas = torch.where(use_lognormal, sigmas, uniform_sigmas) + return sigmas.clamp(self.sigma_min, self.sigma_max) + + def _preconditioning(self, sigmas: torch.Tensor, like: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if sigmas.ndim == 2 and like.ndim == 5: + sigma_shape = (sigmas.shape[0], 1, sigmas.shape[1], 1, 1) + else: + sigma_shape = (sigmas.shape[0],) + (1,) * (like.ndim - 1) + sigma = sigmas.to(device=like.device, dtype=torch.float32).view(sigma_shape) + sigma_data = torch.tensor(self.sigma_data, device=like.device, dtype=torch.float32) + denom = sigma.square() + sigma_data.square() + c_skip = sigma_data.square() / denom + c_out = sigma * sigma_data / denom.sqrt() + c_in = denom.rsqrt() + return ( + c_skip.to(dtype=like.dtype), + c_out.to(dtype=like.dtype), + c_in.to(dtype=like.dtype), + ) + + def _sigma_to_timestep(self, sigmas: torch.Tensor) -> torch.Tensor: + sigmas = sigmas.to(dtype=torch.float32) + if self.timestep_mapping == "c_noise": + return 0.25 * sigmas.clamp_min(1e-6).log() + if self.timestep_mapping == "sigma": + return sigmas + if self.timestep_mapping == "log_sigma": + return sigmas.clamp_min(1e-6).log() + if self.timestep_mapping == "sigma_to_t": + return sigmas / (sigmas + self.sigma_data) + raise ValueError(f"Unsupported timestep_mapping: {self.timestep_mapping}") + + def _loss_weights(self, sigmas: torch.Tensor) -> torch.Tensor: + if self.loss_weighting == "none": + weights = torch.ones_like(sigmas) + elif self.loss_weighting == "edm": + weights = (sigmas**2 + self.sigma_data**2) / (sigmas * self.sigma_data).clamp_min(1e-6) ** 2 + else: + raise ValueError(f"Unsupported loss_weighting: {self.loss_weighting}") + + if self.max_loss_weight > 0: + weights = weights.clamp_max(self.max_loss_weight) + return weights + + def _make_edm_policy_inputs( + self, + wm_inputs: dict, + sample_frames: List[torch.Tensor], + sigmas: torch.Tensor, + sample_sigmas: Optional[List[torch.Tensor]] = None, + sample_condition_mask: Optional[List[bool]] = None, + ) -> dict: + latents = wm_inputs["hidden_states"] + batch_size, _, t_lat, h_lat, w_lat = latents.shape + dtype = latents.dtype + if sample_sigmas is None: + sample_sigmas = [sigmas for _ in sample_frames] + if len(sample_sigmas) != len(sample_frames): + raise ValueError(f"Expected {len(sample_frames)} sample sigmas, got {len(sample_sigmas)}.") + + scaled_sample_frames = [] + for frame, frame_sigmas in zip(sample_frames, sample_sigmas): + if self.preconditioning: + _, _, c_in = self._preconditioning(frame_sigmas, frame) + frame = frame * c_in + scaled_sample_frames.append(frame.unsqueeze(2)) + + hidden_states = torch.cat([latents, *scaled_sample_frames], dim=2) + condition_mask = latents.new_zeros((batch_size, 1, t_lat + len(sample_frames), h_lat, w_lat)) + obs_condition_mask = wm_inputs.get("condition_mask", None) + if obs_condition_mask is not None: + condition_mask[:, :, :t_lat] = obs_condition_mask.to(device=latents.device, dtype=latents.dtype) + else: + condition_mask[:, :, :t_lat] = 1.0 + + obs_timestep = wm_inputs.get("timestep", None) + if obs_timestep is not None: + obs_timestep = obs_timestep.to(device=latents.device, dtype=dtype) + if obs_timestep.ndim == 1: + obs_timestep = obs_timestep.view(batch_size, 1, 1, 1, 1).expand(batch_size, 1, t_lat, 1, 1) + else: + obs_sigmas = latents.new_full((batch_size,), self.conditional_sigma, dtype=torch.float32) + obs_timestep = self._sigma_to_timestep(obs_sigmas).view(batch_size, 1, 1, 1, 1) + obs_timestep = obs_timestep.to(device=latents.device, dtype=dtype) + obs_timestep = obs_timestep.expand(batch_size, 1, t_lat, 1, 1) + + target_timesteps = [] + for frame_sigmas in sample_sigmas: + target_timestep = self._sigma_to_timestep(frame_sigmas).view(batch_size, 1, 1, 1, 1) + target_timesteps.append(target_timestep.to(device=latents.device, dtype=dtype)) + target_timestep = torch.cat(target_timesteps, dim=2) + timestep_tensor = torch.cat([obs_timestep, target_timestep], dim=2) + + if sample_condition_mask is not None: + if len(sample_condition_mask) != len(sample_frames): + raise ValueError(f"Expected {len(sample_frames)} sample condition masks, got {len(sample_condition_mask)}.") + for frame_idx, is_condition in enumerate(sample_condition_mask): + if is_condition: + condition_mask[:, :, t_lat + frame_idx] = 1.0 + + return { + "hidden_states": hidden_states.to(dtype), + "timestep": timestep_tensor, + "encoder_hidden_states": wm_inputs["encoder_hidden_states"], + "condition_mask": condition_mask.to(dtype), + "padding_mask": wm_inputs.get("padding_mask", None), + } + + def _denoise_x0( + self, + wm_inputs: dict, + sample_frames: List[torch.Tensor], + sigmas: torch.Tensor, + sample_sigmas: Optional[List[torch.Tensor]] = None, + sample_condition_mask: Optional[List[bool]] = None, + ) -> torch.Tensor: + if sample_sigmas is None: + sample_sigmas = [sigmas for _ in sample_frames] + policy_inputs = self._make_edm_policy_inputs( + wm_inputs=wm_inputs, + sample_frames=sample_frames, + sigmas=sigmas, + sample_sigmas=sample_sigmas, + sample_condition_mask=sample_condition_mask, + ) + raw_pred_frames = self._run_transformer(policy_inputs, num_target_frames=len(sample_frames)) + if not self.preconditioning: + return raw_pred_frames + + sample_stack = torch.stack([frame.float() for frame in sample_frames], dim=2) + sigma_stack = torch.stack([frame_sigmas.to(device=sample_stack.device) for frame_sigmas in sample_sigmas], dim=1) + c_skip, c_out, _ = self._preconditioning(sigma_stack, sample_stack) + return c_skip.float() * sample_stack + c_out.float() * raw_pred_frames.float() + + def _karras_sigmas( + self, + num_steps: int, + device: torch.device, + sigma_max: Optional[float] = None, + sigma_min: Optional[float] = None, + ) -> torch.Tensor: + sigma_max = self.sigma_max if sigma_max is None else float(sigma_max) + sigma_min = self.sigma_min if sigma_min is None else float(sigma_min) + if sigma_max < sigma_min: + raise ValueError(f"sigma_max must be >= sigma_min, got {sigma_max:g} < {sigma_min:g}.") + if num_steps <= 1: + return torch.tensor([sigma_max], device=device, dtype=torch.float32) + + ramp = torch.linspace(0, 1, num_steps, device=device, dtype=torch.float32) + min_inv_rho = sigma_min ** (1.0 / self.rho) + max_inv_rho = sigma_max ** (1.0 / self.rho) + return (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** self.rho + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + batch_images = [example["image"] for example in examples] + future_images = [example["future_image"] for example in examples] if "future_image" in examples[0] else None + instructions = [example["lang"] for example in examples] + actions = self._select_action_chunk([example["action"] for example in examples]) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + latents = wm_inputs["hidden_states"] + actions = actions.to(device=latents.device, dtype=torch.float32) + target_action_frame = self._actions_to_latent_frame(actions, latents).float() + target_frames = [target_action_frame.to(latents.dtype)] + target_names = ["action"] + target_future_frames = None + future_frame_counts = None + future_start_index = None + + if future_images is not None and self.future_image_loss_weight > 0: + target_future_frames, future_frame_counts = self._encode_future_image_frames(future_images) + future_start_index = len(target_frames) + for frame_idx in range(target_future_frames.shape[2]): + target_frames.append(target_future_frames[:, :, frame_idx].to(latents.dtype)) + target_names.append("future_image") + + batch_size = target_action_frame.shape[0] + sigmas = self._sample_sigmas(batch_size, latents.device) + sigma_view = sigmas.view(batch_size, 1, 1, 1) + noises = [torch.randn_like(target_frame).to(latents.dtype) for target_frame in target_frames] + sample_frames = [ + target_frame + sigma_view.to(target_frame.dtype) * noise + for target_frame, noise in zip(target_frames, noises) + ] + + pred_frames = self._denoise_x0(wm_inputs=wm_inputs, sample_frames=sample_frames, sigmas=sigmas) + pred_action_frame = pred_frames[:, :, 0] + + loss_weight = self._loss_weights(sigmas).view(batch_size, 1, 1, 1) + action_loss = F.mse_loss(pred_action_frame, target_action_frame, reduction="none") * loss_weight + + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + if action_mask is not None: + action_mask = torch.tensor(np.array(action_mask), device=latents.device, dtype=torch.float32) + action_mask = action_mask[:, -(self.future_action_window_size + 1):, :] + latent_mask = self._actions_to_latent_frame(action_mask, latents).float().clamp(0.0, 1.0) + action_loss = action_loss * latent_mask + action_loss = action_loss.sum() / latent_mask.sum().clamp_min(1.0) + else: + action_loss = action_loss.mean() + + total_loss = action_loss * self.action_loss_weight + output = {"action_loss": total_loss, "action_latent_loss": action_loss.detach()} + + if target_future_frames is not None and future_frame_counts is not None and future_start_index is not None: + future_end_index = future_start_index + target_future_frames.shape[2] + pred_future_frame = pred_frames[:, :, future_start_index:future_end_index] + future_mask = self._latent_frame_mask( + future_frame_counts, + target_future_frames.shape[2], + pred_future_frame, + ) + future_loss = ( + F.mse_loss(pred_future_frame, target_future_frames.float(), reduction="none") + * loss_weight.unsqueeze(2) + * future_mask + ) + future_denom = future_mask.sum().clamp_min(1.0) * pred_future_frame.shape[1] * pred_future_frame.shape[3] * pred_future_frame.shape[4] + future_image_loss = future_loss.sum() / future_denom + total_loss = total_loss + future_image_loss * self.future_image_loss_weight + output["action_loss"] = total_loss + output["future_image_loss"] = future_image_loss.detach() + + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + latents = wm_inputs["hidden_states"] + batch_size, channels, _, height, width = latents.shape + action_shape = (batch_size, self.future_action_window_size + 1, self.action_dim) + future_frame_counts = self._image_frame_counts(batch_images) + num_future_frames = max(future_frame_counts) + + num_inference_steps = max(int(kwargs.get("num_inference_steps", self.num_inference_steps)), 1) + inference_sigma_min = float(kwargs.get("inference_sigma_min", self.inference_sigma_min)) + inference_sigma_max = float(kwargs.get("inference_sigma_max", self.inference_sigma_max)) + solver_steps = num_inference_steps - 1 if num_inference_steps > 1 else 1 + sigmas = self._karras_sigmas( + solver_steps, + latents.device, + sigma_max=inference_sigma_max, + sigma_min=inference_sigma_min, + ) + debug_trace = self._begin_wm_debug_trace() + self._log_wm_debug( + debug_trace, + ( + f"start num_inference_steps={num_inference_steps} sampler={self.sampler} " + f"train_sigma_min={self.sigma_min:g} train_sigma_max={self.sigma_max:g} " + f"inference_sigma_min={inference_sigma_min:g} " + f"inference_sigma_max={inference_sigma_max:g} " + f"preconditioning={self.preconditioning} timestep_mapping={self.timestep_mapping}" + ), + obs_latents=latents, + sigmas=sigmas, + ) + sample_frames = [ + torch.randn(batch_size, channels, height, width, device=latents.device, dtype=latents.dtype) + * sigmas[0].to(dtype=latents.dtype) + for _ in range(1 + num_future_frames) + ] + + if num_inference_steps == 1: + sigma_batch = sigmas[0].expand(batch_size) + pred_frames = self._denoise_x0(wm_inputs=wm_inputs, sample_frames=sample_frames, sigmas=sigma_batch) + self._log_wm_debug( + debug_trace, + f"single_step sigma={sigmas[0].item():.4g}", + sample_action=sample_frames[0], + pred_action=pred_frames[:, :, 0], + pred_future=pred_frames[:, :, 1:] if pred_frames.shape[2] > 1 else None, + ) + else: + previous_derivatives = None + for step_idx in range(len(sigmas) - 1): + sigma = sigmas[step_idx] + next_sigma = sigmas[step_idx + 1] + dt = (next_sigma - sigma).to(device=latents.device, dtype=latents.dtype) + sigma_batch = sigma.expand(batch_size) + pred_frames = self._denoise_x0(wm_inputs=wm_inputs, sample_frames=sample_frames, sigmas=sigma_batch) + derivatives = [] + euler_frames = [] + for frame_idx, sample in enumerate(sample_frames): + pred_x0 = pred_frames[:, :, frame_idx].to(dtype=sample.dtype) + derivative = (sample - pred_x0) / sigma.clamp_min(1e-6).to(dtype=sample.dtype) + derivatives.append(derivative) + euler_frames.append(sample + dt.to(dtype=sample.dtype) * derivative) + + self._log_wm_debug( + debug_trace, + f"step={step_idx} sigma={sigma.item():.4g}->next={next_sigma.item():.4g}", + sample_action_before=sample_frames[0], + sample_future_before=sample_frames[1] if len(sample_frames) > 1 else None, + pred_action=pred_frames[:, :, 0], + pred_future=pred_frames[:, :, 1:] if pred_frames.shape[2] > 1 else None, + derivative_action=derivatives[0], + euler_action=euler_frames[0], + ) + + if self.sampler == "2ab" and previous_derivatives is not None: + sample_frames = [ + sample + + dt.to(dtype=sample.dtype) + * (1.5 * derivative - 0.5 * previous_derivative.to(dtype=derivative.dtype)) + for sample, derivative, previous_derivative in zip( + sample_frames, + derivatives, + previous_derivatives, + ) + ] + elif self.sampler == "heun" and next_sigma > self.sigma_min: + next_sigma_batch = next_sigma.expand(batch_size) + next_pred_frames = self._denoise_x0( + wm_inputs=wm_inputs, + sample_frames=euler_frames, + sigmas=next_sigma_batch, + ) + sample_frames = [ + sample + + dt.to(dtype=sample.dtype) + * ( + derivative + + (euler - next_pred_frames[:, :, frame_idx].to(dtype=sample.dtype)) + / next_sigma.clamp_min(1e-6).to(dtype=sample.dtype) + ) + * 0.5 + for frame_idx, (sample, euler, derivative) in enumerate( + zip(sample_frames, euler_frames, derivatives) + ) + ] + else: + sample_frames = euler_frames + previous_derivatives = [derivative.detach() for derivative in derivatives] + + sample_frames[0] = self._project_action_frame_to_action_manifold( + sample_frames[0], + action_shape, + latents, + ) + self._log_wm_debug( + debug_trace, + f"step={step_idx} after_update", + sample_action_after=sample_frames[0], + sample_future_after=sample_frames[1] if len(sample_frames) > 1 else None, + ) + + clean_sigma_batch = sigmas[-1].expand(batch_size) + pred_frames = self._denoise_x0(wm_inputs=wm_inputs, sample_frames=sample_frames, sigmas=clean_sigma_batch) + self._log_wm_debug( + debug_trace, + f"clean_denoise sigma={sigmas[-1].item():.4g}", + sample_action=sample_frames[0], + sample_future=sample_frames[1] if len(sample_frames) > 1 else None, + pred_action=pred_frames[:, :, 0], + pred_future=pred_frames[:, :, 1:] if pred_frames.shape[2] > 1 else None, + ) + + pred_action_frame = pred_frames[:, :, 0].float() + pred_future_frames = pred_frames[:, :, 1:].float() + pred_actions = self._latent_frame_to_actions(pred_action_frame, action_shape) + self._log_wm_debug( + debug_trace, + "final_action", + pred_action_frame=pred_action_frame, + pred_actions=pred_actions, + ) + + self._log_wm_debug(debug_trace, "final_future", pred_future_frames=pred_future_frames) + pred_future_images = self._decode_latent_frames(pred_future_frames, frame_counts=future_frame_counts) + + return { + "normalized_actions": pred_actions.detach().cpu().numpy(), + "pred_future_images": pred_future_images, + } diff --git a/starVLA/model/framework/WM4A/JoyRA05MaskFutureImage.py b/starVLA/model/framework/WM4A/JoyRA05MaskFutureImage.py new file mode 100644 index 0000000000000000000000000000000000000000..953569de48f07aae9c6e0cec36ce6145fdb742f9 --- /dev/null +++ b/starVLA/model/framework/WM4A/JoyRA05MaskFutureImage.py @@ -0,0 +1,452 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""Wan2.2-TI2V Perceiver with masked future-image denoising.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import List, Optional + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import ( + CosmoPredict25PerceiverFutureImageDefaultConfig, +) +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverMaskedFutureImage import ( + CosmoPredict25_Perceiver_MaskedFutureImage, +) +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.vlm import get_vlm_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class JoyRA05MaskFutureImageDefaultConfig(CosmoPredict25PerceiverFutureImageDefaultConfig): + """Wan2.2-TI2V Perceiver + masked future-image defaults.""" + + name: str = "JoyRA05MaskFutureImage" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + "height": 224, + "width": 224, + "freeze_text_encoder": True, + "freeze_vae": True, + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 3072, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + "timestep_scale": 1000.0, + "single_frame_condition_prob": 0.0, + "change_mask_enabled": True, + "change_mask_top_ratio": 0.25, + "change_mask_static_weight": 0.05, + "change_mask_soft_loss": True, + "masked_denoising": False, + "condition_static_regions": False, + }) + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 81, + "num_inference_steps": 50, + "guidance_scale": 5.0, + "output_type": "pil", + "height": 224, + "width": 224, + "max_sequence_length": 512, + "conditioning_mode": "image", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + +@FRAMEWORK_REGISTRY.register("JoyRA05MaskFutureImage") +class JoyRA05_MaskedFutureImage(CosmoPredict25_Perceiver_MaskedFutureImage): + """Perceiver action head plus Wan2.2 per-token masked flow matching.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(JoyRA05MaskFutureImageDefaultConfig, config) + + self.qwen_vl_interface = get_vlm_model(config=self.config) + # 保持与历史 checkpoint 键名一致:主模块名使用 wan_interface.* + self.wan_interface = get_world_model(config=self.config) + + qwen_hidden = self.qwen_vl_interface.model.config.hidden_size + wm_hidden = self.wan_interface.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = qwen_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = qwen_hidden + + wm_cfg = self.config.framework.get("world_model", {}) if self.config is not None else {} + self._pool_wm_sequence = bool(wm_cfg.get("pool_wm_sequence", False)) + self.wm_projector = nn.Linear(wm_hidden, qwen_hidden) + self.wm_post_norm = nn.LayerNorm(qwen_hidden, eps=1e-6) + gain = float(wm_cfg.get("wm_projector_init_gain", 0.02)) + nn.init.xavier_uniform_(self.wm_projector.weight, gain=gain) + nn.init.zeros_(self.wm_projector.bias) + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + + qwenvl_cfg = self.config.framework.get("qwenvl", {}) if self.config is not None else {} + if self._as_bool(wm_cfg.get("freeze_text_encoder", True)) and hasattr(self.wan_interface, "text_encoder"): + for p in self.wan_interface.text_encoder.parameters(): + p.requires_grad = False + if self._as_bool(wm_cfg.get("freeze_vae", True)) and hasattr(self.wan_interface, "vae"): + for p in self.wan_interface.vae.parameters(): + p.requires_grad = False + if self._as_bool(qwenvl_cfg.get("is_frozen", True)): + for p in self.qwen_vl_interface.parameters(): + p.requires_grad = False + + + def _fuse_vlm_with_wm(self, last_vlm_hidden: torch.Tensor, last_wm_hidden: torch.Tensor) -> torch.Tensor: + if self._pool_wm_sequence: + last_wm_hidden = last_wm_hidden.mean(dim=1, keepdim=True) + wm_input = last_wm_hidden.to(dtype=self.wm_projector.weight.dtype) + wm_aligned = self.wm_post_norm(self.wm_projector(wm_input)).to(dtype=last_vlm_hidden.dtype) + return torch.cat([last_vlm_hidden, wm_aligned], dim=1) + + def forward(self, examples: List[dict] = None, **kwargs) -> dict: + training_cfg = self._future_training_cfg() + examples, single_frame_ratio = self._maybe_apply_single_frame_condition(examples, training_cfg) + + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + action_mask = [example["action_mask"] for example in examples] if "action_mask" in examples[0] else None + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + wm_inputs = self.wan_interface.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.wan_interface(**wm_inputs, output_hidden_states=True, return_dict=True) + last_wm_hidden = wm_outputs.hidden_states[-1] + qwen_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwen_outputs.hidden_states[-1] + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor(np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + repeated_diffusion_steps = ( + self.config.trainer.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "trainer") + else self.config.framework.action_model.get("repeated_diffusion_steps", 4) + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + state = self._align_state_dim(state) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_mask_repeated = None + if action_mask is not None: + action_mask_tensor = torch.tensor(np.array(action_mask), device=last_hidden.device, dtype=last_hidden.dtype) + action_mask_target = action_mask_tensor[:, -(self.future_action_window_size + 1):, :] + action_mask_repeated = action_mask_target.repeat(repeated_diffusion_steps, 1, 1) + + embodiment_tag_repeated = None + if embodiment_tag is not None: + embodiment_tag = torch.tensor(np.array(embodiment_tag), device=last_hidden.device, dtype=torch.int64).view(-1) + embodiment_tag_repeated = embodiment_tag.repeat(repeated_diffusion_steps) + + action_loss = self.action_model( + last_hidden_repeated, + actions_target_repeated, + state_repeated, + embodiment_tag_repeated, + action_mask=action_mask_repeated, + ) + + output = {"action_loss": action_loss} + future_image_loss = self._cosmos25_future_image_loss(examples) + if future_image_loss is None: + if single_frame_ratio > 0.0: + output["single_frame_condition_ratio"] = single_frame_ratio + return output + + loss_weight = float(self._future_training_cfg().get("loss_weight", 1.0)) + output["perceiver_action_loss"] = action_loss.detach() + output["future_image_loss"] = future_image_loss.detach() + if single_frame_ratio > 0.0: + output["single_frame_condition_ratio"] = single_frame_ratio + output["action_loss"] = action_loss + future_image_loss * loss_weight + return output + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + embodiment_tag = [example["embodiment_tag"] for example in examples] if "embodiment_tag" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + qwen_inputs = self.qwen_vl_interface.build_qwenvl_inputs(images=batch_images, instructions=instructions) + wm_inputs = self.wan_interface.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.wan_interface( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_wm_hidden = wm_outputs.hidden_states[-1] + + qwen_outputs = self.qwen_vl_interface( + **qwen_inputs, + output_attentions=False, + output_hidden_states=True, + return_dict=True, + ) + last_vlm_hidden = qwen_outputs.hidden_states[-1] + + last_hidden = self._fuse_vlm_with_wm(last_vlm_hidden, last_wm_hidden) + + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + state = self._align_state_dim(state) + embodiment_tag = ( + torch.from_numpy(np.array(embodiment_tag)).to(last_hidden.device, dtype=torch.int64) + if embodiment_tag is not None + else None + ) + if embodiment_tag is not None: + embodiment_tag = embodiment_tag.view(-1) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state, embodiment_tag) + + output = {"normalized_actions": pred_actions.detach().cpu().numpy()} + + generation_cfg = self._get_future_image_generation_cfg(kwargs) + if not bool(generation_cfg.pop("enabled", True)): + return output + + return_full_video = bool(generation_cfg.pop("return_full_video", False)) + future_frame_index = int(generation_cfg.pop("future_frame_index", -1)) + max_samples = int(generation_cfg.pop("max_samples", 1)) + generation_inputs = self._build_generation_inputs(batch_images, instructions, generation_cfg) + output["pred_future_images"] = self._generate_future_images( + generation_inputs, + batch_size=len(examples), + max_samples=max_samples, + future_frame_index=future_frame_index, + return_full_video=return_full_video, + ) + + return output + + def _make_wan_timestep( + self, + hidden_states: torch.Tensor, + denoise_mask: torch.Tensor, + flow_time: torch.Tensor, + timestep_scale: float, + ) -> torch.Tensor: + """Convert the latent denoise mask into Wan's per-patch timestep tokens.""" + batch_size, _, num_frames, height, width = hidden_states.shape + p_t, p_h, p_w = self.wan_interface.transformer.config.patch_size + if num_frames % p_t or height % p_h or width % p_w: + raise ValueError( + "Wan latent shape must be divisible by transformer.patch_size; " + f"got {(num_frames, height, width)} and {(p_t, p_h, p_w)}." + ) + + patch_mask = F.max_pool3d( + denoise_mask.float(), + kernel_size=(p_t, p_h, p_w), + stride=(p_t, p_h, p_w), + ) + patch_mask = patch_mask[:, 0].flatten(1) + seq_len = patch_mask.shape[1] + rope_max_seq_len = getattr(self.wan_interface.transformer.config, "rope_max_seq_len", None) + if rope_max_seq_len is not None and seq_len > int(rope_max_seq_len): + raise ValueError( + f"Wan future-image seq_len={seq_len} exceeds rope_max_seq_len={rope_max_seq_len}. " + "Reduce observation frames or image resolution." + ) + + scaled_time = flow_time.to(device=hidden_states.device, dtype=torch.float32) * float(timestep_scale) + return patch_mask * scaled_time[:, None] + + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + """Compute masked Wan flow loss (method name retained for parent forward compatibility).""" + if "future_image" not in examples[0]: + return None + + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + prompt_embeds = self.wan_interface._encode_text(instructions) + clean_latents = self.wan_interface._encode_images_vae(raw_sequences) + dtype = self.wan_interface.transformer.dtype + clean_latents = clean_latents.to(dtype=dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width) + + use_change_mask = self._as_bool(training_cfg.get("change_mask_enabled", True)) + if use_change_mask: + change_binary, change_loss_weight = self._build_latent_change_masks( + batch_images=batch_images, + future_images=future_images, + latent_height=height, + latent_width=width, + training_cfg=training_cfg, + device=device, + ) + change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype) + change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32) + else: + change_binary = clean_latents.new_ones((batch_size, 1, 1, height, width)) + change_loss_weight = clean_latents.new_ones( + (batch_size, 1, 1, height, width), dtype=torch.float32 + ) + + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + time_view = flow_time.view(batch_size, 1, 1, 1, 1).to(dtype=clean_latents.dtype) + + noise = torch.randn_like(clean_latents) + noisy_latents = clean_latents * (1.0 - time_view) + noise * time_view + use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", False)) + use_static_conditioning = use_masked_denoising and self._as_bool( + training_cfg.get("condition_static_regions", False) + ) + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) + if use_masked_denoising: + denoise_mask = denoise_mask * change_binary + hidden_states = torch.where(denoise_mask.bool(), noisy_latents, clean_latents) + target_velocity = noise.float() - clean_latents.float() + + timestep_mask = denoise_mask if use_static_conditioning else target_spatial_mask + timestep = self._make_wan_timestep( + hidden_states=hidden_states, + denoise_mask=timestep_mask, + flow_time=flow_time, + timestep_scale=float(training_cfg.get("timestep_scale", 1000.0)), + ) + + if hasattr(self.wan_interface, "_intermediate_features"): + self.wan_interface._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.wan_interface.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.wan_interface, "_intermediate_features"): + self.wan_interface._intermediate_features.clear() + + if use_static_conditioning: + change_loss_weight = change_loss_weight * change_binary.float() + spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width) + loss_mask = target_spatial_mask * spatial_loss_weight + loss_mask = loss_mask.expand(batch_size, channels, num_latents, height, width) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + """Build arguments accepted by Diffusers WanImageToVideoPipeline.""" + mode = str(cfg.pop("conditioning_mode", "image")).lower() + if mode not in {"auto", "image", "video"}: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + height = cfg.pop("height", getattr(self.wan_interface, "height", 480)) + width = cfg.pop("width", getattr(self.wan_interface, "width", 832)) + resolved_height, resolved_width = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "image": [self._as_sequence(images)[-1] for images in batch_images], + "prompt": instructions, + "height": resolved_height, + "width": resolved_width, + "num_frames": cfg.pop("num_frames", 81), + "num_inference_steps": cfg.pop("num_inference_steps", 50), + "guidance_scale": cfg.pop("guidance_scale", 5.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + } + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + # Cosmos-only knobs may still be present in a shared YAML. + cfg.pop("conditional_frame_timestep", None) + cfg.pop("num_latent_conditional_frames", None) + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs diff --git a/starVLA/model/framework/WM4A/WM4A_OFT.py b/starVLA/model/framework/WM4A/WM4A_OFT.py new file mode 100644 index 0000000000000000000000000000000000000000..e8d47be481e1fdfcda4deb781d31d2f1ebf60e9a --- /dev/null +++ b/starVLA/model/framework/WM4A/WM4A_OFT.py @@ -0,0 +1,199 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +WM4A-OFT Framework — World Model + MLP Regression for Action Prediction. + +A lightweight WM4A variant inspired by OpenVLA-OFT: instead of a heavy +flow-matching diffusion action head, it uses a simple MLP with L1 regression +over pooled DiT hidden states. + +Supports any world-model backend registered in ``get_world_model()`` +(Cosmos-Predict2, Wan2.2-TI2V, etc.). The world model hidden_dim is +auto-detected at runtime. + +Architecture: + Text encoder + Image encoder → DiT Transformer + → hidden_states [B, N_tokens, hidden_dim] + → Adaptive pool → [B, chunk_len, hidden_dim] + → MLP (L1 regression) → action predictions [B, chunk_len, action_dim] + +Key differences from WM4A-GR00T variants: + - Action head: MLP L1 regression (not flow-matching diffusion) + - No repeated_diffusion_steps (single forward pass) + - Faster training & inference, suitable for real-time deployment +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch +import torch.nn as nn + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.MLP_ActionHeader import get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class WM4AOFTDefaultConfig: + """WM4A-OFT default parameters.""" + + name: str = "WM4A_OFT" + + # === World Model backbone (any supported WM) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B", + "extract_layers": [-1], + }) + + # Legacy compat: vlm/__init__.py and world_model/__init__.py fall back to + # config.framework.qwenvl.base_vlm when world_model.base_wm is absent. + # Some action heads (VLA_AdapterHeader, LayerwiseFM) also read + # qwenvl.vl_hidden_dim / num_vl_layers. WM4A_OFT uses neither of those + # action heads, so we only mirror base_vlm here for the factory fallback. + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B", + }) + + # === Action head (MLP L1 regression) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "MLP", + "action_dim": 7, + # Will be auto-set at runtime from world model hidden_size + "action_hidden_dim": 3072, + "future_action_window_size": 8, + "past_action_window_size": 0, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("WM4A_OFT") +class WM4A_OFT(baseframework): + """ + World-Model-for-Action framework with MLP regression (OFT variant). + + Components: + - Any DiT world model backbone for spatiotemporal feature extraction + - Adaptive pooling to compress spatial tokens into action queries + - MLP regression head (L1 loss) for continuous action prediction + + This is a lightweight alternative to the GR00T variants that use + flow-matching diffusion heads. Faster training and inference, + suitable for real-time deployment. + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(WM4AOFTDefaultConfig, config) + + # Load world model backbone + self.backbone = get_world_model(config=self.config) + + # Auto-align action_hidden_dim to world model hidden size + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.action_model.action_hidden_dim = wm_hidden + + self.action_model = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # Learnable projection: pool N spatial tokens → chunk_len action queries + self.action_query_proj = nn.Linear(wm_hidden, self.chunk_len * wm_hidden) + + self.l1_loss = nn.L1Loss() + + def _pool_to_action_queries(self, hidden_states: torch.Tensor) -> torch.Tensor: + """Pool spatiotemporal tokens into fixed-size action queries. + + Args: + hidden_states: [B, N_tokens, hidden_dim] from DiT + + Returns: + action_queries: [B, chunk_len, hidden_dim] + """ + B, N, H = hidden_states.shape + # Global average pool over spatial tokens → [B, H] + pooled = hidden_states.mean(dim=1) # [B, H] + # Project to chunk_len separate queries + queries = self.action_query_proj(pooled) # [B, chunk_len * H] + action_queries = queries.view(B, self.chunk_len, H) # [B, chunk_len, H] + return action_queries + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + # Step 1: World model input encoding + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + # Step 2: DiT forward to extract spatiotemporal features + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] # [B, N_tokens, hidden_dim] + + # Step 3: Pool to action queries and predict + with torch.autocast("cuda", dtype=torch.float32): + action_queries = self._pool_to_action_queries(last_hidden) # [B, chunk_len, H] + pred_actions = self.action_model.predict_action(action_queries) # [B, chunk_len, action_dim] + + actions = torch.tensor( + np.array(actions), device=pred_actions.device, dtype=pred_actions.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + action_loss = self.l1_loss(pred_actions, actions_target) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> np.ndarray: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.float32): + action_queries = self._pool_to_action_queries(last_hidden) + pred_actions = self.action_model.predict_action(action_queries) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} diff --git a/starVLA/model/framework/WM4A/WanGR00T.py b/starVLA/model/framework/WM4A/WanGR00T.py new file mode 100644 index 0000000000000000000000000000000000000000..0aaca9a1819fbd32757f99aa653e226248f40f99 --- /dev/null +++ b/starVLA/model/framework/WM4A/WanGR00T.py @@ -0,0 +1,277 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +WanGR00T Framework — Wan2.2-TI2V World Model for Action Prediction. + +Uses Wan2.2-TI2V-5B (DiT-based Text+Image-to-Video model) as the perception +backbone. The DiT's intermediate representations encode spatiotemporal +dynamics learned from large-scale video generation pretraining, +which are passed directly to the action head as cross-attention condition +for continuous action prediction. + +Architecture: + UMT5 (text) + VAE (image→latent) → WanTransformer3D + → hidden_states [B, N, 3072] + → FlowmatchingActionHead (cross-attention on 3072-dim tokens) + → action predictions + +Key differences from CosmoPredict2GR00T: + - Text encoder: UMT5-XXL (dim=4096) vs T5 (dim=1024) + - VAE latent channels: 48 vs 16 + - DiT hidden dim: 3072 (24×128) vs 2048 (16×128) + - 30 transformer blocks vs 28 +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.GR00T_ActionHeader import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class WanGR00TDefaultConfig: + """WanGR00T default parameters.""" + + name: str = "WanGR00T" + + # === World Model backbone (Wan2.2-TI2V-5B-Diffusers) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + }) + + # Legacy compat: factory functions (vlm/__init__, world_model/__init__) + # fall back to qwenvl.base_vlm when world_model.base_wm is absent. + # vl_hidden_dim is read by some action heads (VLA_AdapterHeader, LayerwiseFM). + # TODO next version should refactor to remove this redundant config section and update all shared utilities to read from world_model.base_wm instead of qwenvl.base_vlm. + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 3072, + }) + + # === Action head (Flow-matching / DiT diffusion) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "DiT-B", + "action_hidden_dim": 1024, + "hidden_size": 1024, + "add_pos_embed": True, + "max_seq_len": 1024, + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 7, + "action_horizon": 8, + "past_action_window_size": 0, + "repeated_diffusion_steps": 8, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "num_inference_timesteps": 4, + "num_target_vision_tokens": 32, + "diffusion_model_cfg": { + # Decoupled from world model hidden_size; wm_projector bridges the gap + "cross_attention_dim": 512, + "dropout": 0.2, + "final_dropout": True, + "interleave_self_attention": True, + "norm_type": "ada_norm", + "num_layers": 16, + "output_dim": 1024, + "positional_embeddings": None, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("WanGR00T") +class Wan_GR00T(baseframework): + """ + World-Model-for-Action framework using Wan2.2-TI2V-5B backbone. + + Components: + - Wan2.2-TI2V DiT (UMT5 + VAE + WanTransformer3D) for features + - Flow-matching (DiT) diffusion head for continuous action prediction + + The Wan world model provides spatiotemporal representations learned + from large-scale video generation pretraining with expand_timesteps + image conditioning (per-token timestep expansion). + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(WanGR00TDefaultConfig, config) + + # Load world model backbone + self.backbone = get_world_model(config=self.config) + + # Project world model features to action model's cross-attention dim + wm_hidden = self.backbone.model.config.hidden_size + cross_attn_dim = self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim + self.wm_projector = torch.nn.Linear(wm_hidden, cross_attn_dim) + + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + state = [example["state"] for example in examples] if "state" in examples[0] else None + + # Step 1: World model input encoding (UMT5 + VAE) + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + # Step 2: DiT forward to extract spatiotemporal features + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + # hidden_states[-1]: [B, N_tokens, hidden_dim=3072] + last_hidden = wm_outputs.hidden_states[-1] + last_hidden = self.wm_projector(last_hidden) + + # Step 3: Action head forward and loss + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=last_hidden.device, dtype=last_hidden.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + repeated_diffusion_steps = ( + self.config.framework.action_model.get("repeated_diffusion_steps", 4) + if self.config and hasattr(self.config, "framework") + else 4 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + last_hidden_repeated = last_hidden.repeat(repeated_diffusion_steps, 1, 1) + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=last_hidden.device, dtype=last_hidden.dtype) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_loss = self.action_model(last_hidden_repeated, actions_target_repeated, state_repeated) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> dict: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + last_hidden = self.wm_projector(last_hidden) + + state = ( + torch.from_numpy(np.array(state)).to(last_hidden.device, dtype=last_hidden.dtype) + if state is not None + else None + ) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(last_hidden, state) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + + + +if __name__ == "__main__": + import argparse + import os + + from PIL import Image + from omegaconf import OmegaConf + + if os.getenv("DEBUGPY_ENABLE", "0") == "1": + import debugpy + debugpy.listen(("0.0.0.0", 10092)) + print("Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + parser = argparse.ArgumentParser() + parser.add_argument( + "--config_yaml", + type=str, + default="./starVLA/config/training/starvla_cotrain_libero.yaml", + help="Path to YAML config", + ) + args, clipargs = parser.parse_known_args() + + cfg = OmegaConf.load(args.config_yaml) + + # Point to the diffusers-format model + cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers" + cfg.framework.world_model = { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + } + + model: Wan_GR00T = Wan_GR00T(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image, image], + "lang": "This is a fake instruction for testing.", + } + sample2 = sample.copy() + sample2["lang"] = "Another fake instruction for testing." + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output["action_loss"] + print(f"Action Loss: {action_loss.item()}") + + predict_output = model.predict_action(examples=[sample]) + normalized_actions = predict_output["normalized_actions"] + print(f"Unnormalized Action: {normalized_actions}") + + print("Finished") diff --git a/starVLA/model/framework/WM4A/WanOFT.py b/starVLA/model/framework/WM4A/WanOFT.py new file mode 100644 index 0000000000000000000000000000000000000000..e68d9f738cc8b81d1bf402903c75f4d9cc76203d --- /dev/null +++ b/starVLA/model/framework/WM4A/WanOFT.py @@ -0,0 +1,224 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +WanOFT Framework — Wan2.2-TI2V World Model + MLP Regression for Action Prediction. + +Uses Wan2.2-TI2V-5B (DiT-based Text+Image-to-Video model) as the perception +backbone with a lightweight MLP action head (L1 regression). + +Architecture: + UMT5 (text) + VAE (image→latent) → WanTransformer3D + → hidden_states [B, N, 3072] + → Global avg pool → [B, 3072] + → Linear projection → [B, chunk_len, 3072] + → MLP (L1 regression) → action predictions [B, chunk_len, action_dim] + +Key differences from WanGR00T: + - Action head: MLP L1 regression (not flow-matching diffusion) + - No repeated_diffusion_steps (single forward pass) + - Faster training & inference +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch +import torch.nn as nn + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.MLP_ActionHeader import get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class WanOFTDefaultConfig: + """WanOFT default parameters.""" + + name: str = "WanOFT" + + # === World Model backbone (Wan2.2-TI2V-5B-Diffusers) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + }) + + # === Action head (MLP L1 regression) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "MLP", + "action_dim": 7, + "action_hidden_dim": 3072, + "future_action_window_size": 8, + "past_action_window_size": 0, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("WanOFT") +class Wan_OFT(baseframework): + """ + World-Model-for-Action framework using Wan2.2-TI2V + MLP regression. + + Components: + - Wan2.2-TI2V DiT (UMT5 + VAE + WanTransformer3D) for features + - Adaptive pooling + MLP regression head (L1 loss) + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(WanOFTDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.action_model.action_hidden_dim = wm_hidden + + self.action_model = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + self.action_query_proj = nn.Linear(wm_hidden, self.chunk_len * wm_hidden) # Project into a two-layer MLP + + self.l1_loss = nn.L1Loss() + + def _pool_to_action_queries(self, hidden_states: torch.Tensor) -> torch.Tensor: + B, N, H = hidden_states.shape + pooled = hidden_states.mean(dim=1) + queries = self.action_query_proj(pooled) + action_queries = queries.view(B, self.chunk_len, H) + return action_queries + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.float32): + action_queries = self._pool_to_action_queries(last_hidden) # B, chunk_len, hidden_dim + pred_actions = self.action_model.predict_action(action_queries) + + actions = torch.tensor( + np.array(actions), device=pred_actions.device, dtype=pred_actions.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + action_loss = self.l1_loss(pred_actions, actions_target) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> np.ndarray: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + last_hidden = wm_outputs.hidden_states[-1] + + with torch.autocast("cuda", dtype=torch.float32): + action_queries = self._pool_to_action_queries(last_hidden) + pred_actions = self.action_model.predict_action(action_queries) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + +if __name__ == "__main__": + import argparse + import os + + from PIL import Image + from omegaconf import OmegaConf + + if os.getenv("DEBUGPY_ENABLE", "0") == "1": + import debugpy + debugpy.listen(("0.0.0.0", 10092)) + print("Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + parser = argparse.ArgumentParser() + parser.add_argument( + "--config_yaml", + type=str, + default="./starVLA/config/training/starvla_cotrain_libero.yaml", + help="Path to YAML config", + ) + args, clipargs = parser.parse_known_args() + + cfg = OmegaConf.load(args.config_yaml) + + cfg.framework.name = "WanOFT" + cfg.framework.qwenvl.base_vlm = "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers" + cfg.framework.world_model = { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + } + + model: Wan_OFT = Wan_OFT(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image, image], + "lang": "This is a fake instruction for testing.", + } + sample2 = sample.copy() + sample2["lang"] = "Another fake instruction for testing." + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output["action_loss"] + print(f"Action Loss: {action_loss.item()}") + + predict_output = model.predict_action(examples=[sample]) + normalized_actions = predict_output["normalized_actions"] + print(f"Predicted Action: {normalized_actions}") + print("Finished") diff --git a/starVLA/model/framework/WM4A/WanPI.py b/starVLA/model/framework/WM4A/WanPI.py new file mode 100644 index 0000000000000000000000000000000000000000..2f462c86ae8f1238c123f2d3cd925f3cde4c31c3 --- /dev/null +++ b/starVLA/model/framework/WM4A/WanPI.py @@ -0,0 +1,294 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +""" +WanPI Framework — Wan2.2-TI2V World Model + Layer-wise Cross-DiT Flow-Matching. + +Uses Wan2.2-TI2V-5B (DiT-based Text+Image-to-Video model) as the perception +backbone with a layer-wise cross-DiT flow-matching action head, inspired by π₀. + +Architecture: + UMT5 (text) + VAE (image→latent) → WanTransformer3D (30 blocks) + → Multi-layer hidden_states [30 × (B, N, 3072)] + → LayerwiseFlowmatchingActionHead (cross-DiT) + → action predictions [B, chunk_len, action_dim] + +Key differences from WanGR00T: + - Action head: Layer-wise cross-DiT (not single-layer flow-matching) + - Uses ALL transformer layers (not just last hidden state) + - More expressive multi-scale feature fusion +""" + +import sys +from pathlib import Path + +_workspace_root = Path(__file__).parent.parent.parent.parent.parent +if str(_workspace_root) not in sys.path: + sys.path.insert(0, str(_workspace_root)) + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +import numpy as np +import torch + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +IGNORE_INDEX = -100 + +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.LayerwiseFM_ActionHeader import LayerwiseFlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class WanPIDefaultConfig: + """WanPI default parameters.""" + + name: str = "WanPI" + + # === World Model backbone (Wan2.2-TI2V-5B-Diffusers) === + world_model: dict = field(default_factory=lambda: { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + }) + + # LayerwiseFM reads qwenvl.vl_hidden_dim and qwenvl.num_vl_layers + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 1024, + "num_vl_layers": 30, + }) + + # === Action head (Layer-wise Flow-matching / cross-DiT) === + action_model: dict = field(default_factory=lambda: { + "action_model_type": "LayerwiseFM", + "action_dim": 7, + "state_dim": 7, + "future_action_window_size": 15, + "past_action_window_size": 0, + "repeated_diffusion_steps": 2, + "num_inference_timesteps": 4, + "add_pos_embed": True, + "max_seq_len": 1024, + "num_target_vision_tokens": 32, + "noise_beta_alpha": 1.5, + "noise_beta_beta": 1.0, + "noise_s": 0.999, + "num_timestep_buckets": 1000, + "diffusion_model_cfg": { + "cross_attention_dim": 1024, + }, + }) + + obs_image_size: Optional[list] = None + + +@FRAMEWORK_REGISTRY.register("WanPI") +class Wan_PI(baseframework): + """ + World-Model-for-Action framework using Wan2.2-TI2V + Layer-wise cross-DiT. + + Components: + - Wan2.2-TI2V DiT (UMT5 + VAE + WanTransformer3D) for features + - Layer-wise cross-DiT flow-matching head fed by all transformer layers + """ + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + super().__init__() + self.config = merge_framework_config(WanPIDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + + # Auto-detect hidden size and num layers from world model + wm_hidden = self.backbone.model.config.hidden_size + # Cosmos uses transformer_blocks, Wan uses blocks + if hasattr(self.backbone.transformer, 'transformer_blocks'): + num_blocks = len(self.backbone.transformer.transformer_blocks) + else: + num_blocks = len(self.backbone.transformer.blocks) + + # Project world model features to action model's cross-attention dim + cross_attn_dim = self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim + self.wm_projector = torch.nn.Linear(wm_hidden, cross_attn_dim) + + # Sync vl_hidden_dim so LayerwiseFM action head stays consistent + self.config.framework.qwenvl.vl_hidden_dim = cross_attn_dim + self.config.framework.qwenvl.num_vl_layers = num_blocks + + self.action_model: LayerwiseFlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + + # Register hooks for ALL transformer blocks + self._all_hidden_states = [] + self._all_hooks = [] + self._register_all_hooks() + + def _register_all_hooks(self): + """Register forward hooks on ALL transformer blocks for layerwise features.""" + for hook in self._all_hooks: + hook.remove() + self._all_hooks.clear() + + if hasattr(self.backbone.transformer, 'transformer_blocks'): + blocks = self.backbone.transformer.transformer_blocks + else: + blocks = self.backbone.transformer.blocks + for block in blocks: + hook = block.register_forward_hook(self._capture_all_hook) + self._all_hooks.append(hook) + + def _capture_all_hook(self, module, input, output): + if isinstance(output, tuple): + self._all_hidden_states.append(output[0]) + else: + self._all_hidden_states.append(output) + + def forward(self, examples: List[dict] = None, **kwargs) -> Tuple: + batch_images = [example["image"] for example in examples] + instructions = [example["lang"] for example in examples] + actions = [example["action"] for example in examples] + + state = [example["state"] for example in examples] if "state" in examples[0] else None + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + + with torch.autocast("cuda", dtype=torch.bfloat16): + self._all_hidden_states.clear() + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + vl_embs_list = list(self._all_hidden_states) + vl_embs_list = [self.wm_projector(h) for h in vl_embs_list] + base_hidden = vl_embs_list[-1] + + with torch.autocast("cuda", dtype=torch.float32): + actions = torch.tensor( + np.array(actions), device=base_hidden.device, dtype=base_hidden.dtype + ) + actions_target = actions[:, -(self.future_action_window_size + 1):, :] + + repeated_diffusion_steps = ( + self.config.framework.action_model.get("repeated_diffusion_steps", 2) + if self.config and hasattr(self.config, "framework") + else 2 + ) + actions_target_repeated = actions_target.repeat(repeated_diffusion_steps, 1, 1) + vl_embs_list_repeated = [h.repeat(repeated_diffusion_steps, 1, 1) for h in vl_embs_list] + + state_repeated = None + if state is not None: + state = torch.tensor(np.array(state), device=base_hidden.device, dtype=base_hidden.dtype) + state_repeated = state.repeat(repeated_diffusion_steps, 1, 1) + + action_loss = self.action_model( + vl_embs_list_repeated, actions_target_repeated, state_repeated + ) + + return {"action_loss": action_loss} + + @torch.inference_mode() + def predict_action(self, examples: List[dict], **kwargs) -> np.ndarray: + if type(examples) is not list: + examples = [examples] + batch_images = [to_pil_preserve(example["image"]) for example in examples] + instructions = [example["lang"] for example in examples] + state = [example["state"] for example in examples] if "state" in examples[0] else None + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + + wm_inputs = self.backbone.build_inputs(images=batch_images, instructions=instructions) + with torch.autocast("cuda", dtype=torch.bfloat16): + self._all_hidden_states.clear() + wm_outputs = self.backbone( + **wm_inputs, + output_hidden_states=True, + return_dict=True, + ) + vl_embs_list = list(self._all_hidden_states) + vl_embs_list = [self.wm_projector(h) for h in vl_embs_list] + + state = ( + torch.from_numpy(np.array(state)).to(vl_embs_list[-1].device, dtype=vl_embs_list[-1].dtype) + if state is not None + else None + ) + + with torch.autocast("cuda", dtype=torch.float32): + pred_actions = self.action_model.predict_action(vl_embs_list, state) + + normalized_actions = pred_actions.detach().cpu().numpy() + return {"normalized_actions": normalized_actions} + + +if __name__ == "__main__": + import argparse + import os + + from PIL import Image + from omegaconf import OmegaConf + + if os.getenv("DEBUGPY_ENABLE", "0") == "1": + import debugpy + debugpy.listen(("0.0.0.0", 10092)) + print("Rank 0 waiting for debugger attach on port 10092...") + debugpy.wait_for_client() + + parser = argparse.ArgumentParser() + parser.add_argument( + "--config_yaml", + type=str, + default="./starVLA/config/training/starvla_cotrain_libero.yaml", + help="Path to YAML config", + ) + args, clipargs = parser.parse_known_args() + + cfg = OmegaConf.load(args.config_yaml) + + cfg.framework.name = "WanPI" + cfg.framework.qwenvl = { + "base_vlm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 3072, + "num_vl_layers": 30, + } + cfg.framework.world_model = { + "base_wm": "./playground/Pretrained_models/Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + } + + model: Wan_PI = Wan_PI(cfg) + print(model) + + image = Image.fromarray(np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)) + sample = { + "action": np.random.uniform(-1, 1, size=(16, 7)).astype(np.float16), + "image": [image, image], + "lang": "This is a fake instruction for testing.", + "state": np.random.uniform(-1, 1, size=(1, 7)).astype(np.float16), + } + sample2 = sample.copy() + sample2["lang"] = "Another fake instruction for testing." + + batch = [sample, sample2] + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model.to(device) + forward_output = model(batch) + action_loss = forward_output["action_loss"] + print(f"Action Loss: {action_loss.item()}") + + predict_output = model.predict_action(examples=[sample]) + normalized_actions = predict_output["normalized_actions"] + print(f"Predicted Action: {normalized_actions}") + print("Finished") diff --git a/starVLA/model/framework/WM4A/__init__.py b/starVLA/model/framework/WM4A/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69937c1621fda2a64c60e43374b97df53fd05857 --- /dev/null +++ b/starVLA/model/framework/WM4A/__init__.py @@ -0,0 +1,11 @@ +"""WM4A — World-Model-for-Action frameworks. + +Frameworks that use a World Model (e.g. Cosmos-Reason2) as the perception +backbone live here. World models may share the same Qwen3-VL architecture +under the hood but are trained on video prediction / physical reasoning, +providing richer temporal representations for action prediction. + +The interface contract is identical to VLM4A frameworks: + - forward(examples) -> {"action_loss": Tensor} + - predict_action(examples) -> {"normalized_actions": np.ndarray} +""" diff --git a/starVLA/model/framework/WanPerceiverMaskedFutureImage.py b/starVLA/model/framework/WanPerceiverMaskedFutureImage.py new file mode 100644 index 0000000000000000000000000000000000000000..f33519338c5a9b4dc816d733eb0720fc7f5dbd1e --- /dev/null +++ b/starVLA/model/framework/WanPerceiverMaskedFutureImage.py @@ -0,0 +1,268 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""Wan2.2-TI2V Perceiver with masked future-image denoising.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import List, Optional + +import torch +import torch.nn.functional as F + +from deployment.model_server.tools.image_tools import to_pil_preserve +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverFutureImage import ( + CosmoPredict25PerceiverFutureImageDefaultConfig, +) +from starVLA.model.framework.WM4A.CosmoPredict25PerceiverMaskedFutureImage import ( + CosmoPredict25_Perceiver_MaskedFutureImage, +) +from starVLA.model.framework.base_framework import baseframework +from starVLA.model.framework.share_tools import merge_framework_config +from starVLA.model.modules.action_model.PerceiverHead_original import FlowmatchingActionHead, get_action_model +from starVLA.model.modules.world_model import get_world_model +from starVLA.model.tools import FRAMEWORK_REGISTRY +from starVLA.training.trainer_utils.trainer_tools import resize_images + + +@dataclass +class WanPerceiverMaskedFutureImageDefaultConfig(CosmoPredict25PerceiverFutureImageDefaultConfig): + """Wan2.2-TI2V Perceiver + masked future-image defaults.""" + + name: str = "WanPerceiverMaskedFutureImage" + + world_model: dict = field(default_factory=lambda: { + "base_wm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "extract_layers": [-1], + "height": 224, + "width": 224, + "freeze_text_encoder": True, + "freeze_vae": True, + }) + + qwenvl: dict = field(default_factory=lambda: { + "base_vlm": "Wan-AI/Wan2.2-TI2V-5B-Diffusers", + "vl_hidden_dim": 3072, + }) + + future_image_training: dict = field(default_factory=lambda: { + "enabled": True, + "loss_weight": 1.0, + "train_time_distribution": "logitnormal", + "shift": 5.0, + "timestep_scale": 1000.0, + "single_frame_condition_prob": 0.0, + "change_mask_enabled": True, + "change_mask_top_ratio": 0.25, + "change_mask_static_weight": 0.05, + "change_mask_soft_loss": True, + "masked_denoising": False, + "condition_static_regions": False, + }) + + future_image_generation: dict = field(default_factory=lambda: { + "enabled": True, + "num_frames": 9, + "num_inference_steps": 50, + "guidance_scale": 5.0, + "output_type": "pil", + "height": 224, + "width": "auto", + "max_sequence_length": 512, + "conditioning_mode": "image", + "max_samples": 1, + "return_full_video": False, + "future_frame_index": -1, + "negative_prompt": None, + }) + + +@FRAMEWORK_REGISTRY.register("WanPerceiverMaskedFutureImage") +class Wan_Perceiver_MaskedFutureImage(CosmoPredict25_Perceiver_MaskedFutureImage): + """Perceiver action head plus Wan2.2 per-token masked flow matching.""" + + def __init__(self, config: Optional[dict] = None, **kwargs) -> None: + baseframework.__init__(self) + self.config = merge_framework_config(WanPerceiverMaskedFutureImageDefaultConfig, config) + + self.backbone = get_world_model(config=self.config) + wm_hidden = self.backbone.model.config.hidden_size + self.config.framework.qwenvl.vl_hidden_dim = wm_hidden + self.config.framework.action_model.diffusion_model_cfg.cross_attention_dim = wm_hidden + self.action_model: FlowmatchingActionHead = get_action_model(config=self.config) + + self.future_action_window_size = self.config.framework.action_model.future_action_window_size + self.past_action_window_size = self.config.framework.action_model.past_action_window_size + self.chunk_len = self.past_action_window_size + 1 + self.future_action_window_size + self.state_dim = self.config.framework.action_model.get("state_dim", None) + + def _make_wan_timestep( + self, + hidden_states: torch.Tensor, + denoise_mask: torch.Tensor, + flow_time: torch.Tensor, + timestep_scale: float, + ) -> torch.Tensor: + """Convert the latent denoise mask into Wan's per-patch timestep tokens.""" + batch_size, _, num_frames, height, width = hidden_states.shape + p_t, p_h, p_w = self.backbone.transformer.config.patch_size + if num_frames % p_t or height % p_h or width % p_w: + raise ValueError( + "Wan latent shape must be divisible by transformer.patch_size; " + f"got {(num_frames, height, width)} and {(p_t, p_h, p_w)}." + ) + + patch_mask = F.max_pool3d( + denoise_mask.float(), + kernel_size=(p_t, p_h, p_w), + stride=(p_t, p_h, p_w), + ) + patch_mask = patch_mask[:, 0].flatten(1) + seq_len = patch_mask.shape[1] + rope_max_seq_len = getattr(self.backbone.transformer.config, "rope_max_seq_len", None) + if rope_max_seq_len is not None and seq_len > int(rope_max_seq_len): + raise ValueError( + f"Wan future-image seq_len={seq_len} exceeds rope_max_seq_len={rope_max_seq_len}. " + "Reduce observation frames or image resolution." + ) + + scaled_time = flow_time.to(device=hidden_states.device, dtype=torch.float32) * float(timestep_scale) + return patch_mask * scaled_time[:, None] + + def _cosmos25_future_image_loss(self, examples: List[dict]) -> Optional[torch.Tensor]: + """Compute masked Wan flow loss (method name retained for parent forward compatibility).""" + if "future_image" not in examples[0]: + return None + + training_cfg = self._future_training_cfg() + if not self._as_bool(training_cfg.get("enabled", True)): + return None + + batch_images = [to_pil_preserve(example["image"]) for example in examples] + future_images = [to_pil_preserve(example["future_image"]) for example in examples] + instructions = [example["lang"] for example in examples] + + train_obs_image_size = getattr(self.config.framework, "obs_image_size", None) + if train_obs_image_size: + batch_images = resize_images(batch_images, target_size=train_obs_image_size) + future_images = resize_images(future_images, target_size=train_obs_image_size) + + raw_sequences, condition_counts, sample_counts = self._build_future_video_sequences( + batch_images=batch_images, + future_images=future_images, + ) + prompt_embeds = self.backbone._encode_text(instructions) + clean_latents = self.backbone._encode_images_vae(raw_sequences) + dtype = self.backbone.transformer.dtype + clean_latents = clean_latents.to(dtype=dtype) + batch_size, channels, num_latents, height, width = clean_latents.shape + device = clean_latents.device + + target_mask = clean_latents.new_zeros((batch_size, 1, num_latents, 1, 1), dtype=torch.float32) + for batch_idx, (condition_count, sample_count) in enumerate(zip(condition_counts, sample_counts)): + condition_count = max(1, min(int(condition_count), num_latents)) + sample_count = min(max(condition_count + 1, int(sample_count)), num_latents) + target_mask[batch_idx, :, condition_count:sample_count] = 1.0 + target_spatial_mask = target_mask.expand(batch_size, 1, num_latents, height, width) + + use_change_mask = self._as_bool(training_cfg.get("change_mask_enabled", True)) + if use_change_mask: + change_binary, change_loss_weight = self._build_latent_change_masks( + batch_images=batch_images, + future_images=future_images, + latent_height=height, + latent_width=width, + training_cfg=training_cfg, + device=device, + ) + change_binary = change_binary.unsqueeze(2).to(dtype=clean_latents.dtype) + change_loss_weight = change_loss_weight.unsqueeze(2).to(dtype=torch.float32) + else: + change_binary = clean_latents.new_ones((batch_size, 1, 1, height, width)) + change_loss_weight = clean_latents.new_ones( + (batch_size, 1, 1, height, width), dtype=torch.float32 + ) + + train_time = self._sample_train_times( + batch_size=batch_size, + device=device, + distribution=training_cfg.get("train_time_distribution", "logitnormal"), + ) + flow_time = self._shift_time(train_time, shift=float(training_cfg.get("shift", 5.0))) + time_view = flow_time.view(batch_size, 1, 1, 1, 1).to(dtype=clean_latents.dtype) + + noise = torch.randn_like(clean_latents) + noisy_latents = clean_latents * (1.0 - time_view) + noise * time_view + use_masked_denoising = self._as_bool(training_cfg.get("masked_denoising", False)) + use_static_conditioning = use_masked_denoising and self._as_bool( + training_cfg.get("condition_static_regions", False) + ) + denoise_mask = target_spatial_mask.to(dtype=clean_latents.dtype) + if use_masked_denoising: + denoise_mask = denoise_mask * change_binary + hidden_states = torch.where(denoise_mask.bool(), noisy_latents, clean_latents) + target_velocity = noise.float() - clean_latents.float() + + timestep_mask = denoise_mask if use_static_conditioning else target_spatial_mask + timestep = self._make_wan_timestep( + hidden_states=hidden_states, + denoise_mask=timestep_mask, + flow_time=flow_time, + timestep_scale=float(training_cfg.get("timestep_scale", 1000.0)), + ) + + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = self.backbone.transformer( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=prompt_embeds.to(device=device, dtype=dtype), + return_dict=False, + ) + pred = pred[0] if isinstance(pred, tuple) else pred + pred = pred.sample if hasattr(pred, "sample") else pred + if hasattr(self.backbone, "_intermediate_features"): + self.backbone._intermediate_features.clear() + + if use_static_conditioning: + change_loss_weight = change_loss_weight * change_binary.float() + spatial_loss_weight = change_loss_weight.expand(batch_size, 1, num_latents, height, width) + loss_mask = target_spatial_mask * spatial_loss_weight + loss_mask = loss_mask.expand(batch_size, channels, num_latents, height, width) + future_loss = F.mse_loss(pred.float(), target_velocity, reduction="none") + return (future_loss * loss_mask).sum() / loss_mask.sum().clamp_min(1.0) + + def _build_generation_inputs(self, batch_images: List, instructions: List[str], cfg: dict) -> dict: + """Build arguments accepted by Diffusers WanImageToVideoPipeline.""" + mode = str(cfg.pop("conditioning_mode", "image")).lower() + if mode not in {"auto", "image", "video"}: + raise ValueError( + "future_image_generation.conditioning_mode must be one of " + f"'auto', 'image', or 'video', got {mode!r}." + ) + + height = cfg.pop("height", getattr(self.backbone, "height", 480)) + width = cfg.pop("width", getattr(self.backbone, "width", 832)) + resolved_height, resolved_width = self._resolve_generation_size_values(batch_images, height, width) + generation_inputs = { + "image": [self._as_sequence(images)[-1] for images in batch_images], + "prompt": instructions, + "height": resolved_height, + "width": resolved_width, + "num_frames": cfg.pop("num_frames", 9), + "num_inference_steps": cfg.pop("num_inference_steps", 50), + "guidance_scale": cfg.pop("guidance_scale", 5.0), + "output_type": cfg.pop("output_type", "pil"), + "return_dict": True, + "max_sequence_length": cfg.pop("max_sequence_length", 512), + } + negative_prompt = cfg.pop("negative_prompt", None) + if negative_prompt is not None: + generation_inputs["negative_prompt"] = negative_prompt + + # Cosmos-only knobs may still be present in a shared YAML. + cfg.pop("conditional_frame_timestep", None) + cfg.pop("num_latent_conditional_frames", None) + generation_inputs.update({key: value for key, value in cfg.items() if value is not None}) + return generation_inputs diff --git a/starVLA/model/framework/__init__.py b/starVLA/model/framework/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c4468383662afe2e74283e9e39023b5b796891 --- /dev/null +++ b/starVLA/model/framework/__init__.py @@ -0,0 +1,63 @@ +""" +Framework factory utilities. +Automatically builds registered framework implementations +based on configuration. + +Each framework module (e.g., M1.py, QwenFast.py) should register itself: + from starVLA.model.framework.framework_registry import FRAMEWORK_REGISTRY + + @FRAMEWORK_REGISTRY.register("InternVLA-M1") + def build_model_framework(config): + return InternVLA_M1(config=config) +""" + +import pkgutil +import importlib +from starVLA.model.tools import FRAMEWORK_REGISTRY + +from starVLA.training.trainer_utils import initialize_overwatch + +logger = initialize_overwatch(__name__) + +try: + pkg_path = __path__ +except NameError: + pkg_path = None + +# Auto-import all framework submodules to trigger registration +if pkg_path is not None: + for _, module_name, _ in pkgutil.walk_packages(pkg_path, prefix=f"{__name__}."): + try: + importlib.import_module(module_name) + except Exception as e: + logger.warning(f"Warning: Failed to auto-import framework submodule {module_name}: {e}") + +def build_framework(cfg): + """ + Build a framework model from config. + Args: + cfg: Config object (OmegaConf / namespace) containing: + cfg.framework.name: Identifier string (e.g. "InternVLA-M1") + Returns: + nn.Module: Instantiated framework model. + """ + + if not hasattr(cfg.framework, "name"): + cfg.framework.name = cfg.framework.framework_py # Backward compatibility for legacy config yaml + + if cfg.framework.name == "QwenOFT": + from starVLA.model.framework.QwenOFT import Qwenvl_OFT + return Qwenvl_OFT(cfg) + elif cfg.framework.name == "QwenFast": + from starVLA.model.framework.QwenFast import Qwenvl_Fast + return Qwenvl_Fast(cfg) + + # auto detect from registry + framework_id = cfg.framework.name + if framework_id not in FRAMEWORK_REGISTRY._registry: + raise NotImplementedError(f"Framework {cfg.framework.name} is not implemented. Plz, python yourframework_py to specify framework module.") + + MODLE_CLASS = FRAMEWORK_REGISTRY[framework_id] + return MODLE_CLASS(cfg) + +__all__ = ["build_framework", "FRAMEWORK_REGISTRY"] diff --git a/starVLA/model/framework/base_framework.py b/starVLA/model/framework/base_framework.py new file mode 100644 index 0000000000000000000000000000000000000000..4ae78bcbaa6999a721331d0c25f1c0459b6ddc23 --- /dev/null +++ b/starVLA/model/framework/base_framework.py @@ -0,0 +1,236 @@ +""" +Base framework abstraction providing: +- Pretrained loading (config + normalization stats + weights) +- Action space utilities (dimension, stats, (un)normalization) +- Trainable module discovery helper +Note: No device placement or optimizer concerns handled here (delegated to trainer). +""" + +import torch.nn as nn +from typing import List + +from pathlib import Path + +import torch +import torch.nn as nn +import numpy as np + +from typing import List + +from pathlib import Path +from typing import Dict, List +from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel +import numpy as np +from starVLA.model.tools import auto_get_trainable_modules + +from starVLA.model.framework.share_tools import read_mode_config +from starVLA.training.trainer_utils import initialize_overwatch +from starVLA.model.framework.share_tools import dict_to_namespace +from starVLA.model.framework.__init__ import build_framework + +logger = initialize_overwatch(__name__) + + +# PreTrainedModel, AutoModel, PretrainedConfig, are so good, find sometime to study them +# TODO @JinhuiYE find sometime to merge yaml config with transformer config + +class baseframework(PreTrainedModel): + """ + Lightweight base class for higher-level VLA model assemblies. + Subclasses are expected to: + - Accept a structured config + - Register components in __init__ + - Use provided helpers for action normalization handling + """ + + def __init__( + self, + hf_config = PretrainedConfig() + ) -> None: + """ + Initialize base nn.Module. Subclasses add components. + """ + + super().__init__(hf_config) + + @classmethod + def from_pretrained( + cls, + pretrained_checkpoint: str, + **kwargs, + ) -> None: + """ + Restore a model instance from a saved checkpoint. + + Workflow: + 1. Resolve checkpoint path + 2. Load config + dataset normalization statistics + 3. Build model with loaded config + 4. Load state_dict strictly (reports missing/unexpected keys) + 5. Attach normalization stats for later un-normalization + + Args: + pretrained_checkpoint: Path to .pt file inside run/checkpoints directory. + **kwargs: Extra constructor overrides passed to subclass. + + Returns: + baseframework: Instantiated model (left on CPU; caller decides device). + + Raises: + RuntimeError: If state_dict key mismatch occurs under strict=True. + FileNotFoundError: If underlying files are missing (surfaced earlier). + """ + pretrained_checkpoint = Path(pretrained_checkpoint) + model_config, norm_stats = read_mode_config(pretrained_checkpoint) # read config and norm_stats + + config = dict_to_namespace(model_config) + model_config = config + model_config.trainer.pretrained_checkpoint = None + # FrameworkModel = cls(config=model_config, **kwargs) # TODO find cls by config + FrameworkModel = build_framework(cfg=model_config) + # set for action un-norm + FrameworkModel.norm_stats = norm_stats + # Load from Checkpoint (Custom --> should load both *projector* and *llm* weights) + model_state_dict = torch.load(pretrained_checkpoint, map_location="cpu") + # logger.info(f"Loading model weights from `{pretrained_checkpoint}`") + model_keys = set(FrameworkModel.state_dict().keys()) + checkpoint_keys = set(model_state_dict.keys()) + try: + FrameworkModel.load_state_dict(model_state_dict, strict=True) + except RuntimeError as e: + # must keep all keys matched + common_keys = model_keys.intersection(checkpoint_keys) + missing_keys = model_keys - common_keys + unexpected_keys = checkpoint_keys - common_keys + if missing_keys: + logger.warning(f"Missing keys in state_dict: {missing_keys}") + if unexpected_keys: + logger.warning(f"Unexpected keys in state_dict: {unexpected_keys}") + + raise e + + # **ensure model is on GPU** + FrameworkModel = FrameworkModel + return FrameworkModel + + @staticmethod + def _check_unnorm_key(norm_stats, unnorm_key): + """ + Infer or validate the dataset stats key used for un-normalization. + + Args: + norm_stats: Dict[str, dict] mapping dataset key -> stats block. + unnorm_key: Optional explicit dataset key. + + Returns: + str: Resolved key. + + Raises: + AssertionError: If multiple datasets present and key not provided, + or provided key not found. + """ + if unnorm_key is None: + assert len(norm_stats) == 1, ( + f"Your model was trained on more than one dataset, " + f"please pass a `unnorm_key` from the following options to choose the statistics " + f"used for un-normalizing actions: {norm_stats.keys()}" + ) + unnorm_key = next(iter(norm_stats.keys())) + + assert unnorm_key in norm_stats, ( + f"The `unnorm_key` you chose is not in the set of available dataset statistics, " + f"please choose from: {norm_stats.keys()}" + ) + return unnorm_key + + @classmethod + def get_action_stats(self, unnorm_key=None): + """ + Retrieve raw action normalization statistics. + + Args: + unnorm_key: Optional dataset stats key. + + Returns: + dict: Stats structure (e.g. q01, q99, mask). + """ + unnorm_key = self._check_unnorm_key(self.norm_stats, unnorm_key) + return self.norm_stats[unnorm_key]["action"] + + @property + def trainable_module_keys(self, max_depth=1) -> List[str]: + """ + Enumerate trainable submodule names up to a depth. + + Args: + max_depth: Descent depth when traversing module tree. + + Returns: + List[str]: Module path names considered trainable. + """ + keys = auto_get_trainable_modules(self, max_depth=max_depth) # auto check which modules are trainable + return keys + + @staticmethod + def unnormalize_actions(normalized_actions: np.ndarray, action_norm_stats: Dict[str, np.ndarray]) -> np.ndarray: + """ + Map normalized actions (≈[-1, 1]) back to original value range. + + Steps: + - Clamp values to [-1, 1] + - Threshold channel index 6 to {0,1} (binary semantic) + - Apply linear scaling for masked dimensions using: + original = 0.5 * (norm + 1) * (q99 - q01) + q01 + + Args: + normalized_actions: Array shape [T, D] (or chunk length × action_dim). + action_norm_stats: Dict containing: + q01 (array-like): Lower percentile (per-dimension). + q99 (array-like): Upper percentile (per-dimension). + mask (optional bool array): True => apply de-normalization; False => keep original normalized value. + + Returns: + np.ndarray: Unnormalized actions (same shape as input). + """ + mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["q01"], dtype=bool)) + action_high, action_low = np.array(action_norm_stats["q99"]), np.array(action_norm_stats["q01"]) + normalized_actions = np.clip(normalized_actions, -1, 1) + normalized_actions[:, 6] = np.where(normalized_actions[:, 6] < 0.5, 0, 1) + actions = np.where( + mask, + 0.5 * (normalized_actions + 1) * (action_high - action_low) + action_low, + normalized_actions, + ) + + return actions + + @staticmethod + def _check_unnorm_key(norm_stats, unnorm_key): + """ + Duplicate helper (retained for backward compatibility). + See primary _check_unnorm_key above. + """ + if unnorm_key is None: + assert len(norm_stats) == 1, ( + f"Your model was trained on more than one dataset, " + f"please pass a `unnorm_key` from the following options to choose the statistics " + f"used for un-normalizing actions: {norm_stats.keys()}" + ) + unnorm_key = next(iter(norm_stats.keys())) + + assert unnorm_key in norm_stats, ( + f"The `unnorm_key` you chose is not in the set of available dataset statistics, " + f"please choose from: {norm_stats.keys()}" + ) + return unnorm_key + + @classmethod + def get_action_stats(self, unnorm_key=None, norm_stats=None): + """ + Duplicate stats accessor (retained for backward compatibility). + # in future, it will own to policy interface and pack as + """ + if norm_stats ==None: + norm_stats = self.norm_stats + unnorm_key = self._check_unnorm_key(norm_stats, unnorm_key) + return norm_stats[unnorm_key]["action"] diff --git a/starVLA/model/framework/share_tools.py b/starVLA/model/framework/share_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..b51d0a69d899690af3d5fc11f54701ebd4466c93 --- /dev/null +++ b/starVLA/model/framework/share_tools.py @@ -0,0 +1,331 @@ +""" +Shared configuration / utility helpers for framework components: +- NamespaceWithGet: lightweight namespace behaving like a dict +- OmegaConf conversion helpers +- Config merging decorator for model __init__ +- Checkpoint config/statistics loading +""" + +import os +from pathlib import Path +from types import SimpleNamespace +import json + +from typing import Union, List +import torchvision +import os +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +from types import SimpleNamespace +import torch, json +import torch.nn as nn +import numpy as np +from PIL import Image +import re +from omegaconf import OmegaConf +from types import SimpleNamespace +import inspect +import functools +from typing import Any + + +from starVLA.training.trainer_utils import initialize_overwatch + +# Initialize Overwatch =>> Wraps `logging.Logger` +overwatch = initialize_overwatch(__name__) + + +from types import SimpleNamespace + + +class NamespaceWithGet(SimpleNamespace): + def get(self, key, default=None): + """ + Return attribute value if present, else default (dict-like API). + + Args: + key: Attribute name. + default: Fallback if attribute missing. + + Returns: + Any: Stored value or default. + """ + return getattr(self, key, default) + + def items(self): + """ + Iterate (key, value) pairs like dict.items(). + + Returns: + Generator[Tuple[str, Any], None, None] + """ + return ((key, getattr(self, key)) for key in self.__dict__) + + def __iter__(self): + """ + Return iterator over attribute keys (enables dict unpacking **obj). + + Returns: + Iterator[str] + """ + return iter(self.__dict__) + + def to_dict(self): + """ + Recursively convert nested NamespaceWithGet objects into plain dicts. + + Returns: + dict: Fully materialized dictionary structure. + """ + return {key: value.to_dict() if isinstance(value, NamespaceWithGet) else value for key, value in self.items()} + + +def dict_to_namespace(d): + """ + Create an OmegaConf config from a plain dictionary. + + Args: + d: Input dictionary. + + Returns: + OmegaConf: DictConfig instance. + """ + return OmegaConf.create(d) + + +def _to_omegaconf(x: Any): + """ + Convert diverse input types into an OmegaConf object. + + Accepted types: + - None -> empty DictConfig + - str path -> load YAML/JSON via OmegaConf.load + - dict -> DictConfig + - DictConfig / ListConfig -> returned unchanged + - NamespaceWithGet / SimpleNamespace -> converted via vars()/to_dict() + + Args: + x: Input candidate. + + Returns: + OmegaConf: Normalized configuration node. + """ + if x is None: + return OmegaConf.create({}) + if isinstance(x, OmegaConf.__class__): # fallback, typically not hit + return x + try: + # OmegaConf node detection + from omegaconf import DictConfig, ListConfig + + if isinstance(x, (DictConfig, ListConfig)): + return x + except Exception: + pass + + if isinstance(x, str): + # treat as path + return OmegaConf.load(x) + if isinstance(x, dict): + return OmegaConf.create(x) + if isinstance(x, NamespaceWithGet) or isinstance(x, SimpleNamespace): + # convert to plain dict + try: + d = x.to_dict() if hasattr(x, "to_dict") else vars(x) + except Exception: + d = vars(x) + return OmegaConf.create(d) + # fallback: try to create + return OmegaConf.create(x) + + +def merge_pram_config(init): + """ + Decorator for __init__ to unify config handling. + + Behavior: + 1. Extract 'config' kwarg / arg (path | dict | OmegaConf | namespace) + 2. Convert to OmegaConf + 3. Merge with explicitly passed init parameters (explicit overrides file) + 4. Attach merged config to self.config + 5. Call original __init__ with merged config + + Args: + init: Original __init__ function. + + Returns: + Wrapped initializer. + """ + + @functools.wraps(init) + def wrapper(self, *args, **kwargs): + # Map positional args to parameter names (excluding self) + sig = inspect.signature(init) + param_names = [name for i, (name, p) in enumerate(sig.parameters.items()) if i > 0] + + init_kwargs = {} + for name, val in zip(param_names, args): + init_kwargs[name] = val + # override with explicit kwargs + init_kwargs.update(kwargs) + + # get provided config (if any) + provided_config = init_kwargs.get("config", None) + + loaded_cfg = _to_omegaconf(provided_config) + + # build params cfg from explicit init args (other than config) + params = {k: v for k, v in init_kwargs.items() if k != "config"} + params_cfg = OmegaConf.create(params) if params else OmegaConf.create({}) + + # merge: loaded_cfg <- params_cfg (params override file) + merged = OmegaConf.merge(loaded_cfg, params_cfg) + + # set on instance + try: + # prefer attaching OmegaConf directly + self.config = merged + except Exception: + # fallback to dict + self.config = OmegaConf.to_container(merged, resolve=True) + + # prepare kwargs for original init: ensure config is the merged OmegaConf + call_kwargs = dict(init_kwargs) + call_kwargs["config"] = merged + + # call original __init__ using keyword args only (safer) + return init(self, **call_kwargs) + + return wrapper + + +def merge_framework_config(default_config_cls, cfg): + """ + Merge a framework default dataclass into cfg.framework while preserving YAML overrides. + + WM4A frameworks keep their backbone/action-head defaults in dataclasses, then + let the training YAML and command-line dotlist override only the fields that + are experiment-specific. + """ + import dataclasses + + from omegaconf import DictConfig + + defaults_instance = default_config_cls() + defaults_omega = OmegaConf.create(dataclasses.asdict(defaults_instance)) + + if hasattr(cfg, "framework"): + yaml_fw = cfg.framework + if hasattr(yaml_fw, "_cfg"): + yaml_fw = yaml_fw._cfg + if not isinstance(yaml_fw, DictConfig): + yaml_fw = OmegaConf.create(yaml_fw if isinstance(yaml_fw, dict) else {}) + else: + yaml_fw = OmegaConf.create({}) + + merged_fw = OmegaConf.merge(defaults_omega, yaml_fw) + + if hasattr(cfg, "_cfg") and isinstance(cfg._cfg, DictConfig): + cfg._cfg.framework = merged_fw + if hasattr(cfg, "_children") and "framework" in cfg._children: + old_accessed = cfg._children["framework"]._local_accessed.copy() + del cfg._children["framework"] + new_child = cfg.framework + new_child._local_accessed.update(old_accessed) + elif isinstance(cfg, DictConfig): + cfg.framework = merged_fw + else: + cfg.framework = merged_fw + + return cfg + + +def read_model_config(pretrained_checkpoint): + """ + Load global model configuration and dataset normalization statistics + associated with a saved checkpoint (.pt). + + Expected directory layout: + /checkpoints/.pt + /config.json + /dataset_statistics.json + + Args: + pretrained_checkpoint: Path to a .pt checkpoint file. + + Returns: + tuple: + global_cfg (dict): Loaded config.json contents. + norm_stats (dict): Dataset statistics for (de)normalization. + + Raises: + FileNotFoundError: If checkpoint or required JSON files are missing. + AssertionError: If file suffix or structure invalid. + """ + if os.path.isfile(pretrained_checkpoint): + overwatch.info(f"Loading from local checkpoint path `{(checkpoint_pt := Path(pretrained_checkpoint))}`") + + # [Validate] Checkpoint Path should look like `...//checkpoints/.pt` + assert checkpoint_pt.suffix == ".pt" + run_dir = checkpoint_pt.parents[1] + + # Get paths for `config.json`, `dataset_statistics.json` and pretrained checkpoint + config_json, dataset_statistics_json = run_dir / "config.json", run_dir / "dataset_statistics.json" + assert config_json.exists(), f"Missing `config.json` for `{run_dir = }`" + assert dataset_statistics_json.exists(), f"Missing `dataset_statistics.json` for `{run_dir = }`" + + # Otherwise =>> try looking for a match on `model_id_or_path` on the HF Hub (`model_id_or_path`) + # Load VLA Config (and corresponding base VLM `ModelConfig`) from `config.json` + with open(config_json, "r") as f: + global_cfg = json.load(f) + + # Load Dataset Statistics for Action Denormalization + with open(dataset_statistics_json, "r") as f: + norm_stats = json.load(f) + else: + overwatch.error(f"❌ Pretrained checkpoint `{pretrained_checkpoint}` does not exist.") + raise FileNotFoundError(f"Pretrained checkpoint `{pretrained_checkpoint}` does not exist.") + return global_cfg, norm_stats + + +def read_mode_config(pretrained_checkpoint): + """ + Same as read_model_config (legacy duplicate kept for backward compatibility). + + Args: + pretrained_checkpoint: Path to a .pt checkpoint file. + + Returns: + tuple: + vla_cfg (dict) + norm_stats (dict) + """ + if os.path.isfile(pretrained_checkpoint): + overwatch.info(f"Loading from local checkpoint path `{(checkpoint_pt := Path(pretrained_checkpoint))}`") + + # [Validate] Checkpoint Path should look like `...//checkpoints/.pt` + assert checkpoint_pt.suffix == ".pt" + run_dir = checkpoint_pt.parents[1] + + # Get paths for `config.json`, `dataset_statistics.json` and pretrained checkpoint + config_yaml, dataset_statistics_json = run_dir / "config.yaml", run_dir / "dataset_statistics.json" + assert config_yaml.exists(), f"Missing `config.yaml` for `{run_dir = }`" + assert dataset_statistics_json.exists(), f"Missing `dataset_statistics.json` for `{run_dir = }`" + + # Otherwise =>> try looking for a match on `model_id_or_path` on the HF Hub (`model_id_or_path`) + # Load VLA Config (and corresponding base VLM `ModelConfig`) from `config.json` + try: + ocfg = OmegaConf.load(str(config_yaml)) + global_cfg = OmegaConf.to_container(ocfg, resolve=True) + except Exception as e: + overwatch.error(f"❌ Failed to load YAML config `{config_yaml}`: {e}") + raise + + # Load Dataset Statistics for Action Denormalization + with open(dataset_statistics_json, "r") as f: + norm_stats = json.load(f) + else: + overwatch.error(f"❌ Pretrained checkpoint `{pretrained_checkpoint}` does not exist.") + raise FileNotFoundError(f"Pretrained checkpoint `{pretrained_checkpoint}` does not exist.") + return global_cfg, norm_stats diff --git a/starVLA/model/modules/action_model/DiT4DiTPerceiverHead.py b/starVLA/model/modules/action_model/DiT4DiTPerceiverHead.py new file mode 100644 index 0000000000000000000000000000000000000000..50edd1d3e6269099801259f5328b629e8dc0afc0 --- /dev/null +++ b/starVLA/model/modules/action_model/DiT4DiTPerceiverHead.py @@ -0,0 +1,247 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +"""DiT4DiT-compatible Perceiver action heads. + +These heads keep the starVLA Perceiver action architecture, but use DiT4DiT's +action flow time convention: t=0 is clean action and t=1 is noise. +""" + +import numpy as np +import torch + +from starVLA.model.modules.action_model.PerceiverHead import ( + CategorySpecificFlowmatchingActionHead, + FlowmatchingActionHead, +) + + +class DiT4DiTFlowmatchingActionHead(FlowmatchingActionHead): + """DiT4DiT-compatible action flow direction.""" + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return sample / self.config.noise_s + + def forward( + self, + vl_embs: torch.Tensor, + actions: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, + encoder_attention_mask=None, + action_mask=None, + ): + device = vl_embs.device + + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] + + noisy_trajectory = (1 - t) * actions + t * noise + velocity = noise - actions + + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized) + + state_features = self.state_encoder(state) if state is not None else None + + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = ( + torch.cat((state_features, future_tokens, action_features), dim=1) + if state_features is not None + else torch.cat((future_tokens, action_features), dim=1) + ) + + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=t_discretized, + ) + pred = self.action_decoder(model_output) + pred_actions = pred[:, -actions.shape[1]:] + + if action_mask is not None: + if isinstance(action_mask, np.ndarray): + action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + else: + action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + loss = ((pred_actions - velocity) ** 2) * action_mask + return loss.sum() / action_mask.sum() + return ((pred_actions - velocity) ** 2).mean() + + @torch.no_grad() + def predict_action( + self, + vl_embs: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, + ) -> torch.Tensor: + batch_size = vl_embs.shape[0] + device = vl_embs.device + actions = torch.randn( + size=(batch_size, self.config.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + ) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state) if state is not None else None + + for t in range(num_steps): + t_cont = 1.0 - t / float(num_steps) + t_discretized = int(t_cont * self.num_timestep_buckets) + + timesteps_tensor = torch.full(size=(batch_size,), fill_value=t_discretized, device=device) + action_features = self.action_encoder(actions, timesteps_tensor) + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = ( + torch.cat((state_features, future_tokens, action_features), dim=1) + if state_features is not None + else torch.cat((future_tokens, action_features), dim=1) + ) + + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=timesteps_tensor, + ) + pred = self.action_decoder(model_output) + + pred_velocity = pred[:, -self.action_horizon:] + actions = actions - dt * pred_velocity + return actions + + +class DiT4DiTCategorySpecificFlowmatchingActionHead(CategorySpecificFlowmatchingActionHead): + """Category-specific DiT4DiT-compatible action flow direction.""" + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return sample / self.config.noise_s + + def forward( + self, + vl_embs: torch.Tensor, + actions: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, + encoder_attention_mask=None, + action_mask=None, + ): + device = vl_embs.device + + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] + + noisy_trajectory = (1 - t) * actions + t * noise + velocity = noise - actions + + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized, embodiment_tag) + + state_features = self.state_encoder(state, embodiment_tag) if state is not None else None + + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = ( + torch.cat((state_features, future_tokens, action_features), dim=1) + if state_features is not None + else torch.cat((future_tokens, action_features), dim=1) + ) + + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=t_discretized, + ) + pred = self.action_decoder(model_output, embodiment_tag) + pred_actions = pred[:, -actions.shape[1]:] + + if action_mask is not None: + if isinstance(action_mask, np.ndarray): + action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + else: + action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + loss = ((pred_actions - velocity) ** 2) * action_mask + return loss.sum() / action_mask.sum() + return ((pred_actions - velocity) ** 2).mean() + + @torch.no_grad() + def predict_action( + self, + vl_embs: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = 24, + ) -> torch.Tensor: + batch_size = vl_embs.shape[0] + device = vl_embs.device + actions = torch.randn( + size=(batch_size, self.config.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + ) + assert embodiment_tag is not None, "Embodiment tag is required for prediction" + embodiment_tag = torch.tensor(embodiment_tag, device=device, dtype=torch.long) + if embodiment_tag.dim() == 0: + embodiment_tag = embodiment_tag.repeat(batch_size) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state, embodiment_tag) if state is not None else None + + for t in range(num_steps): + t_cont = 1.0 - t / float(num_steps) + t_discretized = int(t_cont * self.num_timestep_buckets) + + timesteps_tensor = torch.full(size=(batch_size,), fill_value=t_discretized, device=device) + action_features = self.action_encoder(actions, timesteps_tensor, embodiment_tag) + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = ( + torch.cat((state_features, future_tokens, action_features), dim=1) + if state_features is not None + else torch.cat((future_tokens, action_features), dim=1) + ) + + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=timesteps_tensor, + ) + pred = self.action_decoder(model_output, embodiment_tag) + + pred_velocity = pred[:, -self.action_horizon:] + actions = actions - dt * pred_velocity + return actions + + +def get_action_model(config=None): + action_model_config = config.framework.action_model + use_category_specific = getattr(action_model_config, "use_category_specific", False) + + print("use_category_specific", use_category_specific, "head_variant", "dit4dit") + if use_category_specific: + return DiT4DiTCategorySpecificFlowmatchingActionHead(full_config=config) + return DiT4DiTFlowmatchingActionHead(full_config=config) diff --git a/starVLA/model/modules/action_model/DiTActionHeader.py b/starVLA/model/modules/action_model/DiTActionHeader.py new file mode 100644 index 0000000000000000000000000000000000000000..788ef80d23af3fe476b553058ac53d8a01fc1204 --- /dev/null +++ b/starVLA/model/modules/action_model/DiTActionHeader.py @@ -0,0 +1,221 @@ +# Copyright 2025 CogACT. All rights reserved. +# Modified by [Jinhui YE/ HKUST University] in [2025]. +# Modification: [add global config ]. +""" +Diffusion-based action prediction head (DiT variant). + +Provides: + - Size presets (S/B/L) for transformer-based temporal action diffusion backbone + - ActionModel: wraps diffusion process (training + optional DDIM sampling creation) +""" + +from starVLA.model.modules.action_model.DiT_modules.models import DiT +from starVLA.model.modules.action_model import create_diffusion +from .DiT_modules import gaussian_diffusion as gd + +import torch +from torch import nn + + +# Create model sizes of ActionModels +def DiT_S(**kwargs): # TODO move to config for reproducibility + """ + Small DiT variant. + + Args: + **kwargs: Passed through to DiT constructor. + + Returns: + DiT: Initialized small model. + """ + return DiT(depth=6, token_size=384, num_heads=4, **kwargs) + + +def DiT_B(**kwargs): + """ + Base DiT variant. + + Args: + **kwargs: Passed through to DiT constructor. + + Returns: + DiT: Initialized base model. + """ + return DiT(depth=12, token_size=768, num_heads=12, **kwargs) + + +def DiT_L(**kwargs): + """ + Large DiT variant. + + Args: + **kwargs: Passed through to DiT constructor. + + Returns: + DiT: Initialized large model. + """ + return DiT(depth=24, token_size=1024, num_heads=16, **kwargs) + + +# Model size +DiT_models = {"DiT-S": DiT_S, "DiT-B": DiT_B, "DiT-L": DiT_L} + + +# Create ActionModel +class ActionModel(nn.Module): + """ + Diffusion temporal action head. + + Components: + - DiT transformer backbone (token-wise denoiser) + - Gaussian diffusion scheduler (noise forward/backward) + - Optional DDIM sampler (created lazily) + + Responsibilities: + - Forward: add noise + predict denoised residual + - loss(): simple MSE on noise prediction + - create_ddim(): build deterministic sampler + """ + + def __init__( + self, + action_hidden_dim, + model_type, + in_channels, + future_action_window_size, + past_action_window_size, + diffusion_steps=100, + noise_schedule="squaredcos_cap_v2", + ): + """ + Initialize diffusion model and backbone. + + Args: + action_hidden_dim: Hidden size of conditioning tokens (QFormer output dim). + model_type: One of {'DiT-S','DiT-B','DiT-L'}. + in_channels: Action dimensionality (per timestep). + future_action_window_size: Number of future steps modeled. + past_action_window_size: Number of past steps possibly encoded (for context). + diffusion_steps: Total diffusion timesteps. + noise_schedule: Scheduler type string. + """ + super().__init__() + self.in_channels = in_channels + self.noise_schedule = noise_schedule + # GaussianDiffusion offers forward and backward functions q_sample and p_sample. + self.diffusion_steps = diffusion_steps + self.diffusion = create_diffusion( + timestep_respacing="", + noise_schedule=noise_schedule, + diffusion_steps=self.diffusion_steps, + sigma_small=True, + learn_sigma=False, + ) + self.ddim_diffusion = None + if self.diffusion.model_var_type in [gd.ModelVarType.LEARNED, gd.ModelVarType.LEARNED_RANGE]: + learn_sigma = True + else: + learn_sigma = False + self.past_action_window_size = past_action_window_size + self.future_action_window_size = future_action_window_size + self.token_size = action_hidden_dim # QFormer output size + self.net = DiT_models[model_type]( + in_channels=in_channels, + class_dropout_prob=0.1, + learn_sigma=learn_sigma, + future_action_window_size=future_action_window_size, + past_action_window_size=past_action_window_size, + ) + + def forward(self, gt_action, condition, **kwargs): + """ + Perform one diffusion training step. + + Args: + gt_action: Ground truth action tensor [B, T, C]. + condition: Conditioning tokens [B, L, D]. + **kwargs: Ignored (reserved). + + Returns: + tuple: + noise_pred: Predicted noise tensor. + noise: Sampled noise tensor. + timestep: Timesteps used per batch element. + """ + # sample random noise and timestep + noise = torch.randn_like(gt_action) # [B, T, C] + timestep = torch.randint(0, self.diffusion.num_timesteps, (gt_action.size(0),), device=gt_action.device) + + # sample x_t from x + x_t = self.diffusion.q_sample(gt_action, timestep, noise) + + # predict noise from x_t + noise_pred = self.net(x_t, timestep, condition) + + assert noise_pred.shape == noise.shape == gt_action.shape + + return noise_pred, noise, timestep + + def loss(self, noise_pred, noise): + """ + Compute MSE noise prediction loss. + + Args: + noise_pred: Predicted noise tensor. + noise: Target noise tensor. + + Returns: + torch.Tensor: Scalar loss. + """ + # Compute L2 loss + loss = ((noise_pred - noise) ** 2).mean() + # Optional: loss += loss_vlb + + return loss + + def create_ddim(self, ddim_step=10): + """ + Lazily create DDIM sampler instance. + + Args: + ddim_step: Number of DDIM steps. + + Returns: + Diffusion: DDIM diffusion object. + """ + self.ddim_diffusion = create_diffusion( + timestep_respacing="ddim" + str(ddim_step), + noise_schedule=self.noise_schedule, + diffusion_steps=self.diffusion_steps, + sigma_small=True, + learn_sigma=False, + ) + return self.ddim_diffusion + + +def get_action_model(model_typ="DiT-B", config=None): + """ + Factory: build ActionModel from global framework config. + + Args: + model_typ: (Unused override; model type inferred from config). + config: Global config (expects config.framework.action_model namespace). + + Returns: + ActionModel: Initialized diffusion action head. + """ + action_model_cfg = config.framework.action_model + + model_type = action_model_cfg.action_model_type + action_hidden_dim = action_model_cfg.action_hidden_dim + action_dim = action_model_cfg.action_dim + future_action_window_size = action_model_cfg.future_action_window_size + past_action_window_size = action_model_cfg.past_action_window_size + + return ActionModel( + model_type=model_type, # Model type, e.g., 'DiT-B' + action_hidden_dim=action_hidden_dim, # Hidden size of action tokens + in_channels=action_dim, # Input channel size + future_action_window_size=future_action_window_size, # Future action window size + past_action_window_size=past_action_window_size, # Past action window size + ) diff --git a/starVLA/model/modules/action_model/DiT_modules/diffusion_utils.py b/starVLA/model/modules/action_model/DiT_modules/diffusion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..919632e8616e714e610bf7a3081ee173db3c886b --- /dev/null +++ b/starVLA/model/modules/action_model/DiT_modules/diffusion_utils.py @@ -0,0 +1,79 @@ +# Modified from OpenAI's diffusion repos +# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py +# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion +# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py + +import torch as th +import numpy as np + + +def normal_kl(mean1, logvar1, mean2, logvar2): + """ + Compute the KL divergence between two gaussians. + Shapes are automatically broadcasted, so batches can be compared to + scalars, among other use cases. + """ + tensor = None + for obj in (mean1, logvar1, mean2, logvar2): + if isinstance(obj, th.Tensor): + tensor = obj + break + assert tensor is not None, "at least one argument must be a Tensor" + + # Force variances to be Tensors. Broadcasting helps convert scalars to + # Tensors, but it does not work for th.exp(). + logvar1, logvar2 = [x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor) for x in (logvar1, logvar2)] + + return 0.5 * (-1.0 + logvar2 - logvar1 + th.exp(logvar1 - logvar2) + ((mean1 - mean2) ** 2) * th.exp(-logvar2)) + + +def approx_standard_normal_cdf(x): + """ + A fast approximation of the cumulative distribution function of the + standard normal. + """ + return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3)))) + + +def continuous_gaussian_log_likelihood(x, *, means, log_scales): + """ + Compute the log-likelihood of a continuous Gaussian distribution. + :param x: the targets + :param means: the Gaussian mean Tensor. + :param log_scales: the Gaussian log stddev Tensor. + :return: a tensor like x of log probabilities (in nats). + """ + centered_x = x - means + inv_stdv = th.exp(-log_scales) + normalized_x = centered_x * inv_stdv + log_probs = th.distributions.Normal(th.zeros_like(x), th.ones_like(x)).log_prob(normalized_x) + return log_probs + + +def discretized_gaussian_log_likelihood(x, *, means, log_scales): + """ + Compute the log-likelihood of a Gaussian distribution discretizing to a + given image. + :param x: the target images. It is assumed that this was uint8 values, + rescaled to the range [-1, 1]. + :param means: the Gaussian mean Tensor. + :param log_scales: the Gaussian log stddev Tensor. + :return: a tensor like x of log probabilities (in nats). + """ + assert x.shape == means.shape == log_scales.shape + centered_x = x - means + inv_stdv = th.exp(-log_scales) + plus_in = inv_stdv * (centered_x + 1.0 / 255.0) + cdf_plus = approx_standard_normal_cdf(plus_in) + min_in = inv_stdv * (centered_x - 1.0 / 255.0) + cdf_min = approx_standard_normal_cdf(min_in) + log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12)) + log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12)) + cdf_delta = cdf_plus - cdf_min + log_probs = th.where( + x < -0.999, + log_cdf_plus, + th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))), + ) + assert log_probs.shape == x.shape + return log_probs diff --git a/starVLA/model/modules/action_model/DiT_modules/gaussian_diffusion.py b/starVLA/model/modules/action_model/DiT_modules/gaussian_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..37b41e9651626b90ce0e38cbef910d09043eb2e4 --- /dev/null +++ b/starVLA/model/modules/action_model/DiT_modules/gaussian_diffusion.py @@ -0,0 +1,840 @@ +# Modified from OpenAI's diffusion repos +# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py +# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion +# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py + + +import math + +import numpy as np +import torch as th +import enum + +from .diffusion_utils import discretized_gaussian_log_likelihood, normal_kl + + +def mean_flat(tensor): + """ + Take the mean over all non-batch dimensions. + """ + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + + +class ModelMeanType(enum.Enum): + """ + Which type of output the model predicts. + """ + + PREVIOUS_X = enum.auto() # the model predicts x_{t-1} + START_X = enum.auto() # the model predicts x_0 + EPSILON = enum.auto() # the model predicts epsilon + + +class ModelVarType(enum.Enum): + """ + What is used as the model's output variance. + The LEARNED_RANGE option has been added to allow the model to predict + values between FIXED_SMALL and FIXED_LARGE, making its job easier. + """ + + LEARNED = enum.auto() + FIXED_SMALL = enum.auto() + FIXED_LARGE = enum.auto() + LEARNED_RANGE = enum.auto() + + +class LossType(enum.Enum): + MSE = enum.auto() # use raw MSE loss (and KL when learning variances) + RESCALED_MSE = enum.auto() # use raw MSE loss (with RESCALED_KL when learning variances) + KL = enum.auto() # use the variational lower-bound + RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB + + def is_vb(self): + return self == LossType.KL or self == LossType.RESCALED_KL + + +def _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, warmup_frac): + betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float64) + warmup_time = int(num_diffusion_timesteps * warmup_frac) + betas[:warmup_time] = np.linspace(beta_start, beta_end, warmup_time, dtype=np.float64) + return betas + + +def get_beta_schedule(beta_schedule, *, beta_start, beta_end, num_diffusion_timesteps): + """ + This is the deprecated API for creating beta schedules. + See get_named_beta_schedule() for the new library of schedules. + """ + if beta_schedule == "quad": + betas = ( + np.linspace( + beta_start**0.5, + beta_end**0.5, + num_diffusion_timesteps, + dtype=np.float64, + ) + ** 2 + ) + elif beta_schedule == "linear": + betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64) + elif beta_schedule == "warmup10": + betas = _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, 0.1) + elif beta_schedule == "warmup50": + betas = _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, 0.5) + elif beta_schedule == "const": + betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float64) + elif beta_schedule == "jsd": # 1/T, 1/(T-1), 1/(T-2), ..., 1 + betas = 1.0 / np.linspace(num_diffusion_timesteps, 1, num_diffusion_timesteps, dtype=np.float64) + else: + raise NotImplementedError(beta_schedule) + assert betas.shape == (num_diffusion_timesteps,) + return betas + + +def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): + """ + Get a pre-defined beta schedule for the given name. + The beta schedule library consists of beta schedules which remain similar + in the limit of num_diffusion_timesteps. + Beta schedules may be added, but should not be removed or changed once + they are committed to maintain backwards compatibility. + """ + if schedule_name == "linear": + # Linear schedule from Ho et al, extended to work for any number of + # diffusion steps. + scale = 1000 / num_diffusion_timesteps + return get_beta_schedule( + "linear", + beta_start=scale * 0.0001, + beta_end=scale * 0.02, + num_diffusion_timesteps=num_diffusion_timesteps, + ) + elif schedule_name == "squaredcos_cap_v2": + return betas_for_alpha_bar( + num_diffusion_timesteps, + lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, + ) + else: + raise NotImplementedError(f"unknown beta schedule: {schedule_name}") + + +def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): + """ + Create a beta schedule that discretizes the given alpha_t_bar function, + which defines the cumulative product of (1-beta) over time from t = [0,1]. + :param num_diffusion_timesteps: the number of betas to produce. + :param alpha_bar: a lambda that takes an argument t from 0 to 1 and + produces the cumulative product of (1-beta) up to that + part of the diffusion process. + :param max_beta: the maximum beta to use; use values lower than 1 to + prevent singularities. + """ + betas = [] + for i in range(num_diffusion_timesteps): + t1 = i / num_diffusion_timesteps + t2 = (i + 1) / num_diffusion_timesteps + betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) + return np.array(betas) + + +class GaussianDiffusion: + """ + Utilities for training and sampling diffusion models. + Original ported from this codebase: + https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42 + :param betas: a 1-D numpy array of betas for each diffusion timestep, + starting at T and going to 1. + """ + + def __init__(self, *, betas, model_mean_type, model_var_type, loss_type): + + self.model_mean_type = model_mean_type + self.model_var_type = model_var_type + self.loss_type = loss_type + + # Use float64 for accuracy. + betas = np.array(betas, dtype=np.float64) + self.betas = betas + assert len(betas.shape) == 1, "betas must be 1-D" + assert (betas > 0).all() and (betas <= 1).all() + + self.num_timesteps = int(betas.shape[0]) + + alphas = 1.0 - betas + self.alphas_cumprod = np.cumprod(alphas, axis=0) + self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1]) + self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0) + assert self.alphas_cumprod_prev.shape == (self.num_timesteps,) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod) + self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod) + self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod) + self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod) + self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1) + + # calculations for posterior q(x_{t-1} | x_t, x_0) + self.posterior_variance = betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.posterior_log_variance_clipped = ( + np.log(np.append(self.posterior_variance[1], self.posterior_variance[1:])) + if len(self.posterior_variance) > 1 + else np.array([]) + ) + + self.posterior_mean_coef1 = betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) + self.posterior_mean_coef2 = (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod) + + def q_mean_variance(self, x_start, t): + """ + Get the distribution q(x_t | x_0). + :param x_start: the [N x C x ...] tensor of noiseless inputs. + :param t: the number of diffusion steps (minus 1). Here, 0 means one step. + :return: A tuple (mean, variance, log_variance), all of x_start's shape. + """ + mean = _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) + log_variance = _extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) + return mean, variance, log_variance + + def q_sample(self, x_start, t, noise=None): + """ + Diffuse the data for a given number of diffusion steps. + In other words, sample from q(x_t | x_0). + :param x_start: the initial data batch. + :param t: the number of diffusion steps (minus 1). Here, 0 means one step. + :param noise: if specified, the split-out normal noise. + :return: A noisy version of x_start. + """ + if noise is None: + noise = th.randn_like(x_start) + assert noise.shape == x_start.shape + return ( + _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise + ) + + def q_posterior_mean_variance(self, x_start, x_t, t): + """ + Compute the mean and variance of the diffusion posterior: + q(x_{t-1} | x_t, x_0) + """ + assert x_start.shape == x_t.shape + posterior_mean = ( + _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t + ) + posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape) + posterior_log_variance_clipped = self.posterior_log_variance_clipped + # posterior_log_variance_clipped = _extract_into_tensor( + # self.posterior_log_variance_clipped, t, x_t.shape + # ) + assert ( + posterior_mean.shape[0] + == posterior_variance.shape[0] + # == posterior_log_variance_clipped.shape[0] + == x_start.shape[0] + ) + return posterior_mean, posterior_variance, posterior_log_variance_clipped + + def p_mean_variance(self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None): + """ + Apply the model to get p(x_{t-1} | x_t), as well as a prediction of + the initial x, x_0. + :param model: the model, which takes a signal and a batch of timesteps + as input. + :param x: the [N x C x ...] tensor at time t. + :param t: a 1-D Tensor of timesteps. + :param clip_denoised: if True, clip the denoised signal into [-1, 1]. + :param denoised_fn: if not None, a function which applies to the + x_start prediction before it is used to sample. Applies before + clip_denoised. + :param model_kwargs: if not None, a dict of extra keyword arguments to + pass to the model. This can be used for conditioning. + :return: a dict with the following keys: + - 'mean': the model mean output. + - 'variance': the model variance output. + - 'log_variance': the log of 'variance'. + - 'pred_xstart': the prediction for x_0. + """ + if model_kwargs is None: + model_kwargs = {} + + B, C = x.shape[:2] + assert t.shape == (B,) + model_output = model(x, t, **model_kwargs) + if isinstance(model_output, tuple): + model_output, extra = model_output + else: + extra = None + + if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]: + assert model_output.shape == (B, C * 2, *x.shape[2:]) + model_output, model_var_values = th.split(model_output, C, dim=1) + min_log = _extract_into_tensor(self.posterior_log_variance_clipped, t, x.shape) + max_log = _extract_into_tensor(np.log(self.betas), t, x.shape) + # The model_var_values is [-1, 1] for [min_var, max_var]. + frac = (model_var_values + 1) / 2 + model_log_variance = frac * max_log + (1 - frac) * min_log + model_variance = th.exp(model_log_variance) + else: + if len(self.betas) == 1: + model_variance, model_log_variance = { + ModelVarType.FIXED_SMALL: ( + self.posterior_variance, + self.posterior_log_variance_clipped, + ), + }[self.model_var_type] + model_variance = _extract_into_tensor(model_variance, t, x.shape) + else: + model_variance, model_log_variance = { + # for fixedlarge, we set the initial (log-)variance like so + # to get a better decoder log likelihood. + ModelVarType.FIXED_LARGE: ( + np.append(self.posterior_variance[1], self.betas[1:]), + np.log(np.append(self.posterior_variance[1], self.betas[1:])), + ), + ModelVarType.FIXED_SMALL: ( + self.posterior_variance, + self.posterior_log_variance_clipped, + ), + }[self.model_var_type] + model_variance = _extract_into_tensor(model_variance, t, x.shape) + model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape) + + def process_xstart(x): + if denoised_fn is not None: + x = denoised_fn(x) + if clip_denoised: + return x.clamp(-1, 1) + return x + + if self.model_mean_type == ModelMeanType.START_X: + pred_xstart = process_xstart(model_output) + else: + pred_xstart = process_xstart(self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)) + model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x, t=t) + + assert model_mean.shape == pred_xstart.shape == x.shape # == model_log_variance.shape + return { + "mean": model_mean, + "variance": model_variance, + "log_variance": model_log_variance, + "pred_xstart": pred_xstart, + "extra": extra, + } + + def _predict_xstart_from_eps(self, x_t, t, eps): + assert x_t.shape == eps.shape + return ( + _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps + ) + + def _predict_eps_from_xstart(self, x_t, t, pred_xstart): + return ( + _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart + ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) + + def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None): + """ + Compute the mean for the previous step, given a function cond_fn that + computes the gradient of a conditional log probability with respect to + x. In particular, cond_fn computes grad(log(p(y|x))), and we want to + condition on y. + This uses the conditioning strategy from Sohl-Dickstein et al. (2015). + """ + gradient = cond_fn(x, t, **model_kwargs) + new_mean = p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float() + return new_mean + + def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None): + """ + Compute what the p_mean_variance output would have been, should the + model's score function be conditioned by cond_fn. + See condition_mean() for details on cond_fn. + Unlike condition_mean(), this instead uses the conditioning strategy + from Song et al (2020). + """ + alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) + + eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"]) + eps = eps - (1 - alpha_bar).sqrt() * cond_fn(x, t, **model_kwargs) + + out = p_mean_var.copy() + out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps) + out["mean"], _, _ = self.q_posterior_mean_variance(x_start=out["pred_xstart"], x_t=x, t=t) + return out + + def p_sample( + self, + model, + x, + t, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + ): + """ + Sample x_{t-1} from the model at the given timestep. + :param model: the model to sample from. + :param x: the current tensor at x_{t-1}. + :param t: the value of t, starting at 0 for the first diffusion step. + :param clip_denoised: if True, clip the x_start prediction to [-1, 1]. + :param denoised_fn: if not None, a function which applies to the + x_start prediction before it is used to sample. + :param cond_fn: if not None, this is a gradient function that acts + similarly to the model. + :param model_kwargs: if not None, a dict of extra keyword arguments to + pass to the model. This can be used for conditioning. + :return: a dict containing the following keys: + - 'sample': a random sample from the model. + - 'pred_xstart': a prediction of x_0. + """ + out = self.p_mean_variance( + model, + x, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + model_kwargs=model_kwargs, + ) + noise = th.randn_like(x) + nonzero_mask = (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) # no noise when t == 0 + if cond_fn is not None: + out["mean"] = self.condition_mean(cond_fn, out, x, t, model_kwargs=model_kwargs) + sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise + return {"sample": sample, "pred_xstart": out["pred_xstart"]} + + def p_sample_loop( + self, + model, + shape, + noise=None, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + device=None, + progress=False, + ): + """ + Generate samples from the model. + :param model: the model module. + :param shape: the shape of the samples, (N, C, H, W). + :param noise: if specified, the noise from the encoder to sample. + Should be of the same shape as `shape`. + :param clip_denoised: if True, clip x_start predictions to [-1, 1]. + :param denoised_fn: if not None, a function which applies to the + x_start prediction before it is used to sample. + :param cond_fn: if not None, this is a gradient function that acts + similarly to the model. + :param model_kwargs: if not None, a dict of extra keyword arguments to + pass to the model. This can be used for conditioning. + :param device: if specified, the device to create the samples on. + If not specified, use a model parameter's device. + :param progress: if True, show a tqdm progress bar. + :return: a non-differentiable batch of samples. + """ + final = None + for sample in self.p_sample_loop_progressive( + model, + shape, + noise=noise, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + cond_fn=cond_fn, + model_kwargs=model_kwargs, + device=device, + progress=progress, + ): + final = sample + return final["sample"] + + def p_sample_loop_progressive( + self, + model, + shape, + noise=None, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + device=None, + progress=False, + ): + """ + Generate samples from the model and yield intermediate samples from + each timestep of diffusion. + Arguments are the same as p_sample_loop(). + Returns a generator over dicts, where each dict is the return value of + p_sample(). + """ + if device is None: + device = next(model.parameters()).device + assert isinstance(shape, (tuple, list)) + if noise is not None: + img = noise + else: + img = th.randn(*shape, device=device) + indices = list(range(self.num_timesteps))[::-1] + + if progress: + # Lazy import so that we don't depend on tqdm. + from tqdm.auto import tqdm + + indices = tqdm(indices) + + for i in indices: + t = th.tensor([i] * shape[0], device=device) + with th.no_grad(): + out = self.p_sample( + model, + img, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + cond_fn=cond_fn, + model_kwargs=model_kwargs, + ) + yield out + img = out["sample"] + + def ddim_sample( + self, + model, + x, + t, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + eta=0.0, + ): + """ + Sample x_{t-1} from the model using DDIM. + Same usage as p_sample(). + """ + out = self.p_mean_variance( + model, + x, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + model_kwargs=model_kwargs, + ) + if cond_fn is not None: + out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs) + + # Usually our model outputs epsilon, but we re-derive it + # in case we used x_start or x_prev prediction. + eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"]) + + alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) + alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape) + sigma = eta * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * th.sqrt(1 - alpha_bar / alpha_bar_prev) + # Equation 12. + noise = th.randn_like(x) + mean_pred = out["pred_xstart"] * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev - sigma**2) * eps + nonzero_mask = (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) # no noise when t == 0 + sample = mean_pred + nonzero_mask * sigma * noise + return {"sample": sample, "pred_xstart": out["pred_xstart"]} + + def ddim_reverse_sample( + self, + model, + x, + t, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + eta=0.0, + ): + """ + Sample x_{t+1} from the model using DDIM reverse ODE. + """ + assert eta == 0.0, "Reverse ODE only for deterministic path" + out = self.p_mean_variance( + model, + x, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + model_kwargs=model_kwargs, + ) + if cond_fn is not None: + out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs) + # Usually our model outputs epsilon, but we re-derive it + # in case we used x_start or x_prev prediction. + eps = ( + _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x - out["pred_xstart"] + ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape) + alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape) + + # Equation 12. reversed + mean_pred = out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps + + return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]} + + def ddim_sample_loop( + self, + model, + shape, + noise=None, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + device=None, + progress=False, + eta=0.0, + ): + """ + Generate samples from the model using DDIM. + Same usage as p_sample_loop(). + """ + final = None + for sample in self.ddim_sample_loop_progressive( + model, + shape, + noise=noise, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + cond_fn=cond_fn, + model_kwargs=model_kwargs, + device=device, + progress=progress, + eta=eta, + ): + final = sample + return final["sample"] + + def ddim_sample_loop_progressive( + self, + model, + shape, + noise=None, + clip_denoised=True, + denoised_fn=None, + cond_fn=None, + model_kwargs=None, + device=None, + progress=False, + eta=0.0, + ): + """ + Use DDIM to sample from the model and yield intermediate samples from + each timestep of DDIM. + Same usage as p_sample_loop_progressive(). + """ + if device is None: + device = next(model.parameters()).device + assert isinstance(shape, (tuple, list)) + if noise is not None: + img = noise + else: + img = th.randn(*shape, device=device) + indices = list(range(self.num_timesteps))[::-1] + + if progress: + # Lazy import so that we don't depend on tqdm. + from tqdm.auto import tqdm + + indices = tqdm(indices) + + for i in indices: + t = th.tensor([i] * shape[0], device=device) + with th.no_grad(): + out = self.ddim_sample( + model, + img, + t, + clip_denoised=clip_denoised, + denoised_fn=denoised_fn, + cond_fn=cond_fn, + model_kwargs=model_kwargs, + eta=eta, + ) + yield out + img = out["sample"] + + def _vb_terms_bpd(self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None): + """ + Get a term for the variational lower-bound. + The resulting units are bits (rather than nats, as one might expect). + This allows for comparison to other papers. + :return: a dict with the following keys: + - 'output': a shape [N] tensor of NLLs or KLs. + - 'pred_xstart': the x_0 predictions. + """ + true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(x_start=x_start, x_t=x_t, t=t) + out = self.p_mean_variance(model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs) + kl = normal_kl(true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]) + kl = mean_flat(kl) / np.log(2.0) + + decoder_nll = -discretized_gaussian_log_likelihood( + x_start, means=out["mean"], log_scales=0.5 * out["log_variance"] + ) + assert decoder_nll.shape == x_start.shape + decoder_nll = mean_flat(decoder_nll) / np.log(2.0) + + # At the first timestep return the decoder NLL, + # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t)) + output = th.where((t == 0), decoder_nll, kl) + return {"output": output, "pred_xstart": out["pred_xstart"]} + + def training_losses(self, model, x_start, t, model_kwargs=None, noise=None): + """ + Compute training losses for a single timestep. + :param model: the model to evaluate loss on. + :param x_start: the [N x C x ...] tensor of inputs. + :param t: a batch of timestep indices. + :param model_kwargs: if not None, a dict of extra keyword arguments to + pass to the model. This can be used for conditioning. + :param noise: if specified, the specific Gaussian noise to try to remove. + :return: a dict with the key "loss" containing a tensor of shape [N]. + Some mean or variance settings may also have other keys. + """ + if model_kwargs is None: + model_kwargs = {} + if noise is None: + noise = th.randn_like(x_start) + x_t = self.q_sample(x_start, t, noise=noise) + + terms = {} + + if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL: + terms["loss"] = self._vb_terms_bpd( + model=model, + x_start=x_start, + x_t=x_t, + t=t, + clip_denoised=False, + model_kwargs=model_kwargs, + )["output"] + if self.loss_type == LossType.RESCALED_KL: + terms["loss"] *= self.num_timesteps + elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE: + model_output = model(x_t, t, **model_kwargs) + + if self.model_var_type in [ + ModelVarType.LEARNED, + ModelVarType.LEARNED_RANGE, + ]: + B, C = x_t.shape[:2] + assert model_output.shape == (B, C * 2, *x_t.shape[2:]) + model_output, model_var_values = th.split(model_output, C, dim=1) + frozen_out = th.cat([model_output.detach(), model_var_values], dim=1) + terms["vb"] = self._vb_terms_bpd( + model=lambda *args, r=frozen_out: r, + x_start=x_start, + x_t=x_t, + t=t, + clip_denoised=False, + )["output"] + if self.loss_type == LossType.RESCALED_MSE: + # Divide by 1000 for equivalence with initial implementation. + # Without a factor of 1/1000, the VB term hurts the MSE term. + terms["vb"] *= self.num_timesteps / 1000.0 + + target = { + ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(x_start=x_start, x_t=x_t, t=t)[0], + ModelMeanType.START_X: x_start, + ModelMeanType.EPSILON: noise, + }[self.model_mean_type] + assert model_output.shape == target.shape == x_start.shape + terms["mse"] = mean_flat((target - model_output) ** 2) + if "vb" in terms: + terms["loss"] = terms["mse"] + terms["vb"] + else: + terms["loss"] = terms["mse"] + else: + raise NotImplementedError(self.loss_type) + + return terms + + def _prior_bpd(self, x_start): + """ + Get the prior KL term for the variational lower-bound, measured in + bits-per-dim. + This term can't be optimized, as it only depends on the encoder. + :param x_start: the [N x C x ...] tensor of inputs. + :return: a batch of [N] KL values (in bits), one per batch element. + """ + batch_size = x_start.shape[0] + t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) + qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) + kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0) + return mean_flat(kl_prior) / np.log(2.0) + + def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None): + """ + Compute the entire variational lower-bound, measured in bits-per-dim, + as well as other related quantities. + :param model: the model to evaluate loss on. + :param x_start: the [N x C x ...] tensor of inputs. + :param clip_denoised: if True, clip denoised samples. + :param model_kwargs: if not None, a dict of extra keyword arguments to + pass to the model. This can be used for conditioning. + :return: a dict containing the following keys: + - total_bpd: the total variational lower-bound, per batch element. + - prior_bpd: the prior term in the lower-bound. + - vb: an [N x T] tensor of terms in the lower-bound. + - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep. + - mse: an [N x T] tensor of epsilon MSEs for each timestep. + """ + device = x_start.device + batch_size = x_start.shape[0] + + vb = [] + xstart_mse = [] + mse = [] + for t in list(range(self.num_timesteps))[::-1]: + t_batch = th.tensor([t] * batch_size, device=device) + noise = th.randn_like(x_start) + x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise) + # Calculate VLB term at the current timestep + with th.no_grad(): + out = self._vb_terms_bpd( + model, + x_start=x_start, + x_t=x_t, + t=t_batch, + clip_denoised=clip_denoised, + model_kwargs=model_kwargs, + ) + vb.append(out["output"]) + xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2)) + eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"]) + mse.append(mean_flat((eps - noise) ** 2)) + + vb = th.stack(vb, dim=1) + xstart_mse = th.stack(xstart_mse, dim=1) + mse = th.stack(mse, dim=1) + + prior_bpd = self._prior_bpd(x_start) + total_bpd = vb.sum(dim=1) + prior_bpd + return { + "total_bpd": total_bpd, + "prior_bpd": prior_bpd, + "vb": vb, + "xstart_mse": xstart_mse, + "mse": mse, + } + + +def _extract_into_tensor(arr, timesteps, broadcast_shape): + """ + Extract values from a 1-D numpy array for a batch of indices. + :param arr: the 1-D numpy array. + :param timesteps: a tensor of indices into the array to extract. + :param broadcast_shape: a larger shape of K dimensions with the batch + dimension equal to the length of timesteps. + :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims. + """ + res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float() + while len(res.shape) < len(broadcast_shape): + res = res[..., None] + return res + th.zeros(broadcast_shape, device=timesteps.device) diff --git a/starVLA/model/modules/action_model/DiT_modules/models.py b/starVLA/model/modules/action_model/DiT_modules/models.py new file mode 100644 index 0000000000000000000000000000000000000000..dc03416455596c4988b8800a9c66d0846f63909b --- /dev/null +++ b/starVLA/model/modules/action_model/DiT_modules/models.py @@ -0,0 +1,553 @@ +# Modified from facebookresearch's DiT repos +# DiT: https://github.com/facebookresearch/DiT/blob/main/models.py + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# -------------------------------------------------------- +# References: +# GLIDE: https://github.com/openai/glide-text2im +# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py +# -------------------------------------------------------- + +import torch +import torch.nn as nn +import math +from timm.models.vision_transformer import Attention, Mlp + + +def modulate(x, shift, scale): + return x * (1 + scale) + shift + + +################################################################################# +# Embedding Layers for Timesteps and conditions # +################################################################################# + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + """ + + def __init__(self, hidden_size, frequency_embedding_size=256): + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + self.frequency_embedding_size = frequency_embedding_size + + @staticmethod + def timestep_embedding(t, dim, max_period=10000): + """ + Create sinusoidal timestep embeddings. + :param t: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( + device=t.device + ) + args = t[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + def forward(self, t): + t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(next(self.mlp.parameters()).dtype) + t_emb = self.mlp(t_freq) + return t_emb + + +class LabelEmbedder(nn.Module): + """ + Embeds conditions into vector representations. Also handles label dropout for classifier-free guidance. + """ + + def __init__(self, in_size, hidden_size, dropout_prob=0.1, conditions_shape=(1, 1, 4096)): + super().__init__() + self.linear = nn.Linear(in_size, hidden_size) + self.dropout_prob = dropout_prob + if dropout_prob > 0: + self.uncondition = nn.Parameter(torch.empty(conditions_shape[1:])) + + def token_drop(self, conditions, force_drop_ids=None): + """ + Drops conditions to enable classifier-free guidance. + """ + if force_drop_ids is None: + drop_ids = torch.rand(conditions.shape[0], device=conditions.device) < self.dropout_prob + else: + drop_ids = force_drop_ids == 1 + conditions = torch.where( + drop_ids.unsqueeze(1).unsqueeze(1).expand(conditions.shape[0], *self.uncondition.shape), + self.uncondition, + conditions, + ) + return conditions + + def forward(self, conditions, train, force_drop_ids=None): + use_dropout = self.dropout_prob > 0 + if (train and use_dropout) or (force_drop_ids is not None): + conditions = self.token_drop(conditions, force_drop_ids) + embeddings = self.linear(conditions) + return embeddings + + +################################################################################# +# Embedding Layers for Actions and # +################################################################################# +class ActionEmbedder(nn.Module): + def __init__(self, action_size, hidden_size): + super().__init__() + self.linear = nn.Linear(action_size, hidden_size) + + def forward(self, x): + x = self.linear(x) + return x + + +# Action_History is not used now +class HistoryEmbedder(nn.Module): + def __init__(self, action_size, hidden_size): + super().__init__() + self.linear = nn.Linear(action_size, hidden_size) + + def forward(self, x): + x = self.linear(x) + return x + + +################################################################################# +# Core DiT Model # +################################################################################# + + +class DiTBlock(nn.Module): + """ + A DiT block with self-attention conditioning. + """ + + def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): + super().__init__() + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0) + + def forward(self, x): + x = x + self.attn(self.norm1(x)) + x = x + self.mlp(self.norm2(x)) + return x + + +class FinalLayer(nn.Module): + """ + The final layer of DiT. + """ + + def __init__(self, hidden_size, out_channels): + super().__init__() + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.linear = nn.Linear(hidden_size, out_channels, bias=True) + + def forward(self, x): + x = self.norm_final(x) + x = self.linear(x) + return x + + +class DiT(nn.Module): + """ + Diffusion model with a Transformer backbone. + """ + + def __init__( + self, + in_channels=7, + hidden_size=1152, + depth=28, + num_heads=16, + mlp_ratio=4.0, + class_dropout_prob=0.1, + token_size=4096, + future_action_window_size=1, + past_action_window_size=0, + learn_sigma=False, + n_conditon_token=64, + ): + super().__init__() + + assert past_action_window_size == 0, "Error: action_history is not used now" + self.num_cond_tokens = n_conditon_token + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels * 2 if learn_sigma else in_channels + self.class_dropout_prob = class_dropout_prob + self.num_heads = num_heads + self.past_action_window_size = past_action_window_size + self.future_action_window_size = future_action_window_size + + # Action history is not used now. + self.history_embedder = HistoryEmbedder(action_size=in_channels, hidden_size=token_size) + + self.x_embedder = ActionEmbedder(action_size=in_channels, hidden_size=token_size) + self.t_embedder = TimestepEmbedder(token_size) + conditions_shape = (1, n_conditon_token, token_size) + + self.z_embedder = LabelEmbedder( + in_size=token_size, + hidden_size=token_size, + dropout_prob=class_dropout_prob, + conditions_shape=conditions_shape, + ) + scale = token_size**-0.5 + + # Learnable positional embeddings + # 1+64, one for the conditional token, and one for the current action prediction + self.positional_embedding = nn.Parameter( + scale + * torch.randn(self.num_cond_tokens + future_action_window_size + past_action_window_size + 1, token_size) + ) + + self.blocks = nn.ModuleList([DiTBlock(token_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)]) + self.final_layer = FinalLayer(token_size, self.out_channels) + self.initialize_weights() + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + self.apply(_basic_init) + + # # Initialize token_embed like nn.Linear + nn.init.normal_(self.x_embedder.linear.weight, std=0.02) + nn.init.constant_(self.x_embedder.linear.bias, 0) + + nn.init.normal_(self.history_embedder.linear.weight, std=0.02) + nn.init.constant_(self.history_embedder.linear.bias, 0) + + # Initialize label embedding table: + if self.class_dropout_prob > 0: + nn.init.normal_(self.z_embedder.uncondition, std=0.02) + nn.init.normal_(self.z_embedder.linear.weight, std=0.02) + nn.init.constant_(self.z_embedder.linear.bias, 0) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + def forward(self, x, t, z): + """ + Forward pass of DiT. + history: (B, H, D) tensor of action history # not used now + x: (B, T, D) tensor of predicting action inputs + t: (B,) tensor of diffusion timesteps + z: [B, num_cond_tokens, D] -- condition token + """ + x = self.x_embedder(x) # (N, T, D) + t = self.t_embedder(t) # (N, D) + z = self.z_embedder(z, self.training) # [N, num_cond_tokens, D] + c = t.unsqueeze(1) + z # (N, 64, D) + x = torch.cat((c, x), dim=1) # (N, T+64, D) + x = x + self.positional_embedding # (N, T+64, D) + for block in self.blocks: + x = block(x) # (N, T+64, D) + x = self.final_layer(x) # (N, T+64, out_channels) + return x[:, self.num_cond_tokens :, :] # (N, T, C) + + def forward_with_cfg(self, x, t, z, cfg_scale): + """ + Forward pass of Diffusion, but also batches the unconditional forward pass for classifier-free guidance. + """ + + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + half = x[: len(x) // 2] + combined = torch.cat([half, half], dim=0).to(next(self.x_embedder.parameters()).dtype) + model_out = self.forward(combined, t, z) + # eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:] + eps, rest = model_out[:, :, : self.in_channels], model_out[:, :, self.in_channels :] + cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) + half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) + eps = torch.cat([half_eps, half_eps], dim=0) + # return torch.cat([eps, rest], dim=1) + return torch.cat([eps, rest], dim=2) + + +# Cross-Attention DiT Implementation + + +class CrossAttention(nn.Module): + """ + Cross-attention module that supports both self-attention and cross-attention. + """ + + def __init__(self, hidden_size, num_heads, qkv_bias=True, attn_drop=0.0, proj_drop=0.0): + super().__init__() + assert hidden_size % num_heads == 0 + self.num_heads = num_heads + self.head_dim = hidden_size // num_heads + self.scale = self.head_dim**-0.5 + + self.q = nn.Linear(hidden_size, hidden_size, bias=qkv_bias) + self.kv = nn.Linear(hidden_size, hidden_size * 2, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(hidden_size, hidden_size) + self.proj_drop = nn.Dropout(proj_drop) + + def forward(self, x, context=None): + """ + Args: + x: query tensor [B, N, C] + context: key/value tensor [B, M, C]. If None, performs self-attention + """ + B, N, C = x.shape + + # Query from x + q = self.q(x).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + + # Key and Value from context (or x if self-attention) + if context is None: + context = x + M = context.shape[1] + kv = self.kv(context).reshape(B, M, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + k, v = kv.unbind(0) + + # Attention computation + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class DiTBlockCrossAttn(nn.Module): + """ + A DiT block with only cross-attention + MLP. + """ + + def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): + super().__init__() + + # Cross-attention components + self.norm_attn = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.cross_attn = CrossAttention(hidden_size, num_heads=num_heads, **block_kwargs) + + # MLP components + self.norm_mlp = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0) + + def forward(self, x, encoder_features=None): + """ + Args: + x: input tensor [B, N, C] (action-related tokens) + encoder_features: encoder features [B, M, C] (e.g., vision-language features) + """ + # Cross-attention (if encoder features provided) or self-attention (if None) + if encoder_features is not None: + # Cross-attention: Query from x, Key/Value from encoder_features + x = x + self.cross_attn(self.norm_attn(x), context=encoder_features) + else: + # Self-attention: Query, Key, Value all from x (for backward compatibility) + x = x + self.cross_attn(self.norm_attn(x), context=None) + + # MLP + x = x + self.mlp(self.norm_mlp(x)) + return x + + +class DiTBlockSelfAttn(nn.Module): + """ + A DiT block with only self-attention + MLP. + """ + + def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs): + super().__init__() + + # Self-attention components (same as original DiTBlock) + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs) + + # MLP components (same as original DiTBlock) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + mlp_hidden_dim = int(hidden_size * mlp_ratio) + approx_gelu = lambda: nn.GELU(approximate="tanh") + self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0) + + def forward(self, x, encoder_features=None): + """ + Args: + x: input tensor [B, N, C] (action-related tokens) + encoder_features: encoder features [B, M, C] (not used in self-attention, for interface compatibility) + """ + # Self-attention (identical to original DiTBlock) + x = x + self.attn(self.norm1(x)) + + # MLP (identical to original DiTBlock) + x = x + self.mlp(self.norm2(x)) + return x + + +class DiTCrossAttn(nn.Module): + """ + Diffusion model with a Transformer backbone supporting cross-attention. + """ + + def __init__( + self, + in_channels=7, + hidden_size=1152, + depth=28, + num_heads=16, + mlp_ratio=4.0, + class_dropout_prob=0.1, + token_size=4096, + future_action_window_size=1, + past_action_window_size=0, + learn_sigma=False, + n_conditon_token=64, + ): + super().__init__() + + assert past_action_window_size == 0, "Error: action_history is not used now" + self.num_cond_tokens = n_conditon_token + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels * 2 if learn_sigma else in_channels + self.class_dropout_prob = class_dropout_prob + self.num_heads = num_heads + self.past_action_window_size = past_action_window_size + self.future_action_window_size = future_action_window_size + + # Action history is not used now. + self.history_embedder = HistoryEmbedder(action_size=in_channels, hidden_size=token_size) + + self.x_embedder = ActionEmbedder(action_size=in_channels, hidden_size=token_size) + self.t_embedder = TimestepEmbedder(token_size) + conditions_shape = (1, n_conditon_token, token_size) + + self.z_embedder = LabelEmbedder( + in_size=token_size, + hidden_size=token_size, + dropout_prob=class_dropout_prob, + conditions_shape=conditions_shape, + ) + scale = token_size**-0.5 + + # Learnable positional embeddings + actual_action_length = future_action_window_size + past_action_window_size + 1 + self.positional_embedding = nn.Parameter( + scale * torch.randn(self.num_cond_tokens + actual_action_length, token_size) + ) + + # Alternating cross-attention and self-attention blocks + self.blocks = nn.ModuleList() + for layer_idx in range(depth): + if layer_idx % 2 == 0: # Even layers (0, 2, 4, ...): Cross-Attention + block = DiTBlockCrossAttn(token_size, num_heads, mlp_ratio=mlp_ratio) + else: # Odd layers (1, 3, 5, ...): Self-Attention + block = DiTBlockSelfAttn(token_size, num_heads, mlp_ratio=mlp_ratio) + self.blocks.append(block) + self.final_layer = FinalLayer(token_size, self.out_channels) + self.initialize_weights() + + def initialize_weights(self): + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + + self.apply(_basic_init) + + # Initialize embedders + nn.init.normal_(self.x_embedder.linear.weight, std=0.02) + nn.init.constant_(self.x_embedder.linear.bias, 0) + + nn.init.normal_(self.history_embedder.linear.weight, std=0.02) + nn.init.constant_(self.history_embedder.linear.bias, 0) + + # Initialize label embedding table: + if self.class_dropout_prob > 0: + nn.init.normal_(self.z_embedder.uncondition, std=0.02) + nn.init.normal_(self.z_embedder.linear.weight, std=0.02) + nn.init.constant_(self.z_embedder.linear.bias, 0) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + def forward(self, x, t, z, encoder_features=None): + """ + Forward pass of DiT with cross-attention. + Args: + x: (B, T, D) tensor of predicting action inputs + t: (B,) tensor of diffusion timesteps + z: [B, num_cond_tokens, D] -- condition token + encoder_features: [B, M, D] -- encoder features for cross-attention (e.g., vision-language features) + """ + x = self.x_embedder(x) # (N, T, D) + t = self.t_embedder(t) # (N, D) + z = self.z_embedder(z, self.training) # [N, num_cond_tokens, D] + c = t.unsqueeze(1) + z # (N, 64, D) + x = torch.cat((c, x), dim=1) # (N, T+64, D) + x = x + self.positional_embedding # (N, T+64, D) + + # Pass through cross-attention blocks + for block in self.blocks: + x = block(x, encoder_features=encoder_features) # (N, T+64, D) + + x = self.final_layer(x) # (N, T+64, out_channels) + return x[:, self.num_cond_tokens :, :] # (N, T, C) + + def forward_with_cfg(self, x, t, z, cfg_scale, encoder_features=None): + """ + Forward pass with classifier-free guidance for cross-attention DiT. + """ + # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb + half = x[: len(x) // 2] + combined = torch.cat([half, half], dim=0).to(next(self.x_embedder.parameters()).dtype) + + # Handle encoder features for CFG: conditional + unconditional + if encoder_features is not None: + # First half: conditional (with encoder features) + # Second half: unconditional (without encoder features, set to None) + encoder_features_combined = torch.cat([encoder_features, encoder_features], dim=0) + # Note: For true CFG, you might want to pass None for the second half: + # But this would require modifying the forward pass to handle mixed batches + else: + encoder_features_combined = None + + model_out = self.forward(combined, t, z, encoder_features=encoder_features_combined) + eps, rest = model_out[:, :, : self.in_channels], model_out[:, :, self.in_channels :] + cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) + half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) + eps = torch.cat([half_eps, half_eps], dim=0) + return torch.cat([eps, rest], dim=2) diff --git a/starVLA/model/modules/action_model/DiT_modules/respace.py b/starVLA/model/modules/action_model/DiT_modules/respace.py new file mode 100644 index 0000000000000000000000000000000000000000..612c4d9eb4a0b9c65821a0e5fbed102588cab886 --- /dev/null +++ b/starVLA/model/modules/action_model/DiT_modules/respace.py @@ -0,0 +1,121 @@ +# Modified from OpenAI's diffusion repos +# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py +# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion +# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py + +import numpy as np +import torch as th + +from .gaussian_diffusion import GaussianDiffusion + + +def space_timesteps(num_timesteps, section_counts): + """ + Create a list of timesteps to use from an original diffusion process, + given the number of timesteps we want to take from equally-sized portions + of the original process. + For example, if there's 300 timesteps and the section counts are [10,15,20] + then the first 100 timesteps are strided to be 10 timesteps, the second 100 + are strided to be 15 timesteps, and the final 100 are strided to be 20. + If the stride is a string starting with "ddim", then the fixed striding + from the DDIM paper is used, and only one section is allowed. + :param num_timesteps: the number of diffusion steps in the original + process to divide up. + :param section_counts: either a list of numbers, or a string containing + comma-separated numbers, indicating the step count + per section. As a special case, use "ddimN" where N + is a number of steps to use the striding from the + DDIM paper. + :return: a set of diffusion steps from the original process to use. + """ + if isinstance(section_counts, str): + if section_counts.startswith("ddim"): + desired_count = int(section_counts[len("ddim") :]) + if desired_count == 1: + return set([50]) + for i in range(1, num_timesteps): + if len(range(0, num_timesteps, i)) == desired_count: + return set(range(0, num_timesteps, i)) + raise ValueError(f"cannot create exactly {num_timesteps} steps with an integer stride") + section_counts = [int(x) for x in section_counts.split(",")] + size_per = num_timesteps // len(section_counts) + extra = num_timesteps % len(section_counts) + start_idx = 0 + all_steps = [] + for i, section_count in enumerate(section_counts): + size = size_per + (1 if i < extra else 0) + if size < section_count: + raise ValueError(f"cannot divide section of {size} steps into {section_count}") + if section_count <= 1: + frac_stride = 1 + else: + frac_stride = (size - 1) / (section_count - 1) + cur_idx = 0.0 + taken_steps = [] + for _ in range(section_count): + taken_steps.append(start_idx + round(cur_idx)) + cur_idx += frac_stride + all_steps += taken_steps + start_idx += size + return set(all_steps) + + +class SpacedDiffusion(GaussianDiffusion): + """ + A diffusion process which can skip steps in a base diffusion process. + :param use_timesteps: a collection (sequence or set) of timesteps from the + original diffusion process to retain. + :param kwargs: the kwargs to create the base diffusion process. + """ + + def __init__(self, use_timesteps, **kwargs): + self.use_timesteps = set(use_timesteps) + self.timestep_map = [] + self.original_num_steps = len(kwargs["betas"]) + + base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa + last_alpha_cumprod = 1.0 + new_betas = [] + for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod): + if i in self.use_timesteps: + new_betas.append(1 - alpha_cumprod / last_alpha_cumprod) + last_alpha_cumprod = alpha_cumprod + self.timestep_map.append(i) + kwargs["betas"] = np.array(new_betas) + super().__init__(**kwargs) + + def p_mean_variance(self, model, *args, **kwargs): # pylint: disable=signature-differs + return super().p_mean_variance(self._wrap_model(model), *args, **kwargs) + + def training_losses(self, model, *args, **kwargs): # pylint: disable=signature-differs + return super().training_losses(self._wrap_model(model), *args, **kwargs) + + def condition_mean(self, cond_fn, *args, **kwargs): + return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs) + + def condition_score(self, cond_fn, *args, **kwargs): + return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs) + + def _wrap_model(self, model): + if isinstance(model, _WrappedModel): + return model + return _WrappedModel(model, self.timestep_map, self.original_num_steps) + + def _scale_timesteps(self, t): + # Scaling is done by the wrapped model. + return t + + +class _WrappedModel: + def __init__(self, model, timestep_map, original_num_steps): + self.model = model + self.timestep_map = timestep_map + # self.rescale_timesteps = rescale_timesteps + self.original_num_steps = original_num_steps + + def __call__(self, x, ts, **kwargs): + map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype) + new_ts = map_tensor[ts] + # if self.rescale_timesteps: + # new_ts = new_ts.float() * (1000.0 / self.original_num_steps) + return self.model(x, new_ts, **kwargs) diff --git a/starVLA/model/modules/action_model/DiT_modules/timestep_sampler.py b/starVLA/model/modules/action_model/DiT_modules/timestep_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..fdaa45acfcf239d7b6aaf5a83ee12fd553bc06b8 --- /dev/null +++ b/starVLA/model/modules/action_model/DiT_modules/timestep_sampler.py @@ -0,0 +1,143 @@ +# Modified from OpenAI's diffusion repos +# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py +# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion +# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py + +from abc import ABC, abstractmethod + +import numpy as np +import torch as th +import torch.distributed as dist + + +def create_named_schedule_sampler(name, diffusion): + """ + Create a ScheduleSampler from a library of pre-defined samplers. + :param name: the name of the sampler. + :param diffusion: the diffusion object to sample for. + """ + if name == "uniform": + return UniformSampler(diffusion) + elif name == "loss-second-moment": + return LossSecondMomentResampler(diffusion) + else: + raise NotImplementedError(f"unknown schedule sampler: {name}") + + +class ScheduleSampler(ABC): + """ + A distribution over timesteps in the diffusion process, intended to reduce + variance of the objective. + By default, samplers perform unbiased importance sampling, in which the + objective's mean is unchanged. + However, subclasses may override sample() to change how the resampled + terms are reweighted, allowing for actual changes in the objective. + """ + + @abstractmethod + def weights(self): + """ + Get a numpy array of weights, one per diffusion step. + The weights needn't be normalized, but must be positive. + """ + + def sample(self, batch_size, device): + """ + Importance-sample timesteps for a batch. + :param batch_size: the number of timesteps. + :param device: the torch device to save to. + :return: a tuple (timesteps, weights): + - timesteps: a tensor of timestep indices. + - weights: a tensor of weights to scale the resulting losses. + """ + w = self.weights() + p = w / np.sum(w) + indices_np = np.random.choice(len(p), size=(batch_size,), p=p) + indices = th.from_numpy(indices_np).long().to(device) + weights_np = 1 / (len(p) * p[indices_np]) + weights = th.from_numpy(weights_np).float().to(device) + return indices, weights + + +class UniformSampler(ScheduleSampler): + def __init__(self, diffusion): + self.diffusion = diffusion + self._weights = np.ones([diffusion.num_timesteps]) + + def weights(self): + return self._weights + + +class LossAwareSampler(ScheduleSampler): + def update_with_local_losses(self, local_ts, local_losses): + """ + Update the reweighting using losses from a model. + Call this method from each rank with a batch of timesteps and the + corresponding losses for each of those timesteps. + This method will perform synchronization to make sure all of the ranks + maintain the exact same reweighting. + :param local_ts: an integer Tensor of timesteps. + :param local_losses: a 1D Tensor of losses. + """ + batch_sizes = [th.tensor([0], dtype=th.int32, device=local_ts.device) for _ in range(dist.get_world_size())] + dist.all_gather( + batch_sizes, + th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device), + ) + + # Pad all_gather batches to be the maximum batch size. + batch_sizes = [x.item() for x in batch_sizes] + max_bs = max(batch_sizes) + + timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes] + loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes] + dist.all_gather(timestep_batches, local_ts) + dist.all_gather(loss_batches, local_losses) + timesteps = [x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]] + losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]] + self.update_with_all_losses(timesteps, losses) + + @abstractmethod + def update_with_all_losses(self, ts, losses): + """ + Update the reweighting using losses from a model. + Sub-classes should override this method to update the reweighting + using losses from the model. + This method directly updates the reweighting without synchronizing + between workers. It is called by update_with_local_losses from all + ranks with identical arguments. Thus, it should have deterministic + behavior to maintain state across workers. + :param ts: a list of int timesteps. + :param losses: a list of float losses, one per timestep. + """ + + +class LossSecondMomentResampler(LossAwareSampler): + def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001): + self.diffusion = diffusion + self.history_per_term = history_per_term + self.uniform_prob = uniform_prob + self._loss_history = np.zeros([diffusion.num_timesteps, history_per_term], dtype=np.float64) + self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int) + + def weights(self): + if not self._warmed_up(): + return np.ones([self.diffusion.num_timesteps], dtype=np.float64) + weights = np.sqrt(np.mean(self._loss_history**2, axis=-1)) + weights /= np.sum(weights) + weights *= 1 - self.uniform_prob + weights += self.uniform_prob / len(weights) + return weights + + def update_with_all_losses(self, ts, losses): + for t, loss in zip(ts, losses): + if self._loss_counts[t] == self.history_per_term: + # Shift out the oldest loss term. + self._loss_history[t, :-1] = self._loss_history[t, 1:] + self._loss_history[t, -1] = loss + else: + self._loss_history[t, self._loss_counts[t]] = loss + self._loss_counts[t] += 1 + + def _warmed_up(self): + return (self._loss_counts == self.history_per_term).all() diff --git a/starVLA/model/modules/action_model/GR00T_ActionHeader.py b/starVLA/model/modules/action_model/GR00T_ActionHeader.py new file mode 100644 index 0000000000000000000000000000000000000000..e3daa05b21451565db3edb04f6d770100e2e22e1 --- /dev/null +++ b/starVLA/model/modules/action_model/GR00T_ActionHeader.py @@ -0,0 +1,419 @@ +# Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved. +# Modified by [Junqiu YU/ Fudan University] in [2025]. +# Modification: [rm and add some connect adapter to match with starVLA, e.g., "rm "]. +# Action repeat is inspired by CogACT + + + +from dataclasses import dataclass, field +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.distributions import Beta +from transformers import PretrainedConfig +from transformers.feature_extraction_utils import BatchFeature + +from starVLA.model.modules.action_model.flow_matching_head.action_encoder import ( + SinusoidalPositionalEncoding, + swish, +) + +from starVLA.model.modules.action_model.flow_matching_head.cross_attention_dit import DiT + +# TODO try to meger DiT Modules with follow_match_head, they are just the same arch, but diff loss, use diffusers package will be simple + +class CategorySpecificLinear(nn.Module): + def __init__(self, num_categories, input_dim, hidden_dim): + super().__init__() + self.num_categories = num_categories + # For each category, we have separate weights and biases. + self.W = nn.Parameter(0.02 * torch.randn(num_categories, input_dim, hidden_dim)) + self.b = nn.Parameter(torch.zeros(num_categories, hidden_dim)) + + def forward(self, x, cat_ids): + selected_W = self.W[cat_ids] + selected_b = self.b[cat_ids] + # import ipdb; ipdb.set_trace() + return torch.bmm(x, selected_W) + selected_b.unsqueeze(1) + + +class CategorySpecificMLP(nn.Module): + def __init__(self, num_categories, input_dim, hidden_dim, output_dim): + super().__init__() + self.num_categories = num_categories + self.layer1 = CategorySpecificLinear(num_categories, input_dim, hidden_dim) + self.layer2 = CategorySpecificLinear(num_categories, hidden_dim, output_dim) + + def forward(self, x, cat_ids): + hidden = F.relu(self.layer1(x, cat_ids)) + return self.layer2(hidden, cat_ids) + + + +class MLP(nn.Module): + def __init__(self, input_dim, hidden_dim, output_dim): + super().__init__() + self.layer1 = nn.Linear(input_dim, hidden_dim) + self.layer2 = nn.Linear(hidden_dim, output_dim) + + def forward(self, x): + return self.layer2(F.relu(self.layer1(x))) + + +class ActionEncoder(nn.Module): + def __init__(self, action_dim, hidden_size): + super().__init__() + self.hidden_size = hidden_size + self.action_dim = action_dim + self.layer1 = nn.Linear(action_dim, hidden_size) + self.layer2 = nn.Linear(2 * hidden_size, hidden_size) + self.layer3 = nn.Linear(hidden_size, hidden_size) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError( + "Expected `timesteps` to have shape (B,) so we can replicate across T." + ) + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.layer1(actions) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then layer2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.layer2(x)) + + # 5) Finally W3 => (B, T, w) + x = self.layer3(x) + return x + + + +class MultiEmbodimentActionEncoder(nn.Module): + def __init__(self, action_dim, hidden_size, num_embodiments): + super().__init__() + self.hidden_size = hidden_size + self.num_embodiments = num_embodiments + + # W1: R^{w x d}, W2: R^{w x 2w}, W3: R^{w x w} + self.W1 = CategorySpecificLinear(num_embodiments, action_dim, hidden_size) # (d -> w) + self.W2 = CategorySpecificLinear(num_embodiments, 2 * hidden_size, hidden_size) # (2w -> w) + self.W3 = CategorySpecificLinear(num_embodiments, hidden_size, hidden_size) # (w -> w) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps, cat_ids): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + cat_ids: shape (B,) + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError( + "Expected `timesteps` to have shape (B,) so we can replicate across T." + ) + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.W1(actions, cat_ids) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then W2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.W2(x, cat_ids)) + + # 5) Finally W3 => (B, T, w) + x = self.W3(x, cat_ids) + return x + + +@dataclass +class FlowmatchingActionHeadConfig(PretrainedConfig): + """NOTE: N1.5 uses XEmbFlowmatchingPolicyHeadConfig as action head""" + + add_pos_embed: bool = field( + default=True, metadata={"help": "Whether to add positional embedding"} + ) + diffusion_model_cfg: dict = field( + default=None, metadata={"help": "Diffusion model configuration."} + ) + input_embedding_dim: int = field( + default=1536, metadata={"help": "Input embedding channel dimension."} + ) + + hidden_size: int = field(default=1024, metadata={"help": "Input embedding dimension."}) + max_seq_len: int = field(default=1024, metadata={"help": "Maxium Sequence Length"}) + action_dim: int = field(default=None, metadata={"help": "Action dimension."}) + action_horizon: int = field(default=None, metadata={"help": "Action horizon."}) + noise_beta_alpha: float = field(default=1.5, metadata={"help": ""}) + noise_beta_beta: float = field(default=1.0, metadata={"help": ""}) + noise_s: float = field( + default=0.999, metadata={"help": "Flow matching noise Beta distribution s."} + ) + num_timestep_buckets: int = field( + default=1000, metadata={"help": "Number of timestep discretization buckets."} + ) + num_inference_timesteps: int = field( + default=None, + metadata={"help": "Number of inference steps for noise diffusion."}, + ) + max_num_embodiments: int = field(default=32, metadata={"help": "Number of embodiments."}) + tune_projector: bool = field(default=True, metadata={"help": "Whether to tune the projector."}) + tune_diffusion_model: bool = field( + default=True, metadata={"help": "Whether to tune the diffusion model."} + ) + load_pretrained_det_decode_layer_path: str = field( + default=None, metadata={"help": "Path to pretrained detection model."} + ) + detection_coeff: float = field(default=1.0, metadata={"help": "Detection coefficient."}) + + freeze_decode_layer: bool = field(default=False) + expand_batch: int = field(default=None) + use_vlln: bool = field(default=True) + + vl_self_attention_cfg: dict = field(default=None) + num_target_vision_tokens: int = field( + default=32, metadata={"help": "Number of target vision tokens."} + ) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + + +DiTConfig = { + "DiT-B": {"input_embedding_dim": 768, "attention_head_dim": 64, "num_attention_heads": 12}, + "DiT-L": {"input_embedding_dim": 1536, "attention_head_dim": 48, "num_attention_heads": 32}, +} + +class FlowmatchingActionHead(nn.Module): + def __init__( + self, + full_config, + ): + super().__init__() + config = full_config.framework.action_model + self.hidden_size = config.hidden_size # @JinhuiYE + self.full_config = full_config + action_model_type = config.action_model_type + action_model_cfg = DiTConfig[action_model_type] + + self.input_embedding_dim = action_model_cfg["input_embedding_dim"] + diffusion_model_cfg = config.diffusion_model_cfg + diffusion_model_cfg = {**action_model_cfg, **diffusion_model_cfg} + self.model = DiT(**diffusion_model_cfg) + self.action_dim = config.action_dim + self.action_horizon = config.future_action_window_size + 1 + self.num_inference_timesteps = config.num_inference_timesteps + + self.state_encoder = MLP( + input_dim=config.state_dim, + hidden_dim=self.hidden_size, + output_dim=self.input_embedding_dim, + ) if config.state_dim else None + + self.action_encoder = ActionEncoder( + action_dim=config.action_dim, + hidden_size=self.input_embedding_dim, + ) + self.action_decoder = MLP( + input_dim=self.model.config.output_dim, + hidden_dim=self.hidden_size, + output_dim=self.action_dim, + ) + self.future_tokens = nn.Embedding(config.num_target_vision_tokens, self.input_embedding_dim) + nn.init.normal_(self.future_tokens.weight, mean=0.0, std=0.02) + + if config.add_pos_embed: + self.position_embedding = nn.Embedding(config.max_seq_len, self.input_embedding_dim) + nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) + + self.beta_dist = Beta(config.noise_beta_alpha, config.noise_beta_beta) + self.num_timestep_buckets = config.num_timestep_buckets + self.config = config + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return (self.config.noise_s - sample) / self.config.noise_s + + def prepare_input(self, batch: dict) -> BatchFeature: + return BatchFeature(data=batch) + + + + def forward(self, vl_embs: torch.Tensor, actions: torch.Tensor, state: torch.Tensor = None, encoder_attention_mask=None, action_mask=None): + """ + vl_embs: shape (B, seq_length, feature_dim) + actions: shape (B, future_action_window_size, D_action) + """ + device = vl_embs.device + + # Embed noised action trajectory. + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] # shape (B,1,1) for broadcast + + noisy_trajectory = (1 - t) * noise + t * actions + velocity = actions - noise + + # Convert (continuous) t -> discrete if needed + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized) + + + # embed state + state_features = self.state_encoder(state) if state is not None else None + + + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Join VLM features with state and action embedding along sequence dimension. + model_output = self.model( + hidden_states=sa_embs, + encoder_hidden_states=vl_embs, + encoder_attention_mask=encoder_attention_mask, + timestep=t_discretized, + return_all_hidden_states=False, # NOTE (YL): not using flare now + ) + pred = self.action_decoder(model_output) + pred_actions = pred[:, -actions.shape[1] :] + # Use action_mask if provided, otherwise compute mean loss over all dimensions + + # if action_mask is not None: + # # Ensure action_mask is on the same device and has the same dtype as pred_actions + # if isinstance(action_mask, np.ndarray): + # action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + # else: + # action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + + # # Compute masked loss: only consider valid action dimensions + # loss = ((pred_actions - velocity) ** 2) * action_mask + # loss = loss.sum() / action_mask.sum() + # else: + # # Fallback to mean loss if no mask is provided + # loss = ((pred_actions - velocity) ** 2).mean() + # Slice out only the action portion of pred and target. + loss = ((pred_actions - velocity) ** 2).mean() + return loss + + @torch.no_grad() + def predict_action(self, vl_embs: torch.Tensor, state: torch.Tensor = None) -> torch.Tensor: + # Set initial actions as the sampled noise. + batch_size = vl_embs.shape[0] + device = vl_embs.device + actions = torch.randn( # yes, here make sure action_horizon align with data loader? or share from clinet? + size=(batch_size, self.config.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + ) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state) if state is not None else None + # 只在第一步注册 hooks 并分析 + analyze_attention = state_features is not None + + + # Run denoising steps. + for t in range(num_steps): + t_cont = t / float(num_steps) # e.g. goes 0, 1/N, 2/N, ... + t_discretized = int(t_cont * self.num_timestep_buckets) + + # Embed noised action trajectory. + timesteps_tensor = torch.full( + size=(batch_size,), fill_value=t_discretized, device=device + ) + action_features = self.action_encoder(actions, timesteps_tensor) + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # Join vision, language, state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + + # Run model forward. + model_output = self.model( + hidden_states=sa_embs, + encoder_hidden_states=vl_embs, + timestep=timesteps_tensor, + ) + pred = self.action_decoder(model_output) + + pred_velocity = pred[:, -self.action_horizon :] + + # Update actions using euler integration. + actions = actions + dt * pred_velocity + + return actions + + @property + def device(self): + return next(iter(self.parameters())).device + + @property + def dtype(self): + return next(iter(self.parameters())).dtype + + + +def get_action_model(config=None): + """ + Factory: build FlowmatchingActionHead from global framework config. + + Args: + config: Global config (expects config.framework.action_model namespace). + + Returns: + FlowmatchingActionHead: Initialized FlowMatchingActionHead. + """ + return FlowmatchingActionHead( + full_config=config + ) + + +if __name__ == "__main__": + # TODO make each backbone.py can be debug independently + + pass diff --git a/starVLA/model/modules/action_model/LayerwiseFM_ActionHeader.py b/starVLA/model/modules/action_model/LayerwiseFM_ActionHeader.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e000e2941d9a200d74304fa731ab142adc52a1 --- /dev/null +++ b/starVLA/model/modules/action_model/LayerwiseFM_ActionHeader.py @@ -0,0 +1,414 @@ +# Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved. +# Modified by [Junqiu YU/ Fudan University] in [2025]. +# Modification: [rm and add some connect adapter to match with starVLA, e.g., "rm "]. + + + +from dataclasses import dataclass, field + +import torch +import torch.nn.functional as F +from torch import nn +from torch.distributions import Beta +from transformers import PretrainedConfig +from transformers.feature_extraction_utils import BatchFeature + +from starVLA.model.modules.action_model.flow_matching_head.action_encoder import ( + SinusoidalPositionalEncoding, + swish, +) + +from starVLA.model.modules.action_model.flow_matching_head.cross_attention_dit import DiT, SelfAttentionTransformer + +# TODO try to meger DiT Modules with follow_match_head, they are just the same arch, but diff loss, use diffusers package will be simple + +class CategorySpecificLinear(nn.Module): + def __init__(self, num_categories, input_dim, hidden_dim): + super().__init__() + self.num_categories = num_categories + # For each category, we have separate weights and biases. + self.W = nn.Parameter(0.02 * torch.randn(num_categories, input_dim, hidden_dim)) + self.b = nn.Parameter(torch.zeros(num_categories, hidden_dim)) + + def forward(self, x, cat_ids): + selected_W = self.W[cat_ids] + selected_b = self.b[cat_ids] + # import ipdb; ipdb.set_trace() + return torch.bmm(x, selected_W) + selected_b.unsqueeze(1) + + +class CategorySpecificMLP(nn.Module): + def __init__(self, num_categories, input_dim, hidden_dim, output_dim): + super().__init__() + self.num_categories = num_categories + self.layer1 = CategorySpecificLinear(num_categories, input_dim, hidden_dim) + self.layer2 = CategorySpecificLinear(num_categories, hidden_dim, output_dim) + + def forward(self, x, cat_ids): + hidden = F.relu(self.layer1(x, cat_ids)) + return self.layer2(hidden, cat_ids) + + + +class MLP(nn.Module): + def __init__(self, input_dim, hidden_dim=1024, output_dim=2048): + super().__init__() + self.layer1 = nn.Linear(input_dim, hidden_dim) + self.layer2 = nn.Linear(hidden_dim, output_dim) + + def forward(self, x): + return self.layer2(F.relu(self.layer1(x))) + + +class ActionEncoder(nn.Module): + def __init__(self, action_dim, hidden_size=1024): + super().__init__() + self.hidden_size = hidden_size + self.action_dim = action_dim + self.layer1 = nn.Linear(action_dim, hidden_size) + self.layer2 = nn.Linear(2 * hidden_size, hidden_size) + self.layer3 = nn.Linear(hidden_size, hidden_size) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError( + "Expected `timesteps` to have shape (B,) so we can replicate across T." + ) + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.layer1(actions) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then layer2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.layer2(x)) + + # 5) Finally W3 => (B, T, w) + x = self.layer3(x) + return x + + + +class MultiEmbodimentActionEncoder(nn.Module): + def __init__(self, action_dim, hidden_size=1024, num_embodiments=8): + super().__init__() + self.hidden_size = hidden_size + self.num_embodiments = num_embodiments + + # W1: R^{w x d}, W2: R^{w x 2w}, W3: R^{w x w} + self.W1 = CategorySpecificLinear(num_embodiments, action_dim, hidden_size) # (d -> w) + self.W2 = CategorySpecificLinear(num_embodiments, 2 * hidden_size, hidden_size) # (2w -> w) + self.W3 = CategorySpecificLinear(num_embodiments, hidden_size, hidden_size) # (w -> w) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps, cat_ids): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + cat_ids: shape (B,) + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError( + "Expected `timesteps` to have shape (B,) so we can replicate across T." + ) + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.W1(actions, cat_ids) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then W2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.W2(x, cat_ids)) + + # 5) Finally W3 => (B, T, w) + x = self.W3(x, cat_ids) + return x + + +@dataclass +class FlowmatchingActionHeadConfig(PretrainedConfig): + """NOTE: N1.5 uses XEmbFlowmatchingPolicyHeadConfig as action head""" + + add_pos_embed: bool = field( + default=True, metadata={"help": "Whether to add positional embedding"} + ) + diffusion_model_cfg: dict = field( + default=None, metadata={"help": "Diffusion model configuration."} + ) + input_embedding_dim: int = field( + default=1536, metadata={"help": "Input embedding channel dimension."} + ) + + hidden_size: int = field(default=1024, metadata={"help": "Input embedding dimension."}) + max_seq_len: int = field(default=1024, metadata={"help": "Maxium Sequence Length"}) + action_dim: int = field(default=None, metadata={"help": "Action dimension."}) + action_horizon: int = field(default=None, metadata={"help": "Action horizon."}) + noise_beta_alpha: float = field(default=1.5, metadata={"help": ""}) + noise_beta_beta: float = field(default=1.0, metadata={"help": ""}) + noise_s: float = field( + default=0.999, metadata={"help": "Flow matching noise Beta distribution s."} + ) + num_timestep_buckets: int = field( + default=1000, metadata={"help": "Number of timestep discretization buckets."} + ) + num_inference_timesteps: int = field( + default=None, + metadata={"help": "Number of inference steps for noise diffusion."}, + ) + max_num_embodiments: int = field(default=32, metadata={"help": "Number of embodiments."}) + tune_projector: bool = field(default=True, metadata={"help": "Whether to tune the projector."}) + tune_diffusion_model: bool = field( + default=True, metadata={"help": "Whether to tune the diffusion model."} + ) + load_pretrained_det_decode_layer_path: str = field( + default=None, metadata={"help": "Path to pretrained detection model."} + ) + detection_coeff: float = field(default=1.0, metadata={"help": "Detection coefficient."}) + + freeze_decode_layer: bool = field(default=False) + expand_batch: int = field(default=None) + use_vlln: bool = field(default=True) + + vl_self_attention_cfg: dict = field(default=None) + num_target_vision_tokens: int = field( + default=32, metadata={"help": "Number of target vision tokens."} + ) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + + + + +DiTConfig = {"num_layers": 36, "input_embedding_dim": 2048, "attention_head_dim": 64, "num_attention_heads": 32} # default for qwen2.5-vl + + +class LayerwiseFlowmatchingActionHead(nn.Module): + def __init__( + self, + global_config, + **kwargs, + ): + super().__init__() + action_config = global_config.framework.action_model + diffusion_model_cfg = action_config.diffusion_model_cfg + + # 更新 DiTConfig 到 diffusion_model_cfg + DiTConfig["num_layers"] = global_config.framework.qwenvl.num_vl_layers + DiTConfig["input_embedding_dim"] = global_config.framework.qwenvl.vl_hidden_dim + DiTConfig["num_attention_heads"] = DiTConfig["input_embedding_dim"] // DiTConfig["attention_head_dim"] + diffusion_model_cfg.update(DiTConfig) + # diffusion_model_cfg["interleave_self_attention"] = False + diffusion_model_cfg.cross_attention_dim = DiTConfig["input_embedding_dim"] # should match vl embedding dim, but for some case we might want to change it for cross + self attention + self.input_embedding_dim = global_config.framework.qwenvl.vl_hidden_dim + self.model = DiT(**diffusion_model_cfg) # TODO better way is copy LLM from VLM + self.dit_out_hidden_size = self.input_embedding_dim + self.action_dim = action_config.action_dim + self.action_horizon = action_config.future_action_window_size + 1 + self.num_inference_timesteps = action_config.num_inference_timesteps + + self.state_encoder = MLP( + input_dim=action_config.state_dim, + output_dim=self.input_embedding_dim, + ) if action_config.state_dim else None + + self.action_encoder = ActionEncoder( + action_dim=action_config.action_dim, + hidden_size=self.input_embedding_dim, + ) + self.action_decoder = MLP( + input_dim=self.input_embedding_dim, + hidden_dim=1024, + output_dim=self.action_dim, + ) + self.future_tokens = nn.Embedding(action_config.num_target_vision_tokens, self.input_embedding_dim) + nn.init.normal_(self.future_tokens.weight, mean=0.0, std=0.02) + + if action_config.add_pos_embed: + self.position_embedding = nn.Embedding(action_config.max_seq_len, self.input_embedding_dim) + nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) + + self.beta_dist = Beta(action_config.noise_beta_alpha, action_config.noise_beta_beta) + self.num_timestep_buckets = action_config.num_timestep_buckets + self.config = action_config + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return (self.config.noise_s - sample) / self.config.noise_s + + def prepare_input(self, batch: dict) -> BatchFeature: + return BatchFeature(data=batch) + + + def forward(self, vl_embs_list: list, actions: torch.Tensor, state: torch.Tensor = None): + """ + vl_embs: list of torch.Tensor, each shape (B, seq_length, feature_dim) + actions: shape (B, future_action_window_size, D_action) + """ + device = actions.device + num_layers = len(vl_embs_list) + B, L, D = vl_embs_list[0].shape + # Embed noised action trajectory. + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] # shape (B,1,1) for broadcast + + noisy_trajectory = (1 - t) * noise + t * actions + velocity = actions - noise + + # Convert (continuous) t -> discrete if needed + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized) + + # Embed state + state_features = self.state_encoder(state) if state is not None else None + + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(B, -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Encode timesteps + temb = self.model.timestep_encoder(t_discretized) + + # Layerwise cross-attention with vl_embs + model_output = sa_embs + for layer_idx, layer in enumerate(self.model.transformer_blocks): + model_output = layer( + hidden_states=model_output, + encoder_hidden_states=vl_embs_list[layer_idx], # Use layer-specific vl_embs + temb=temb, + ) + + # TODO miss self att and _process_output, but work well + pred = self.action_decoder(model_output) + pred_actions = pred[:, -actions.shape[1] :] + + # Slice out only the action portion of pred and target. + loss = ((pred_actions - velocity) ** 2).mean() + return loss + + @torch.no_grad() + def predict_action(self, vl_embs_list: list, state: torch.Tensor = None) -> torch.Tensor: + # Set initial actions as the sampled noise. + batch_size = vl_embs_list[0].shape[0] + device = vl_embs_list[0].device + actions = torch.randn( + size=(batch_size, self.action_horizon, self.action_dim), + dtype=vl_embs_list[0].dtype, + device=device, + ) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state) if state is not None else None + + # Run denoising steps. + for t in range(num_steps): + t_cont = t / float(num_steps) + t_discretized_int = int(t_cont * self.num_timestep_buckets) + timesteps_tensor = torch.full( + size=(batch_size,), fill_value=t_discretized_int, device=device, dtype=torch.long + ) + + # Embed current action trajectory with timestep + action_features = self.action_encoder(actions, timesteps_tensor) + + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(batch_size, -1, -1) + sa_embs = ( + torch.cat((state_features, future_tokens, action_features), dim=1) + if state_features is not None + else torch.cat((future_tokens, action_features), dim=1) + ) + + # Encode timestep + temb = self.model.timestep_encoder(timesteps_tensor) + + # Layerwise cross-attention with vl_embs_list + model_output = sa_embs + for layer_idx, layer in enumerate(self.model.transformer_blocks): + model_output = layer( + hidden_states=model_output, + encoder_hidden_states=vl_embs_list[layer_idx], + temb=temb, + ) + # TODO miss self att and _process_output + pred = self.action_decoder(model_output) + pred_velocity = pred[:, -self.action_horizon :] + + # Euler integration + actions = actions + dt * pred_velocity + return actions + + @property + def device(self): + return next(iter(self.parameters())).device + + @property + def dtype(self): + return next(iter(self.parameters())).dtype + + + +def get_action_model(config=None): + """ + Factory: build FlowmatchingActionHead from global framework config. + + Args: + config: Global config (expects config.framework.action_model namespace). + + Returns: + FlowmatchingActionHead: Initialized FlowMatchingActionHead. + """ + return LayerwiseFlowmatchingActionHead( + global_config=config + ) + + + +if __name__ == "__main__": + # TODO make each backbone.py can be debug independently + + pass \ No newline at end of file diff --git a/starVLA/model/modules/action_model/MLP_ActionHeader.py b/starVLA/model/modules/action_model/MLP_ActionHeader.py new file mode 100644 index 0000000000000000000000000000000000000000..0cef440ff2aa82be16d767c437b8c9bd888c2669 --- /dev/null +++ b/starVLA/model/modules/action_model/MLP_ActionHeader.py @@ -0,0 +1,113 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Jinhui YE / HKUST University] in [2025]. + +"""Implementations of various action heads, which serve as alternatives to VLM sequential token prediction.""" +"this file is adap from https://github.com/moojink/openvla-oft/blob/main/prismatic/models/action_heads.py" + +import torch.nn as nn + + +class MLPResNetBlock(nn.Module): + """One MLP ResNet block with a residual connection.""" + def __init__(self, dim): + super().__init__() + self.dim = dim + self.ffn = nn.Sequential( # feedforward network, similar to the ones in Transformers + nn.LayerNorm(dim), + nn.Linear(dim, dim), + nn.ReLU(), + ) + + def forward(self, x): + # x: (batch_size, hidden_dim) + # We follow the module ordering of "Pre-Layer Normalization" feedforward networks in Transformers as + # described here: https://arxiv.org/pdf/2002.04745.pdf + identity = x + x = self.ffn(x) + x = x + identity + return x + + +class MLPResNet(nn.Module): + """MLP with residual connection blocks.""" + def __init__(self, num_blocks, input_dim, hidden_dim, output_dim): + super().__init__() + self.layer_norm1 = nn.LayerNorm(input_dim) + self.fc1 = nn.Linear(input_dim, hidden_dim) + self.relu = nn.ReLU() + self.mlp_resnet_blocks = nn.ModuleList() + for _ in range(num_blocks): + self.mlp_resnet_blocks.append(MLPResNetBlock(dim=hidden_dim)) + self.layer_norm2 = nn.LayerNorm(hidden_dim) + self.fc2 = nn.Linear(hidden_dim, output_dim) + + def forward(self, x): + # x: (batch_size, input_dim) + x = self.layer_norm1(x) # shape: (batch_size, input_dim) + x = self.fc1(x) # shape: (batch_size, hidden_dim) + x = self.relu(x) # shape: (batch_size, hidden_dim) + for block in self.mlp_resnet_blocks: + x = block(x) # shape: (batch_size, hidden_dim) + x = self.layer_norm2(x) # shape: (batch_size, hidden_dim) + x = self.fc2(x) # shape: (batch_size, output_dim) + return x + + +class L1RegressionActionHead(nn.Module): + """Simple MLP-based action head that generates continuous actions via L1 regression.""" + def __init__( + self, + input_dim=2048, + hidden_dim=4096, + action_dim=7, + NUM_ACTIONS_CHUNK=8, + ): + super().__init__() + self.action_dim = action_dim + self.NUM_ACTIONS_CHUNK = NUM_ACTIONS_CHUNK + + + self.model = MLPResNet( + num_blocks=2, input_dim=input_dim , hidden_dim=hidden_dim, output_dim=action_dim + ) + + def predict_action(self, actions_hidden_states): + """ + actions_hidden_states: (B, chunk_len, hidden_dim) + 返回: (B, chunk_len, action_dim) + """ + batch_size, chunk_len, hidden_dim = actions_hidden_states.shape + x = actions_hidden_states.reshape(batch_size * chunk_len, hidden_dim) + x = self.model(x) # (B * chunk_len, action_dim) + actions = x.view(batch_size, chunk_len, self.action_dim) + return actions + + def forward(self, actions_hidden_states): + return self.predict_action(actions_hidden_states) + + +def get_action_model(config=None): + """ + Factory: build ActionModel from global framework config. + + Args: + config: Global config (expects config.framework.action_model namespace). + Returns: + ActionModel: Initialized diffusion action head. + """ + action_model_cfg = config.framework.action_model + model_type = action_model_cfg.action_model_type + action_hidden_dim = action_model_cfg.action_hidden_dim + action_dim = action_model_cfg.action_dim + future_action_window_size = action_model_cfg.future_action_window_size + past_action_window_size = action_model_cfg.past_action_window_size + + action_model = L1RegressionActionHead( + input_dim=action_hidden_dim, + hidden_dim=action_hidden_dim*2, + action_dim=action_dim, + NUM_ACTIONS_CHUNK=past_action_window_size+1+future_action_window_size, + ) + + return action_model diff --git a/starVLA/model/modules/action_model/PerceiverHead.py b/starVLA/model/modules/action_model/PerceiverHead.py new file mode 100644 index 0000000000000000000000000000000000000000..a3fff1e1f9e2a65b9caac1e02323cd542a5e0322 --- /dev/null +++ b/starVLA/model/modules/action_model/PerceiverHead.py @@ -0,0 +1,701 @@ +# Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved. +# Modified by [Junqiu YU/ Fudan University] in [2025]. +# Modification: [rm and add some connect adapter to match with starVLA, e.g., "rm "]. +# Action repeat is inspired by CogACT + +from dataclasses import dataclass, field + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.distributions import Beta +from transformers import PretrainedConfig +from transformers.feature_extraction_utils import BatchFeature + +from starVLA.model.modules.action_model.flow_matching_head.action_encoder import ( + SinusoidalPositionalEncoding, + swish, +) +from starVLA.model.modules.action_model.time_aware_action_head import TimeAwareActionHead, TimeAwareActionHead_Config + +# TODO try to meger DiT Modules with follow_match_head, they are just the same arch, but diff loss, use diffusers package will be simple + + +class CategorySpecificLinear(nn.Module): + + def __init__(self, num_categories, input_dim, hidden_dim): + super().__init__() + self.num_categories = num_categories + # For each category, we have separate weights and biases. + self.W = nn.Parameter(0.02 * torch.randn(num_categories, input_dim, hidden_dim)) + self.b = nn.Parameter(torch.zeros(num_categories, hidden_dim)) + + def forward(self, x, cat_ids): + selected_W = self.W[cat_ids] + selected_b = self.b[cat_ids] + # import ipdb; ipdb.set_trace() + return torch.bmm(x, selected_W) + selected_b.unsqueeze(1) + + +class CategorySpecificMLP(nn.Module): + + def __init__(self, num_categories, input_dim, hidden_dim, output_dim): + super().__init__() + self.num_categories = num_categories + self.layer1 = CategorySpecificLinear(num_categories, input_dim, hidden_dim) + self.layer2 = CategorySpecificLinear(num_categories, hidden_dim, output_dim) + + def forward(self, x, cat_ids): + hidden = F.relu(self.layer1(x, cat_ids)) + return self.layer2(hidden, cat_ids) + + +class MLP(nn.Module): + + def __init__(self, input_dim, hidden_dim, output_dim): + super().__init__() + self.layer1 = nn.Linear(input_dim, hidden_dim) + self.layer2 = nn.Linear(hidden_dim, output_dim) + + def forward(self, x): + return self.layer2(F.relu(self.layer1(x))) + + +class ActionEncoder(nn.Module): + + def __init__(self, action_dim, hidden_size): + super().__init__() + self.hidden_size = hidden_size + self.action_dim = action_dim + self.layer1 = nn.Linear(action_dim, hidden_size) + self.layer2 = nn.Linear(2 * hidden_size, hidden_size) + self.layer3 = nn.Linear(hidden_size, hidden_size) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps): + # print('################# ActionEncoder.forward-1') + B, T, _ = actions.shape + + # print(timesteps.shape) # torch.Size([32]) + if timesteps.dim() == 1 and timesteps.shape[0] == B: + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError("Expected `timesteps` to have shape (B,) so we can replicate across T.") + # print(timesteps.shape) # torch.Size([32, 16]) + tau_emb = self.pos_encoding(timesteps).to(dtype=actions.dtype) + # print(tau_emb.shape) # torch.Size([32, 16, 768]) + + # print(actions.shape) # torch.Size([32, 16, 32]) + a_emb = self.layer1(actions) + # print(a_emb.shape) # torch.Size([32, 16, 768]) + + x = torch.cat([a_emb, tau_emb], dim=-1) + # print(x.shape) # torch.Size([32, 16, 1536]) + x = swish(self.layer2(x)) + # print(x.shape) # torch.Size([32, 16, 768]) + x = self.layer3(x) + # print(x.shape) # torch.Size([32, 16, 768]) + # print('################# ActionEncoder.forward-2') + return x + + +class MultiEmbodimentActionEncoder(nn.Module): + + def __init__(self, action_dim, hidden_size, num_embodiments): + super().__init__() + self.hidden_size = hidden_size + self.num_embodiments = num_embodiments + + # W1: R^{w x d}, W2: R^{w x 2w}, W3: R^{w x w} + self.W1 = CategorySpecificLinear(num_embodiments, action_dim, hidden_size) # (d -> w) + self.W2 = CategorySpecificLinear(num_embodiments, 2 * hidden_size, hidden_size) # (2w -> w) + self.W3 = CategorySpecificLinear(num_embodiments, hidden_size, hidden_size) # (w -> w) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps, cat_ids): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + cat_ids: shape (B,) + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError("Expected `timesteps` to have shape (B,) so we can replicate across T.") + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.W1(actions, cat_ids) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then W2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.W2(x, cat_ids)) + + # 5) Finally W3 => (B, T, w) + x = self.W3(x, cat_ids) + return x + + +@dataclass +class FlowmatchingActionHeadConfig(PretrainedConfig): + """NOTE: N1.5 uses XEmbFlowmatchingPolicyHeadConfig as action head""" + + add_pos_embed: bool = field(default=True, metadata={"help": "Whether to add positional embedding"}) + diffusion_model_cfg: dict = field(default=None, metadata={"help": "Diffusion model configuration."}) + input_embedding_dim: int = field(default=1536, metadata={"help": "Input embedding channel dimension."}) + + hidden_size: int = field(default=1024, metadata={"help": "Input embedding dimension."}) + max_seq_len: int = field(default=1024, metadata={"help": "Maxium Sequence Length"}) + action_dim: int = field(default=None, metadata={"help": "Action dimension."}) + action_horizon: int = field(default=None, metadata={"help": "Action horizon."}) + noise_beta_alpha: float = field(default=1.5, metadata={"help": ""}) + noise_beta_beta: float = field(default=1.0, metadata={"help": ""}) + noise_s: float = field(default=0.999, metadata={"help": "Flow matching noise Beta distribution s."}) + num_timestep_buckets: int = field(default=1000, metadata={"help": "Number of timestep discretization buckets."}) + num_inference_timesteps: int = field( + default=None, + metadata={"help": "Number of inference steps for noise diffusion."}, + ) + max_num_embodiments: int = field(default=32, metadata={"help": "Number of embodiments."}) + tune_projector: bool = field(default=True, metadata={"help": "Whether to tune the projector."}) + tune_diffusion_model: bool = field(default=True, metadata={"help": "Whether to tune the diffusion model."}) + load_pretrained_det_decode_layer_path: str = field(default=None, + metadata={"help": "Path to pretrained detection model."}) + detection_coeff: float = field(default=1.0, metadata={"help": "Detection coefficient."}) + + freeze_decode_layer: bool = field(default=False) + expand_batch: int = field(default=None) + use_vlln: bool = field(default=True) + + vl_self_attention_cfg: dict = field(default=None) + num_target_vision_tokens: int = field(default=64, metadata={"help": "Number of target vision tokens."}) + use_category_specific: bool = field(default=False, + metadata={"help": "Whether to use category-specific encoders and decoders."}) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + + +DiTConfig = { + "DiT-B": { + "input_embedding_dim": 768, + "attention_head_dim": 64, + "num_attention_heads": 12 + }, + "DiT-L": { + "input_embedding_dim": 1536, + "attention_head_dim": 48, + "num_attention_heads": 32 + }, +} + + +# 训练时 +# future_image支路,self.backbone.transformer() +# 训练时 +# action支路,self.backbone.build_inputs、self.backbone.forward()、self.action_model.forward() +# 推理时 +# future_image支路,self.backbone.generate() +# 推理时 +# action支路,self.backbone.build_inputs()、self.backbone.forward()、self.action_model.predict_action() +class FlowmatchingActionHead(nn.Module): + """Original FlowmatchingActionHead using standard MLP encoders and decoders.""" + + def __init__(self, full_config): + # print('################# FlowmatchingActionHead-1') + super().__init__() + config = full_config.framework.action_model + self.hidden_size = config.hidden_size + self.full_config = full_config + action_model_type = config.action_model_type + action_model_cfg = DiTConfig[action_model_type] + self.input_embedding_dim = action_model_cfg["input_embedding_dim"] + diffusion_model_cfg = config.diffusion_model_cfg + diffusion_model_cfg = {**action_model_cfg, **diffusion_model_cfg} + vl_input_dim = diffusion_model_cfg.get('cross_attention_dim', 2048) + output_dim=diffusion_model_cfg['output_dim'] + # print(self.hidden_size) # 1024 + # print(self.input_embedding_dim) # 768 + # print(vl_input_dim) # 2048 + # print(output_dim) # 1024 + + action_cfg = TimeAwareActionHead_Config( + action_dim=self.input_embedding_dim, + vl_input_dim=vl_input_dim, + output_dim=output_dim, + num_target_vision_tokens=config.num_target_vision_tokens, + ) + self.model = TimeAwareActionHead(config=action_cfg) + # print(type(self.model)) # + + self.action_dim = config.action_dim + self.action_horizon = config.future_action_window_size + 1 + self.num_inference_timesteps = config.num_inference_timesteps + # print(self.action_dim) # 32 + # print(self.action_horizon) # 16 + # print(self.num_inference_timesteps) # 20 + + self.state_encoder = MLP( + input_dim=config.state_dim, + hidden_dim=self.hidden_size, + output_dim=self.input_embedding_dim, + ) if config.state_dim else None + # print(config.state_dim) # 64 + # print(self.hidden_size) # 1024 + # print(self.input_embedding_dim) # 768 + + self.action_encoder = ActionEncoder( + action_dim=config.action_dim, + hidden_size=self.input_embedding_dim, + ) + # print(config.action_dim) # 32 + # print(self.input_embedding_dim) # 768 + + self.action_decoder = MLP( + input_dim=self.model.config.output_dim, + hidden_dim=self.hidden_size, + output_dim=self.action_dim, + ) + # print(self.model.config.output_dim) # 1024 + # print(self.hidden_size) # 1024 + # print(self.action_dim) # 32 + + self.future_tokens = nn.Embedding(config.num_target_vision_tokens, self.input_embedding_dim) + nn.init.normal_(self.future_tokens.weight, mean=0.0, std=0.02) + # print(config.num_target_vision_tokens) # 64 + # print(self.input_embedding_dim) # 768 + + if config.add_pos_embed: + self.position_embedding = nn.Embedding(config.max_seq_len, self.input_embedding_dim) + nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) + # print(config.add_pos_embed) # True + # print(config.max_seq_len) # 1024 + # print(self.input_embedding_dim) # 768 + + self.beta_dist = Beta(config.noise_beta_alpha, config.noise_beta_beta) + self.num_timestep_buckets = config.num_timestep_buckets + self.config = config + # print(self.num_timestep_buckets) # 1000 + # print('################# FlowmatchingActionHead-2') + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return (self.config.noise_s - sample) / self.config.noise_s + + def prepare_input(self, batch: dict) -> BatchFeature: + return BatchFeature(data=batch) + + def forward(self, + vl_embs: torch.Tensor, actions: torch.Tensor, state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, encoder_attention_mask=None, action_mask=None, use_vjepa2ac=False, repeated_diffusion_steps=-1 + ): + # print('################# FlowmatchingActionHead.forward-1') + device = vl_embs.device + + # 1. 对action加噪得到noisy_trajectory,并生成降噪目标velocity + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + # print(noise.shape) # torch.Size([32, 16, 32]) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + # print(t.shape) # torch.Size([32]) + t = t[:, None, None] + # print(t.shape) # torch.Size([32, 1, 1]) + noisy_trajectory = (1 - t) * noise + t * actions + # print(noisy_trajectory.shape) # torch.Size([32, 16, 32]) + velocity = actions - noise + # print(velocity.shape) # torch.Size([32, 16, 32]) + + # 2. 编码state + state_features = self.state_encoder(state) if state is not None else None + # print(state.shape) # torch.Size([32, 1, 64]) + # print(state_features.shape) # torch.Size([32, 1, 768]) + + # 3. 将t离散化并,对noised_action做时间编码 + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + # print(self.num_timestep_buckets) # 1000 + # print(t_discretized.shape) # torch.Size([32]) + action_features = self.action_encoder(noisy_trajectory, t_discretized) + # print(action_features.shape) # torch.Size([32, 16, 768]) + + # 4. 位置编码 + # print(self.config.add_pos_embed) # True + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # 5. 将state-token、future-tokens和noised-action-tokens拼接得到sa-tokens + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(action_features.shape[0], -1, -1) + # print(self.future_tokens.weight.shape) # torch.Size([64, 768]) + # print(future_tokens.shape) # torch.Size([32, 64, 768]) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + # print(sa_embs.shape) # torch.Size([32, 81, 768]) + + # 6. PerceiverHead前向传播 + # (1) Perceiver-Head和DiT-Head的区别在于前者是cross_attn+ffn,而后者兼具self_attn+cross_attn+ffn, + # (2) 此外,与MoT使用逐层的vl-tokens作为qkv,然后和action-tokens拼接一起计算attn不同, + # Perceiver首先分别对sa-tokens和vl-tokens做AdaLN,然后将sa-tokens作为q、将concat(sa-tokens,vl-tokens)作为kv, + # 这里的sa-tokens就是state-tokens、future-tokens和action-tokens拼接起来的, + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=t_discretized, + ) + # print(type(self.model)) # + # print(sa_embs.shape) # torch.Size([32, 81, 768]) + # print(vl_embs.shape) # torch.Size([32, 196, 2048]) + # print(model_output.shape) # torch.Size([32, 81, 1024]) + pred = self.action_decoder(model_output[:, -actions.shape[1]:, :]) + # print(pred.shape) # torch.Size([32, 16, 32]) + pred_actions = pred + # print(pred_actions.shape) # torch.Size([32, 16, 32]) + + # 7. 计算action_loss + # 若提供了action_mask则只在有效动作维度上计算loss、若未提供action_mask则在所有动作维度上计算loss; + # print(action_mask.shape) # torch.Size([32, 16, 32]) + if action_mask is not None: + if isinstance(action_mask, np.ndarray): + action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + else: + action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + + loss = ((pred_actions - velocity)**2) * action_mask + loss = loss.sum() / action_mask.sum() + else: + # Fallback to mean loss if no mask is provided + loss = ((pred_actions - velocity)**2).mean() + + # 8. 分离target_emb + # 其中判断条件为,列表中的任意两个tensor_a,b之间差距小于阈值:|a-b|≤atol+rtol*max(|a|,|b|) + target_emb = model_output[:, 1:1+self.future_tokens.weight.shape[0], :] + # print(target_emb.shape) # torch.Size([32, 64, 1024]) + target_emb_groups = target_emb.chunk(repeated_diffusion_steps, dim=0) + all_equal = all(torch.allclose(target_emb_groups[0], target_emb_groups[i], atol=1e-5, rtol=0) for i in range(1, repeated_diffusion_steps)) + # print('') + # print(target_emb_groups[0][0, 0, :5]) + # print(target_emb_groups[1][0, 0, :5]) + # print(target_emb_groups[2][0, 0, :5]) + # print(target_emb_groups[3][0, 0, :5]) + assert all_equal, "/mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/model/modules/action_model/PerceiverHead.py is ERROR" + target_emb_stacked = torch.stack(target_emb_groups, dim=0) # 形状: (N, *) + target_emb = torch.mean(target_emb_stacked, dim=0) + # print(target_emb[0, 0, :5]) + # print(target_emb.shape) # torch.Size([8, 64, 1024]) + + # print('################# FlowmatchingActionHead.forward-2') + if use_vjepa2ac: + return loss, target_emb + else: + return loss + + @torch.no_grad() + def predict_action(self, vl_embs: torch.Tensor, state: torch.Tensor = None, embodiment_tag: torch.Tensor = None) -> torch.Tensor: + # print('################# FlowmatchingActionHead.predict_action-1') + + # 1. 生成随机噪声 + batch_size = vl_embs.shape[0] + device = vl_embs.device + actions = torch.randn( + size=(batch_size, self.config.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + ) + # print(self.config.action_horizon) # 16 + # print(self.config.action_dim) # 32 + # print(vl_embs.shape) # torch.Size([8, 196, 2048]) + # print(actions.shape) # torch.Size([8, 16, 32]) + + # 2. 编码state + state_features = self.state_encoder(state) if state is not None else None + # print(state.shape) # torch.Size([8, 1, 64]) + # print(state_features.shape) # torch.Size([8, 1, 768]) + + # 3. 迭代降噪 + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + # print(self.num_inference_timesteps) # 20 + # print(self.num_timestep_buckets) # 1000 + for t in range(num_steps): + # print(t) # 0 1 2 ... 19 + t_cont = t / float(num_steps) + # print(t_cont) # 0.0 0.05 0.1 ... 0.95 + t_discretized = int(t_cont * self.num_timestep_buckets) + # print(t_discretized) # 0 50 100 ... 950 + + # 3.1 将t离散化并,对noised_action做时间编码 + timesteps_tensor = torch.full(size=(batch_size,), fill_value=t_discretized, device=device) + # print(timesteps_tensor.shape) # torch.Size([8]) + # print(actions.shape) # torch.Size([8, 16, 32]) + action_features = self.action_encoder(actions, timesteps_tensor) + # print(action_features.shape) # torch.Size([8, 16, 768]) + + # 3.2 位置编码 + # print(self.config.add_pos_embed) # True + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # 3.3 将state-token、future-tokens和noised-action-tokens拼接得到sa-tokens + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # 3.4 PerceiverHead前向传播 + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=timesteps_tensor, + ) + # print(model_output.shape) # torch.Size([8, 49, 1024]) + pred = self.action_decoder(model_output) + # print(pred.shape) # torch.Size([8, 49, 32]) + # print(self.action_horizon) # 16 + pred_velocity = pred[:, -self.action_horizon:] + # print(pred_velocity.shape) # torch.Size([8, 16, 32]) + + # 3.5 降噪 + actions = actions + dt * pred_velocity + # print(actions.shape) # torch.Size([8, 16, 32]) + + # print('################# FlowmatchingActionHead.predict_action-2') + return actions + + @property + def device(self): + return next(iter(self.parameters())).device + + @property + def dtype(self): + return next(iter(self.parameters())).dtype + + +class CategorySpecificFlowmatchingActionHead(nn.Module): + """Category-specific FlowmatchingActionHead using category-specific encoders and decoders.""" + + def __init__( + self, + full_config, + ): + super().__init__() + config = full_config.framework.action_model + self.hidden_size = config.hidden_size # @JinhuiYE + self.full_config = full_config + action_model_type = config.action_model_type + action_model_cfg = DiTConfig[action_model_type] + + self.input_embedding_dim = action_model_cfg["input_embedding_dim"] + diffusion_model_cfg = config.diffusion_model_cfg + diffusion_model_cfg = {**action_model_cfg, **diffusion_model_cfg} + vl_input_dim = diffusion_model_cfg.get('cross_attention_dim', 2048) + action_cfg = TimeAwareActionHead_Config(action_dim=self.input_embedding_dim, vl_input_dim=vl_input_dim) + + self.model = TimeAwareActionHead(config=action_cfg) + self.action_dim = config.action_dim + self.action_horizon = config.future_action_window_size + 1 + self.num_inference_timesteps = config.num_inference_timesteps + + self.state_encoder = CategorySpecificMLP( + num_categories=config.max_num_embodiments, + input_dim=config.state_dim, + hidden_dim=self.hidden_size, + output_dim=self.input_embedding_dim, + ) if config.state_dim else None + + self.action_encoder = MultiEmbodimentActionEncoder( + action_dim=config.action_dim, + hidden_size=self.input_embedding_dim, + num_embodiments=config.max_num_embodiments, + ) + self.action_decoder = CategorySpecificMLP( + num_categories=config.max_num_embodiments, + input_dim=self.model.config.output_dim, + hidden_dim=self.hidden_size, + output_dim=self.action_dim, + ) + self.future_tokens = nn.Embedding(config.num_target_vision_tokens, self.input_embedding_dim) + nn.init.normal_(self.future_tokens.weight, mean=0.0, std=0.02) + + if config.add_pos_embed: + self.position_embedding = nn.Embedding(config.max_seq_len, self.input_embedding_dim) + nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) + + self.beta_dist = Beta(config.noise_beta_alpha, config.noise_beta_beta) + self.num_timestep_buckets = config.num_timestep_buckets + self.config = config + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return (self.config.noise_s - sample) / self.config.noise_s + + def prepare_input(self, batch: dict) -> BatchFeature: + return BatchFeature(data=batch) + + def forward(self, + vl_embs: torch.Tensor, + actions: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, + encoder_attention_mask=None, + action_mask=None): + """ + vl_embs: shape (B, seq_length, feature_dim) + actions: shape (B, future_action_window_size, D_action) + embodiment_tag: shape (B,) - required for category-specific operations + action_mask: shape (B, future_action_window_size, D_action) - optional mask for valid action dimensions + """ + device = vl_embs.device + + # Embed noised action trajectory. + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] # shape (B,1,1) for broadcast + + noisy_trajectory = (1 - t) * noise + t * actions + velocity = actions - noise + + # Convert (continuous) t -> discrete if needed + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized, embodiment_tag) + + # embed state + state_features = self.state_encoder(state, embodiment_tag) if state is not None else None + + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Join VLM features with state and action embedding along sequence dimension. + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=t_discretized, + ) + pred = self.action_decoder(model_output, embodiment_tag) + pred_actions = pred[:, -actions.shape[1]:] + + # Use action_mask if provided, otherwise compute mean loss over all dimensions + if action_mask is not None: + # Ensure action_mask is on the same device and has the same dtype as pred_actions + if isinstance(action_mask, np.ndarray): + action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + else: + action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + + # Compute masked loss: only consider valid action dimensions + loss = ((pred_actions - velocity)**2) * action_mask + loss = loss.sum() / action_mask.sum() + else: + # Fallback to mean loss if no mask is provided + loss = ((pred_actions - velocity)**2).mean() + return loss + + @torch.no_grad() + def predict_action(self, + vl_embs: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = 24) -> torch.Tensor: + # Set initial actions as the sampled noise. + batch_size = vl_embs.shape[0] + device = vl_embs.device + actions = torch.randn( + size=(batch_size, self.config.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + ) + assert embodiment_tag is not None, "Embodiment tag is required for prediction" + embodiment_tag = torch.tensor(embodiment_tag, device=device, dtype=torch.long) # + # 如果是标量,扩展到 batch_size + if embodiment_tag.dim() == 0: + embodiment_tag = embodiment_tag.repeat(batch_size) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state, embodiment_tag) if state is not None else None + + # Run denoising steps. + for t in range(num_steps): + t_cont = t / float(num_steps) # e.g. goes 0, 1/N, 2/N, ... + t_discretized = int(t_cont * self.num_timestep_buckets) + + # Embed noised action trajectory. + timesteps_tensor = torch.full(size=(batch_size,), fill_value=t_discretized, device=device) + action_features = self.action_encoder(actions, timesteps_tensor, embodiment_tag) + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # Join vision, language, state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Run model forward. + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=timesteps_tensor, + ) + pred = self.action_decoder(model_output, embodiment_tag) + + pred_velocity = pred[:, -self.action_horizon:] + + # Update actions using euler integration. + actions = actions + dt * pred_velocity + return actions + + @property + def device(self): + return next(iter(self.parameters())).device + + @property + def dtype(self): + return next(iter(self.parameters())).dtype + + +def get_action_model(config=None): + """ + Factory: build FlowmatchingActionHead from global framework config. + + Args: + config: Global config (expects config.framework.action_model namespace). + + Returns: + FlowmatchingActionHead or CategorySpecificFlowmatchingActionHead: Initialized action model. + """ + action_model_config = config.framework.action_model + use_category_specific = getattr(action_model_config, 'use_category_specific', False) + + print('use_category_specific', use_category_specific) + if use_category_specific: + return CategorySpecificFlowmatchingActionHead(full_config=config) + else: + return FlowmatchingActionHead(full_config=config) + + +if __name__ == "__main__": + # TODO make each backbone.py can be debug independently + + pass diff --git a/starVLA/model/modules/action_model/PerceiverHead_original.py b/starVLA/model/modules/action_model/PerceiverHead_original.py new file mode 100644 index 0000000000000000000000000000000000000000..282d9b5aa6e8b448588740da6a3db119a022bc04 --- /dev/null +++ b/starVLA/model/modules/action_model/PerceiverHead_original.py @@ -0,0 +1,642 @@ +# Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved. +# Modified by [Junqiu YU/ Fudan University] in [2025]. +# Modification: [rm and add some connect adapter to match with starVLA, e.g., "rm "]. +# Action repeat is inspired by CogACT + +from dataclasses import dataclass, field + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.distributions import Beta +from transformers import PretrainedConfig +from transformers.feature_extraction_utils import BatchFeature + +from starVLA.model.modules.action_model.flow_matching_head.action_encoder import ( + SinusoidalPositionalEncoding, + swish, +) +from starVLA.model.modules.action_model.time_aware_action_head_original import TimeAwareActionHead, TimeAwareActionHead_Config + + +class VLSelfAttention(nn.Module): + def __init__(self, hidden_size, num_attention_heads=32, dropout=0.2, num_layers=4): + super().__init__() + self.num_layers = num_layers + self.layers = nn.ModuleList([ + nn.TransformerEncoderLayer( + d_model=hidden_size, + nhead=num_attention_heads, + dim_feedforward=hidden_size * 4, + dropout=dropout, + activation="gelu", + batch_first=True, + norm_first=True + ) + for _ in range(num_layers) + ]) + self.dropout = nn.Dropout(dropout) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return self.dropout(x) + + + + +# TODO try to meger DiT Modules with follow_match_head, they are just the same arch, but diff loss, use diffusers package will be simple + + +class CategorySpecificLinear(nn.Module): + + def __init__(self, num_categories, input_dim, hidden_dim): + super().__init__() + self.num_categories = num_categories + # For each category, we have separate weights and biases. + self.W = nn.Parameter(0.02 * torch.randn(num_categories, input_dim, hidden_dim)) + self.b = nn.Parameter(torch.zeros(num_categories, hidden_dim)) + + def forward(self, x, cat_ids): + selected_W = self.W[cat_ids] + selected_b = self.b[cat_ids] + # import ipdb; ipdb.set_trace() + return torch.bmm(x, selected_W) + selected_b.unsqueeze(1) + + +class CategorySpecificMLP(nn.Module): + + def __init__(self, num_categories, input_dim, hidden_dim, output_dim): + super().__init__() + self.num_categories = num_categories + self.layer1 = CategorySpecificLinear(num_categories, input_dim, hidden_dim) + self.layer2 = CategorySpecificLinear(num_categories, hidden_dim, output_dim) + + def forward(self, x, cat_ids): + hidden = F.relu(self.layer1(x, cat_ids)) + return self.layer2(hidden, cat_ids) + + +class MLP(nn.Module): + + def __init__(self, input_dim, hidden_dim, output_dim): + super().__init__() + self.layer1 = nn.Linear(input_dim, hidden_dim) + self.layer2 = nn.Linear(hidden_dim, output_dim) + + def forward(self, x): + return self.layer2(F.relu(self.layer1(x))) + + +class ActionEncoder(nn.Module): + + def __init__(self, action_dim, hidden_size): + super().__init__() + self.hidden_size = hidden_size + self.action_dim = action_dim + self.layer1 = nn.Linear(action_dim, hidden_size) + self.layer2 = nn.Linear(2 * hidden_size, hidden_size) + self.layer3 = nn.Linear(hidden_size, hidden_size) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError("Expected `timesteps` to have shape (B,) so we can replicate across T.") + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.layer1(actions) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then layer2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.layer2(x)) + + # 5) Finally W3 => (B, T, w) + x = self.layer3(x) + return x + + +class MultiEmbodimentActionEncoder(nn.Module): + + def __init__(self, action_dim, hidden_size, num_embodiments): + super().__init__() + self.hidden_size = hidden_size + self.num_embodiments = num_embodiments + + # W1: R^{w x d}, W2: R^{w x 2w}, W3: R^{w x w} + self.W1 = CategorySpecificLinear(num_embodiments, action_dim, hidden_size) # (d -> w) + self.W2 = CategorySpecificLinear(num_embodiments, 2 * hidden_size, hidden_size) # (2w -> w) + self.W3 = CategorySpecificLinear(num_embodiments, hidden_size, hidden_size) # (w -> w) + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps, cat_ids): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + cat_ids: shape (B,) + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError("Expected `timesteps` to have shape (B,) so we can replicate across T.") + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.W1(actions, cat_ids) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then W2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.W2(x, cat_ids)) + + # 5) Finally W3 => (B, T, w) + x = self.W3(x, cat_ids) + return x + + +@dataclass +class FlowmatchingActionHeadConfig(PretrainedConfig): + """NOTE: N1.5 uses XEmbFlowmatchingPolicyHeadConfig as action head""" + + add_pos_embed: bool = field(default=True, metadata={"help": "Whether to add positional embedding"}) + diffusion_model_cfg: dict = field(default=None, metadata={"help": "Diffusion model configuration."}) + input_embedding_dim: int = field(default=1536, metadata={"help": "Input embedding channel dimension."}) + + hidden_size: int = field(default=1024, metadata={"help": "Input embedding dimension."}) + max_seq_len: int = field(default=1024, metadata={"help": "Maxium Sequence Length"}) + action_dim: int = field(default=None, metadata={"help": "Action dimension."}) + action_horizon: int = field(default=None, metadata={"help": "Action horizon."}) + noise_beta_alpha: float = field(default=1.5, metadata={"help": ""}) + noise_beta_beta: float = field(default=1.0, metadata={"help": ""}) + noise_s: float = field(default=0.999, metadata={"help": "Flow matching noise Beta distribution s."}) + num_timestep_buckets: int = field(default=1000, metadata={"help": "Number of timestep discretization buckets."}) + num_inference_timesteps: int = field( + default=None, + metadata={"help": "Number of inference steps for noise diffusion."}, + ) + max_num_embodiments: int = field(default=32, metadata={"help": "Number of embodiments."}) + tune_projector: bool = field(default=True, metadata={"help": "Whether to tune the projector."}) + tune_diffusion_model: bool = field(default=True, metadata={"help": "Whether to tune the diffusion model."}) + load_pretrained_det_decode_layer_path: str = field(default=None, + metadata={"help": "Path to pretrained detection model."}) + detection_coeff: float = field(default=1.0, metadata={"help": "Detection coefficient."}) + + freeze_decode_layer: bool = field(default=False) + expand_batch: int = field(default=None) + use_vlln: bool = field(default=True) + + vl_self_attention_cfg: dict = field(default=None) + num_target_vision_tokens: int = field(default=32, metadata={"help": "Number of target vision tokens."}) + use_category_specific: bool = field(default=False, + metadata={"help": "Whether to use category-specific encoders and decoders."}) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + + +DiTConfig = { + "DiT-B": { + "input_embedding_dim": 768, + "attention_head_dim": 64, + "num_attention_heads": 12 + }, + "DiT-L": { + "input_embedding_dim": 1536, + "attention_head_dim": 48, + "num_attention_heads": 32 + }, +} + + +class FlowmatchingActionHead(nn.Module): + """Original FlowmatchingActionHead using standard MLP encoders and decoders.""" + + def __init__( + self, + full_config, + ): + super().__init__() + config = full_config.framework.action_model + self.hidden_size = config.hidden_size # @JinhuiYE + self.full_config = full_config + action_model_type = config.action_model_type + action_model_cfg = DiTConfig[action_model_type] + + self.input_embedding_dim = action_model_cfg["input_embedding_dim"] + diffusion_model_cfg = config.diffusion_model_cfg + diffusion_model_cfg = {**action_model_cfg, **diffusion_model_cfg} + vl_input_dim = diffusion_model_cfg.get('cross_attention_dim', 2048) + action_cfg = TimeAwareActionHead_Config(action_dim=self.input_embedding_dim, vl_input_dim=vl_input_dim) + + self.model = TimeAwareActionHead(config=action_cfg) + self.action_dim = config.action_dim + self.action_horizon = config.future_action_window_size + 1 + # self.num_inference_timesteps = config.num_inference_timesteps + self.num_inference_timesteps = 20 + + self.state_encoder = MLP( + input_dim=config.state_dim, + hidden_dim=self.hidden_size, + output_dim=self.input_embedding_dim, + ) if config.state_dim else None + + self.action_encoder = ActionEncoder( + action_dim=config.action_dim, + hidden_size=self.input_embedding_dim, + ) + self.action_decoder = MLP( + input_dim=self.model.config.output_dim, + hidden_dim=self.hidden_size, + output_dim=self.action_dim, + ) + self.future_tokens = nn.Embedding(config.num_target_vision_tokens, self.input_embedding_dim) + nn.init.normal_(self.future_tokens.weight, mean=0.0, std=0.02) + + if config.add_pos_embed: + self.position_embedding = nn.Embedding(config.max_seq_len, self.input_embedding_dim) + nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) + + self.beta_dist = Beta(config.noise_beta_alpha, config.noise_beta_beta) + self.num_timestep_buckets = config.num_timestep_buckets + self.config = config + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return (self.config.noise_s - sample) / self.config.noise_s + + def prepare_input(self, batch: dict) -> BatchFeature: + return BatchFeature(data=batch) + + def forward(self, + vl_embs: torch.Tensor, + actions: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, + encoder_attention_mask=None, + action_mask=None): + """ + vl_embs: shape (B, seq_length, feature_dim) + actions: shape (B, future_action_window_size, D_action) + embodiment_tag: shape (B,) - not used in this version + action_mask: shape (B, future_action_window_size, D_action) - optional mask for valid action dimensions + """ + device = vl_embs.device + + # Embed noised action trajectory. + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] # shape (B,1,1) for broadcast + + noisy_trajectory = (1 - t) * noise + t * actions + velocity = actions - noise + + # Convert (continuous) t -> discrete if needed + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized) + + # embed state + state_features = self.state_encoder(state) if state is not None else None + + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Join VLM features with state and action embedding along sequence dimension. + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=t_discretized, + ) + pred = self.action_decoder(model_output) + pred_actions = pred[:, -actions.shape[1]:] + + # Use action_mask if provided, otherwise compute mean loss over all dimensions + if action_mask is not None: + # Ensure action_mask is on the same device and has the same dtype as pred_actions + if isinstance(action_mask, np.ndarray): + action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + else: + action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + + # Compute masked loss: only consider valid action dimensions + loss = ((pred_actions - velocity)**2) * action_mask + loss = loss.sum() / action_mask.sum() + else: + # Fallback to mean loss if no mask is provided + loss = ((pred_actions - velocity)**2).mean() + return loss + + @torch.no_grad() + def predict_action(self, + vl_embs: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None) -> torch.Tensor: + # Set initial actions as the sampled noise. + batch_size = vl_embs.shape[0] + manual_seed = 42 + generator = torch.Generator(device=vl_embs.device) + generator.manual_seed(manual_seed) + device = vl_embs.device + actions = torch.randn( + size=(batch_size, self.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + generator=generator, + ) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state) if state is not None else None + + # Run denoising steps. + for t in range(num_steps): + t_cont = t / float(num_steps) # e.g. goes 0, 1/N, 2/N, ... + t_discretized = int(t_cont * self.num_timestep_buckets) + + # Embed noised action trajectory. + timesteps_tensor = torch.full(size=(batch_size,), fill_value=t_discretized, device=device) + action_features = self.action_encoder(actions, timesteps_tensor) + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # Join vision, language, state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Run model forward. + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=timesteps_tensor, + ) + pred = self.action_decoder(model_output) + + pred_velocity = pred[:, -self.action_horizon:] + + # Update actions using euler integration. + actions = actions + dt * pred_velocity + return actions + + @property + def device(self): + return next(iter(self.parameters())).device + + @property + def dtype(self): + return next(iter(self.parameters())).dtype + + +class CategorySpecificFlowmatchingActionHead(nn.Module): + """Category-specific FlowmatchingActionHead using category-specific encoders and decoders.""" + + def __init__( + self, + full_config, + ): + super().__init__() + config = full_config.framework.action_model + self.hidden_size = config.hidden_size # @JinhuiYE + self.full_config = full_config + action_model_type = config.action_model_type + action_model_cfg = DiTConfig[action_model_type] + + self.input_embedding_dim = action_model_cfg["input_embedding_dim"] + diffusion_model_cfg = config.diffusion_model_cfg + diffusion_model_cfg = {**action_model_cfg, **diffusion_model_cfg} + vl_input_dim = diffusion_model_cfg.get('cross_attention_dim', 2048) + action_cfg = TimeAwareActionHead_Config(action_dim=self.input_embedding_dim, vl_input_dim=vl_input_dim) + + self.model = TimeAwareActionHead(config=action_cfg) + self.action_dim = config.action_dim + self.action_horizon = config.future_action_window_size + 1 + self.num_inference_timesteps = config.num_inference_timesteps + + self.state_encoder = CategorySpecificMLP( + num_categories=config.max_num_embodiments, + input_dim=config.state_dim, + hidden_dim=self.hidden_size, + output_dim=self.input_embedding_dim, + ) if config.state_dim else None + + self.action_encoder = MultiEmbodimentActionEncoder( + action_dim=config.action_dim, + hidden_size=self.input_embedding_dim, + num_embodiments=config.max_num_embodiments, + ) + self.action_decoder = CategorySpecificMLP( + num_categories=config.max_num_embodiments, + input_dim=self.model.config.output_dim, + hidden_dim=self.hidden_size, + output_dim=self.action_dim, + ) + self.future_tokens = nn.Embedding(config.num_target_vision_tokens, self.input_embedding_dim) + nn.init.normal_(self.future_tokens.weight, mean=0.0, std=0.02) + + if config.add_pos_embed: + self.position_embedding = nn.Embedding(config.max_seq_len, self.input_embedding_dim) + nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) + + self.beta_dist = Beta(config.noise_beta_alpha, config.noise_beta_beta) + self.num_timestep_buckets = config.num_timestep_buckets + self.config = config + + def sample_time(self, batch_size, device, dtype): + sample = self.beta_dist.sample([batch_size]).to(device, dtype=dtype) + return (self.config.noise_s - sample) / self.config.noise_s + + def prepare_input(self, batch: dict) -> BatchFeature: + return BatchFeature(data=batch) + + def forward(self, + vl_embs: torch.Tensor, + actions: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = None, + encoder_attention_mask=None, + action_mask=None): + """ + vl_embs: shape (B, seq_length, feature_dim) + actions: shape (B, future_action_window_size, D_action) + embodiment_tag: shape (B,) - required for category-specific operations + action_mask: shape (B, future_action_window_size, D_action) - optional mask for valid action dimensions + """ + device = vl_embs.device + + # Embed noised action trajectory. + noise = torch.randn(actions.shape, device=actions.device, dtype=actions.dtype) + t = self.sample_time(actions.shape[0], device=actions.device, dtype=actions.dtype) + t = t[:, None, None] # shape (B,1,1) for broadcast + + noisy_trajectory = (1 - t) * noise + t * actions + velocity = actions - noise + + # Convert (continuous) t -> discrete if needed + t_discretized = (t[:, 0, 0] * self.num_timestep_buckets).long() + action_features = self.action_encoder(noisy_trajectory, t_discretized, embodiment_tag) + + # embed state + state_features = self.state_encoder(state, embodiment_tag) if state is not None else None + + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Join VLM features with state and action embedding along sequence dimension. + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=t_discretized, + ) + pred = self.action_decoder(model_output, embodiment_tag) + pred_actions = pred[:, -actions.shape[1]:] + + # Use action_mask if provided, otherwise compute mean loss over all dimensions + if action_mask is not None: + # Ensure action_mask is on the same device and has the same dtype as pred_actions + if isinstance(action_mask, np.ndarray): + action_mask = torch.from_numpy(action_mask).to(device=pred_actions.device, dtype=pred_actions.dtype) + else: + action_mask = action_mask.to(device=pred_actions.device, dtype=pred_actions.dtype) + + # Compute masked loss: only consider valid action dimensions + loss = ((pred_actions - velocity)**2) * action_mask + loss = loss.sum() / action_mask.sum() + else: + # Fallback to mean loss if no mask is provided + loss = ((pred_actions - velocity)**2).mean() + return loss + + @torch.no_grad() + def predict_action(self, + vl_embs: torch.Tensor, + state: torch.Tensor = None, + embodiment_tag: torch.Tensor = 24) -> torch.Tensor: + # Set initial actions as the sampled noise. + batch_size = vl_embs.shape[0] + device = vl_embs.device + actions = torch.randn( + size=(batch_size, self.action_horizon, self.config.action_dim), + dtype=vl_embs.dtype, + device=device, + ) + assert embodiment_tag is not None, "Embodiment tag is required for prediction" + embodiment_tag = torch.tensor(embodiment_tag, device=device, dtype=torch.long) # + # 如果是标量,扩展到 batch_size + if embodiment_tag.dim() == 0: + embodiment_tag = embodiment_tag.repeat(batch_size) + + num_steps = self.num_inference_timesteps + dt = 1.0 / num_steps + + state_features = self.state_encoder(state, embodiment_tag) if state is not None else None + + # Run denoising steps. + for t in range(num_steps): + t_cont = t / float(num_steps) # e.g. goes 0, 1/N, 2/N, ... + t_discretized = int(t_cont * self.num_timestep_buckets) + + # Embed noised action trajectory. + timesteps_tensor = torch.full(size=(batch_size,), fill_value=t_discretized, device=device) + action_features = self.action_encoder(actions, timesteps_tensor, embodiment_tag) + # Maybe add position embedding. + if self.config.add_pos_embed: + pos_ids = torch.arange(action_features.shape[1], dtype=torch.long, device=device) + pos_embs = self.position_embedding(pos_ids).unsqueeze(0) + action_features = action_features + pos_embs + + # Join vision, language, state and action embedding along sequence dimension. + future_tokens = self.future_tokens.weight.unsqueeze(0).expand(vl_embs.shape[0], -1, -1) + sa_embs = torch.cat((state_features, future_tokens, action_features), dim=1) \ + if state_features is not None else torch.cat((future_tokens, action_features), dim=1) + + # Run model forward. + model_output = self.model( + latents=sa_embs, + visual_language_states=vl_embs, + timestep=timesteps_tensor, + ) + pred = self.action_decoder(model_output, embodiment_tag) + + pred_velocity = pred[:, -self.action_horizon:] + + # Update actions using euler integration. + actions = actions + dt * pred_velocity + return actions + + @property + def device(self): + return next(iter(self.parameters())).device + + @property + def dtype(self): + return next(iter(self.parameters())).dtype + + +def get_action_model(config=None): + """ + Factory: build FlowmatchingActionHead from global framework config. + + Args: + config: Global config (expects config.framework.action_model namespace). + + Returns: + FlowmatchingActionHead or CategorySpecificFlowmatchingActionHead: Initialized action model. + """ + action_model_config = config.framework.action_model + use_category_specific = getattr(action_model_config, 'use_category_specific', False) + + if use_category_specific: + return CategorySpecificFlowmatchingActionHead(full_config=config) + else: + return FlowmatchingActionHead(full_config=config) + + +if __name__ == "__main__": + # TODO make each backbone.py can be debug independently + + pass diff --git a/starVLA/model/modules/action_model/VLA_AdapterHeader.py b/starVLA/model/modules/action_model/VLA_AdapterHeader.py new file mode 100644 index 0000000000000000000000000000000000000000..b30c288549db550f35d7da71066fa872a9a0748c --- /dev/null +++ b/starVLA/model/modules/action_model/VLA_AdapterHeader.py @@ -0,0 +1,391 @@ +""" +action_heads.py + +Implementations of various action heads, which serve as alternatives to VLM sequential token prediction. +""" + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def learnable_random_perturbations(seq_len, dim, device, dtype): + random_perturbations = nn.Parameter(torch.zeros(seq_len, dim, device=device, dtype=dtype)) + nn.init.normal_(random_perturbations, mean=0.0, std=0.02) + return random_perturbations + + +class L1RegressionActionHead(nn.Module): + """Simple MLP-based action head that generates continuous actions via L1 regression.""" + def __init__( + self, + full_config, + ): + super().__init__() + self.config = full_config + + input_dim = full_config.framework.qwenvl.vl_hidden_dim + hidden_dim = full_config.framework.action_model.hidden_dim + action_dim = full_config.framework.action_model.action_dim + + self.action_query_num = full_config.framework.action_model.get("action_query_num", 64) + use_pro_version = full_config.framework.action_model.use_pro_version + + self.action_dim = action_dim + self.hidden_dim = hidden_dim + + self.num_actions_chunk = self.config.framework.action_model.num_actions_chunk + self.model = MLPResNet( + num_blocks=24, + input_dim=input_dim*action_dim, + hidden_dim=hidden_dim, + output_dim=action_dim, + use_pro_version=use_pro_version + ) + + def predict_action( + self, + actions_hidden_states, + proprio=None, + proprio_projector=None, + phase="Inference" + ): + """ + Args: + actions_hidden_states: [B, Layers, Total_Len, D] + + 根据 Qwen_Adapter 的逻辑,Total_Len = (Vision_Len + Action_Query_Num)。 + Language Tokens 已经在 Adapter 阶段被过滤掉了,所以这里不需要额外处理 Language。 + """ + batch_size = actions_hidden_states.shape[0] + device = actions_hidden_states.device + + # 1. Proprioception Processing + if proprio is not None and proprio_projector is not None: + proprio = proprio.reshape(batch_size, -1).to(dtype=actions_hidden_states.dtype) + proprio_features = proprio_projector(proprio) + proprio_features = proprio_features.unsqueeze(dim=1) # (bsz, 1, llm_dim) + else: + proprio_features = None + + # Action Query Tokens (h_a) + action_query_states = actions_hidden_states[:, :, -self.action_query_num:, :] + + task_hidden_states = actions_hidden_states[:, :, :-self.action_query_num, :] + + # 3. Action Chunk Queries Init + cond_actions_hidden_states = torch.zeros( + (batch_size, self.action_dim * self.num_actions_chunk, self.hidden_dim), + device=device, dtype=actions_hidden_states.dtype + ).detach() + + rearranged_actions_hidden_states = cond_actions_hidden_states.reshape( + batch_size, self.num_actions_chunk, -1 + ) + + # Denoising Noise + if phase == "Training": + batch_size, seq_len, dim = rearranged_actions_hidden_states.shape + random_perturbations = learnable_random_perturbations(seq_len, dim, device=rearranged_actions_hidden_states.device, dtype=rearranged_actions_hidden_states.dtype) + rearranged_actions_hidden_states = (rearranged_actions_hidden_states + random_perturbations) + + # 4. MLP Forward + action = self.model( + rearranged_actions_hidden_states, + h_a=action_query_states, # [B, Layers, query_num, D] + p=proprio_features, # [B, 1, D] + h_t=task_hidden_states # [B, Layers, vis_len, D] + ) + + return action + + +class MLPResNet(nn.Module): + """MLP with residual connection blocks.""" + def __init__( + self, + num_blocks, + input_dim, + hidden_dim, + output_dim, + use_pro_version=False + ): + + super().__init__() + self.layer_norm1 = nn.LayerNorm(input_dim) + self.fc1 = nn.Linear(input_dim, hidden_dim) + self.relu = nn.ReLU() + self.mlp_resnet_blocks = nn.ModuleList() + + for _ in range(num_blocks): + if use_pro_version: + self.mlp_resnet_blocks.append(MLPResNetBlock_Pro(dim=hidden_dim)) + else: + self.mlp_resnet_blocks.append(MLPResNetBlock(dim=hidden_dim)) + + self.layer_norm2 = nn.LayerNorm(hidden_dim) + self.fc2 = nn.Linear(hidden_dim, output_dim) + + + def forward(self, x, h_a=None, h_t=None, p=None): + # x: (batch_size, input_dim) + x = self.layer_norm1(x) + x = self.fc1(x) + x = self.relu(x) + + for i, block in enumerate(self.mlp_resnet_blocks): + idx = i + 1 + + cur_h_t = None + if h_t is not None and h_t.shape[1] > idx: + cur_h_t = h_t[:, idx, :] + + cur_h_a = None + if h_a is not None and h_a.shape[1] > idx: + cur_h_a = h_a[:, idx, :] + + x = block(x, h_t=cur_h_t, h_a=cur_h_a, p=p) + + x = self.layer_norm2(x) + x = self.fc2(x) + return x + + +def apply_rope(q, k, cos, sin): + cos = cos.unsqueeze(0).unsqueeze(0) + sin = sin.unsqueeze(0).unsqueeze(0) + + def rotate_half(x): + x1 = x[..., ::2] + x2 = x[..., 1::2] + return torch.stack((-x2, x1), dim=-1).reshape_as(x) + + q_rot = (q * cos) + (rotate_half(q) * sin) + k_rot = (k * cos) + (rotate_half(k) * sin) + + return q_rot, k_rot + + +class RotaryPositionEmbedding(nn.Module): + def __init__(self, dim, base=10000): + super().__init__() + assert dim % 2 == 0, "RoPE head_dim must be an even number" + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + def forward(self, seq_len, device, dtype): + t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype) + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + emb = torch.cat([freqs, freqs], dim=-1) + return emb.cos().to(dtype), emb.sin().to(dtype) + + +class MLPResNetBlock(nn.Module): + """ + Standard MLP ResNet Block. + """ + def __init__(self, dim): + super().__init__() + self.dim = dim + self.ffn = nn.Sequential( + nn.LayerNorm(dim), + nn.Linear(dim, dim), + nn.ReLU(), + ) + self.num_heads = 8 + self.head_dim = dim // self.num_heads + self.q_proj = nn.Linear(dim, dim) + self.k_proj = nn.Linear(dim, dim) + self.v_proj = nn.Linear(dim, dim) + self.o_proj = nn.Linear(dim, dim) + self.gating_factor = nn.Parameter(torch.zeros(1)) + + def forward(self, x, h_t=None, h_a=None, p=None): + g = self.gating_factor + ratio_g = torch.tanh(g) + + conditions = [] + if h_a is not None: + if h_a.dim() == 2: h_a = h_a.unsqueeze(1) + conditions.append(h_a) + if p is not None: + if p.dim() == 2: p = p.unsqueeze(1) + conditions.append(p) + + h_cond = torch.cat(conditions, dim=1) if len(conditions) > 0 else None + + if h_t is not None: + if h_t.dim() == 2: h_t = h_t.unsqueeze(1) + + B, T, C = x.shape + K_cond = h_cond.size(1) if h_cond is not None else 0 + K_task = h_t.size(1) if h_t is not None else 0 + + # Self Attention Projection + q_1 = self.q_proj(x) + k_tokens = self.k_proj(x) + v_tokens = self.v_proj(x) + + # Reshape Self + q_1 = q_1.view(B, T, self.num_heads, self.head_dim).transpose(1, 2) + k_tokens = k_tokens.view(B, T, self.num_heads, self.head_dim).transpose(1, 2) + v_tokens = v_tokens.view(B, T, self.num_heads, self.head_dim).transpose(1, 2) + + attn_scores_list = [] + # Score: Self + attn_scores_list.append(torch.matmul(q_1, k_tokens.transpose(-2, -1))) + + # Process Task (Vision) + v_task_reshaped = None + if h_t is not None: + k_task = self.k_proj(h_t) + v_task = self.v_proj(h_t) + k_task = k_task.view(B, K_task, self.num_heads, self.head_dim).transpose(1, 2) + v_task_reshaped = v_task.view(B, K_task, self.num_heads, self.head_dim).transpose(1, 2) + + attn_scores_list.append(torch.matmul(q_1, k_task.transpose(-2, -1))) + + # Process Adapter (Action/Proprio) + v_cond_reshaped = None + if h_cond is not None: + k_cond = self.k_proj(h_cond) + v_cond = self.v_proj(h_cond) + k_cond = k_cond.view(B, K_cond, self.num_heads, self.head_dim).transpose(1, 2) + v_cond_reshaped = v_cond.view(B, K_cond, self.num_heads, self.head_dim).transpose(1, 2) + + attn_scores_list.append(torch.matmul(q_1, k_cond.transpose(-2, -1)) * ratio_g) + + # Softmax + attn_scores = torch.cat(attn_scores_list, dim=-1) + attn_scores = attn_scores / math.sqrt(self.head_dim) + attn_weights = torch.softmax(attn_scores, dim=-1) + + # Combine Values + v_combined_list = [v_tokens] + if v_task_reshaped is not None: v_combined_list.append(v_task_reshaped) + if v_cond_reshaped is not None: v_combined_list.append(v_cond_reshaped) + + v_combined = torch.cat(v_combined_list, dim=2) + + # Output Projection + output = torch.matmul(attn_weights, v_combined) + output = output.transpose(1, 2).contiguous().view(B, T, C) + output = self.o_proj(output) + + x = self.ffn(output + x) + return x + + +class MLPResNetBlock_Pro(nn.Module): + """ + MLP ResNet Block Pro with RoPE and dimension checks. + """ + def __init__(self, dim, num_heads=8): + super().__init__() + self.dim = dim + self.num_heads = num_heads + self.head_dim = dim // num_heads + + self.ffn = nn.Sequential( + nn.LayerNorm(dim), + nn.Linear(dim, dim), + nn.ReLU(), + ) + + self.q_proj = nn.Linear(dim, dim) + self.k_self = nn.Linear(dim, dim) + self.v_self = nn.Linear(dim, dim) + + self.k_adapter = nn.Linear(dim, dim) + self.v_adapter = nn.Linear(dim, dim) + + self.k_task = nn.Linear(dim, dim) + self.v_task = nn.Linear(dim, dim) + + self.o_proj = nn.Linear(dim, dim) + self.gating_factor = nn.Parameter(torch.zeros(1)) + self.rope = RotaryPositionEmbedding(self.head_dim) + + def forward(self, x, h_a=None, h_t=None, p=None): + g = self.gating_factor + ratio_g = torch.tanh(g) + + # 1. Prepare Conditions + cond_list = [] + if h_a is not None: + if h_a.dim() == 2: h_a = h_a.unsqueeze(1) + cond_list.append(h_a) + if p is not None: + if p.dim() == 2: p = p.unsqueeze(1) + cond_list.append(p) + h_adapter = torch.cat(cond_list, dim=1) if cond_list else None + + if h_t is not None: + if h_t.dim() == 2: h_t = h_t.unsqueeze(1) + + B, T, C = x.shape + K_a = h_adapter.size(1) if h_adapter is not None else 0 + K_t = h_t.size(1) if h_t is not None else 0 + + def to_heads(t, L): + return t.view(B, L, self.num_heads, self.head_dim).transpose(1, 2) + + # Self Attention + q_1 = self.q_proj(x) + k_self = self.k_self(x) + v_self = self.v_self(x) + + q_1 = to_heads(q_1, T) + k_self = to_heads(k_self, T) + v_self = to_heads(v_self, T) + + # RoPE: Self + cos_main, sin_main = self.rope(seq_len=T, device=x.device, dtype=x.dtype) + q_1, k_self = apply_rope(q_1, k_self, cos_main, sin_main) + + attn_scores = [torch.matmul(q_1, k_self.transpose(-2, -1))] + v_list = [v_self] + + # Adapter Attention (Action/Proprio) - With RoPE + if h_adapter is not None: + k_adp = self.k_adapter(h_adapter) + v_adp = self.v_adapter(h_adapter) + k_adp, v_adp = to_heads(k_adp, K_a), to_heads(v_adp, K_a) + + cos_a, sin_a = self.rope(seq_len=K_a, device=x.device, dtype=x.dtype) + _, k_adp = apply_rope(k_adp, k_adp, cos_a, sin_a) + + attn_scores.append(torch.matmul(q_1, k_adp.transpose(-2, -1))) + v_list.append(v_adp) + + # Task Attention (Vision) - With RoPE & Gating + if h_t is not None: + k_tsk = self.k_task(h_t) + v_tsk = self.v_task(h_t) + k_tsk, v_tsk = to_heads(k_tsk, K_t), to_heads(v_tsk, K_t) + + cos_t, sin_t = self.rope(seq_len=K_t, device=x.device, dtype=x.dtype) + _, k_tsk = apply_rope(k_tsk, k_tsk, cos_t, sin_t) + + attn_scores.append(torch.matmul(q_1, k_tsk.transpose(-2, -1)) * ratio_g) + v_list.append(v_tsk) + + # Merge & Output + attn_scores = torch.cat(attn_scores, dim=-1) / math.sqrt(self.head_dim) + attn_weights = torch.softmax(attn_scores, dim=-1) + + v_combined = torch.cat(v_list, dim=2) + output = torch.matmul(attn_weights, v_combined) + + output = output.transpose(1, 2).contiguous().view(B, T, C) + output = self.o_proj(output) + + x = self.ffn(output + x) + return x + + +def get_action_model(config=None): + return L1RegressionActionHead( + full_config=config + ) \ No newline at end of file diff --git a/starVLA/model/modules/action_model/__init__.py b/starVLA/model/modules/action_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6de094b9274ded3b4326e675726b37021cd29ef4 --- /dev/null +++ b/starVLA/model/modules/action_model/__init__.py @@ -0,0 +1,40 @@ +# Modified from OpenAI's diffusion repos +# GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py +# ADM: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion +# IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py + +from .DiT_modules import gaussian_diffusion as gd +from .DiT_modules.respace import SpacedDiffusion, space_timesteps + + +def create_diffusion( + timestep_respacing, + noise_schedule="linear", + use_kl=False, + sigma_small=False, + predict_xstart=False, + learn_sigma=True, + rescale_learned_sigmas=False, + diffusion_steps=1000, +): + betas = gd.get_named_beta_schedule(noise_schedule, diffusion_steps) + if use_kl: + loss_type = gd.LossType.RESCALED_KL + elif rescale_learned_sigmas: + loss_type = gd.LossType.RESCALED_MSE + else: + loss_type = gd.LossType.MSE + if timestep_respacing is None or timestep_respacing == "": + timestep_respacing = [diffusion_steps] + return SpacedDiffusion( + use_timesteps=space_timesteps(diffusion_steps, timestep_respacing), + betas=betas, + model_mean_type=(gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X), + model_var_type=( + (gd.ModelVarType.FIXED_LARGE if not sigma_small else gd.ModelVarType.FIXED_SMALL) + if not learn_sigma + else gd.ModelVarType.LEARNED_RANGE + ), + loss_type=loss_type, + # rescale_timesteps=rescale_timesteps, + ) diff --git a/starVLA/model/modules/action_model/fast_ActionHeader.py b/starVLA/model/modules/action_model/fast_ActionHeader.py new file mode 100644 index 0000000000000000000000000000000000000000..27352fed49220c77679cb81dba29d3af8f366fe4 --- /dev/null +++ b/starVLA/model/modules/action_model/fast_ActionHeader.py @@ -0,0 +1,131 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Jinhui YE / HKUST University] in [2025]. + +"""Fast Action Tokenizer Adapter +"this file is adapted from https://huggingface.co/physical-intelligence/fast" + +Overview: + This module encapsulates a lightweight "action → language model-readable sequence" converter (Fast_Action_Tokenizer). + Its core objective is to convert continuous/discrete raw robot actions (raw_actions) into + pseudo-natural language token strings like ... + This facilitates direct integration into multimodal large models (VLM/LLM) dialogue templates, + leveraging their language modeling capabilities for action prediction. +""" + +import torch.nn as nn +from typing import List, Dict, Any, Callable, Optional +import os +import sys +import numpy as np +from transformers import PreTrainedTokenizerFast + + + +class Fast_Action_Tokenizer(nn.Module): + """One MLP ResNet block with a residual connection.""" + def __init__(self, fast_tokenizer_name=None): + super().__init__() + + if fast_tokenizer_name is None: + fast_tokenizer_name = os.environ.get("FAST_TOKENIZER_PATH", "physical-intelligence/fast") + + # Load the UniversalActionProcessor from local path, bypassing AutoProcessor + # which requires sentencepiece via AutoTokenizer internally. + if os.path.isdir(fast_tokenizer_name): + # Add local path to sys.path so we can import the custom processor + if fast_tokenizer_name not in sys.path: + sys.path.insert(0, fast_tokenizer_name) + from processing_action_tokenizer import UniversalActionProcessor + bpe_tokenizer = PreTrainedTokenizerFast.from_pretrained(fast_tokenizer_name) + self.fast_tokenizer = UniversalActionProcessor(bpe_tokenizer=bpe_tokenizer) + else: + # Fallback to HuggingFace download + from transformers import AutoProcessor + self.fast_tokenizer = AutoProcessor.from_pretrained( + fast_tokenizer_name, trust_remote_code=True + ) + + + def encoder_action2fastoken(self, raw_actions): + # x: (batch_size, chunck, dim) + batch_actions = np.stack(raw_actions, axis=0) # (B, T, D) + batch_fast_tokens = self.fast_tokenizer(batch_actions) + + return batch_fast_tokens # List[str] + + def decoder_action(self, generated_ids): + # api https://huggingface.co/physical-intelligence/fast + # return: (batch_size, chunck, dim) + pred_actions = self.fast_tokenizer.decode([generated_ids - self._ACTION_TOKEN_MIN]) + return pred_actions + + + def fit_tokenizer_on_datasets(self, action_dataset, datasets_path="", ): + # 如果 datasets_path 存在, 直接读取 + if os.path.exists(datasets_path): + + self.fast_tokenizer = AutoProcessor.from_pretrained( + datasets_path, trust_remote_code=True + ) + return + else: + # 如果不存在,Fit the tokenizer on the new dataset + new_tokenizer = self.fast_tokenizer.tokenizer.fit(action_dataset) + self.fast_tokenizer = new_tokenizer + + # Save the new tokenizer, optionally push it to the Hugging Face model hub + self.fast_tokenizer.save_pretrained(datasets_path) + + +def get_action_model(config=None): + """ + Factory: build ActionModel from global framework config. + + Args: + config: Global config (expects config.framework.action_model namespace). + Returns: + ActionModel: Initialized diffusion action head. + """ + action_model = Fast_Action_Tokenizer() + + return action_model + + +def start_debugpy_once(): + """start debugpy once""" + import debugpy + if getattr(start_debugpy_once, "_started", False): + return + debugpy.listen(("0.0.0.0", 10094)) + print("🔍 Waiting for VSCode attach on 0.0.0.0:10094 ...") + debugpy.wait_for_client() + start_debugpy_once._started = True + +if __name__ == "__main__": + + start_debugpy_once() + + fast_tokenizer_name = "physical-intelligence/fast" + fast_tokenizer = Fast_Action_Tokenizer(fast_tokenizer_name=fast_tokenizer_name) + raw_actions = [np.random.randn(16, 7), np.random.randn(16, 7)] + + # Load the tokenizer from the Hugging Face hub + tokenizer = AutoProcessor.from_pretrained(fast_tokenizer_name, trust_remote_code=True) + + # basic test + # Tokenize & decode action chunks (we use dummy data here) + action_data = np.random.rand(2, 16, 7) # one batch of action chunks + tokens = tokenizer(action_data) # tokens = list[int] + decoded_actions = tokenizer.decode(tokens) + + # self func test + vlm_tokens = fast_tokenizer.encoder_action2vlmtoken(raw_actions) + print(vlm_tokens) + pred_actions = fast_tokenizer.decoder_action(np.array([12,3,45,87])) + print(pred_actions) + + + + + diff --git a/starVLA/model/modules/action_model/flow_matching_head/__init__.py b/starVLA/model/modules/action_model/flow_matching_head/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3159bfe65645499015bd92609b99d476d69544e9 --- /dev/null +++ b/starVLA/model/modules/action_model/flow_matching_head/__init__.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/starVLA/model/modules/action_model/flow_matching_head/action_encoder.py b/starVLA/model/modules/action_model/flow_matching_head/action_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a27bbbb745be683c7cbc947b4137ffceb9247df0 --- /dev/null +++ b/starVLA/model/modules/action_model/flow_matching_head/action_encoder.py @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +import torch.nn as nn + + +def swish(x): + return x * torch.sigmoid(x) + + +class SinusoidalPositionalEncoding(nn.Module): + """ + Produces a sinusoidal encoding of shape (B, T, w) + given timesteps of shape (B, T). + """ + + def __init__(self, embedding_dim): + super().__init__() + self.embedding_dim = embedding_dim + + def forward(self, timesteps): + # timesteps: shape (B, T) + # We'll compute sin/cos frequencies across dim T + timesteps = timesteps.float() # ensure float + + B, T = timesteps.shape + device = timesteps.device + + half_dim = self.embedding_dim // 2 + # typical log space frequencies for sinusoidal encoding + exponent = -torch.arange(half_dim, dtype=torch.float, device=device) * ( + torch.log(torch.tensor(10000.0)) / half_dim + ) + # Expand timesteps to (B, T, 1) then multiply + freqs = timesteps.unsqueeze(-1) * exponent.exp() # (B, T, half_dim) + + sin = torch.sin(freqs) + cos = torch.cos(freqs) + enc = torch.cat([sin, cos], dim=-1) # (B, T, w) + + return enc + + +class ActionEncoder(nn.Module): + def __init__(self, action_dim, hidden_size): + super().__init__() + self.hidden_size = hidden_size + + # W1: R^{w x d}, W2: R^{w x 2w}, W3: R^{w x w} + self.W1 = nn.Linear(action_dim, hidden_size) # (d -> w) + self.W2 = nn.Linear(2 * hidden_size, hidden_size) # (2w -> w) + self.W3 = nn.Linear(hidden_size, hidden_size) # (w -> w) + + self.pos_encoding = SinusoidalPositionalEncoding(hidden_size) + + def forward(self, actions, timesteps): + """ + actions: shape (B, T, action_dim) + timesteps: shape (B,) -- a single scalar per batch item + returns: shape (B, T, hidden_size) + """ + B, T, _ = actions.shape + + # 1) Expand each batch's single scalar time 'tau' across all T steps + # so that shape => (B, T) + # e.g. if timesteps is (B,), replicate across T + if timesteps.dim() == 1 and timesteps.shape[0] == B: + # shape (B,) => (B,T) + timesteps = timesteps.unsqueeze(1).expand(-1, T) + else: + raise ValueError( + "Expected `timesteps` to have shape (B,) so we can replicate across T." + ) + + # 2) Standard action MLP step for shape => (B, T, w) + a_emb = self.W1(actions) + + # 3) Get the sinusoidal encoding (B, T, w) + tau_emb = self.pos_encoding(timesteps).to(dtype=a_emb.dtype) + + # 4) Concat along last dim => (B, T, 2w), then W2 => (B, T, w), swish + x = torch.cat([a_emb, tau_emb], dim=-1) + x = swish(self.W2(x)) + + # 5) Finally W3 => (B, T, w) + x = self.W3(x) + + return x diff --git a/starVLA/model/modules/action_model/flow_matching_head/cross_attention_dit.py b/starVLA/model/modules/action_model/flow_matching_head/cross_attention_dit.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb9a0886a51f5084991eaef5fd9f4f46f388b8a --- /dev/null +++ b/starVLA/model/modules/action_model/flow_matching_head/cross_attention_dit.py @@ -0,0 +1,377 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional + +import torch +import torch.nn.functional as F +from diffusers import ConfigMixin, ModelMixin +from diffusers.configuration_utils import register_to_config +from diffusers.models.attention import Attention, FeedForward +from diffusers.models.embeddings import ( + SinusoidalPositionalEmbedding, + TimestepEmbedding, + Timesteps, +) +from torch import nn + + +class TimestepEncoder(nn.Module): + def __init__(self, embedding_dim, compute_dtype=torch.float32): + super().__init__() + self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1) + self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim) + + def forward(self, timesteps): + dtype = next(self.parameters()).dtype + timesteps_proj = self.time_proj(timesteps).to(dtype) + timesteps_emb = self.timestep_embedder(timesteps_proj) # (N, D) + return timesteps_emb + + +class AdaLayerNorm(nn.Module): + def __init__( + self, + embedding_dim: int, + norm_elementwise_affine: bool = False, + norm_eps: float = 1e-5, + chunk_dim: int = 0, + ): + super().__init__() + self.chunk_dim = chunk_dim + output_dim = embedding_dim * 2 + self.silu = nn.SiLU() + self.linear = nn.Linear(embedding_dim, output_dim) + self.norm = nn.LayerNorm(output_dim // 2, norm_eps, norm_elementwise_affine) + + def forward( + self, + x: torch.Tensor, + temb: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + temb = self.linear(self.silu(temb)) + scale, shift = temb.chunk(2, dim=1) + x = self.norm(x) * (1 + scale[:, None]) + shift[:, None] + return x + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim: int, + num_attention_heads: int, + attention_head_dim: int, + dropout=0.0, + cross_attention_dim: Optional[int] = None, + activation_fn: str = "geglu", + attention_bias: bool = False, + upcast_attention: bool = False, + norm_elementwise_affine: bool = True, + norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen' + norm_eps: float = 1e-5, + final_dropout: bool = False, + attention_type: str = "default", + positional_embeddings: Optional[str] = None, + num_positional_embeddings: Optional[int] = None, + ff_inner_dim: Optional[int] = None, + ff_bias: bool = True, + attention_out_bias: bool = True, + ): + super().__init__() + self.dim = dim + self.num_attention_heads = num_attention_heads + self.attention_head_dim = attention_head_dim + self.dropout = dropout + self.cross_attention_dim = cross_attention_dim + self.activation_fn = activation_fn + self.attention_bias = attention_bias + self.norm_elementwise_affine = norm_elementwise_affine + self.positional_embeddings = positional_embeddings + self.num_positional_embeddings = num_positional_embeddings + self.norm_type = norm_type + + if positional_embeddings and (num_positional_embeddings is None): + raise ValueError( + "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined." + ) + + if positional_embeddings == "sinusoidal": + self.pos_embed = SinusoidalPositionalEmbedding( + dim, max_seq_length=num_positional_embeddings + ) + else: + self.pos_embed = None + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + if norm_type == "ada_norm": + self.norm1 = AdaLayerNorm(dim) + else: + self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps) + + self.attn1 = Attention( + query_dim=dim, + heads=num_attention_heads, + dim_head=attention_head_dim, + dropout=dropout, + bias=attention_bias, + cross_attention_dim=cross_attention_dim, + upcast_attention=upcast_attention, + out_bias=attention_out_bias, + ) + + # 3. Feed-forward + self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine) + self.ff = FeedForward( + dim, + dropout=dropout, + activation_fn=activation_fn, + final_dropout=final_dropout, + inner_dim=ff_inner_dim, + bias=ff_bias, + ) + if final_dropout: + self.final_dropout = nn.Dropout(dropout) + else: + self.final_dropout = None + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + encoder_hidden_states: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + temb: Optional[torch.LongTensor] = None, + ) -> torch.Tensor: + + # 0. Self-Attention + if self.norm_type == "ada_norm": + norm_hidden_states = self.norm1(hidden_states, temb) + else: + norm_hidden_states = self.norm1(hidden_states) + + if self.pos_embed is not None: + norm_hidden_states = self.pos_embed(norm_hidden_states) + + attn_output = self.attn1( + norm_hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=encoder_attention_mask, #@JinhuiYE original attention_mask=attention_mask + ) + if self.final_dropout: + attn_output = self.final_dropout(attn_output) + + hidden_states = attn_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + # 4. Feed-forward + norm_hidden_states = self.norm3(hidden_states) + ff_output = self.ff(norm_hidden_states) + + hidden_states = ff_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + return hidden_states + + +class DiT(ModelMixin, ConfigMixin): + _supports_gradient_checkpointing = True + + # register_to_config 的作用是创建类的时候会自动把传入的参数注册到 config 中,这样后续调用的时候可以通过 self.config.xxx 调用 还不是 self.xxx + @register_to_config # 去看一下这个的作用 --> 将传入的参数注册到配置中 TODO 改为我们的单例模式, 写一个 能够merge 的 @merge_pram_config + def __init__( + self, + num_attention_heads: int = 8, + attention_head_dim: int = 64, + output_dim: int = 26, + num_layers: int = 12, + dropout: float = 0.1, + attention_bias: bool = True, + activation_fn: str = "gelu-approximate", + num_embeds_ada_norm: Optional[int] = 1000, + upcast_attention: bool = False, + norm_type: str = "ada_norm", + norm_elementwise_affine: bool = False, + norm_eps: float = 1e-5, + max_num_positional_embeddings: int = 512, + compute_dtype=torch.float32, + final_dropout: bool = True, + positional_embeddings: Optional[str] = "sinusoidal", + interleave_self_attention=False, + cross_attention_dim: Optional[int] = None, + **kwargs + ): + super().__init__() + self.attention_head_dim = attention_head_dim + self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim + self.gradient_checkpointing = False + + # Timestep encoder + # self.config.compute_dtype 可能不存在,要提前处理 + compute_dtype = getattr(self.config, 'compute_dtype', torch.float32) + self.timestep_encoder = TimestepEncoder( # TODO BUG, train 的时候 self.config.compute_dtype 不会报错, 但是 eval 的时候会 + embedding_dim=self.inner_dim, compute_dtype=compute_dtype + ) + + all_blocks = [] + for idx in range(self.config.num_layers): + + use_self_attn = idx % 2 == 1 and interleave_self_attention + curr_cross_attention_dim = cross_attention_dim if not use_self_attn else None + + all_blocks += [ + BasicTransformerBlock( + self.inner_dim, + self.config.num_attention_heads, + self.config.attention_head_dim, + dropout=self.config.dropout, + activation_fn=self.config.activation_fn, + attention_bias=self.config.attention_bias, + upcast_attention=self.config.upcast_attention, + norm_type=norm_type, + norm_elementwise_affine=self.config.norm_elementwise_affine, + norm_eps=self.config.norm_eps, + positional_embeddings=positional_embeddings, + num_positional_embeddings=self.config.max_num_positional_embeddings, + final_dropout=final_dropout, + cross_attention_dim=curr_cross_attention_dim, + ) + ] + self.transformer_blocks = nn.ModuleList(all_blocks) + + # Output blocks + self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6) + self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim) + self.proj_out_2 = nn.Linear(self.inner_dim, self.config.output_dim) + print( + "Total number of DiT parameters: ", + sum(p.numel() for p in self.parameters() if p.requires_grad), + ) + + def forward( + self, + hidden_states: torch.Tensor, # Shape: (B, T, D) + encoder_hidden_states: torch.Tensor, # Shape: (B, S, D) + timestep: Optional[torch.LongTensor] = None, + return_all_hidden_states: bool = False, + encoder_attention_mask=None + ): + # Encode timesteps + temb = self.timestep_encoder(timestep) + + # Process through transformer blocks - single pass through the blocks + hidden_states = hidden_states.contiguous() + encoder_hidden_states = encoder_hidden_states.contiguous() + + all_hidden_states = [hidden_states] + + # Process through transformer blocks + for idx, block in enumerate(self.transformer_blocks): + if idx % 2 == 1 and self.config.interleave_self_attention: + hidden_states = block( + hidden_states, + attention_mask=None, + encoder_hidden_states=None, + encoder_attention_mask=None, + temb=temb, + ) + else: + hidden_states = block( + hidden_states, + attention_mask=None, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + temb=temb, + ) + all_hidden_states.append(hidden_states) + + # Output processing + conditioning = temb + shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1) + hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None] + if return_all_hidden_states: + return self.proj_out_2(hidden_states), all_hidden_states + else: + return self.proj_out_2(hidden_states) + + +class SelfAttentionTransformer(ModelMixin, ConfigMixin): + _supports_gradient_checkpointing = True + + @register_to_config + def __init__( + self, + num_attention_heads: int = 8, + attention_head_dim: int = 64, + output_dim: int = 26, + num_layers: int = 12, + dropout: float = 0.1, + attention_bias: bool = True, + activation_fn: str = "gelu-approximate", + num_embeds_ada_norm: Optional[int] = 1000, + upcast_attention: bool = False, + max_num_positional_embeddings: int = 512, + compute_dtype=torch.float32, + final_dropout: bool = True, + positional_embeddings: Optional[str] = "sinusoidal", + interleave_self_attention=False, + ): + super().__init__() + + self.attention_head_dim = attention_head_dim + self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim + self.gradient_checkpointing = False + + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + self.inner_dim, + self.config.num_attention_heads, + self.config.attention_head_dim, + dropout=self.config.dropout, + activation_fn=self.config.activation_fn, + attention_bias=self.config.attention_bias, + upcast_attention=self.config.upcast_attention, + positional_embeddings=positional_embeddings, + num_positional_embeddings=self.config.max_num_positional_embeddings, + final_dropout=final_dropout, + ) + for _ in range(self.config.num_layers) + ] + ) + print( + "Total number of SelfAttentionTransformer parameters: ", + sum(p.numel() for p in self.parameters() if p.requires_grad), + ) + + def forward( + self, + hidden_states: torch.Tensor, # Shape: (B, T, D) + return_all_hidden_states: bool = False, + ): + # Process through transformer blocks - single pass through the blocks + hidden_states = hidden_states.contiguous() + all_hidden_states = [hidden_states] + + # Process through transformer blocks + for idx, block in enumerate(self.transformer_blocks): + hidden_states = block(hidden_states) + all_hidden_states.append(hidden_states) + + if return_all_hidden_states: + return hidden_states, all_hidden_states + else: + return hidden_states diff --git a/starVLA/model/modules/action_model/time_aware_action_head.py b/starVLA/model/modules/action_model/time_aware_action_head.py new file mode 100644 index 0000000000000000000000000000000000000000..48fd032b9638f502172fe67865f9fb4ea1227150 --- /dev/null +++ b/starVLA/model/modules/action_model/time_aware_action_head.py @@ -0,0 +1,383 @@ +from collections import OrderedDict +from typing import Optional +from dataclasses import dataclass, field +import torch +import torch.nn as nn +from diffusers.models.embeddings import TimestepEmbedding, Timesteps +from transformers import PreTrainedModel, PretrainedConfig + + +class AdaLayerNorm(nn.Module): + def __init__(self, embedding_dim: int, time_embedding_dim: Optional[int] = None): + super().__init__() + + if time_embedding_dim is None: + time_embedding_dim = embedding_dim + + self.silu = nn.SiLU() + self.linear = nn.Linear(time_embedding_dim, 2 * embedding_dim, bias=True) + nn.init.zeros_(self.linear.weight) + nn.init.zeros_(self.linear.bias) + + # elementwise_affine=False: 不创建可学习参数 + self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6) + + def forward( + self, x: torch.Tensor, timestep_embedding: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + emb = self.linear(self.silu(timestep_embedding)) + shift, scale = emb.view(len(x), 1, -1).chunk(2, dim=-1) + x = self.norm(x) * (1 + scale) + shift + return x + + +class SquaredReLU(nn.Module): + def forward(self, x: torch.Tensor): + return torch.square(torch.relu(x)) + + +@dataclass +class FlowmatchingActionHeadConfig(PretrainedConfig): + """NOTE: N1.5 uses XEmbFlowmatchingPolicyHeadConfig as action head""" + + add_pos_embed: bool = field( + default=True, metadata={"help": "Whether to add positional embedding"} + ) + model_dtype: str = field(default="float32", metadata={"help": "Model data type."}) + diffusion_model_cfg: dict = field( + default=None, metadata={"help": "Diffusion model configuration."} + ) + input_embedding_dim: int = field( + default=1536, metadata={"help": "Input embedding channel dimension."} + ) + backbone_embedding_dim: int = field( + default=1536, metadata={"help": "Backbone embedding channel dimension."} + ) + + hidden_size: int = field(default=1024, metadata={"help": "Input embedding dimension."}) + max_seq_len: int = field(default=1024, metadata={"help": "Maxium Sequence Length"}) + action_dim: int = field(default=None, metadata={"help": "Action dimension."}) + action_horizon: int = field(default=None, metadata={"help": "Action horizon."}) + noise_beta_alpha: float = field(default=1.5, metadata={"help": ""}) + noise_beta_beta: float = field(default=1.0, metadata={"help": ""}) + noise_s: float = field( + default=0.999, metadata={"help": "Flow matching noise Beta distribution s."} + ) + num_timestep_buckets: int = field( + default=1000, metadata={"help": "Number of timestep discretization buckets."} + ) + num_inference_timesteps: int = field( + default=None, + metadata={"help": "Number of inference steps for noise diffusion."}, + ) + max_num_embodiments: int = field(default=32, metadata={"help": "Number of embodiments."}) + tune_projector: bool = field(default=True, metadata={"help": "Whether to tune the projector."}) + tune_diffusion_model: bool = field( + default=True, metadata={"help": "Whether to tune the diffusion model."} + ) + load_pretrained_det_decode_layer_path: str = field( + default=None, metadata={"help": "Path to pretrained detection model."} + ) + detection_coeff: float = field(default=1.0, metadata={"help": "Detection coefficient."}) + + freeze_decode_layer: bool = field(default=False) + expand_batch: int = field(default=None) + use_vlln: bool = field(default=True) + + vl_self_attention_cfg: dict = field(default=None) + + initializer_range: float = field(default=0.02) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + + +class PerceiverAttentionBlock(nn.Module): + def __init__( + self, d_model: int, n_heads: int, time_embedding_dim: Optional[int] = None, + num_non_action_tokens: int = 65, + ): + super().__init__() + # head_dim = embed_dim // num_heads + self.attn = nn.MultiheadAttention(embed_dim=d_model, num_heads=n_heads, batch_first=True) + self.num_non_action_tokens = num_non_action_tokens + + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("sq_relu", SquaredReLU()), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ] + ) + ) + + # ln_1: 对latents归一化 — 前num_non_action_tokens个token做普通LN,后16个token做AdaLN + self.ln_1 = AdaLayerNorm(d_model, time_embedding_dim) + self.ln_1_plain = nn.LayerNorm(d_model, eps=1e-6) + # ln_2: 对x(vl_tokens)做普通LN,不做AdaLN + self.ln_2_plain = nn.LayerNorm(d_model, eps=1e-6) + # ln_ff: 对latents归一化 — 前num_non_action_tokens个token做普通LN,后16个token做AdaLN + self.ln_ff = AdaLayerNorm(d_model, time_embedding_dim) + self.ln_ff_plain = nn.LayerNorm(d_model, eps=1e-6) + + def attention(self, q: torch.Tensor, kv: torch.Tensor): + attn_output, attn_output_weights = self.attn(q, kv, kv, need_weights=False) + return attn_output + + # 我们希望future_tokens能够和action_tokens完全解耦,具体来说: + # (1)self.ln_1和self.ln_ff在对latents做归一化时,拆分为两组,对前65个token做普通LN、对后16个token做AdaLN; + # (2)不对x(vl_tokens)做AdaLN,而是改做普通LN; + # (3)分离attention,future_tokens只与state_tokens、future_tokens和vl_tokens做cross-attn, + # 而action_tokens可以对以上所有tokens做cross-attn + def forward_for_WAM_VJEPA2AC( + self, + x: torch.Tensor, + latents: torch.Tensor, + timestep_embedding: torch.Tensor = None, + ): + # print('################# PerceiverAttentionBlock.forward_for_WAM_VJEPA2AC-1') + num_action_tokens = latents.shape[1] - self.num_non_action_tokens + + # (1) ln_1: 对latents做归一化 — 前65个token做普通LN,后16个token做AdaLN + # print(latents.shape) # torch.Size([32, 81, 768]) + normed_non_action = self.ln_1_plain(latents[:, :self.num_non_action_tokens]) + # print(normed_non_action.shape) # torch.Size([32, 65, 768]) + normed_action = self.ln_1(latents[:, self.num_non_action_tokens:], timestep_embedding) + # print(normed_action.shape) # torch.Size([32, 16, 768]) + normed_latents = torch.cat([normed_non_action, normed_action], dim=1) + # print(normed_latents.shape) # torch.Size([32, 81, 768]) + + # (2) ln_2: 对x(vl_tokens)做普通LN + # print(x.shape) # torch.Size([32, 196, 768]) + normed_x = self.ln_2_plain(x) + # print(normed_x.shape) # torch.Size([32, 196, 768]) + + # (3) 分离attention + # future_tokens只attend [state_tokens, future_tokens, vl_tokens] + # action_tokens可以attend [state_tokens, future_tokens, action_tokens, vl_tokens] + non_action_kv = torch.cat([normed_non_action, normed_x], dim=1) + # print(non_action_kv.shape) # torch.Size([32, 261, 768]) + full_kv = torch.cat([normed_latents, normed_x], dim=1) + # print(full_kv.shape) # torch.Size([32, 277, 768]) + + non_action_attn = self.attention(q=normed_non_action, kv=non_action_kv) + action_attn = self.attention(q=normed_action, kv=full_kv) + # print(non_action_attn.shape) # torch.Size([32, 65, 768]) + # print(action_attn.shape) # torch.Size([32, 16, 768]) + + latents_non_action = latents[:, :self.num_non_action_tokens] + non_action_attn + # print(latents_non_action.shape) # torch.Size([32, 65, 768]) + latents_action = latents[:, self.num_non_action_tokens:] + action_attn + # print(latents_action.shape) # torch.Size([32, 16, 768]) + latents = torch.cat([latents_non_action, latents_action], dim=1) + # print(latents.shape) # torch.Size([32, 81, 768]) + + # (4) ln_ff: 对latents做归一化 — 前65个token做普通LN,后16个token做AdaLN + ff_non_action = self.mlp(self.ln_ff_plain(latents[:, :self.num_non_action_tokens])) + # print(ff_non_action.shape) # torch.Size([32, 65, 768]) + ff_action = self.mlp(self.ln_ff(latents[:, self.num_non_action_tokens:], timestep_embedding)) + # print(ff_action.shape) # torch.Size([32, 16, 768]) + latents = torch.cat([ + latents[:, :self.num_non_action_tokens] + ff_non_action, + latents[:, self.num_non_action_tokens:] + ff_action, + ], dim=1) + # print(latents.shape) # torch.Size([32, 81, 768]) + + # print('################# PerceiverAttentionBlock.forward_for_WAM_VJEPA2AC-2') + return latents + + def forward( + self, + x: torch.Tensor, + latents: torch.Tensor, + timestep_embedding: torch.Tensor = None, + ): + print('Warning: this function should not used in WAM-VJEPA !!!!!! ' + '(in /mnt/workspace/users/maxiangkai/projects/WM4A/starVLA/model/modules/action_model/time_aware_action_head.py)') + normed_latents = self.ln_1(latents, timestep_embedding) + latents = latents + self.attention( + q=normed_latents, + kv=torch.cat([normed_latents, self.ln_2(x, timestep_embedding)], dim=1), + ) + latents = latents + self.mlp(self.ln_ff(latents, timestep_embedding)) + return latents + + +class TimestepEncoder(nn.Module): + def __init__(self, time_channel, time_embedding_dim, compute_dtype=torch.float32): + super().__init__() + self.position = Timesteps( + time_channel, flip_sin_to_cos=True, downscale_freq_shift=0 + ) + self.time_embedding = TimestepEmbedding( + in_channels=time_channel, + time_embed_dim=time_embedding_dim, + ) + def forward(self, timesteps): + dtype = next(self.parameters()).dtype + time_feature = self.position(timesteps).to(dtype=dtype) + time_feature = time_feature.unsqueeze(1) + time_embedding = self.time_embedding(time_feature) # (N,1,D) + return time_embedding + + +class TimeAwareActionHead_Config(PretrainedConfig): + model_type = "TimeAwareActionHead" + def __init__( + self, + time_channel: int = 320, + time_embedding_dim: int = 768, + time_out_dim: int = None, + action_dim=768, + vl_input_dim=2048, + heads: int = 16, + layers: int = 16, + output_dim=1024, + compute_dtype=torch.float32, + initializer_range=0.02, + num_target_vision_tokens=64, + **kwargs, + ): + # head_dim = embed_dim(action_dim) // num_heads + self.time_channel = time_channel + self.time_embedding_dim = time_embedding_dim + self.time_out_dim = time_out_dim + self.action_dim = action_dim + self.vl_input_dim = vl_input_dim + self.heads = heads + self.layers = layers + self.output_dim = output_dim + self.compute_dtype = compute_dtype + self.initializer_range = initializer_range + self.num_target_vision_tokens = num_target_vision_tokens + super().__init__(**kwargs) + + def convert_to_dict(self): + return { + "time_channel": self.time_channel, + "time_embedding_dim": self.time_embedding_dim, + "time_out_dim": self.time_out_dim, + "action_dim": self.action_dim, + "vl_input_dim": self.vl_input_dim, + "heads": self.heads, + "layers": self.layers, + "output_dim": self.output_dim, + # "compute_dtype": self.compute_dtype, # issue: TypeError: Object of type dtype is not JSON serializable + "initializer_range": self.initializer_range, + "num_target_vision_tokens": self.num_target_vision_tokens, + } + + +class TimeAwareActionHead(PreTrainedModel): + supports_gradient_checkpointing = True + config_class = TimeAwareActionHead_Config + def __init__(self, + config: TimeAwareActionHead_Config, + ): + super().__init__(config) + self.config = config + self.vl_input_dim = self.config.vl_input_dim + self.output_dim = self.config.output_dim + self.action_dim = self.config.action_dim + self.num_target_vision_tokens = self.config.num_target_vision_tokens + + self.time_encoder = TimestepEncoder( + time_channel=self.config.time_channel, + time_embedding_dim=self.config.time_embedding_dim, + compute_dtype=self.config.compute_dtype + ) + + self.time_aware_linear = nn.Linear( + self.config.time_embedding_dim, self.action_dim, bias=True + ) + + if self.vl_input_dim is not None: + self.proj_in = nn.Linear(self.vl_input_dim, self.action_dim) + + self.perceiver_blocks = nn.Sequential( + *[ + PerceiverAttentionBlock( + d_model=self.action_dim, + n_heads=self.config.heads, + time_embedding_dim=self.config.time_embedding_dim, + num_non_action_tokens=self.num_target_vision_tokens+1, + ) + for _ in range(self.config.layers) + ] + ) + + if self.output_dim is not None: + self.proj_out = nn.Sequential( + nn.Linear(self.action_dim, self.output_dim), nn.LayerNorm(self.output_dim) + ) + + print( + "Total number of TimeAwareActionHead parameters: ", + sum(p.numel() for p in self.parameters() if p.requires_grad), + ) + + def init_weights(self): + for module in self.children(): + module.apply(self._init_weights) + + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + nn.init.zeros_(module.weight[module.padding_idx]) + elif isinstance(module, nn.LayerNorm): + if module.weight is not None: + nn.init.ones_(module.weight) + if module.bias is not None: + nn.init.zeros_(module.bias) + + def forward( + self, + latents: torch.Tensor, # Shape: (B, T, D) + visual_language_states: torch.Tensor, # Shape: (B, S, D) + timestep: Optional[torch.LongTensor] = None, + ): + # print('###### TimeAwareActionHead.forward-1') + # print(timestep.shape) # torch.Size([32]) + time_embedding = self.time_encoder(timestep) + # print(time_embedding.shape) # torch.Size([32, 1, 768]) + time_bais = self.time_aware_linear(torch.nn.functional.silu(time_embedding)) + # print(time_bais.shape) # torch.Size([32, 1, 768]) + + # 这里的81个tokens是由三组tokens拼接得到的, + # 首先是1*state_token,随后是64*future_token,最后是16*action_token, + # 我们认为这个time_baise只应该施加在action_tokens上, + # print(latents.shape) # torch.Size([32, 81, 1024]) + latents[:, self.num_target_vision_tokens+1:] = latents[:, self.num_target_vision_tokens+1:] + time_bais + # print(latents.shape) # torch.Size([32, 81, 1024]) + + if self.vl_input_dim is not None: + visual_language_states = self.proj_in(visual_language_states) + + # 我们重构了PerceiverAttentionBlock中的注意力机制, + # 确保future_tokens不会看到被time_step影响的action_tokens + for l_block in self.perceiver_blocks: + latents = l_block.forward_for_WAM_VJEPA2AC( + x=visual_language_states, + latents=latents, + timestep_embedding=time_embedding, + ) + + if self.output_dim is not None: + latents = self.proj_out(latents) + # print('###### TimeAwareActionHead.forward-2') + return latents + + +# register +from transformers import AutoConfig,AutoModel +AutoConfig.register("TimeAwareActionHead", TimeAwareActionHead_Config) +AutoModel.register(TimeAwareActionHead_Config, TimeAwareActionHead) \ No newline at end of file diff --git a/starVLA/model/modules/action_model/time_aware_action_head_original.py b/starVLA/model/modules/action_model/time_aware_action_head_original.py new file mode 100644 index 0000000000000000000000000000000000000000..4ade18c7f8c651051224e59b3d03ac9c7c32d05e --- /dev/null +++ b/starVLA/model/modules/action_model/time_aware_action_head_original.py @@ -0,0 +1,297 @@ +from collections import OrderedDict +from typing import Optional +from dataclasses import dataclass, field +import torch +import torch.nn as nn +from diffusers.models.embeddings import TimestepEmbedding, Timesteps +from transformers import PreTrainedModel, PretrainedConfig + +class AdaLayerNorm(nn.Module): + def __init__(self, embedding_dim: int, time_embedding_dim: Optional[int] = None): + super().__init__() + + if time_embedding_dim is None: + time_embedding_dim = embedding_dim + + self.silu = nn.SiLU() + self.linear = nn.Linear(time_embedding_dim, 2 * embedding_dim, bias=True) + nn.init.zeros_(self.linear.weight) + nn.init.zeros_(self.linear.bias) + + # elementwise_affine=False: 不创建可学习参数 + self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6) + + def forward( + self, x: torch.Tensor, timestep_embedding: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + emb = self.linear(self.silu(timestep_embedding)) + shift, scale = emb.view(len(x), 1, -1).chunk(2, dim=-1) + x = self.norm(x) * (1 + scale) + shift + return x + + +class SquaredReLU(nn.Module): + def forward(self, x: torch.Tensor): + return torch.square(torch.relu(x)) + + + +@dataclass +class FlowmatchingActionHeadConfig(PretrainedConfig): + """NOTE: N1.5 uses XEmbFlowmatchingPolicyHeadConfig as action head""" + + add_pos_embed: bool = field( + default=True, metadata={"help": "Whether to add positional embedding"} + ) + model_dtype: str = field(default="float32", metadata={"help": "Model data type."}) + diffusion_model_cfg: dict = field( + default=None, metadata={"help": "Diffusion model configuration."} + ) + input_embedding_dim: int = field( + default=1536, metadata={"help": "Input embedding channel dimension."} + ) + backbone_embedding_dim: int = field( + default=1536, metadata={"help": "Backbone embedding channel dimension."} + ) + + hidden_size: int = field(default=1024, metadata={"help": "Input embedding dimension."}) + max_seq_len: int = field(default=1024, metadata={"help": "Maxium Sequence Length"}) + action_dim: int = field(default=None, metadata={"help": "Action dimension."}) + action_horizon: int = field(default=None, metadata={"help": "Action horizon."}) + noise_beta_alpha: float = field(default=1.5, metadata={"help": ""}) + noise_beta_beta: float = field(default=1.0, metadata={"help": ""}) + noise_s: float = field( + default=0.999, metadata={"help": "Flow matching noise Beta distribution s."} + ) + num_timestep_buckets: int = field( + default=1000, metadata={"help": "Number of timestep discretization buckets."} + ) + num_inference_timesteps: int = field( + default=None, + metadata={"help": "Number of inference steps for noise diffusion."}, + ) + max_num_embodiments: int = field(default=32, metadata={"help": "Number of embodiments."}) + tune_projector: bool = field(default=True, metadata={"help": "Whether to tune the projector."}) + tune_diffusion_model: bool = field( + default=True, metadata={"help": "Whether to tune the diffusion model."} + ) + load_pretrained_det_decode_layer_path: str = field( + default=None, metadata={"help": "Path to pretrained detection model."} + ) + detection_coeff: float = field(default=1.0, metadata={"help": "Detection coefficient."}) + + freeze_decode_layer: bool = field(default=False) + expand_batch: int = field(default=None) + use_vlln: bool = field(default=True) + + vl_self_attention_cfg: dict = field(default=None) + + initializer_range: float = field(default=0.02) + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for key, value in kwargs.items(): + setattr(self, key, value) + + +class PerceiverAttentionBlock(nn.Module): + def __init__( + self, d_model: int, n_heads: int, time_embedding_dim: Optional[int] = None + ): + super().__init__() + # head_dim = embed_dim // num_heads + self.attn = nn.MultiheadAttention(embed_dim=d_model, num_heads=n_heads, batch_first=True) + + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("sq_relu", SquaredReLU()), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ] + ) + ) + + self.ln_1 = AdaLayerNorm(d_model, time_embedding_dim) + self.ln_2 = AdaLayerNorm(d_model, time_embedding_dim) + self.ln_ff = AdaLayerNorm(d_model, time_embedding_dim) + + def attention(self, q: torch.Tensor, kv: torch.Tensor): + attn_output, attn_output_weights = self.attn(q, kv, kv, need_weights=False) + return attn_output + + def forward( + self, + x: torch.Tensor, + latents: torch.Tensor, + timestep_embedding: torch.Tensor = None, + ): + normed_latents = self.ln_1(latents, timestep_embedding) + latents = latents + self.attention( + q=normed_latents, + kv=torch.cat([normed_latents, self.ln_2(x, timestep_embedding)], dim=1), + ) + latents = latents + self.mlp(self.ln_ff(latents, timestep_embedding)) + return latents + + +class TimestepEncoder(nn.Module): + def __init__(self, time_channel, time_embedding_dim, compute_dtype=torch.float32): + super().__init__() + self.position = Timesteps( + time_channel, flip_sin_to_cos=True, downscale_freq_shift=0 + ) + self.time_embedding = TimestepEmbedding( + in_channels=time_channel, + time_embed_dim=time_embedding_dim, + ) + def forward(self, timesteps): + dtype = next(self.parameters()).dtype + time_feature = self.position(timesteps).to(dtype=dtype) + time_feature = time_feature.unsqueeze(1) + time_embedding = self.time_embedding(time_feature) # (N,1,D) + return time_embedding + + +class TimeAwareActionHead_Config(PretrainedConfig): + model_type = "TimeAwareActionHead" + def __init__( + self, + time_channel: int = 320, + time_embedding_dim: int = 768, + time_out_dim: int = None, + action_dim=768, + vl_input_dim=2048, + heads: int = 16, + layers: int = 16, + output_dim=1024, + compute_dtype=torch.float32, + initializer_range=0.02, + **kwargs, + ): + # head_dim = embed_dim(action_dim) // num_heads + self.time_channel = time_channel + self.time_embedding_dim = time_embedding_dim + self.time_out_dim = time_out_dim + self.action_dim = action_dim + self.vl_input_dim = vl_input_dim + self.heads = heads + self.layers = layers + self.output_dim = output_dim + self.compute_dtype = compute_dtype + self.initializer_range = initializer_range + super().__init__(**kwargs) + + def convert_to_dict(self): + return { + "time_channel": self.time_channel, + "time_embedding_dim": self.time_embedding_dim, + "time_out_dim": self.time_out_dim, + "action_dim": self.action_dim, + "vl_input_dim": self.vl_input_dim, + "heads": self.heads, + "layers": self.layers, + "output_dim": self.output_dim, + # "compute_dtype": self.compute_dtype, # issue: TypeError: Object of type dtype is not JSON serializable + "initializer_range": self.initializer_range, + } + +class TimeAwareActionHead(PreTrainedModel): + supports_gradient_checkpointing = True + config_class = TimeAwareActionHead_Config + def __init__(self, + config: TimeAwareActionHead_Config, + ): + super().__init__(config) + self.config = config + self.vl_input_dim = self.config.vl_input_dim + self.output_dim = self.config.output_dim + self.action_dim = self.config.action_dim + + self.time_encoder = TimestepEncoder( + time_channel=self.config.time_channel, + time_embedding_dim=self.config.time_embedding_dim, + compute_dtype=self.config.compute_dtype + ) + + self.time_aware_linear = nn.Linear( + self.config.time_embedding_dim, self.action_dim, bias=True + ) + + if self.vl_input_dim is not None: + self.proj_in = nn.Linear(self.vl_input_dim, self.action_dim) + + self.perceiver_blocks = nn.Sequential( + *[ + PerceiverAttentionBlock( + self.action_dim, self.config.heads, time_embedding_dim=self.config.time_embedding_dim, + ) + for _ in range(self.config.layers) + ] + ) + + if self.output_dim is not None: + self.proj_out = nn.Sequential( + nn.Linear(self.action_dim, self.output_dim), nn.LayerNorm(self.output_dim) + ) + + print( + "Total number of TimeAwareActionHead parameters: ", + sum(p.numel() for p in self.parameters() if p.requires_grad), + ) + + def init_weights(self): + for module in self.children(): + module.apply(self._init_weights) + + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + nn.init.zeros_(module.weight[module.padding_idx]) + elif isinstance(module, nn.LayerNorm): + if module.weight is not None: + nn.init.ones_(module.weight) + if module.bias is not None: + nn.init.zeros_(module.bias) + + def forward( + self, + latents: torch.Tensor, # Shape: (B, T, D) + visual_language_states: torch.Tensor, # Shape: (B, S, D) + timestep: Optional[torch.LongTensor] = None, + ): + time_embedding = self.time_encoder(timestep) + + latents = latents + self.time_aware_linear( + torch.nn.functional.silu(time_embedding) + ) + # import ipdb;ipdb.set_trace() + + if self.vl_input_dim is not None: + visual_language_states = self.proj_in(visual_language_states) + + for l_block in self.perceiver_blocks: + latents = l_block( + x=visual_language_states, + latents=latents, + timestep_embedding=time_embedding, + ) + + if self.output_dim is not None: + latents = self.proj_out(latents) + + # print("哈哈哈啊哈哈") + + return latents + + +# register +from transformers import AutoConfig,AutoModel +AutoConfig.register("TimeAwareActionHead", TimeAwareActionHead_Config) +AutoModel.register(TimeAwareActionHead_Config, TimeAwareActionHead) \ No newline at end of file diff --git a/starVLA/model/modules/dino_model/dino.py b/starVLA/model/modules/dino_model/dino.py new file mode 100644 index 0000000000000000000000000000000000000000..e016b9b853e0e1409824b1f83d2b8e7600e06111 --- /dev/null +++ b/starVLA/model/modules/dino_model/dino.py @@ -0,0 +1,144 @@ +""" +DINOv2 vision backbone wrapper. + +Features: + - Loads DINOv2 variants via torch.hub (with local fallback) + - Exposes patch token features (x_norm_patchtokens) + - Provides preprocessing (resize + normalization) for multi-view PIL images + - Parallel per-view preprocessing using ThreadPoolExecutor +""" + +from collections import OrderedDict +import os + +from concurrent.futures import ThreadPoolExecutor +import torch + +import torch +import torch.nn.functional as F +from torch import nn +from torchvision.models._utils import IntermediateLayerGetter +from typing import Dict, List +from torchvision import transforms + + +def apply_transform(view, transform): + return transform(view) + + +# from llavavla.model.modules.dino_model.dino_transforms import make_classification_train_transform + + +class DINOv2BackBone(nn.Module): + """ + Thin wrapper around a DINOv2 model. + + Args: + backone_name: DINOv2 model id (e.g. dinov2_vits14, dinov2_vitb14). + output_channels: (Unused placeholder; retained for future extension). + + Attributes: + body: Loaded DINOv2 model. + num_channels: Feature dimension of patch tokens. + dino_transform: Preprocessing pipeline (resize + tensor + normalize). + """ + + def __init__(self, backone_name="dinov2_vits14", output_channels=1024) -> None: + super().__init__() + try: + self.body = torch.hub.load("facebookresearch/dinov2", backone_name) + except: + import traceback + + traceback.print_exc() + print(f"Failed to load dinov2 from torch hub, loading from local") + TORCH_HOME = os.environ.get("TORCH_HOME", "~/.cache/torch/") + weights_path = os.path.expanduser(f"{TORCH_HOME}/hub/checkpoints/{backone_name}_pretrain.pth") + + code_path = os.path.expanduser(f"{TORCH_HOME}/hub/facebookresearch_dinov2_main") + + self.body = torch.hub.load(code_path, backone_name, source="local", pretrained=False) + + state_dict = torch.load(weights_path) + self.body.load_state_dict(state_dict) + if backone_name == "dinov2_vits14": + self.num_channels = 384 + elif backone_name == "dinov2_vitb14": + self.num_channels = 768 + elif backone_name == "dinov2_vitl14": + self.num_channels = 1024 + elif backone_name == "dinov2_vitg14": + self.num_channels = 1408 + else: + raise NotImplementedError(f"DINOv2 backbone {backone_name} not implemented") + self.dino_transform = transforms.Compose( + [ + transforms.Resize((224, 224)), + transforms.ToTensor(), + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ] + ) + # self.dino_transform = make_classification_train_transform() + + # @torch.no_grad() + def forward(self, tensor): + """ + Forward pass. + + Args: + tensor: Image batch tensor [B*views, 3, H, W]. + + Returns: + torch.Tensor: Patch token features [B*views, N_tokens, C]. + """ + xs = self.body.forward_features(tensor)["x_norm_patchtokens"] + + return xs # B*views, token, dim + + def prepare_dino_input(self, img_list): + """ + Preprocess a batch of multi-view PIL image lists into a tensor suitable for DINO. + + Args: + img_list: List of samples; each sample is List[PIL.Image] (multi-view). + + Returns: + torch.Tensor: Flattened batch of shape [B * num_view, 3, H, W] on model device. + """ + # img_list: is a list of [PIL], each representing multi views of the same example. + # refer to https://github.com/facebookresearch/dinov2/blob/main/dinov2/data/transforms.py + + # use thread pool to parallel process each view + with ThreadPoolExecutor() as executor: + image_tensors = torch.stack( + [ + torch.stack(list(executor.map(lambda view: apply_transform(view, self.dino_transform), views))) + for views in img_list + ] + ) + + # move the tensor to the device of DINO encoder + B, num_view, C, H, W = image_tensors.shape + image_tensors = image_tensors.view(B * num_view, C, H, W) + device = next(self.parameters()).device + image_tensors = image_tensors.to(device) + + return image_tensors + + +def get_dino_model(backone_name="dinov2_vits14") -> DINOv2BackBone: + """ + Factory helper returning a configured DINOv2BackBone. + + Args: + backone_name: DINOv2 variant name. + + Returns: + DINOv2BackBone: Initialized backbone instance. + """ + return DINOv2BackBone(backone_name) + + +if __name__ == "__main__": + dino = DINOv2BackBone() + pass diff --git a/starVLA/model/modules/dino_model/dino_transforms.py b/starVLA/model/modules/dino_model/dino_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5f252b50c54d58f160528c9f2b00fad47103c7 --- /dev/null +++ b/starVLA/model/modules/dino_model/dino_transforms.py @@ -0,0 +1,91 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the Apache License, Version 2.0 +# found in the LICENSE file in the root directory of this source tree. + +from typing import Sequence + +import torch +from torchvision import transforms + + +class GaussianBlur(transforms.RandomApply): + """ + Apply Gaussian Blur to the PIL image. + """ + + def __init__(self, *, p: float = 0.5, radius_min: float = 0.1, radius_max: float = 2.0): + # NOTE: torchvision is applying 1 - probability to return the original image + keep_p = 1 - p + transform = transforms.GaussianBlur(kernel_size=9, sigma=(radius_min, radius_max)) + super().__init__(transforms=[transform], p=keep_p) + + +class MaybeToTensor(transforms.ToTensor): + """ + Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor, or keep as is if already a tensor. + """ + + def __call__(self, pic): + """ + Args: + pic (PIL Image, numpy.ndarray or torch.tensor): Image to be converted to tensor. + Returns: + Tensor: Converted image. + """ + if isinstance(pic, torch.Tensor): + return pic + return super().__call__(pic) + + +# Use timm's names +IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) +IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) + + +def make_normalize_transform( + mean: Sequence[float] = IMAGENET_DEFAULT_MEAN, + std: Sequence[float] = IMAGENET_DEFAULT_STD, +) -> transforms.Normalize: + return transforms.Normalize(mean=mean, std=std) + + +# This roughly matches torchvision's preset for classification training: +# https://github.com/pytorch/vision/blob/main/references/classification/presets.py#L6-L44 +def make_classification_train_transform( + *, + crop_size: int = 224, + interpolation=transforms.InterpolationMode.BICUBIC, + hflip_prob: float = 0.5, + mean: Sequence[float] = IMAGENET_DEFAULT_MEAN, + std: Sequence[float] = IMAGENET_DEFAULT_STD, +): + transforms_list = [transforms.RandomResizedCrop(crop_size, interpolation=interpolation)] + if hflip_prob > 0.0: + transforms_list.append(transforms.RandomHorizontalFlip(hflip_prob)) + transforms_list.extend( + [ + MaybeToTensor(), + make_normalize_transform(mean=mean, std=std), + ] + ) + return transforms.Compose(transforms_list) + + +# This matches (roughly) torchvision's preset for classification evaluation: +# https://github.com/pytorch/vision/blob/main/references/classification/presets.py#L47-L69 +def make_classification_eval_transform( + *, + resize_size: int = 256, + interpolation=transforms.InterpolationMode.BICUBIC, + crop_size: int = 224, + mean: Sequence[float] = IMAGENET_DEFAULT_MEAN, + std: Sequence[float] = IMAGENET_DEFAULT_STD, +) -> transforms.Compose: + transforms_list = [ + transforms.Resize(resize_size, interpolation=interpolation), + transforms.CenterCrop(crop_size), + MaybeToTensor(), + make_normalize_transform(mean=mean, std=std), + ] + return transforms.Compose(transforms_list) diff --git a/starVLA/model/modules/projector/QFormer.py b/starVLA/model/modules/projector/QFormer.py new file mode 100644 index 0000000000000000000000000000000000000000..362c1f86bc61638a8454cc6e13d307dbb38fc8be --- /dev/null +++ b/starVLA/model/modules/projector/QFormer.py @@ -0,0 +1,185 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.distributed as dist + + +class CrossAttentionBlock(nn.Module): + def __init__(self, hidden_dim, num_heads, mlp_ratio=4.0, dropout=0.1): + super().__init__() + self.norm1 = nn.LayerNorm(hidden_dim) + self.cross_attn = nn.MultiheadAttention( + embed_dim=hidden_dim, num_heads=num_heads, batch_first=True, dropout=dropout + ) + + self.norm2 = nn.LayerNorm(hidden_dim) + self.mlp = nn.Sequential( + nn.Linear(hidden_dim, int(hidden_dim * mlp_ratio)), + nn.GELU(), + nn.Linear(int(hidden_dim * mlp_ratio), hidden_dim), + ) + self.dropout = nn.Dropout(dropout) + + def forward(self, query, encoder_hidden_state, encoder_attention_mask=None): + """ + Cross-attention block forward. + Args: + query (Tensor): Shape [B, Q, D]. Learnable query tokens propagated across layers. + encoder_hidden_state (Tensor): Shape [B, L, D]. Features from one encoder layer. + encoder_attention_mask (Tensor | None): Shape [B, L]. 1/True=keep (visible), 0/False=mask. None disables masking. + Returns: + Tensor: Updated query tokens of shape [B, Q, D]. + Details: + 1. LayerNorm + MultiheadAttention (Q = query, K/V = encoder_hidden_state). + 2. Residual path: query = query + attn_output, then add MLP residual. + 3. Dropout is applied only on the MLP output. + """ + q = self.norm1(query) + kv = encoder_hidden_state + + if encoder_attention_mask is not None: + attn_mask = encoder_attention_mask.unsqueeze(1).to(dtype=torch.bool) # [B, 1, L] + else: + attn_mask = None + + attn_output, _ = self.cross_attn(q, kv, kv, key_padding_mask=attn_mask) + query = query + attn_output + query = query + self.dropout(self.mlp(self.norm2(query))) + return query + + +class LayerwiseQFormer(nn.Module): + def __init__( + self, input_hidden_dim=2048, output_hidden_dim=768, num_query_tokens=64, num_layers=37, num_heads=8, config=None + ): + super().__init__() + self.input_hidden_dim = input_hidden_dim + self.output_hidden_dim = output_hidden_dim + self.num_query_tokens = num_query_tokens + self.num_layers = num_layers + self.config = config + # Project input to output dimension + self.proj = nn.Linear(input_hidden_dim, output_hidden_dim) + # Learnable query tokens + self.query_tokens = nn.Parameter(torch.randn(num_query_tokens, output_hidden_dim)) + + # Independent cross-attention blocks (one per encoder layer) + self.layers = nn.ModuleList([CrossAttentionBlock(output_hidden_dim, num_heads) for _ in range(num_layers)]) + + def forward(self, hidden_states_list, encoder_attention_mask=None): + """ + Layer-wise Q-Former forward pass. + Args: + hidden_states_list (List[Tensor]): Length == num_layers. Each tensor is [B, L, Din], raw encoder layer outputs (before projection). + encoder_attention_mask (Tensor | None): Shape [B, L]. Same semantics as in CrossAttentionBlock. + Returns: + Tensor: Aggregated query tokens of shape [B, Q, Dout]. + Pipeline: + 1. Stack per-layer features to [B, N, L, Din] and linearly project to Dout. + 2. Expand global learnable query tokens to batch: [B, Q, Dout]. + 3. Apply cross-attention layer-by-layer: each query attends only to the corresponding encoder layer features. + Notes: + - Asserts len(hidden_states_list) == num_layers. + - Does not modify gradient flow of hidden_states_list. + """ + # hidden_states_list = self.scale_hook(hidden_states_list) + + assert ( + len(hidden_states_list) == self.num_layers + ), f"Expected {self.num_layers} layers, got {len(hidden_states_list)}" + + B = hidden_states_list[0].size(0) + # Project input hidden states to output dimension + # Result shape [B, N, L, Din] + hs = torch.stack(hidden_states_list, dim=1) + # proj_hs shape [B, N, L, Dout] + proj_hs = self.proj(hs) + # 3) Unbind back to list, each element restored to [B, L, Dout] + hidden_states_list = list(proj_hs.unbind(dim=1)) + + # Expand query tokens for each batch + query = self.query_tokens.unsqueeze(0).expand(B, -1, -1) # [B, Q, D] + + # Iterate through each layer and apply cross-attention + for i, layer in enumerate(self.layers): + query = layer(query, hidden_states_list[i], encoder_attention_mask) + + return query + + def scale_hook(self, hidden_states_list, scale_factor=0.1): + """ + (Experimental / optional) Register gradient scaling hooks on each layer's hidden states. + Args: + hidden_states_list (List[Tensor]): Per-layer feature tensors. + scale_factor (float): Gradient scaling factor (effective only if enabled via config and != 1). + Returns: + List[Tensor]: Original list (no data copy); hooks may be attached in-place. + Design: + - Currently returns immediately (guard condition hard-coded False) as a placeholder. + - Uses attribute _scaled_hook to avoid duplicate hook registration in distributed settings. + - Can be enabled later for gradient dampening or perturbation experiments. + Performance: + - Excessive hook registrations can hurt speed; kept lazy by default. + """ + # --- 1. Register gradient scaling hooks on input hidden_states_list --- + if ( + self.config + and hasattr(self.config.vla, "layer_qformer") + and hasattr(self.config.vla.layer_qformer, "grad_scale") + and self.config.vla.layer_qformer.grad_scale != 1 + ): + scale_factor = self.config.vla.layer_qformer.grad_scale + else: + return hidden_states_list # If grad_scale is not configured, return the original list + + scaled_hidden_states_list = [] + for hidden_states in hidden_states_list: + if hidden_states.requires_grad: + # Ensure gradient scaling is executed only once in distributed settings + if not hasattr(hidden_states, "_scaled_hook"): # Prevent duplicate registration --> Seems to accelerate + hook = lambda grad: grad * scale_factor + hidden_states.register_hook(hook) + hidden_states._scaled_hook = True # Mark as processed + scaled_hidden_states_list.append(hidden_states) + + return hidden_states_list + + +import torch +import torch.nn as nn + + +def get_layerwise_qformer(num_heads=8, config=None, **kwargs): + """ + Build a LayerwiseQFormer instance. + Args: + num_heads (int): Number of attention heads for CrossAttentionBlock. + config: Configuration object; must contain config.framework.layer_qformer with: + - qformer_start_layer / qformer_end_layer: range of layers (start inclusive, end exclusive). + - num_query_tokens: Number of learnable query tokens. + - input_dim: Input feature dimension (Din). + - ouptput_dim: Output feature dimension (Dout). + **kwargs: Reserved for future extensions (unused). + Returns: + LayerwiseQFormer: Instantiated model. + Notes: + - num_layers = end_layer - start_layer (half-open interval). + - Does not perform weight loading or device moves here. + """ + # dist.barrier() + qformer_cfg = config.framework.layer_qformer + num_layers = qformer_cfg.qformer_end_layer - qformer_cfg.qformer_start_layer if config else num_layers + num_query_tokens = qformer_cfg.num_query_tokens + input_hidden_dim = config.framework.layer_qformer.input_dim + output_hidden_dim = config.framework.layer_qformer.ouptput_dim + num_query_tokens = qformer_cfg.num_query_tokens + + qformer = LayerwiseQFormer( + input_hidden_dim=input_hidden_dim, + output_hidden_dim=output_hidden_dim, + num_query_tokens=num_query_tokens, + num_layers=num_layers, + num_heads=num_heads, + config=config, + ) + return qformer diff --git a/starVLA/model/modules/projector/__init__.py b/starVLA/model/modules/projector/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..139597f9cb07c5d48bed18984ec4747f4b4f3438 --- /dev/null +++ b/starVLA/model/modules/projector/__init__.py @@ -0,0 +1,2 @@ + + diff --git a/starVLA/model/modules/vlm/Florence2.py b/starVLA/model/modules/vlm/Florence2.py new file mode 100644 index 0000000000000000000000000000000000000000..d86ff25f35dacdd7b0425826cf86d327cc97a2fd --- /dev/null +++ b/starVLA/model/modules/vlm/Florence2.py @@ -0,0 +1,203 @@ +# Copyright 2025 starVLA community. All rights reserved. +# Licensed under the MIT License, Version 1.0 (the "License"); +# Implemented by [Jinhui YE / HKUST University] in [2025]. + +import torch +from typing import Optional, List +from transformers.modeling_outputs import CausalLMOutputWithPast +from typing import Dict, Optional, List +from typing import List, Union, Dict, Optional + + +import torch +from PIL import Image +from transformers import AutoProcessor, AutoModelForCausalLM + + +from accelerate.logging import get_logger + +logger = get_logger(__name__) + +# IGNORE_INDEX = -100 +# IMAGE_TOKEN_INDEX = 151655 +# VIDEO_TOKEN_INDEX = 151656 +# DEFAULT_IMAGE_TOKEN = "" +# DEFAULT_VIDEO_TOKEN = "