# Copyright 2025 NVIDIA Corp. and affiliates. All rights reserved. # Modified by [Jinhui YE/ HKUST] in [2026]. # 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 # 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): """ Layer-wise cross-attention DiT action head. NOTE on configuration boundary: This module is intentionally decoupled from any specific VLM backbone. It ONLY reads from ``global_config.framework.action_model`` (and its ``diffusion_model_cfg`` sub-tree). The framework (e.g. ``Qwen_PI`` / ``Qwen_PI_v3``) is responsible for populating ``diffusion_model_cfg`` with the correct DiT shape **before** calling ``get_action_model``: diffusion_model_cfg.num_layers = diffusion_model_cfg.input_embedding_dim =