sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
huggingface/diffusers:src/diffusers/models/transformers/consisid_transformer_3d.py
# Copyright 2025 ConsisID Authors and The HuggingFace Team. All rights reserved. # # 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 math from typing import Any import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...loaders import PeftAdapterMixin from ...utils import apply_lora_scale, logging from ...utils.torch_utils import maybe_allow_in_graph from ..attention import Attention, AttentionMixin, FeedForward from ..attention_processor import CogVideoXAttnProcessor2_0 from ..embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps from ..modeling_outputs import Transformer2DModelOutput from ..modeling_utils import ModelMixin from ..normalization import AdaLayerNorm, CogVideoXLayerNormZero logger = logging.get_logger(__name__) # pylint: disable=invalid-name class PerceiverAttention(nn.Module): def __init__(self, dim: int, dim_head: int = 64, heads: int = 8, kv_dim: int | None = None): super().__init__() self.scale = dim_head**-0.5 self.dim_head = dim_head self.heads = heads inner_dim = dim_head * heads self.norm1 = nn.LayerNorm(dim if kv_dim is None else kv_dim) self.norm2 = nn.LayerNorm(dim) self.to_q = nn.Linear(dim, inner_dim, bias=False) self.to_kv = nn.Linear(dim if kv_dim is None else kv_dim, inner_dim * 2, bias=False) self.to_out = nn.Linear(inner_dim, dim, bias=False) def forward(self, image_embeds: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: # Apply normalization image_embeds = self.norm1(image_embeds) latents = self.norm2(latents) batch_size, seq_len, _ = latents.shape # Get batch size and sequence length # Compute query, key, and value matrices query = self.to_q(latents) kv_input = torch.cat((image_embeds, latents), dim=-2) key, value = self.to_kv(kv_input).chunk(2, dim=-1) # Reshape the tensors for multi-head attention query = query.reshape(query.size(0), -1, self.heads, self.dim_head).transpose(1, 2) key = key.reshape(key.size(0), -1, self.heads, self.dim_head).transpose(1, 2) value = value.reshape(value.size(0), -1, self.heads, self.dim_head).transpose(1, 2) # attention scale = 1 / math.sqrt(math.sqrt(self.dim_head)) weight = (query * scale) @ (key * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) output = weight @ value # Reshape and return the final output output = output.permute(0, 2, 1, 3).reshape(batch_size, seq_len, -1) return self.to_out(output) class LocalFacialExtractor(nn.Module): def __init__( self, id_dim: int = 1280, vit_dim: int = 1024, depth: int = 10, dim_head: int = 64, heads: int = 16, num_id_token: int = 5, num_queries: int = 32, output_dim: int = 2048, ff_mult: int = 4, num_scale: int = 5, ): super().__init__() # Storing identity token and query information self.num_id_token = num_id_token self.vit_dim = vit_dim self.num_queries = num_queries assert depth % num_scale == 0 self.depth = depth // num_scale self.num_scale = num_scale scale = vit_dim**-0.5 # Learnable latent query embeddings self.latents = nn.Parameter(torch.randn(1, num_queries, vit_dim) * scale) # Projection layer to map the latent output to the desired dimension self.proj_out = nn.Parameter(scale * torch.randn(vit_dim, output_dim)) # Attention and ConsisIDFeedForward layer stack self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append( nn.ModuleList( [ PerceiverAttention(dim=vit_dim, dim_head=dim_head, heads=heads), # Perceiver Attention layer nn.Sequential( nn.LayerNorm(vit_dim), nn.Linear(vit_dim, vit_dim * ff_mult, bias=False), nn.GELU(), nn.Linear(vit_dim * ff_mult, vit_dim, bias=False), ), # ConsisIDFeedForward layer ] ) ) # Mappings for each of the 5 different ViT features for i in range(num_scale): setattr( self, f"mapping_{i}", nn.Sequential( nn.Linear(vit_dim, vit_dim), nn.LayerNorm(vit_dim), nn.LeakyReLU(), nn.Linear(vit_dim, vit_dim), nn.LayerNorm(vit_dim), nn.LeakyReLU(), nn.Linear(vit_dim, vit_dim), ), ) # Mapping for identity embedding vectors self.id_embedding_mapping = nn.Sequential( nn.Linear(id_dim, vit_dim), nn.LayerNorm(vit_dim), nn.LeakyReLU(), nn.Linear(vit_dim, vit_dim), nn.LayerNorm(vit_dim), nn.LeakyReLU(), nn.Linear(vit_dim, vit_dim * num_id_token), ) def forward(self, id_embeds: torch.Tensor, vit_hidden_states: list[torch.Tensor]) -> torch.Tensor: # Repeat latent queries for the batch size latents = self.latents.repeat(id_embeds.size(0), 1, 1) # Map the identity embedding to tokens id_embeds = self.id_embedding_mapping(id_embeds) id_embeds = id_embeds.reshape(-1, self.num_id_token, self.vit_dim) # Concatenate identity tokens with the latent queries latents = torch.cat((latents, id_embeds), dim=1) # Process each of the num_scale visual feature inputs for i in range(self.num_scale): vit_feature = getattr(self, f"mapping_{i}")(vit_hidden_states[i]) ctx_feature = torch.cat((id_embeds, vit_feature), dim=1) # Pass through the PerceiverAttention and ConsisIDFeedForward layers for attn, ff in self.layers[i * self.depth : (i + 1) * self.depth]: latents = attn(ctx_feature, latents) + latents latents = ff(latents) + latents # Retain only the query latents latents = latents[:, : self.num_queries] # Project the latents to the output dimension latents = latents @ self.proj_out return latents class PerceiverCrossAttention(nn.Module): def __init__(self, dim: int = 3072, dim_head: int = 128, heads: int = 16, kv_dim: int = 2048): super().__init__() self.scale = dim_head**-0.5 self.dim_head = dim_head self.heads = heads inner_dim = dim_head * heads # Layer normalization to stabilize training self.norm1 = nn.LayerNorm(dim if kv_dim is None else kv_dim) self.norm2 = nn.LayerNorm(dim) # Linear transformations to produce queries, keys, and values self.to_q = nn.Linear(dim, inner_dim, bias=False) self.to_kv = nn.Linear(dim if kv_dim is None else kv_dim, inner_dim * 2, bias=False) self.to_out = nn.Linear(inner_dim, dim, bias=False) def forward(self, image_embeds: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor: # Apply layer normalization to the input image and latent features image_embeds = self.norm1(image_embeds) hidden_states = self.norm2(hidden_states) batch_size, seq_len, _ = hidden_states.shape # Compute queries, keys, and values query = self.to_q(hidden_states) key, value = self.to_kv(image_embeds).chunk(2, dim=-1) # Reshape tensors to split into attention heads query = query.reshape(query.size(0), -1, self.heads, self.dim_head).transpose(1, 2) key = key.reshape(key.size(0), -1, self.heads, self.dim_head).transpose(1, 2) value = value.reshape(value.size(0), -1, self.heads, self.dim_head).transpose(1, 2) # Compute attention weights scale = 1 / math.sqrt(math.sqrt(self.dim_head)) weight = (query * scale) @ (key * scale).transpose(-2, -1) # More stable scaling than post-division weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) # Compute the output via weighted combination of values out = weight @ value # Reshape and permute to prepare for final linear transformation out = out.permute(0, 2, 1, 3).reshape(batch_size, seq_len, -1) return self.to_out(out) @maybe_allow_in_graph class ConsisIDBlock(nn.Module): r""" Transformer block used in [ConsisID](https://github.com/PKU-YuanGroup/ConsisID) model. Parameters: dim (`int`): The number of channels in the input and output. num_attention_heads (`int`): The number of heads to use for multi-head attention. attention_head_dim (`int`): The number of channels in each head. time_embed_dim (`int`): The number of channels in timestep embedding. dropout (`float`, defaults to `0.0`): The dropout probability to use. activation_fn (`str`, defaults to `"gelu-approximate"`): Activation function to be used in feed-forward. attention_bias (`bool`, defaults to `False`): Whether or not to use bias in attention projection layers. qk_norm (`bool`, defaults to `True`): Whether or not to use normalization after query and key projections in Attention. norm_elementwise_affine (`bool`, defaults to `True`): Whether to use learnable elementwise affine parameters for normalization. norm_eps (`float`, defaults to `1e-5`): Epsilon value for normalization layers. final_dropout (`bool` defaults to `False`): Whether to apply a final dropout after the last feed-forward layer. ff_inner_dim (`int`, *optional*, defaults to `None`): Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used. ff_bias (`bool`, defaults to `True`): Whether or not to use bias in Feed-forward layer. attention_out_bias (`bool`, defaults to `True`): Whether or not to use bias in Attention output projection layer. """ def __init__( self, dim: int, num_attention_heads: int, attention_head_dim: int, time_embed_dim: int, dropout: float = 0.0, activation_fn: str = "gelu-approximate", attention_bias: bool = False, qk_norm: bool = True, norm_elementwise_affine: bool = True, norm_eps: float = 1e-5, final_dropout: bool = True, ff_inner_dim: int | None = None, ff_bias: bool = True, attention_out_bias: bool = True, ): super().__init__() # 1. Self Attention self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True) self.attn1 = Attention( query_dim=dim, dim_head=attention_head_dim, heads=num_attention_heads, qk_norm="layer_norm" if qk_norm else None, eps=1e-6, bias=attention_bias, out_bias=attention_out_bias, processor=CogVideoXAttnProcessor2_0(), ) # 2. Feed Forward self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True) self.ff = FeedForward( dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout, inner_dim=ff_inner_dim, bias=ff_bias, ) def forward( self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor, image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: text_seq_length = encoder_hidden_states.size(1) # norm & modulate norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1( hidden_states, encoder_hidden_states, temb ) # attention attn_hidden_states, attn_encoder_hidden_states = self.attn1( hidden_states=norm_hidden_states, encoder_hidden_states=norm_encoder_hidden_states, image_rotary_emb=image_rotary_emb, ) hidden_states = hidden_states + gate_msa * attn_hidden_states encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states # norm & modulate norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2( hidden_states, encoder_hidden_states, temb ) # feed-forward norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1) ff_output = self.ff(norm_hidden_states) hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:] encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length] return hidden_states, encoder_hidden_states class ConsisIDTransformer3DModel(ModelMixin, AttentionMixin, ConfigMixin, PeftAdapterMixin): """ A Transformer model for video-like data in [ConsisID](https://github.com/PKU-YuanGroup/ConsisID). Parameters: num_attention_heads (`int`, defaults to `30`): The number of heads to use for multi-head attention. attention_head_dim (`int`, defaults to `64`): The number of channels in each head. in_channels (`int`, defaults to `16`): The number of channels in the input. out_channels (`int`, *optional*, defaults to `16`): The number of channels in the output. flip_sin_to_cos (`bool`, defaults to `True`): Whether to flip the sin to cos in the time embedding. time_embed_dim (`int`, defaults to `512`): Output dimension of timestep embeddings. text_embed_dim (`int`, defaults to `4096`): Input dimension of text embeddings from the text encoder. num_layers (`int`, defaults to `30`): The number of layers of Transformer blocks to use. dropout (`float`, defaults to `0.0`): The dropout probability to use. attention_bias (`bool`, defaults to `True`): Whether to use bias in the attention projection layers. sample_width (`int`, defaults to `90`): The width of the input latents. sample_height (`int`, defaults to `60`): The height of the input latents. sample_frames (`int`, defaults to `49`): The number of frames in the input latents. Note that this parameter was incorrectly initialized to 49 instead of 13 because ConsisID processed 13 latent frames at once in its default and recommended settings, but cannot be changed to the correct value to ensure backwards compatibility. To create a transformer with K latent frames, the correct value to pass here would be: ((K - 1) * temporal_compression_ratio + 1). patch_size (`int`, defaults to `2`): The size of the patches to use in the patch embedding layer. temporal_compression_ratio (`int`, defaults to `4`): The compression ratio across the temporal dimension. See documentation for `sample_frames`. max_text_seq_length (`int`, defaults to `226`): The maximum sequence length of the input text embeddings. activation_fn (`str`, defaults to `"gelu-approximate"`): Activation function to use in feed-forward. timestep_activation_fn (`str`, defaults to `"silu"`): Activation function to use when generating the timestep embeddings. norm_elementwise_affine (`bool`, defaults to `True`): Whether to use elementwise affine in normalization layers. norm_eps (`float`, defaults to `1e-5`): The epsilon value to use in normalization layers. spatial_interpolation_scale (`float`, defaults to `1.875`): Scaling factor to apply in 3D positional embeddings across spatial dimensions. temporal_interpolation_scale (`float`, defaults to `1.0`): Scaling factor to apply in 3D positional embeddings across temporal dimensions. is_train_face (`bool`, defaults to `False`): Whether to use enable the identity-preserving module during the training process. When set to `True`, the model will focus on identity-preserving tasks. is_kps (`bool`, defaults to `False`): Whether to enable keypoint for global facial extractor. If `True`, keypoints will be in the model. cross_attn_interval (`int`, defaults to `2`): The interval between cross-attention layers in the Transformer architecture. A larger value may reduce the frequency of cross-attention computations, which can help reduce computational overhead. cross_attn_dim_head (`int`, optional, defaults to `128`): The dimensionality of each attention head in the cross-attention layers of the Transformer architecture. A larger value increases the capacity to attend to more complex patterns, but also increases memory and computation costs. cross_attn_num_heads (`int`, optional, defaults to `16`): The number of attention heads in the cross-attention layers. More heads allow for more parallel attention mechanisms, capturing diverse relationships between different components of the input, but can also increase computational requirements. LFE_id_dim (`int`, optional, defaults to `1280`): The dimensionality of the identity vector used in the Local Facial Extractor (LFE). This vector represents the identity features of a face, which are important for tasks like face recognition and identity preservation across different frames. LFE_vit_dim (`int`, optional, defaults to `1024`): The dimension of the vision transformer (ViT) output used in the Local Facial Extractor (LFE). This value dictates the size of the transformer-generated feature vectors that will be processed for facial feature extraction. LFE_depth (`int`, optional, defaults to `10`): The number of layers in the Local Facial Extractor (LFE). Increasing the depth allows the model to capture more complex representations of facial features, but also increases the computational load. LFE_dim_head (`int`, optional, defaults to `64`): The dimensionality of each attention head in the Local Facial Extractor (LFE). This parameter affects how finely the model can process and focus on different parts of the facial features during the extraction process. LFE_num_heads (`int`, optional, defaults to `16`): The number of attention heads in the Local Facial Extractor (LFE). More heads can improve the model's ability to capture diverse facial features, but at the cost of increased computational complexity. LFE_num_id_token (`int`, optional, defaults to `5`): The number of identity tokens used in the Local Facial Extractor (LFE). This defines how many identity-related tokens the model will process to ensure face identity preservation during feature extraction. LFE_num_querie (`int`, optional, defaults to `32`): The number of query tokens used in the Local Facial Extractor (LFE). These tokens are used to capture high-frequency face-related information that aids in accurate facial feature extraction. LFE_output_dim (`int`, optional, defaults to `2048`): The output dimension of the Local Facial Extractor (LFE). This dimension determines the size of the feature vectors produced by the LFE module, which will be used for subsequent tasks such as face recognition or tracking. LFE_ff_mult (`int`, optional, defaults to `4`): The multiplication factor applied to the feed-forward network's hidden layer size in the Local Facial Extractor (LFE). A higher value increases the model's capacity to learn more complex facial feature transformations, but also increases the computation and memory requirements. LFE_num_scale (`int`, optional, defaults to `5`): The number of different scales visual feature. A higher value increases the model's capacity to learn more complex facial feature transformations, but also increases the computation and memory requirements. local_face_scale (`float`, defaults to `1.0`): A scaling factor used to adjust the importance of local facial features in the model. This can influence how strongly the model focuses on high frequency face-related content. """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, num_attention_heads: int = 30, attention_head_dim: int = 64, in_channels: int = 16, out_channels: int | None = 16, flip_sin_to_cos: bool = True, freq_shift: int = 0, time_embed_dim: int = 512, text_embed_dim: int = 4096, num_layers: int = 30, dropout: float = 0.0, attention_bias: bool = True, sample_width: int = 90, sample_height: int = 60, sample_frames: int = 49, patch_size: int = 2, temporal_compression_ratio: int = 4, max_text_seq_length: int = 226, activation_fn: str = "gelu-approximate", timestep_activation_fn: str = "silu", norm_elementwise_affine: bool = True, norm_eps: float = 1e-5, spatial_interpolation_scale: float = 1.875, temporal_interpolation_scale: float = 1.0, use_rotary_positional_embeddings: bool = False, use_learned_positional_embeddings: bool = False, is_train_face: bool = False, is_kps: bool = False, cross_attn_interval: int = 2, cross_attn_dim_head: int = 128, cross_attn_num_heads: int = 16, LFE_id_dim: int = 1280, LFE_vit_dim: int = 1024, LFE_depth: int = 10, LFE_dim_head: int = 64, LFE_num_heads: int = 16, LFE_num_id_token: int = 5, LFE_num_querie: int = 32, LFE_output_dim: int = 2048, LFE_ff_mult: int = 4, LFE_num_scale: int = 5, local_face_scale: float = 1.0, ): super().__init__() inner_dim = num_attention_heads * attention_head_dim if not use_rotary_positional_embeddings and use_learned_positional_embeddings: raise ValueError( "There are no ConsisID checkpoints available with disable rotary embeddings and learned positional " "embeddings. If you're using a custom model and/or believe this should be supported, please open an " "issue at https://github.com/huggingface/diffusers/issues." ) # 1. Patch embedding self.patch_embed = CogVideoXPatchEmbed( patch_size=patch_size, in_channels=in_channels, embed_dim=inner_dim, text_embed_dim=text_embed_dim, bias=True, sample_width=sample_width, sample_height=sample_height, sample_frames=sample_frames, temporal_compression_ratio=temporal_compression_ratio, max_text_seq_length=max_text_seq_length, spatial_interpolation_scale=spatial_interpolation_scale, temporal_interpolation_scale=temporal_interpolation_scale, use_positional_embeddings=not use_rotary_positional_embeddings, use_learned_positional_embeddings=use_learned_positional_embeddings, ) self.embedding_dropout = nn.Dropout(dropout) # 2. Time embeddings self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift) self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn) # 3. Define spatio-temporal transformers blocks self.transformer_blocks = nn.ModuleList( [ ConsisIDBlock( dim=inner_dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, time_embed_dim=time_embed_dim, dropout=dropout, activation_fn=activation_fn, attention_bias=attention_bias, norm_elementwise_affine=norm_elementwise_affine, norm_eps=norm_eps, ) for _ in range(num_layers) ] ) self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine) # 4. Output blocks self.norm_out = AdaLayerNorm( embedding_dim=time_embed_dim, output_dim=2 * inner_dim, norm_elementwise_affine=norm_elementwise_affine, norm_eps=norm_eps, chunk_dim=1, ) self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels) self.is_train_face = is_train_face self.is_kps = is_kps # 5. Define identity-preserving config if is_train_face: # LFE configs self.LFE_id_dim = LFE_id_dim self.LFE_vit_dim = LFE_vit_dim self.LFE_depth = LFE_depth self.LFE_dim_head = LFE_dim_head self.LFE_num_heads = LFE_num_heads self.LFE_num_id_token = LFE_num_id_token self.LFE_num_querie = LFE_num_querie self.LFE_output_dim = LFE_output_dim self.LFE_ff_mult = LFE_ff_mult self.LFE_num_scale = LFE_num_scale # cross configs self.inner_dim = inner_dim self.cross_attn_interval = cross_attn_interval self.num_cross_attn = num_layers // cross_attn_interval self.cross_attn_dim_head = cross_attn_dim_head self.cross_attn_num_heads = cross_attn_num_heads self.cross_attn_kv_dim = int(self.inner_dim / 3 * 2) self.local_face_scale = local_face_scale # face modules self._init_face_inputs() self.gradient_checkpointing = False def _init_face_inputs(self): self.local_facial_extractor = LocalFacialExtractor( id_dim=self.LFE_id_dim, vit_dim=self.LFE_vit_dim, depth=self.LFE_depth, dim_head=self.LFE_dim_head, heads=self.LFE_num_heads, num_id_token=self.LFE_num_id_token, num_queries=self.LFE_num_querie, output_dim=self.LFE_output_dim, ff_mult=self.LFE_ff_mult, num_scale=self.LFE_num_scale, ) self.perceiver_cross_attention = nn.ModuleList( [ PerceiverCrossAttention( dim=self.inner_dim, dim_head=self.cross_attn_dim_head, heads=self.cross_attn_num_heads, kv_dim=self.cross_attn_kv_dim, ) for _ in range(self.num_cross_attn) ] ) @apply_lora_scale("attention_kwargs") def forward( self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, timestep: int | float | torch.LongTensor, timestep_cond: torch.Tensor | None = None, image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None, attention_kwargs: dict[str, Any] | None = None, id_cond: torch.Tensor | None = None, id_vit_hidden: torch.Tensor | None = None, return_dict: bool = True, ) -> tuple[torch.Tensor] | Transformer2DModelOutput: # fuse clip and insightface valid_face_emb = None if self.is_train_face: id_cond = id_cond.to(device=hidden_states.device, dtype=hidden_states.dtype) id_vit_hidden = [ tensor.to(device=hidden_states.device, dtype=hidden_states.dtype) for tensor in id_vit_hidden ] valid_face_emb = self.local_facial_extractor( id_cond, id_vit_hidden ) # torch.Size([1, 1280]), list[5](torch.Size([1, 577, 1024])) -> torch.Size([1, 32, 2048]) batch_size, num_frames, channels, height, width = hidden_states.shape # 1. Time embedding timesteps = timestep t_emb = self.time_proj(timesteps) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might actually be running in fp16. so we need to cast here. # there might be better ways to encapsulate this. t_emb = t_emb.to(dtype=hidden_states.dtype) emb = self.time_embedding(t_emb, timestep_cond) # 2. Patch embedding # torch.Size([1, 226, 4096]) torch.Size([1, 13, 32, 60, 90]) hidden_states = self.patch_embed(encoder_hidden_states, hidden_states) # torch.Size([1, 17776, 3072]) hidden_states = self.embedding_dropout(hidden_states) # torch.Size([1, 17776, 3072]) text_seq_length = encoder_hidden_states.shape[1] encoder_hidden_states = hidden_states[:, :text_seq_length] # torch.Size([1, 226, 3072]) hidden_states = hidden_states[:, text_seq_length:] # torch.Size([1, 17550, 3072]) # 3. Transformer blocks ca_idx = 0 for i, block in enumerate(self.transformer_blocks): if torch.is_grad_enabled() and self.gradient_checkpointing: hidden_states, encoder_hidden_states = self._gradient_checkpointing_func( block, hidden_states, encoder_hidden_states, emb, image_rotary_emb, ) else: hidden_states, encoder_hidden_states = block( hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=emb, image_rotary_emb=image_rotary_emb, ) if self.is_train_face: if i % self.cross_attn_interval == 0 and valid_face_emb is not None: hidden_states = hidden_states + self.local_face_scale * self.perceiver_cross_attention[ca_idx]( valid_face_emb, hidden_states ) # torch.Size([2, 32, 2048]) torch.Size([2, 17550, 3072]) ca_idx += 1 hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1) hidden_states = self.norm_final(hidden_states) hidden_states = hidden_states[:, text_seq_length:] # 4. Final block hidden_states = self.norm_out(hidden_states, temb=emb) hidden_states = self.proj_out(hidden_states) # 5. Unpatchify # Note: we use `-1` instead of `channels`: # - It is okay to `channels` use for ConsisID (number of input channels is equal to output channels) p = self.config.patch_size output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p) output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4) if not return_dict: return (output,) return Transformer2DModelOutput(sample=output)
{ "repo_id": "huggingface/diffusers", "file_path": "src/diffusers/models/transformers/consisid_transformer_3d.py", "license": "Apache License 2.0", "lines": 626, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/diffusers:src/diffusers/pipelines/consisid/consisid_utils.py
import importlib.util import os import cv2 import numpy as np import torch from PIL import Image, ImageOps from torchvision.transforms import InterpolationMode from torchvision.transforms.functional import normalize, resize from ...utils import get_logger, load_image logger = get_logger(__name__) _insightface_available = importlib.util.find_spec("insightface") is not None _consisid_eva_clip_available = importlib.util.find_spec("consisid_eva_clip") is not None _facexlib_available = importlib.util.find_spec("facexlib") is not None if _insightface_available: import insightface from insightface.app import FaceAnalysis else: raise ImportError("insightface is not available. Please install it using 'pip install insightface'.") if _consisid_eva_clip_available: from consisid_eva_clip import create_model_and_transforms from consisid_eva_clip.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD else: raise ImportError("consisid_eva_clip is not available. Please install it using 'pip install consisid_eva_clip'.") if _facexlib_available: from facexlib.parsing import init_parsing_model from facexlib.utils.face_restoration_helper import FaceRestoreHelper else: raise ImportError("facexlib is not available. Please install it using 'pip install facexlib'.") def resize_numpy_image_long(image, resize_long_edge=768): """ Resize the input image to a specified long edge while maintaining aspect ratio. Args: image (numpy.ndarray): Input image (H x W x C or H x W). resize_long_edge (int): The target size for the long edge of the image. Default is 768. Returns: numpy.ndarray: Resized image with the long edge matching `resize_long_edge`, while maintaining the aspect ratio. """ h, w = image.shape[:2] if max(h, w) <= resize_long_edge: return image k = resize_long_edge / max(h, w) h = int(h * k) w = int(w * k) image = cv2.resize(image, (w, h), interpolation=cv2.INTER_LANCZOS4) return image def img2tensor(imgs, bgr2rgb=True, float32=True): """Numpy array to tensor. Args: imgs (list[ndarray] | ndarray): Input images. bgr2rgb (bool): Whether to change bgr to rgb. float32 (bool): Whether to change to float32. Returns: list[tensor] | tensor: Tensor images. If returned results only have one element, just return tensor. """ def _totensor(img, bgr2rgb, float32): if img.shape[2] == 3 and bgr2rgb: if img.dtype == "float64": img = img.astype("float32") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = torch.from_numpy(img.transpose(2, 0, 1)) if float32: img = img.float() return img if isinstance(imgs, list): return [_totensor(img, bgr2rgb, float32) for img in imgs] return _totensor(imgs, bgr2rgb, float32) def to_gray(img): """ Converts an RGB image to grayscale by applying the standard luminosity formula. Args: img (torch.Tensor): The input image tensor with shape (batch_size, channels, height, width). The image is expected to be in RGB format (3 channels). Returns: torch.Tensor: The grayscale image tensor with shape (batch_size, 3, height, width). The grayscale values are replicated across all three channels. """ x = 0.299 * img[:, 0:1] + 0.587 * img[:, 1:2] + 0.114 * img[:, 2:3] x = x.repeat(1, 3, 1, 1) return x def process_face_embeddings( face_helper_1, clip_vision_model, face_helper_2, eva_transform_mean, eva_transform_std, app, device, weight_dtype, image, original_id_image=None, is_align_face=True, ): """ Process face embeddings from an image, extracting relevant features such as face embeddings, landmarks, and parsed face features using a series of face detection and alignment tools. Args: face_helper_1: Face helper object (first helper) for alignment and landmark detection. clip_vision_model: Pre-trained CLIP vision model used for feature extraction. face_helper_2: Face helper object (second helper) for embedding extraction. eva_transform_mean: Mean values for image normalization before passing to EVA model. eva_transform_std: Standard deviation values for image normalization before passing to EVA model. app: Application instance used for face detection. device: Device (CPU or GPU) where the computations will be performed. weight_dtype: Data type of the weights for precision (e.g., `torch.float32`). image: Input image in RGB format with pixel values in the range [0, 255]. original_id_image: (Optional) Original image for feature extraction if `is_align_face` is False. is_align_face: Boolean flag indicating whether face alignment should be performed. Returns: tuple: - id_cond: Concatenated tensor of Ante face embedding and CLIP vision embedding - id_vit_hidden: Hidden state of the CLIP vision model, a list of tensors. - return_face_features_image_2: Processed face features image after normalization and parsing. - face_kps: Keypoints of the face detected in the image. """ face_helper_1.clean_all() image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # get antelopev2 embedding face_info = app.get(image_bgr) if len(face_info) > 0: face_info = sorted(face_info, key=lambda x: (x["bbox"][2] - x["bbox"][0]) * (x["bbox"][3] - x["bbox"][1]))[ -1 ] # only use the maximum face id_ante_embedding = face_info["embedding"] # (512,) face_kps = face_info["kps"] else: id_ante_embedding = None face_kps = None # using facexlib to detect and align face face_helper_1.read_image(image_bgr) face_helper_1.get_face_landmarks_5(only_center_face=True) if face_kps is None: face_kps = face_helper_1.all_landmarks_5[0] face_helper_1.align_warp_face() if len(face_helper_1.cropped_faces) == 0: raise RuntimeError("facexlib align face fail") align_face = face_helper_1.cropped_faces[0] # (512, 512, 3) # RGB # in case insightface didn't detect face if id_ante_embedding is None: logger.warning("Failed to detect face using insightface. Extracting embedding with align face") id_ante_embedding = face_helper_2.get_feat(align_face) id_ante_embedding = torch.from_numpy(id_ante_embedding).to(device, weight_dtype) # torch.Size([512]) if id_ante_embedding.ndim == 1: id_ante_embedding = id_ante_embedding.unsqueeze(0) # torch.Size([1, 512]) # parsing if is_align_face: input = img2tensor(align_face, bgr2rgb=True).unsqueeze(0) / 255.0 # torch.Size([1, 3, 512, 512]) input = input.to(device) parsing_out = face_helper_1.face_parse(normalize(input, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))[0] parsing_out = parsing_out.argmax(dim=1, keepdim=True) # torch.Size([1, 1, 512, 512]) bg_label = [0, 16, 18, 7, 8, 9, 14, 15] bg = sum(parsing_out == i for i in bg_label).bool() white_image = torch.ones_like(input) # torch.Size([1, 3, 512, 512]) # only keep the face features return_face_features_image = torch.where(bg, white_image, to_gray(input)) # torch.Size([1, 3, 512, 512]) return_face_features_image_2 = torch.where(bg, white_image, input) # torch.Size([1, 3, 512, 512]) else: original_image_bgr = cv2.cvtColor(original_id_image, cv2.COLOR_RGB2BGR) input = img2tensor(original_image_bgr, bgr2rgb=True).unsqueeze(0) / 255.0 # torch.Size([1, 3, 512, 512]) input = input.to(device) return_face_features_image = return_face_features_image_2 = input # transform img before sending to eva-clip-vit face_features_image = resize( return_face_features_image, clip_vision_model.image_size, InterpolationMode.BICUBIC ) # torch.Size([1, 3, 336, 336]) face_features_image = normalize(face_features_image, eva_transform_mean, eva_transform_std) id_cond_vit, id_vit_hidden = clip_vision_model( face_features_image.to(weight_dtype), return_all_features=False, return_hidden=True, shuffle=False ) # torch.Size([1, 768]), list(torch.Size([1, 577, 1024])) id_cond_vit_norm = torch.norm(id_cond_vit, 2, 1, True) id_cond_vit = torch.div(id_cond_vit, id_cond_vit_norm) id_cond = torch.cat( [id_ante_embedding, id_cond_vit], dim=-1 ) # torch.Size([1, 512]), torch.Size([1, 768]) -> torch.Size([1, 1280]) return ( id_cond, id_vit_hidden, return_face_features_image_2, face_kps, ) # torch.Size([1, 1280]), list(torch.Size([1, 577, 1024])) def process_face_embeddings_infer( face_helper_1, clip_vision_model, face_helper_2, eva_transform_mean, eva_transform_std, app, device, weight_dtype, img_file_path, is_align_face=True, ): """ Process face embeddings from an input image for inference, including alignment, feature extraction, and embedding concatenation. Args: face_helper_1: Face helper object (first helper) for alignment and landmark detection. clip_vision_model: Pre-trained CLIP vision model used for feature extraction. face_helper_2: Face helper object (second helper) for embedding extraction. eva_transform_mean: Mean values for image normalization before passing to EVA model. eva_transform_std: Standard deviation values for image normalization before passing to EVA model. app: Application instance used for face detection. device: Device (CPU or GPU) where the computations will be performed. weight_dtype: Data type of the weights for precision (e.g., `torch.float32`). img_file_path: Path to the input image file (string) or a numpy array representing an image. is_align_face: Boolean flag indicating whether face alignment should be performed (default: True). Returns: tuple: - id_cond: Concatenated tensor of Ante face embedding and CLIP vision embedding. - id_vit_hidden: Hidden state of the CLIP vision model, a list of tensors. - image: Processed face image after feature extraction and alignment. - face_kps: Keypoints of the face detected in the image. """ # Load and preprocess the input image if isinstance(img_file_path, str): image = np.array(load_image(image=img_file_path).convert("RGB")) else: image = np.array(ImageOps.exif_transpose(Image.fromarray(img_file_path)).convert("RGB")) # Resize image to ensure the longer side is 1024 pixels image = resize_numpy_image_long(image, 1024) original_id_image = image # Process the image to extract face embeddings and related features id_cond, id_vit_hidden, align_crop_face_image, face_kps = process_face_embeddings( face_helper_1, clip_vision_model, face_helper_2, eva_transform_mean, eva_transform_std, app, device, weight_dtype, image, original_id_image, is_align_face, ) # Convert the aligned cropped face image (torch tensor) to a numpy array tensor = align_crop_face_image.cpu().detach() tensor = tensor.squeeze() tensor = tensor.permute(1, 2, 0) tensor = tensor.numpy() * 255 tensor = tensor.astype(np.uint8) image = ImageOps.exif_transpose(Image.fromarray(tensor)) return id_cond, id_vit_hidden, image, face_kps def prepare_face_models(model_path, device, dtype): """ Prepare all face models for the facial recognition task. Parameters: - model_path: Path to the directory containing model files. - device: The device (e.g., 'cuda', 'xpu', 'cpu') where models will be loaded. - dtype: Data type (e.g., torch.float32) for model inference. Returns: - face_helper_1: First face restoration helper. - face_helper_2: Second face restoration helper. - face_clip_model: CLIP model for face extraction. - eva_transform_mean: Mean value for image normalization. - eva_transform_std: Standard deviation value for image normalization. - face_main_model: Main face analysis model. """ # get helper model face_helper_1 = FaceRestoreHelper( upscale_factor=1, face_size=512, crop_ratio=(1, 1), det_model="retinaface_resnet50", save_ext="png", device=device, model_rootpath=os.path.join(model_path, "face_encoder"), ) face_helper_1.face_parse = None face_helper_1.face_parse = init_parsing_model( model_name="bisenet", device=device, model_rootpath=os.path.join(model_path, "face_encoder") ) face_helper_2 = insightface.model_zoo.get_model( f"{model_path}/face_encoder/models/antelopev2/glintr100.onnx", providers=["CUDAExecutionProvider"] ) face_helper_2.prepare(ctx_id=0) # get local facial extractor part 1 model, _, _ = create_model_and_transforms( "EVA02-CLIP-L-14-336", os.path.join(model_path, "face_encoder", "EVA02_CLIP_L_336_psz14_s6B.pt"), force_custom_clip=True, ) face_clip_model = model.visual eva_transform_mean = getattr(face_clip_model, "image_mean", OPENAI_DATASET_MEAN) eva_transform_std = getattr(face_clip_model, "image_std", OPENAI_DATASET_STD) if not isinstance(eva_transform_mean, (list, tuple)): eva_transform_mean = (eva_transform_mean,) * 3 if not isinstance(eva_transform_std, (list, tuple)): eva_transform_std = (eva_transform_std,) * 3 eva_transform_mean = eva_transform_mean eva_transform_std = eva_transform_std # get local facial extractor part 2 face_main_model = FaceAnalysis( name="antelopev2", root=os.path.join(model_path, "face_encoder"), providers=["CUDAExecutionProvider"] ) face_main_model.prepare(ctx_id=0, det_size=(640, 640)) # move face models to device face_helper_1.face_det.eval() face_helper_1.face_parse.eval() face_clip_model.eval() face_helper_1.face_det.to(device) face_helper_1.face_parse.to(device) face_clip_model.to(device, dtype=dtype) return face_helper_1, face_helper_2, face_clip_model, face_main_model, eva_transform_mean, eva_transform_std
{ "repo_id": "huggingface/diffusers", "file_path": "src/diffusers/pipelines/consisid/consisid_utils.py", "license": "Apache License 2.0", "lines": 305, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
huggingface/diffusers:src/diffusers/pipelines/consisid/pipeline_consisid.py
# Copyright 2025 ConsisID Authors and The HuggingFace Team. All rights reserved. # # 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 inspect import math from typing import Any, Callable import numpy as np import PIL import torch from transformers import T5EncoderModel, T5Tokenizer from ...callbacks import MultiPipelineCallbacks, PipelineCallback from ...image_processor import PipelineImageInput from ...loaders import CogVideoXLoraLoaderMixin from ...models import AutoencoderKLCogVideoX, ConsisIDTransformer3DModel from ...models.embeddings import get_3d_rotary_pos_embed from ...pipelines.pipeline_utils import DiffusionPipeline from ...schedulers import CogVideoXDPMScheduler from ...utils import is_opencv_available, logging, replace_example_docstring from ...utils.torch_utils import randn_tensor from ...video_processor import VideoProcessor from .pipeline_output import ConsisIDPipelineOutput if is_opencv_available(): import cv2 logger = logging.get_logger(__name__) # pylint: disable=invalid-name EXAMPLE_DOC_STRING = """ Examples: ```python >>> import torch >>> from diffusers import ConsisIDPipeline >>> from diffusers.pipelines.consisid.consisid_utils import prepare_face_models, process_face_embeddings_infer >>> from diffusers.utils import export_to_video >>> from huggingface_hub import snapshot_download >>> snapshot_download(repo_id="BestWishYsh/ConsisID-preview", local_dir="BestWishYsh/ConsisID-preview") >>> ( ... face_helper_1, ... face_helper_2, ... face_clip_model, ... face_main_model, ... eva_transform_mean, ... eva_transform_std, ... ) = prepare_face_models("BestWishYsh/ConsisID-preview", device="cuda", dtype=torch.bfloat16) >>> pipe = ConsisIDPipeline.from_pretrained("BestWishYsh/ConsisID-preview", torch_dtype=torch.bfloat16) >>> pipe.to("cuda") >>> # ConsisID works well with long and well-described prompts. Make sure the face in the image is clearly visible (e.g., preferably half-body or full-body). >>> prompt = "The video captures a boy walking along a city street, filmed in black and white on a classic 35mm camera. His expression is thoughtful, his brow slightly furrowed as if he's lost in contemplation. The film grain adds a textured, timeless quality to the image, evoking a sense of nostalgia. Around him, the cityscape is filled with vintage buildings, cobblestone sidewalks, and softly blurred figures passing by, their outlines faint and indistinct. Streetlights cast a gentle glow, while shadows play across the boy's path, adding depth to the scene. The lighting highlights the boy's subtle smile, hinting at a fleeting moment of curiosity. The overall cinematic atmosphere, complete with classic film still aesthetics and dramatic contrasts, gives the scene an evocative and introspective feel." >>> image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_input.png?download=true" >>> id_cond, id_vit_hidden, image, face_kps = process_face_embeddings_infer( ... face_helper_1, ... face_clip_model, ... face_helper_2, ... eva_transform_mean, ... eva_transform_std, ... face_main_model, ... "cuda", ... torch.bfloat16, ... image, ... is_align_face=True, ... ) >>> video = pipe( ... image=image, ... prompt=prompt, ... num_inference_steps=50, ... guidance_scale=6.0, ... use_dynamic_cfg=False, ... id_vit_hidden=id_vit_hidden, ... id_cond=id_cond, ... kps_cond=face_kps, ... generator=torch.Generator("cuda").manual_seed(42), ... ) >>> export_to_video(video.frames[0], "output.mp4", fps=8) ``` """ def draw_kps(image_pil, kps, color_list=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]): """ This function draws keypoints and the limbs connecting them on an image. Parameters: - image_pil (PIL.Image): Input image as a PIL object. - kps (list of tuples): A list of keypoints where each keypoint is a tuple of (x, y) coordinates. - color_list (list of tuples, optional): list of colors (in RGB format) for each keypoint. Default is a set of five colors. Returns: - PIL.Image: Image with the keypoints and limbs drawn. """ stickwidth = 4 limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]]) kps = np.array(kps) w, h = image_pil.size out_img = np.zeros([h, w, 3]) for i in range(len(limbSeq)): index = limbSeq[i] color = color_list[index[0]] x = kps[index][:, 0] y = kps[index][:, 1] length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5 angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1])) polygon = cv2.ellipse2Poly( (int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1 ) out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color) out_img = (out_img * 0.6).astype(np.uint8) for idx_kp, kp in enumerate(kps): color = color_list[idx_kp] x, y = kp out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1) out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8)) return out_img_pil # Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid def get_resize_crop_region_for_grid(src, tgt_width, tgt_height): """ This function calculates the resize and crop region for an image to fit a target width and height while preserving the aspect ratio. Parameters: - src (tuple): A tuple containing the source image's height (h) and width (w). - tgt_width (int): The target width to resize the image. - tgt_height (int): The target height to resize the image. Returns: - tuple: Two tuples representing the crop region: 1. The top-left coordinates of the crop region. 2. The bottom-right coordinates of the crop region. """ tw = tgt_width th = tgt_height h, w = src r = h / w if r > (th / tw): resize_height = th resize_width = int(round(th / h * w)) else: resize_width = tw resize_height = int(round(tw / w * h)) crop_top = int(round((th - resize_height) / 2.0)) crop_left = int(round((tw - resize_width) / 2.0)) return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width) # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps def retrieve_timesteps( scheduler, num_inference_steps: int | None = None, device: str | torch.device | None = None, timesteps: list[int] | None = None, sigmas: list[float] | None = None, **kwargs, ): r""" Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. Args: scheduler (`SchedulerMixin`): The scheduler to get timesteps from. num_inference_steps (`int`): The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` must be `None`. device (`str` or `torch.device`, *optional*): The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. timesteps (`list[int]`, *optional*): Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, `num_inference_steps` and `sigmas` must be `None`. sigmas (`list[float]`, *optional*): Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed, `num_inference_steps` and `timesteps` must be `None`. Returns: `tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the second element is the number of inference steps. """ if timesteps is not None and sigmas is not None: raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values") if timesteps is not None: accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) if not accepts_timesteps: raise ValueError( f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" f" timestep schedules. Please check whether you are using the correct scheduler." ) scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) timesteps = scheduler.timesteps num_inference_steps = len(timesteps) elif sigmas is not None: accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) if not accept_sigmas: raise ValueError( f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" f" sigmas schedules. Please check whether you are using the correct scheduler." ) scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs) timesteps = scheduler.timesteps num_inference_steps = len(timesteps) else: scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) timesteps = scheduler.timesteps return timesteps, num_inference_steps # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents def retrieve_latents( encoder_output: torch.Tensor, generator: torch.Generator | None = None, sample_mode: str = "sample" ): if hasattr(encoder_output, "latent_dist") and sample_mode == "sample": return encoder_output.latent_dist.sample(generator) elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax": return encoder_output.latent_dist.mode() elif hasattr(encoder_output, "latents"): return encoder_output.latents else: raise AttributeError("Could not access latents of provided encoder_output") class ConsisIDPipeline(DiffusionPipeline, CogVideoXLoraLoaderMixin): r""" Pipeline for image-to-video generation using ConsisID. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) Args: vae ([`AutoencoderKL`]): Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations. text_encoder ([`T5EncoderModel`]): Frozen text-encoder. ConsisID uses [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant. tokenizer (`T5Tokenizer`): Tokenizer of class [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer). transformer ([`ConsisIDTransformer3DModel`]): A text conditioned `ConsisIDTransformer3DModel` to denoise the encoded video latents. scheduler ([`SchedulerMixin`]): A scheduler to be used in combination with `transformer` to denoise the encoded video latents. """ _optional_components = [] model_cpu_offload_seq = "text_encoder->transformer->vae" _callback_tensor_inputs = [ "latents", "prompt_embeds", "negative_prompt_embeds", ] def __init__( self, tokenizer: T5Tokenizer, text_encoder: T5EncoderModel, vae: AutoencoderKLCogVideoX, transformer: ConsisIDTransformer3DModel, scheduler: CogVideoXDPMScheduler, ): super().__init__() self.register_modules( tokenizer=tokenizer, text_encoder=text_encoder, vae=vae, transformer=transformer, scheduler=scheduler, ) self.vae_scale_factor_spatial = ( 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8 ) self.vae_scale_factor_temporal = ( self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4 ) self.vae_scaling_factor_image = ( self.vae.config.scaling_factor if hasattr(self, "vae") and self.vae is not None else 0.7 ) self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial) # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._get_t5_prompt_embeds def _get_t5_prompt_embeds( self, prompt: str | list[str] = None, num_videos_per_prompt: int = 1, max_sequence_length: int = 226, device: torch.device | None = None, dtype: torch.dtype | None = None, ): device = device or self._execution_device dtype = dtype or self.text_encoder.dtype prompt = [prompt] if isinstance(prompt, str) else prompt batch_size = len(prompt) text_inputs = self.tokenizer( prompt, padding="max_length", max_length=max_sequence_length, truncation=True, add_special_tokens=True, return_tensors="pt", ) text_input_ids = text_inputs.input_ids untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids): removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1]) logger.warning( "The following part of your input was truncated because `max_sequence_length` is set to " f" {max_sequence_length} tokens: {removed_text}" ) prompt_embeds = self.text_encoder(text_input_ids.to(device))[0] prompt_embeds = prompt_embeds.to(dtype=dtype, device=device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1) prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1) return prompt_embeds # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt def encode_prompt( self, prompt: str | list[str], negative_prompt: str | list[str] | None = None, do_classifier_free_guidance: bool = True, num_videos_per_prompt: int = 1, prompt_embeds: torch.Tensor | None = None, negative_prompt_embeds: torch.Tensor | None = None, max_sequence_length: int = 226, device: torch.device | None = None, dtype: torch.dtype | None = None, ): r""" Encodes the prompt into text encoder hidden states. Args: prompt (`str` or `list[str]`, *optional*): prompt to be encoded negative_prompt (`str` or `list[str]`, *optional*): The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). do_classifier_free_guidance (`bool`, *optional*, defaults to `True`): Whether to use classifier free guidance or not. num_videos_per_prompt (`int`, *optional*, defaults to 1): Number of videos that should be generated per prompt. torch device to place the resulting embeddings on prompt_embeds (`torch.Tensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.Tensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. device: (`torch.device`, *optional*): torch device dtype: (`torch.dtype`, *optional*): torch dtype """ device = device or self._execution_device prompt = [prompt] if isinstance(prompt, str) else prompt if prompt is not None: batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0] if prompt_embeds is None: prompt_embeds = self._get_t5_prompt_embeds( prompt=prompt, num_videos_per_prompt=num_videos_per_prompt, max_sequence_length=max_sequence_length, device=device, dtype=dtype, ) if do_classifier_free_guidance and negative_prompt_embeds is None: negative_prompt = negative_prompt or "" negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt if prompt is not None and type(prompt) is not type(negative_prompt): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" f" {type(prompt)}." ) elif batch_size != len(negative_prompt): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) negative_prompt_embeds = self._get_t5_prompt_embeds( prompt=negative_prompt, num_videos_per_prompt=num_videos_per_prompt, max_sequence_length=max_sequence_length, device=device, dtype=dtype, ) return prompt_embeds, negative_prompt_embeds def prepare_latents( self, image: torch.Tensor, batch_size: int = 1, num_channels_latents: int = 16, num_frames: int = 13, height: int = 60, width: int = 90, dtype: torch.dtype | None = None, device: torch.device | None = None, generator: torch.Generator | None = None, latents: torch.Tensor | None = None, kps_cond: torch.Tensor | None = None, ): if isinstance(generator, list) and len(generator) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1 shape = ( batch_size, num_frames, num_channels_latents, height // self.vae_scale_factor_spatial, width // self.vae_scale_factor_spatial, ) image = image.unsqueeze(2) # [B, C, F, H, W] if isinstance(generator, list): image_latents = [ retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i]) for i in range(batch_size) ] if kps_cond is not None: kps_cond = kps_cond.unsqueeze(2) kps_cond_latents = [ retrieve_latents(self.vae.encode(kps_cond[i].unsqueeze(0)), generator[i]) for i in range(batch_size) ] else: image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in image] if kps_cond is not None: kps_cond = kps_cond.unsqueeze(2) kps_cond_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in kps_cond] image_latents = torch.cat(image_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W] image_latents = self.vae_scaling_factor_image * image_latents if kps_cond is not None: kps_cond_latents = torch.cat(kps_cond_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W] kps_cond_latents = self.vae_scaling_factor_image * kps_cond_latents padding_shape = ( batch_size, num_frames - 2, num_channels_latents, height // self.vae_scale_factor_spatial, width // self.vae_scale_factor_spatial, ) else: padding_shape = ( batch_size, num_frames - 1, num_channels_latents, height // self.vae_scale_factor_spatial, width // self.vae_scale_factor_spatial, ) latent_padding = torch.zeros(padding_shape, device=device, dtype=dtype) if kps_cond is not None: image_latents = torch.cat([image_latents, kps_cond_latents, latent_padding], dim=1) else: image_latents = torch.cat([image_latents, latent_padding], dim=1) if latents is None: latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) else: latents = latents.to(device) # scale the initial noise by the standard deviation required by the scheduler latents = latents * self.scheduler.init_noise_sigma return latents, image_latents # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.decode_latents def decode_latents(self, latents: torch.Tensor) -> torch.Tensor: latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width] latents = 1 / self.vae_scaling_factor_image * latents frames = self.vae.decode(latents).sample return frames # Copied from diffusers.pipelines.animatediff.pipeline_animatediff_video2video.AnimateDiffVideoToVideoPipeline.get_timesteps def get_timesteps(self, num_inference_steps, timesteps, strength, device): # get the original timestep using init_timestep init_timestep = min(int(num_inference_steps * strength), num_inference_steps) t_start = max(num_inference_steps - init_timestep, 0) timesteps = timesteps[t_start * self.scheduler.order :] return timesteps, num_inference_steps - t_start # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs def prepare_extra_step_kwargs(self, generator, eta): # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502 # and should be between [0, 1] accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) extra_step_kwargs = {} if accepts_eta: extra_step_kwargs["eta"] = eta # check if the scheduler accepts generator accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: extra_step_kwargs["generator"] = generator return extra_step_kwargs def check_inputs( self, image, prompt, height, width, negative_prompt, callback_on_step_end_tensor_inputs, latents=None, prompt_embeds=None, negative_prompt_embeds=None, ): if ( not isinstance(image, torch.Tensor) and not isinstance(image, PIL.Image.Image) and not isinstance(image, list) ): raise ValueError( "`image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `list[PIL.Image.Image]` but is" f" {type(image)}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") if callback_on_step_end_tensor_inputs is not None and not all( k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs ): raise ValueError( f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}" ) if prompt is not None and prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" " only forward one of the two." ) elif prompt is None and prompt_embeds is None: raise ValueError( "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." ) elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") if prompt is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." ) if negative_prompt is not None and negative_prompt_embeds is not None: raise ValueError( f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" f" {negative_prompt_embeds}. Please make sure to only forward one of the two." ) if prompt_embeds is not None and negative_prompt_embeds is not None: if prompt_embeds.shape != negative_prompt_embeds.shape: raise ValueError( "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" f" {negative_prompt_embeds.shape}." ) def _prepare_rotary_positional_embeddings( self, height: int, width: int, num_frames: int, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size) grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size) base_size_width = self.transformer.config.sample_width // self.transformer.config.patch_size base_size_height = self.transformer.config.sample_height // self.transformer.config.patch_size grid_crops_coords = get_resize_crop_region_for_grid( (grid_height, grid_width), base_size_width, base_size_height ) freqs_cos, freqs_sin = get_3d_rotary_pos_embed( embed_dim=self.transformer.config.attention_head_dim, crops_coords=grid_crops_coords, grid_size=(grid_height, grid_width), temporal_size=num_frames, device=device, ) return freqs_cos, freqs_sin @property def guidance_scale(self): return self._guidance_scale @property def num_timesteps(self): return self._num_timesteps @property def attention_kwargs(self): return self._attention_kwargs @property def interrupt(self): return self._interrupt @torch.no_grad() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, image: PipelineImageInput, prompt: str | list[str] | None = None, negative_prompt: str | list[str] | None = None, height: int = 480, width: int = 720, num_frames: int = 49, num_inference_steps: int = 50, guidance_scale: float = 6.0, use_dynamic_cfg: bool = False, num_videos_per_prompt: int = 1, eta: float = 0.0, generator: torch.Generator | list[torch.Generator] | None = None, latents: torch.FloatTensor | None = None, prompt_embeds: torch.FloatTensor | None = None, negative_prompt_embeds: torch.FloatTensor | None = None, output_type: str = "pil", return_dict: bool = True, attention_kwargs: dict[str, Any] | None = None, callback_on_step_end: Callable[[int, int], None] | PipelineCallback | MultiPipelineCallbacks | None = None, callback_on_step_end_tensor_inputs: list[str] = ["latents"], max_sequence_length: int = 226, id_vit_hidden: torch.Tensor | None = None, id_cond: torch.Tensor | None = None, kps_cond: torch.Tensor | None = None, ) -> ConsisIDPipelineOutput | tuple: """ Function invoked when calling the pipeline for generation. Args: image (`PipelineImageInput`): The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`. prompt (`str` or `list[str]`, *optional*): The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead. negative_prompt (`str` or `list[str]`, *optional*): The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). height (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial): The height in pixels of the generated image. This is set to 480 by default for the best results. width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial): The width in pixels of the generated image. This is set to 720 by default for the best results. num_frames (`int`, defaults to `49`): Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will contain 1 extra frame because ConsisID is conditioned with (num_seconds * fps + 1) frames where num_seconds is 6 and fps is 4. However, since videos can be saved at any fps, the only condition that needs to be satisfied is that of divisibility mentioned above. num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. guidance_scale (`float`, *optional*, defaults to 6): Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality. use_dynamic_cfg (`bool`, *optional*, defaults to `False`): If True, dynamically adjusts the guidance scale during inference. This allows the model to use a progressive guidance scale, improving the balance between text-guided generation and image quality over the course of the inference steps. Typically, early inference steps use a higher guidance scale for more faithful image generation, while later steps reduce it for more diverse and natural results. num_videos_per_prompt (`int`, *optional*, defaults to 1): The number of videos to generate per prompt. generator (`torch.Generator` or `list[torch.Generator]`, *optional*): One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. latents (`torch.FloatTensor`, *optional*): Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will be generated by sampling using the supplied random `generator`. prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead of a plain tuple. attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). callback_on_step_end (`Callable`, *optional*): A function that calls at the end of each denoising steps during the inference. The function is called with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by `callback_on_step_end_tensor_inputs`. callback_on_step_end_tensor_inputs (`list`, *optional*): The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the `._callback_tensor_inputs` attribute of your pipeline class. max_sequence_length (`int`, defaults to `226`): Maximum sequence length in encoded prompt. Must be consistent with `self.transformer.config.max_text_seq_length` otherwise may lead to poor results. id_vit_hidden (`torch.Tensor | None`, *optional*): The tensor representing the hidden features extracted from the face model, which are used to condition the local facial extractor. This is crucial for the model to obtain high-frequency information of the face. If not provided, the local facial extractor will not run normally. id_cond (`torch.Tensor | None`, *optional*): The tensor representing the hidden features extracted from the clip model, which are used to condition the local facial extractor. This is crucial for the model to edit facial features If not provided, the local facial extractor will not run normally. kps_cond (`torch.Tensor | None`, *optional*): A tensor that determines whether the global facial extractor use keypoint information for conditioning. If provided, this tensor controls whether facial keypoints such as eyes, nose, and mouth landmarks are used during the generation process. This helps ensure the model retains more facial low-frequency information. Examples: Returns: [`~pipelines.consisid.pipeline_output.ConsisIDPipelineOutput`] or `tuple`: [`~pipelines.consisid.pipeline_output.ConsisIDPipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated images. """ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)): callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial num_frames = num_frames or self.transformer.config.sample_frames num_videos_per_prompt = 1 # 1. Check inputs. Raise error if not correct self.check_inputs( image=image, prompt=prompt, height=height, width=width, negative_prompt=negative_prompt, callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs, latents=latents, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, ) self._guidance_scale = guidance_scale self._attention_kwargs = attention_kwargs self._interrupt = False # 2. Default call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0] device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # 3. Encode input prompt prompt_embeds, negative_prompt_embeds = self.encode_prompt( prompt=prompt, negative_prompt=negative_prompt, do_classifier_free_guidance=do_classifier_free_guidance, num_videos_per_prompt=num_videos_per_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, max_sequence_length=max_sequence_length, device=device, ) if do_classifier_free_guidance: prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) # 4. Prepare timesteps timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device) self._num_timesteps = len(timesteps) # 5. Prepare latents is_kps = getattr(self.transformer.config, "is_kps", False) kps_cond = kps_cond if is_kps else None if kps_cond is not None: kps_cond = draw_kps(image, kps_cond) kps_cond = self.video_processor.preprocess(kps_cond, height=height, width=width).to( device, dtype=prompt_embeds.dtype ) image = self.video_processor.preprocess(image, height=height, width=width).to( device, dtype=prompt_embeds.dtype ) latent_channels = self.transformer.config.in_channels // 2 latents, image_latents = self.prepare_latents( image, batch_size * num_videos_per_prompt, latent_channels, num_frames, height, width, prompt_embeds.dtype, device, generator, latents, kps_cond, ) # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) # 7. Create rotary embeds if required image_rotary_emb = ( self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device) if self.transformer.config.use_rotary_positional_embeddings else None ) # 8. Denoising loop num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0) with self.progress_bar(total=num_inference_steps) as progress_bar: # for DPM-solver++ old_pred_original_sample = None timesteps_cpu = timesteps.cpu() for i, t in enumerate(timesteps): if self.interrupt: continue latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) latent_image_input = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents latent_model_input = torch.cat([latent_model_input, latent_image_input], dim=2) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML timestep = t.expand(latent_model_input.shape[0]) # predict noise model_output noise_pred = self.transformer( hidden_states=latent_model_input, encoder_hidden_states=prompt_embeds, timestep=timestep, image_rotary_emb=image_rotary_emb, attention_kwargs=attention_kwargs, return_dict=False, id_vit_hidden=id_vit_hidden, id_cond=id_cond, )[0] noise_pred = noise_pred.float() # perform guidance if use_dynamic_cfg: self._guidance_scale = 1 + guidance_scale * ( ( 1 - math.cos( math.pi * ((num_inference_steps - timesteps_cpu[i].item()) / num_inference_steps) ** 5.0 ) ) / 2 ) if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 if not isinstance(self.scheduler, CogVideoXDPMScheduler): latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] else: latents, old_pred_original_sample = self.scheduler.step( noise_pred, old_pred_original_sample, t, timesteps[i - 1] if i > 0 else None, latents, **extra_step_kwargs, return_dict=False, ) latents = latents.to(prompt_embeds.dtype) # call the callback, if provided if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_inputs: callback_kwargs[k] = locals()[k] callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if not output_type == "latent": video = self.decode_latents(latents) video = self.video_processor.postprocess_video(video=video, output_type=output_type) else: video = latents # Offload all models self.maybe_free_model_hooks() if not return_dict: return (video,) return ConsisIDPipelineOutput(frames=video)
{ "repo_id": "huggingface/diffusers", "file_path": "src/diffusers/pipelines/consisid/pipeline_consisid.py", "license": "Apache License 2.0", "lines": 848, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/diffusers:src/diffusers/pipelines/consisid/pipeline_output.py
from dataclasses import dataclass import torch from diffusers.utils import BaseOutput @dataclass class ConsisIDPipelineOutput(BaseOutput): r""" Output class for ConsisID pipelines. Args: frames (`torch.Tensor`, `np.ndarray`, or list[list[PIL.Image.Image]]): list of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or Torch tensor of shape `(batch_size, num_frames, channels, height, width)`. """ frames: torch.Tensor
{ "repo_id": "huggingface/diffusers", "file_path": "src/diffusers/pipelines/consisid/pipeline_output.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
huggingface/diffusers:tests/models/transformers/test_models_transformer_consisid.py
# coding=utf-8 # Copyright 2025 HuggingFace Inc. # # 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 unittest import torch from diffusers import ConsisIDTransformer3DModel from ...testing_utils import ( enable_full_determinism, torch_device, ) from ..test_modeling_common import ModelTesterMixin enable_full_determinism() class ConsisIDTransformerTests(ModelTesterMixin, unittest.TestCase): model_class = ConsisIDTransformer3DModel main_input_name = "hidden_states" uses_custom_attn_processor = True @property def dummy_input(self): batch_size = 2 num_channels = 4 num_frames = 1 height = 8 width = 8 embedding_dim = 8 sequence_length = 8 hidden_states = torch.randn((batch_size, num_frames, num_channels, height, width)).to(torch_device) encoder_hidden_states = torch.randn((batch_size, sequence_length, embedding_dim)).to(torch_device) timestep = torch.randint(0, 1000, size=(batch_size,)).to(torch_device) id_vit_hidden = [torch.ones([batch_size, 2, 2]).to(torch_device)] * 1 id_cond = torch.ones(batch_size, 2).to(torch_device) return { "hidden_states": hidden_states, "encoder_hidden_states": encoder_hidden_states, "timestep": timestep, "id_vit_hidden": id_vit_hidden, "id_cond": id_cond, } @property def input_shape(self): return (1, 4, 8, 8) @property def output_shape(self): return (1, 4, 8, 8) def prepare_init_args_and_inputs_for_common(self): init_dict = { "num_attention_heads": 2, "attention_head_dim": 8, "in_channels": 4, "out_channels": 4, "time_embed_dim": 2, "text_embed_dim": 8, "num_layers": 1, "sample_width": 8, "sample_height": 8, "sample_frames": 8, "patch_size": 2, "temporal_compression_ratio": 4, "max_text_seq_length": 8, "cross_attn_interval": 1, "is_kps": False, "is_train_face": True, "cross_attn_dim_head": 1, "cross_attn_num_heads": 1, "LFE_id_dim": 2, "LFE_vit_dim": 2, "LFE_depth": 5, "LFE_dim_head": 8, "LFE_num_heads": 2, "LFE_num_id_token": 1, "LFE_num_querie": 1, "LFE_output_dim": 10, "LFE_ff_mult": 1, "LFE_num_scale": 1, } inputs_dict = self.dummy_input return init_dict, inputs_dict def test_gradient_checkpointing_is_applied(self): expected_set = {"ConsisIDTransformer3DModel"} super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
{ "repo_id": "huggingface/diffusers", "file_path": "tests/models/transformers/test_models_transformer_consisid.py", "license": "Apache License 2.0", "lines": 90, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/diffusers:tests/pipelines/consisid/test_consisid.py
# Copyright 2025 The HuggingFace Team. # # 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 gc import inspect import unittest import numpy as np import torch from PIL import Image from transformers import AutoConfig, AutoTokenizer, T5EncoderModel from diffusers import AutoencoderKLCogVideoX, ConsisIDPipeline, ConsisIDTransformer3DModel, DDIMScheduler from diffusers.utils import load_image from ...testing_utils import ( backend_empty_cache, enable_full_determinism, numpy_cosine_similarity_distance, require_torch_accelerator, slow, torch_device, ) from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineTesterMixin, to_np, ) enable_full_determinism() class ConsisIDPipelineFastTests(PipelineTesterMixin, unittest.TestCase): pipeline_class = ConsisIDPipeline params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"} batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image"}) image_params = TEXT_TO_IMAGE_IMAGE_PARAMS image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS required_optional_params = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback_on_step_end", "callback_on_step_end_tensor_inputs", ] ) test_xformers_attention = False test_layerwise_casting = True test_group_offloading = True def get_dummy_components(self): torch.manual_seed(0) transformer = ConsisIDTransformer3DModel( num_attention_heads=2, attention_head_dim=16, in_channels=8, out_channels=4, time_embed_dim=2, text_embed_dim=32, num_layers=1, sample_width=2, sample_height=2, sample_frames=9, patch_size=2, temporal_compression_ratio=4, max_text_seq_length=16, use_rotary_positional_embeddings=True, use_learned_positional_embeddings=True, cross_attn_interval=1, is_kps=False, is_train_face=True, cross_attn_dim_head=1, cross_attn_num_heads=1, LFE_id_dim=2, LFE_vit_dim=2, LFE_depth=5, LFE_dim_head=8, LFE_num_heads=2, LFE_num_id_token=1, LFE_num_querie=1, LFE_output_dim=21, LFE_ff_mult=1, LFE_num_scale=1, ) torch.manual_seed(0) vae = AutoencoderKLCogVideoX( in_channels=3, out_channels=3, down_block_types=( "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", "CogVideoXDownBlock3D", ), up_block_types=( "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", "CogVideoXUpBlock3D", ), block_out_channels=(8, 8, 8, 8), latent_channels=4, layers_per_block=1, norm_num_groups=2, temporal_compression_ratio=4, ) torch.manual_seed(0) scheduler = DDIMScheduler() config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5") text_encoder = T5EncoderModel(config) tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5") components = { "transformer": transformer, "vae": vae, "scheduler": scheduler, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def get_dummy_inputs(self, device, seed=0): if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device=device).manual_seed(seed) image_height = 16 image_width = 16 image = Image.new("RGB", (image_width, image_height)) id_vit_hidden = [torch.ones([1, 2, 2])] * 1 id_cond = torch.ones(1, 2) inputs = { "image": image, "prompt": "dance monkey", "negative_prompt": "", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "height": image_height, "width": image_width, "num_frames": 8, "max_sequence_length": 16, "id_vit_hidden": id_vit_hidden, "id_cond": id_cond, "output_type": "pt", } return inputs def test_inference(self): device = "cpu" components = self.get_dummy_components() pipe = self.pipeline_class(**components) pipe.to(device) pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) video = pipe(**inputs).frames generated_video = video[0] self.assertEqual(generated_video.shape, (8, 3, 16, 16)) expected_video = torch.randn(8, 3, 16, 16) max_diff = np.abs(generated_video - expected_video).max() self.assertLessEqual(max_diff, 1e10) def test_callback_inputs(self): sig = inspect.signature(self.pipeline_class.__call__) has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters has_callback_step_end = "callback_on_step_end" in sig.parameters if not (has_callback_tensor_inputs and has_callback_step_end): return components = self.get_dummy_components() pipe = self.pipeline_class(**components) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) self.assertTrue( hasattr(pipe, "_callback_tensor_inputs"), f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs", ) def callback_inputs_subset(pipe, i, t, callback_kwargs): # iterate over callback args for tensor_name, tensor_value in callback_kwargs.items(): # check that we're only passing in allowed tensor inputs assert tensor_name in pipe._callback_tensor_inputs return callback_kwargs def callback_inputs_all(pipe, i, t, callback_kwargs): for tensor_name in pipe._callback_tensor_inputs: assert tensor_name in callback_kwargs # iterate over callback args for tensor_name, tensor_value in callback_kwargs.items(): # check that we're only passing in allowed tensor inputs assert tensor_name in pipe._callback_tensor_inputs return callback_kwargs inputs = self.get_dummy_inputs(torch_device) # Test passing in a subset inputs["callback_on_step_end"] = callback_inputs_subset inputs["callback_on_step_end_tensor_inputs"] = ["latents"] output = pipe(**inputs)[0] # Test passing in a everything inputs["callback_on_step_end"] = callback_inputs_all inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs output = pipe(**inputs)[0] def callback_inputs_change_tensor(pipe, i, t, callback_kwargs): is_last = i == (pipe.num_timesteps - 1) if is_last: callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"]) return callback_kwargs inputs["callback_on_step_end"] = callback_inputs_change_tensor inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs output = pipe(**inputs)[0] assert output.abs().sum() < 1e10 def test_inference_batch_single_identical(self): self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3) def test_attention_slicing_forward_pass( self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3 ): if not self.test_attention_slicing: return components = self.get_dummy_components() for key in components: if "text_encoder" in key and hasattr(components[key], "eval"): components[key].eval() pipe = self.pipeline_class(**components) for component in pipe.components.values(): if hasattr(component, "set_default_attn_processor"): component.set_default_attn_processor() pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) generator_device = "cpu" inputs = self.get_dummy_inputs(generator_device) output_without_slicing = pipe(**inputs)[0] pipe.enable_attention_slicing(slice_size=1) inputs = self.get_dummy_inputs(generator_device) output_with_slicing1 = pipe(**inputs)[0] pipe.enable_attention_slicing(slice_size=2) inputs = self.get_dummy_inputs(generator_device) output_with_slicing2 = pipe(**inputs)[0] if test_max_difference: max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max() max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max() self.assertLess( max(max_diff1, max_diff2), expected_max_diff, "Attention slicing should not affect the inference results", ) def test_vae_tiling(self, expected_diff_max: float = 0.4): generator_device = "cpu" components = self.get_dummy_components() # The reason to modify it this way is because ConsisID Transformer limits the generation to resolutions used during initialization. # This limitation comes from using learned positional embeddings which cannot be generated on-the-fly like sincos or RoPE embeddings. # See the if-statement on "self.use_learned_positional_embeddings" in diffusers/models/embeddings.py components["transformer"] = ConsisIDTransformer3DModel.from_config( components["transformer"].config, sample_height=16, sample_width=16, ) pipe = self.pipeline_class(**components) pipe.to("cpu") pipe.set_progress_bar_config(disable=None) # Without tiling inputs = self.get_dummy_inputs(generator_device) inputs["height"] = inputs["width"] = 128 output_without_tiling = pipe(**inputs)[0] # With tiling pipe.vae.enable_tiling( tile_sample_min_height=96, tile_sample_min_width=96, tile_overlap_factor_height=1 / 12, tile_overlap_factor_width=1 / 12, ) inputs = self.get_dummy_inputs(generator_device) inputs["height"] = inputs["width"] = 128 output_with_tiling = pipe(**inputs)[0] self.assertLess( (to_np(output_without_tiling) - to_np(output_with_tiling)).max(), expected_diff_max, "VAE tiling should not affect the inference results", ) @slow @require_torch_accelerator class ConsisIDPipelineIntegrationTests(unittest.TestCase): prompt = "A painting of a squirrel eating a burger." def setUp(self): super().setUp() gc.collect() backend_empty_cache(torch_device) def tearDown(self): super().tearDown() gc.collect() backend_empty_cache(torch_device) def test_consisid(self): generator = torch.Generator("cpu").manual_seed(0) pipe = ConsisIDPipeline.from_pretrained("BestWishYsh/ConsisID-preview", torch_dtype=torch.bfloat16) pipe.enable_model_cpu_offload() prompt = self.prompt image = load_image("https://github.com/PKU-YuanGroup/ConsisID/blob/main/asserts/example_images/2.png?raw=true") id_vit_hidden = [torch.ones([1, 577, 1024])] * 5 id_cond = torch.ones(1, 1280) videos = pipe( image=image, prompt=prompt, height=480, width=720, num_frames=16, id_vit_hidden=id_vit_hidden, id_cond=id_cond, generator=generator, num_inference_steps=1, output_type="pt", ).frames video = videos[0] expected_video = torch.randn(1, 16, 480, 720, 3).numpy() max_diff = numpy_cosine_similarity_distance(video.cpu(), expected_video) assert max_diff < 1e-3, f"Max diff is too high. got {video}"
{ "repo_id": "huggingface/diffusers", "file_path": "tests/pipelines/consisid/test_consisid.py", "license": "Apache License 2.0", "lines": 312, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/diffusers:examples/research_projects/pytorch_xla/inference/flux/flux_inference.py
from argparse import ArgumentParser from pathlib import Path from time import perf_counter import structlog import torch import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met import torch_xla.debug.profiler as xp import torch_xla.distributed.xla_multiprocessing as xmp import torch_xla.runtime as xr from torch_xla.experimental.custom_kernel import FlashAttention from diffusers import FluxPipeline logger = structlog.get_logger() metrics_filepath = "/tmp/metrics_report.txt" def _main(index, args, text_pipe, ckpt_id): cache_path = Path("/tmp/data/compiler_cache_tRiLlium_eXp") cache_path.mkdir(parents=True, exist_ok=True) xr.initialize_cache(str(cache_path), readonly=False) profile_path = Path("/tmp/data/profiler_out_tRiLlium_eXp") profile_path.mkdir(parents=True, exist_ok=True) profiler_port = 9012 profile_duration = args.profile_duration if args.profile: logger.info(f"starting profiler on port {profiler_port}") _ = xp.start_server(profiler_port) device0 = xm.xla_device() logger.info(f"loading flux from {ckpt_id}") flux_pipe = FluxPipeline.from_pretrained( ckpt_id, text_encoder=None, tokenizer=None, text_encoder_2=None, tokenizer_2=None, torch_dtype=torch.bfloat16 ).to(device0) flux_pipe.transformer.enable_xla_flash_attention(partition_spec=("data", None, None, None), is_flux=True) FlashAttention.DEFAULT_BLOCK_SIZES = { "block_q": 1536, "block_k_major": 1536, "block_k": 1536, "block_b": 1536, "block_q_major_dkv": 1536, "block_k_major_dkv": 1536, "block_q_dkv": 1536, "block_k_dkv": 1536, "block_q_dq": 1536, "block_k_dq": 1536, "block_k_major_dq": 1536, } prompt = "photograph of an electronics chip in the shape of a race car with trillium written on its side" width = args.width height = args.height guidance = args.guidance n_steps = 4 if args.schnell else 28 logger.info("starting compilation run...") ts = perf_counter() with torch.no_grad(): prompt_embeds, pooled_prompt_embeds, text_ids = text_pipe.encode_prompt( prompt=prompt, prompt_2=None, max_sequence_length=512 ) prompt_embeds = prompt_embeds.to(device0) pooled_prompt_embeds = pooled_prompt_embeds.to(device0) image = flux_pipe( prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, num_inference_steps=28, guidance_scale=guidance, height=height, width=width, ).images[0] logger.info(f"compilation took {perf_counter() - ts} sec.") image.save("/tmp/compile_out.png") base_seed = 4096 if args.seed is None else args.seed seed_range = 1000 unique_seed = base_seed + index * seed_range xm.set_rng_state(seed=unique_seed, device=device0) times = [] logger.info("starting inference run...") with torch.no_grad(): prompt_embeds, pooled_prompt_embeds, text_ids = text_pipe.encode_prompt( prompt=prompt, prompt_2=None, max_sequence_length=512 ) prompt_embeds = prompt_embeds.to(device0) pooled_prompt_embeds = pooled_prompt_embeds.to(device0) for _ in range(args.itters): ts = perf_counter() if args.profile: xp.trace_detached(f"localhost:{profiler_port}", str(profile_path), duration_ms=profile_duration) image = flux_pipe( prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, num_inference_steps=n_steps, guidance_scale=guidance, height=height, width=width, ).images[0] inference_time = perf_counter() - ts if index == 0: logger.info(f"inference time: {inference_time}") times.append(inference_time) logger.info(f"avg. inference over {args.itters} iterations took {sum(times) / len(times)} sec.") image.save(f"/tmp/inference_out-{index}.png") if index == 0: metrics_report = met.metrics_report() with open(metrics_filepath, "w+") as fout: fout.write(metrics_report) logger.info(f"saved metric information as {metrics_filepath}") if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--schnell", action="store_true", help="run flux schnell instead of dev") parser.add_argument("--width", type=int, default=1024, help="width of the image to generate") parser.add_argument("--height", type=int, default=1024, help="height of the image to generate") parser.add_argument("--guidance", type=float, default=3.5, help="guidance strength for dev") parser.add_argument("--seed", type=int, default=None, help="seed for inference") parser.add_argument("--profile", action="store_true", help="enable profiling") parser.add_argument("--profile-duration", type=int, default=10000, help="duration for profiling in msec.") parser.add_argument("--itters", type=int, default=15, help="items to run inference and get avg time in sec.") args = parser.parse_args() if args.schnell: ckpt_id = "black-forest-labs/FLUX.1-schnell" else: ckpt_id = "black-forest-labs/FLUX.1-dev" text_pipe = FluxPipeline.from_pretrained(ckpt_id, transformer=None, vae=None, torch_dtype=torch.bfloat16).to("cpu") xmp.spawn(_main, args=(args, text_pipe, ckpt_id))
{ "repo_id": "huggingface/diffusers", "file_path": "examples/research_projects/pytorch_xla/inference/flux/flux_inference.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
huggingface/diffusers:src/diffusers/pipelines/transformers_loading_utils.py
# coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. # # 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 contextlib import os import tempfile from typing import TYPE_CHECKING from huggingface_hub import DDUFEntry from tqdm import tqdm from ..utils import is_safetensors_available, is_transformers_available, is_transformers_version if TYPE_CHECKING: from transformers import PreTrainedModel, PreTrainedTokenizer if is_transformers_available(): from transformers import PreTrainedModel, PreTrainedTokenizer if is_safetensors_available(): import safetensors.torch def _load_tokenizer_from_dduf( cls: "PreTrainedTokenizer", name: str, dduf_entries: dict[str, DDUFEntry], **kwargs ) -> "PreTrainedTokenizer": """ Load a tokenizer from a DDUF archive. In practice, `transformers` do not provide a way to load a tokenizer from a DDUF archive. This function is a workaround by extracting the tokenizer files from the DDUF archive and loading the tokenizer from the extracted files. There is an extra cost of extracting the files, but of limited impact as the tokenizer files are usually small-ish. """ with tempfile.TemporaryDirectory() as tmp_dir: for entry_name, entry in dduf_entries.items(): if entry_name.startswith(name + "/"): tmp_entry_path = os.path.join(tmp_dir, *entry_name.split("/")) # need to create intermediary directory if they don't exist os.makedirs(os.path.dirname(tmp_entry_path), exist_ok=True) with open(tmp_entry_path, "wb") as f: with entry.as_mmap() as mm: f.write(mm) return cls.from_pretrained(os.path.dirname(tmp_entry_path), **kwargs) def _load_transformers_model_from_dduf( cls: "PreTrainedModel", name: str, dduf_entries: dict[str, DDUFEntry], **kwargs ) -> "PreTrainedModel": """ Load a transformers model from a DDUF archive. In practice, `transformers` do not provide a way to load a model from a DDUF archive. This function is a workaround by instantiating a model from the config file and loading the weights from the DDUF archive directly. """ config_file = dduf_entries.get(f"{name}/config.json") if config_file is None: raise EnvironmentError( f"Could not find a config.json file for component {name} in DDUF file (contains {dduf_entries.keys()})." ) generation_config = dduf_entries.get(f"{name}/generation_config.json", None) weight_files = [ entry for entry_name, entry in dduf_entries.items() if entry_name.startswith(f"{name}/") and entry_name.endswith(".safetensors") ] if not weight_files: raise EnvironmentError( f"Could not find any weight file for component {name} in DDUF file (contains {dduf_entries.keys()})." ) if not is_safetensors_available(): raise EnvironmentError( "Safetensors is not available, cannot load model from DDUF. Please `pip install safetensors`." ) if is_transformers_version("<", "4.47.0"): raise ImportError( "You need to install `transformers>4.47.0` in order to load a transformers model from a DDUF file. " "You can install it with: `pip install --upgrade transformers`" ) with tempfile.TemporaryDirectory() as tmp_dir: from transformers import AutoConfig, GenerationConfig tmp_config_file = os.path.join(tmp_dir, "config.json") with open(tmp_config_file, "w") as f: f.write(config_file.read_text()) config = AutoConfig.from_pretrained(tmp_config_file) if generation_config is not None: tmp_generation_config_file = os.path.join(tmp_dir, "generation_config.json") with open(tmp_generation_config_file, "w") as f: f.write(generation_config.read_text()) generation_config = GenerationConfig.from_pretrained(tmp_generation_config_file) state_dict = {} with contextlib.ExitStack() as stack: for entry in tqdm(weight_files, desc="Loading state_dict"): # Loop over safetensors files # Memory-map the safetensors file mmap = stack.enter_context(entry.as_mmap()) # Load tensors from the memory-mapped file tensors = safetensors.torch.load(mmap) # Update the state dictionary with tensors state_dict.update(tensors) # `from_pretrained` sets the model to eval mode by default, which is the # correct behavior for inference. Do not call `model.train()` here. return cls.from_pretrained( pretrained_model_name_or_path=None, config=config, generation_config=generation_config, state_dict=state_dict, **kwargs, )
{ "repo_id": "huggingface/diffusers", "file_path": "src/diffusers/pipelines/transformers_loading_utils.py", "license": "Apache License 2.0", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/diffusers:tests/single_file/test_model_flux_transformer_single_file.py
# coding=utf-8 # Copyright 2025 HuggingFace Inc. # # 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 gc from diffusers import ( FluxTransformer2DModel, ) from ..testing_utils import ( backend_empty_cache, enable_full_determinism, torch_device, ) from .single_file_testing_utils import SingleFileModelTesterMixin enable_full_determinism() class TestFluxTransformer2DModelSingleFile(SingleFileModelTesterMixin): model_class = FluxTransformer2DModel ckpt_path = "https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/flux1-dev.safetensors" alternate_keys_ckpt_paths = ["https://huggingface.co/Comfy-Org/flux1-dev/blob/main/flux1-dev-fp8.safetensors"] repo_id = "black-forest-labs/FLUX.1-dev" subfolder = "transformer" def test_device_map_cuda(self): backend_empty_cache(torch_device) model = self.model_class.from_single_file(self.ckpt_path, device_map="cuda") del model gc.collect() backend_empty_cache(torch_device)
{ "repo_id": "huggingface/diffusers", "file_path": "tests/single_file/test_model_flux_transformer_single_file.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:examples/dataset/slurm_compute_rabc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ SLURM-distributed SARM RA-BC annotation pipeline. Computes SARM progress values for all frames in a dataset, distributed across SLURM workers, then merges the shards into a single sarm_progress.parquet. Two subcommands, each a separate SLURM submission: compute – N workers, each computes progress for a subset of episodes aggregate – 1 worker, merges N shards into sarm_progress.parquet, pushes to hub Usage: python slurm_compute_rabc.py compute \\ --repo-id user/dataset --reward-model-path user/sarm_model \\ --stride 10 --device cpu --workers 50 --partition cpu python slurm_compute_rabc.py aggregate \\ --repo-id user/dataset --reward-model-path user/sarm_model \\ --partition cpu --push-to-hub """ import argparse from pathlib import Path from datatrove.executor import LocalPipelineExecutor from datatrove.executor.slurm import SlurmPipelineExecutor from datatrove.pipeline.base import PipelineStep class ComputeProgressShards(PipelineStep): """Each worker computes SARM progress for its assigned episodes.""" def __init__( self, repo_id, reward_model_path, stride=1, head_mode="sparse", device="cpu", shard_dir="rabc_shards" ): super().__init__() if stride < 1: raise ValueError(f"stride must be >= 1, got {stride}") self.repo_id = repo_id self.reward_model_path = reward_model_path self.stride = stride self.head_mode = head_mode self.device = device self.shard_dir = shard_dir def run(self, data=None, rank: int = 0, world_size: int = 1): import logging from pathlib import Path import numpy as np import pyarrow as pa import pyarrow.parquet as pq import torch from tqdm import tqdm from lerobot.policies.sarm.compute_rabc_weights import ( generate_all_frame_indices, interpolate_progress, load_sarm_resources, ) from lerobot.utils.utils import init_logging init_logging() dataset, reward_model, preprocess = load_sarm_resources( self.repo_id, self.reward_model_path, self.device, ) if hasattr(preprocess, "eval"): preprocess.eval() for step in preprocess.steps: if hasattr(step, "eval"): step.eval() image_key = reward_model.config.image_key state_key = reward_model.config.state_key frame_gap = reward_model.config.frame_gap center_idx = reward_model.config.n_obs_steps // 2 dual_mode = reward_model.config.uses_dual_heads compute_sparse = self.head_mode in ("sparse", "both") or not dual_mode compute_dense = self.head_mode in ("dense", "both") and dual_mode my_episodes = list(range(dataset.num_episodes))[rank::world_size] if not my_episodes: logging.info(f"Rank {rank}: no episodes assigned") return logging.info(f"Rank {rank}: {len(my_episodes)} / {dataset.num_episodes} episodes") all_rows = [] for ep_idx in tqdm(my_episodes, desc=f"Rank {rank}"): ep = dataset.meta.episodes[ep_idx] ep_start, ep_end = ep["dataset_from_index"], ep["dataset_to_index"] task = dataset[ep_start].get("task", "perform the task") all_ep_indices = generate_all_frame_indices(ep_start, ep_end, frame_gap) if self.stride > 1: compute_indices = [i for i in all_ep_indices if (i - ep_start) % self.stride == 0] if (ep_end - 1) not in compute_indices: compute_indices.append(ep_end - 1) compute_indices = sorted(set(compute_indices)) else: compute_indices = all_ep_indices frame_results = {} for qi in tqdm(compute_indices, desc=f" Ep {ep_idx}", leave=False): try: sample = dataset[qi] batch = { image_key: sample[image_key], "task": task, "index": qi, "episode_index": ep_idx, } if state_key in sample: batch[state_key] = sample[state_key] with torch.no_grad(): processed = preprocess(batch) vf = processed["video_features"].to(self.device) tf = processed["text_features"].to(self.device) sf = processed.get("state_features") if sf is not None: sf = sf.to(self.device) lengths = processed.get("lengths") sparse_val = dense_val = np.nan if compute_sparse: r = reward_model.calculate_rewards( text_embeddings=tf, video_embeddings=vf, state_features=sf, lengths=lengths, return_all_frames=True, head_mode="sparse", ) sparse_val = float(r[0, center_idx] if r.ndim == 2 else r[center_idx]) if compute_dense: r = reward_model.calculate_rewards( text_embeddings=tf, video_embeddings=vf, state_features=sf, lengths=lengths, return_all_frames=True, head_mode="dense", ) dense_val = float(r[0, center_idx] if r.ndim == 2 else r[center_idx]) frame_results[qi] = (sparse_val, dense_val) except Exception as e: logging.warning(f"Failed frame {qi}: {e}") if not frame_results: logging.warning(f"Episode {ep_idx}: all frames failed, skipping") continue # Interpolate to all frames in this episode computed_idx = np.array(sorted(frame_results.keys())) all_frame_arr = np.arange(ep_start, ep_end) sparse_vals = np.array([frame_results[i][0] for i in computed_idx]) if compute_sparse else None dense_vals = np.array([frame_results[i][1] for i in computed_idx]) if compute_dense else None if self.stride > 1 and len(computed_idx) > 1: if compute_sparse: sparse_vals = interpolate_progress(computed_idx, sparse_vals, all_frame_arr) if compute_dense: dense_vals = interpolate_progress(computed_idx, dense_vals, all_frame_arr) output_frames = all_frame_arr else: # Use only successfully computed frames to avoid indexing mismatch on failures output_frames = computed_idx for i, fi in enumerate(output_frames): row = {"index": int(fi), "episode_index": ep_idx, "frame_index": int(fi - ep_start)} if compute_sparse: row["progress_sparse"] = float(sparse_vals[i]) if compute_dense: row["progress_dense"] = float(dense_vals[i]) all_rows.append(row) if all_rows: import pandas as pd df = pd.DataFrame(all_rows).sort_values("index").reset_index(drop=True) table = pa.Table.from_pandas(df, preserve_index=False) table = table.replace_schema_metadata({b"reward_model_path": self.reward_model_path.encode()}) shard_dir = Path(self.shard_dir) shard_dir.mkdir(parents=True, exist_ok=True) out = shard_dir / f"shard_{rank:05d}.parquet" pq.write_table(table, out) logging.info(f"Rank {rank}: saved {len(df)} rows to {out}") class AggregateProgress(PipelineStep): """Merge all shard parquets into final sarm_progress.parquet.""" def __init__(self, repo_id, reward_model_path, shard_dir="rabc_shards", push_to_hub=False): super().__init__() self.repo_id = repo_id self.reward_model_path = reward_model_path self.shard_dir = shard_dir self.push_to_hub = push_to_hub def run(self, data=None, rank: int = 0, world_size: int = 1): import datetime import logging import os from pathlib import Path import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from lerobot.datasets.lerobot_dataset import LeRobotDataset from lerobot.utils.utils import init_logging init_logging() if rank != 0: return shard_dir = Path(self.shard_dir) shards = sorted(shard_dir.glob("shard_*.parquet")) if not shards: raise FileNotFoundError(f"No shards found in {shard_dir}") # Log shard modification time range to help detect stale files mtimes = [os.path.getmtime(s) for s in shards] oldest = datetime.datetime.fromtimestamp(min(mtimes)).isoformat(timespec="seconds") newest = datetime.datetime.fromtimestamp(max(mtimes)).isoformat(timespec="seconds") logging.info(f"Aggregating {len(shards)} shards (oldest: {oldest}, newest: {newest})") df = pd.concat([pd.read_parquet(s) for s in shards], ignore_index=True) df = df.sort_values("index").reset_index(drop=True) table = pa.Table.from_pandas(df, preserve_index=False) table = table.replace_schema_metadata({b"reward_model_path": self.reward_model_path.encode()}) temp_ds = LeRobotDataset(self.repo_id, download_videos=False) out_path = Path(temp_ds.root) / "sarm_progress.parquet" out_path.parent.mkdir(parents=True, exist_ok=True) pq.write_table(table, out_path) logging.info(f"Saved {len(df)} rows to {out_path}") for col in ["progress_sparse", "progress_dense"]: if col in df.columns: v = df[col].dropna() logging.info( f"{col}: mean={v.mean():.4f} std={v.std():.4f} min={v.min():.4f} max={v.max():.4f}" ) if self.push_to_hub: from huggingface_hub import HfApi api = HfApi() hub_path = "sarm_progress.parquet" logging.info(f"Uploading to {self.repo_id}/{hub_path}") api.upload_file( path_or_fileobj=str(out_path), path_in_repo=hub_path, repo_id=self.repo_id, repo_type="dataset", ) logging.info(f"Uploaded: https://huggingface.co/datasets/{self.repo_id}/blob/main/{hub_path}") def make_compute_executor( repo_id, reward_model_path, stride, head_mode, device, shard_dir, logs_dir, job_name, slurm, workers, partition, cpus_per_task, mem_per_cpu, ): kwargs = { "pipeline": [ ComputeProgressShards(repo_id, reward_model_path, stride, head_mode, device, str(shard_dir)), ], "logging_dir": str(logs_dir / job_name), } if slurm: kwargs.update( { "job_name": job_name, "tasks": workers, "workers": workers, "time": "24:00:00", "partition": partition, "cpus_per_task": cpus_per_task, "sbatch_args": {"mem-per-cpu": mem_per_cpu}, } ) return SlurmPipelineExecutor(**kwargs) kwargs.update({"tasks": workers, "workers": 1}) return LocalPipelineExecutor(**kwargs) def make_aggregate_executor( repo_id, reward_model_path, shard_dir, logs_dir, job_name, slurm, partition, cpus_per_task, mem_per_cpu, push_to_hub, ): kwargs = { "pipeline": [ AggregateProgress(repo_id, reward_model_path, str(shard_dir), push_to_hub), ], "logging_dir": str(logs_dir / job_name), } if slurm: kwargs.update( { "job_name": job_name, "tasks": 1, "workers": 1, "time": "02:00:00", "partition": partition, "cpus_per_task": cpus_per_task, "sbatch_args": {"mem-per-cpu": mem_per_cpu}, } ) return SlurmPipelineExecutor(**kwargs) kwargs.update({"tasks": 1, "workers": 1}) return LocalPipelineExecutor(**kwargs) def _add_shared_args(p): p.add_argument( "--repo-id", type=str, required=True, help="Hugging Face repository identifier, e.g. 'user/dataset'.", ) p.add_argument( "--shard-dir", type=Path, default=Path("rabc_shards"), help="Directory to read/write per-rank parquet shards.", ) p.add_argument( "--logs-dir", type=Path, default=Path("logs"), help="Directory for datatrove logs.", ) p.add_argument( "--job-name", type=str, default=None, help="SLURM job name (defaults to rabc_<subcommand>).", ) p.add_argument( "--slurm", type=int, default=1, help="1 = submit via SLURM; 0 = run locally (useful for debugging).", ) p.add_argument( "--partition", type=str, default=None, help="SLURM partition to submit to.", ) p.add_argument( "--cpus-per-task", type=int, default=4, help="Number of CPUs per SLURM task.", ) p.add_argument( "--mem-per-cpu", type=str, default="4G", help="Memory per CPU, e.g. '4G' or '1950M'.", ) def main(): parser = argparse.ArgumentParser( description="SLURM-distributed SARM RA-BC annotation pipeline", formatter_class=argparse.RawDescriptionHelpFormatter, ) sub = parser.add_subparsers(dest="command", required=True) # compute subcommand cp = sub.add_parser( "compute", help="Distribute progress computation across SLURM workers.", ) _add_shared_args(cp) cp.add_argument( "--reward-model-path", type=str, required=True, help="Path or HF repo id of the SARM reward model.", ) cp.add_argument( "--stride", type=int, default=1, help="Compute every Nth frame; intermediate frames are interpolated (must be >= 1).", ) cp.add_argument( "--head-mode", type=str, default="sparse", choices=["sparse", "dense", "both"], help="Which reward head(s) to compute.", ) cp.add_argument( "--device", type=str, default="cpu", help="Device for reward model inference, e.g. 'cpu' or 'cuda'.", ) cp.add_argument( "--workers", type=int, default=50, help="Number of parallel SLURM tasks (one shard per worker).", ) # aggregate subcommand ap = sub.add_parser( "aggregate", help="Merge per-rank shards into a single sarm_progress.parquet.", ) _add_shared_args(ap) ap.add_argument( "--reward-model-path", type=str, required=True, help="Path or HF repo id of the SARM reward model (stored in parquet metadata).", ) ap.add_argument( "--push-to-hub", action="store_true", help="Upload sarm_progress.parquet to the Hugging Face Hub after aggregation.", ) args = parser.parse_args() job_name = args.job_name or f"rabc_{args.command}" kwargs = vars(args) kwargs["slurm"] = kwargs.pop("slurm") == 1 kwargs["job_name"] = job_name command = kwargs.pop("command") executor = make_compute_executor(**kwargs) if command == "compute" else make_aggregate_executor(**kwargs) executor.run() if __name__ == "__main__": main()
{ "repo_id": "huggingface/lerobot", "file_path": "examples/dataset/slurm_compute_rabc.py", "license": "Apache License 2.0", "lines": 421, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/pi_gemma.py
# Copyright 2025 Physical Intelligence and The HuggingFace Inc. team. All rights reserved. # # 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 __future__ import annotations from typing import TYPE_CHECKING import torch from torch import nn from lerobot.utils.import_utils import _transformers_available if TYPE_CHECKING or _transformers_available: from transformers.cache_utils import DynamicCache from transformers.masking_utils import create_causal_mask from transformers.modeling_layers import GradientCheckpointingLayer from transformers.modeling_outputs import BaseModelOutputWithPast from transformers.models.gemma.modeling_gemma import ( GemmaAttention, GemmaConfig, GemmaForCausalLM, GemmaMLP, GemmaModel, ) from transformers.models.paligemma.modeling_paligemma import ( PaliGemmaForConditionalGeneration, PaliGemmaModel, ) else: GemmaAttention = None GemmaConfig = None GemmaForCausalLM = None GemmaMLP = None GemmaModel = None PaliGemmaModel = None PaliGemmaForConditionalGeneration = None DynamicCache = None GradientCheckpointingLayer = None BaseModelOutputWithPast = None create_causal_mask = None def _gated_residual( x: torch.Tensor | None, y: torch.Tensor | None, gate: torch.Tensor | None, ) -> torch.Tensor | None: """Gated residual: x + y when gate is None, else x + y * gate.""" if x is None and y is None: return None if x is None or y is None: return x if x is not None else y if gate is None: return x + y return x + y * gate def layernorm_forward( layernorm: nn.Module, x: torch.Tensor, cond: torch.Tensor | None = None, ): """ call layernorm and return hidden states and gate if cond is not None, use conditional norm otherwise, use normal gemma norm """ if cond is not None: return layernorm(x, cond=cond) else: return layernorm(x) class PiGemmaRMSNorm(nn.Module): """ Adaptive RMSNorm for PI Gemma (AdaRMS). When cond_dim is set, uses cond to modulate scale/shift/gate; otherwise behaves like standard GemmaRMSNorm. forward(x, cond=None) returns (output, gate) for use with _gated_residual. """ def __init__(self, dim: int, eps: float = 1e-6, cond_dim: int | None = None): super().__init__() self.eps = eps self.dim = dim self.cond_dim = cond_dim if cond_dim is not None: self.dense = nn.Linear(cond_dim, dim * 3, bias=True) nn.init.zeros_(self.dense.weight) else: self.weight = nn.Parameter(torch.zeros(dim)) self.dense = None def _norm(self, x): # Compute variance in float32 (like the source implementation) var = torch.mean(torch.square(x.float()), dim=-1, keepdim=True) # Compute normalization in float32 normed_inputs = x * torch.rsqrt(var + self.eps) return normed_inputs def forward( self, x: torch.Tensor, cond: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor | None]: dtype = x.dtype normed = self._norm(x) if cond is None or self.dense is None: normed = normed * (1.0 + self.weight.float()) return normed.type_as(x), None if cond.shape[-1] != self.cond_dim: raise ValueError(f"Expected cond dim {self.cond_dim}, got {cond.shape[-1]}") modulation = self.dense(cond) if len(x.shape) == 3: modulation = modulation.unsqueeze(1) scale, shift, gate = modulation.chunk(3, dim=-1) normed = normed * (1 + scale.float()) + shift.float() return normed.to(dtype), gate.to(dtype) def extra_repr(self) -> str: if self.dense is not None: return f"dim={self.dim}, eps={self.eps}, adaptive=True, cond_dim={self.cond_dim}" return f"dim={self.dim}, eps={self.eps}" def _get_pi_gemma_decoder_layer_base(): """base for PiGemmaDecoderLayer""" class _PiGemmaDecoderLayerBase(GradientCheckpointingLayer): """Decoder layer that uses PiGemmaRMSNorm and _gated_residual, compatible with v5 Gemma.""" def __init__(self, config: GemmaConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = GemmaAttention(config=config, layer_idx=layer_idx) self.mlp = GemmaMLP(config) cond_dim = ( getattr(config, "adarms_cond_dim", None) if getattr(config, "use_adarms", False) else None ) self.input_layernorm = PiGemmaRMSNorm( config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim ) self.post_attention_layernorm = PiGemmaRMSNorm( config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim ) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values=None, use_cache: bool = False, cache_position: torch.LongTensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, adarms_cond: torch.Tensor | None = None, **kwargs, ) -> torch.Tensor: residual = hidden_states hidden_states, gate = self.input_layernorm(hidden_states, cond=adarms_cond) hidden_states, _ = self.self_attn( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = _gated_residual(residual, hidden_states, gate) residual = hidden_states hidden_states, gate = self.post_attention_layernorm(hidden_states, cond=adarms_cond) hidden_states = self.mlp(hidden_states) hidden_states = _gated_residual(residual, hidden_states, gate) return hidden_states return _PiGemmaDecoderLayerBase class PiGemmaModel(GemmaModel): # type: ignore[misc] """ GemmaModel extended with AdaRMS (adaptive RMSNorm) and gated residuals when config.use_adarms is True. """ def __init__(self, config: GemmaConfig, **kwargs): super().__init__(config, **kwargs) # if not getattr(config, "use_adarms", False): # return cond_dim = getattr(config, "adarms_cond_dim", None) pi_gemma_decoder_layer_base = _get_pi_gemma_decoder_layer_base() self.layers = nn.ModuleList( [pi_gemma_decoder_layer_base(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = PiGemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim) def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: DynamicCache | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, cache_position: torch.LongTensor | None = None, adarms_cond: torch.Tensor | None = None, **kwargs, ) -> BaseModelOutputWithPast: """ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*): Condition for ADARMS. """ output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training and use_cache: import logging logging.warning( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if use_cache and past_key_values is None: past_key_values = DynamicCache() if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = create_causal_mask( config=self.config, inputs_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) # embed positions hidden_states = inputs_embeds # Convert to bfloat16 if the first layer uses bfloat16 if len(self.layers) > 0 and self.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16: hidden_states = hidden_states.to(torch.bfloat16) # create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids) # normalized # Gemma downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5 # See https://github.com/huggingface/transformers/pull/29402 # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for decoder_layer in self.layers[: self.config.num_hidden_layers]: if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, adarms_cond=adarms_cond, **kwargs, ) hidden_states = layer_outputs if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states, _ = self.norm(hidden_states, adarms_cond) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, hidden_states=all_hidden_states, attentions=all_self_attns, ) class PiGemmaForCausalLM(GemmaForCausalLM): # type: ignore[misc] """ Causal LM wrapper using PiGemmaModel as the backbone, for consistency with GemmaForCausalLM and the language model used in pi0_fast. Use this for the action expert in pi0/pi05. """ def __init__(self, config: GemmaConfig, **kwargs): super().__init__(config, **kwargs) self.model = PiGemmaModel(config) class PaliGemmaModelWithPiGemma(PaliGemmaModel): """PaliGemmaModel whose language_model is PiGemmaModel (custom decoder with PiGemmaRMSNorm and gated residuals).""" def __init__(self, config): super().__init__(config) self.language_model = PiGemmaModel(config.text_config) class PaliGemmaForConditionalGenerationWithPiGemma(PaliGemmaForConditionalGeneration): """PaliGemmaForConditionalGeneration using PiGemma decoder for the language model.""" def __init__(self, config): super().__init__(config) self.model = PaliGemmaModelWithPiGemma(config) # Make modules available through conditional class for BC @property def language_model(self): return self.model.language_model __all__ = [ "PiGemmaModel", "PiGemmaForCausalLM", "PiGemmaRMSNorm", "_gated_residual", "layernorm_forward", "PaliGemmaModelWithPiGemma", "PaliGemmaForConditionalGenerationWithPiGemma", ]
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/pi_gemma.py", "license": "Apache License 2.0", "lines": 305, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/openarm_mini/config_openarm_mini.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass from ..config import TeleoperatorConfig @TeleoperatorConfig.register_subclass("openarm_mini") @dataclass class OpenArmMiniConfig(TeleoperatorConfig): """Configuration for OpenArm Mini teleoperator with Feetech motors (dual arms).""" port_right: str = "/dev/ttyUSB0" port_left: str = "/dev/ttyUSB1" use_degrees: bool = True
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/openarm_mini/config_openarm_mini.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/openarm_mini/openarm_mini.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 logging import time from typing import Any from lerobot.motors import Motor, MotorCalibration, MotorNormMode from lerobot.motors.feetech import ( FeetechMotorsBus, OperatingMode, ) from lerobot.processor import RobotAction from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..teleoperator import Teleoperator from .config_openarm_mini import OpenArmMiniConfig logger = logging.getLogger(__name__) # Motors whose direction is inverted during readout RIGHT_MOTORS_TO_FLIP = ["joint_1", "joint_2", "joint_3", "joint_4", "joint_5"] LEFT_MOTORS_TO_FLIP = ["joint_1", "joint_3", "joint_4", "joint_5", "joint_6", "joint_7"] class OpenArmMini(Teleoperator): """ OpenArm Mini Teleoperator with dual Feetech-based arms (8 motors per arm). Each arm has 7 joints plus a gripper, using Feetech STS3215 servos. """ config_class = OpenArmMiniConfig name = "openarm_mini" def __init__(self, config: OpenArmMiniConfig): super().__init__(config) self.config = config norm_mode_body = MotorNormMode.DEGREES motors_right = { "joint_1": Motor(1, "sts3215", norm_mode_body), "joint_2": Motor(2, "sts3215", norm_mode_body), "joint_3": Motor(3, "sts3215", norm_mode_body), "joint_4": Motor(4, "sts3215", norm_mode_body), "joint_5": Motor(5, "sts3215", norm_mode_body), "joint_6": Motor(6, "sts3215", norm_mode_body), "joint_7": Motor(7, "sts3215", norm_mode_body), "gripper": Motor(8, "sts3215", MotorNormMode.RANGE_0_100), } motors_left = { "joint_1": Motor(1, "sts3215", norm_mode_body), "joint_2": Motor(2, "sts3215", norm_mode_body), "joint_3": Motor(3, "sts3215", norm_mode_body), "joint_4": Motor(4, "sts3215", norm_mode_body), "joint_5": Motor(5, "sts3215", norm_mode_body), "joint_6": Motor(6, "sts3215", norm_mode_body), "joint_7": Motor(7, "sts3215", norm_mode_body), "gripper": Motor(8, "sts3215", MotorNormMode.RANGE_0_100), } cal_right = { k.replace("right_", ""): v for k, v in (self.calibration or {}).items() if k.startswith("right_") } cal_left = { k.replace("left_", ""): v for k, v in (self.calibration or {}).items() if k.startswith("left_") } self.bus_right = FeetechMotorsBus( port=self.config.port_right, motors=motors_right, calibration=cal_right, ) self.bus_left = FeetechMotorsBus( port=self.config.port_left, motors=motors_left, calibration=cal_left, ) @property def action_features(self) -> dict[str, type]: features: dict[str, type] = {} for motor in self.bus_right.motors: features[f"right_{motor}.pos"] = float for motor in self.bus_left.motors: features[f"left_{motor}.pos"] = float return features @property def feedback_features(self) -> dict[str, type]: return {} @property def is_connected(self) -> bool: return self.bus_right.is_connected and self.bus_left.is_connected @check_if_already_connected def connect(self, calibrate: bool = True) -> None: logger.info(f"Connecting right arm on {self.config.port_right}...") self.bus_right.connect() logger.info(f"Connecting left arm on {self.config.port_left}...") self.bus_left.connect() if calibrate: self.calibrate() self.configure() logger.info(f"{self} connected.") @property def is_calibrated(self) -> bool: return self.bus_right.is_calibrated and self.bus_left.is_calibrated def calibrate(self) -> None: """ Run calibration procedure for OpenArm Mini. 1. Disable torque 2. Ask user to position arms in hanging position with grippers closed 3. Set this as zero position via half-turn homing 4. Interactive gripper calibration (open/close positions) 5. Save calibration """ if self.calibration: user_input = input( f"Press ENTER to use existing calibration for {self.id}, " f"or type 'c' and press ENTER to run new calibration: " ) if user_input.strip().lower() != "c": logger.info(f"Using existing calibration for {self.id}") cal_right = { k.replace("right_", ""): v for k, v in self.calibration.items() if k.startswith("right_") } cal_left = { k.replace("left_", ""): v for k, v in self.calibration.items() if k.startswith("left_") } self.bus_right.write_calibration(cal_right) self.bus_left.write_calibration(cal_left) return logger.info(f"\nRunning calibration for {self}") self._calibrate_arm("right", self.bus_right) self._calibrate_arm("left", self.bus_left) self._save_calibration() print(f"\nCalibration complete and saved to {self.calibration_fpath}") def _calibrate_arm(self, arm_name: str, bus: FeetechMotorsBus) -> None: """Calibrate a single arm with Feetech motors.""" logger.info(f"\n=== Calibrating {arm_name.upper()} arm ===") bus.disable_torque() logger.info(f"Setting Phase to 12 for all motors in {arm_name.upper()} arm...") for motor in bus.motors: bus.write("Phase", motor, 12) for motor in bus.motors: bus.write("Operating_Mode", motor, OperatingMode.POSITION.value) input( f"\nCalibration: Zero Position ({arm_name.upper()} arm)\n" "Position the arm in the following configuration:\n" " - Arm hanging straight down\n" " - Gripper closed\n" "Press ENTER when ready..." ) homing_offsets = bus.set_half_turn_homings() logger.info(f"{arm_name.capitalize()} arm zero position set.") print(f"\nSetting motor ranges for {arm_name.upper()} arm\n") if self.calibration is None: self.calibration = {} motor_resolution = bus.model_resolution_table[list(bus.motors.values())[0].model] max_res = motor_resolution - 1 for motor_name, motor in bus.motors.items(): prefixed_name = f"{arm_name}_{motor_name}" if motor_name == "gripper": input( f"\nGripper Calibration ({arm_name.upper()} arm)\n" f"Step 1: CLOSE the gripper fully\n" f"Press ENTER when gripper is closed..." ) closed_pos = bus.read("Present_Position", motor_name, normalize=False) logger.info(f" Gripper closed position recorded: {closed_pos}") input("\nStep 2: OPEN the gripper fully\nPress ENTER when gripper is fully open...") open_pos = bus.read("Present_Position", motor_name, normalize=False) logger.info(f" Gripper open position recorded: {open_pos}") if closed_pos < open_pos: range_min = int(closed_pos) range_max = int(open_pos) drive_mode = 0 else: range_min = int(open_pos) range_max = int(closed_pos) drive_mode = 1 logger.info( f" {prefixed_name}: range set to [{range_min}, {range_max}] " f"(0=closed, 100=open, drive_mode={drive_mode})" ) else: range_min = 0 range_max = max_res drive_mode = 0 logger.info(f" {prefixed_name}: range set to [0, {max_res}] (full motor range)") self.calibration[prefixed_name] = MotorCalibration( id=motor.id, drive_mode=drive_mode, homing_offset=homing_offsets[motor_name], range_min=range_min, range_max=range_max, ) cal_for_bus = { k.replace(f"{arm_name}_", ""): v for k, v in self.calibration.items() if k.startswith(f"{arm_name}_") } bus.write_calibration(cal_for_bus) def configure(self) -> None: self.bus_right.disable_torque() self.bus_right.configure_motors() for motor in self.bus_right.motors: self.bus_right.write("Operating_Mode", motor, OperatingMode.POSITION.value) self.bus_left.disable_torque() self.bus_left.configure_motors() for motor in self.bus_left.motors: self.bus_left.write("Operating_Mode", motor, OperatingMode.POSITION.value) def setup_motors(self) -> None: print("\nSetting up RIGHT arm motors...") for motor in reversed(self.bus_right.motors): input(f"Connect the controller board to the RIGHT '{motor}' motor only and press enter.") self.bus_right.setup_motor(motor) print(f"RIGHT '{motor}' motor id set to {self.bus_right.motors[motor].id}") print("\nSetting up LEFT arm motors...") for motor in reversed(self.bus_left.motors): input(f"Connect the controller board to the LEFT '{motor}' motor only and press enter.") self.bus_left.setup_motor(motor) print(f"LEFT '{motor}' motor id set to {self.bus_left.motors[motor].id}") @check_if_not_connected def get_action(self) -> RobotAction: """Get current action from both arms (read positions from all motors).""" start = time.perf_counter() right_positions = self.bus_right.sync_read("Present_Position") left_positions = self.bus_left.sync_read("Present_Position") action: dict[str, Any] = {} for motor, val in right_positions.items(): action[f"right_{motor}.pos"] = -val if motor in RIGHT_MOTORS_TO_FLIP else val for motor, val in left_positions.items(): action[f"left_{motor}.pos"] = -val if motor in LEFT_MOTORS_TO_FLIP else val dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} read action: {dt_ms:.1f}ms") return action def send_feedback(self, feedback: dict[str, float]) -> None: raise NotImplementedError("Feedback is not yet implemented for OpenArm Mini.") @check_if_not_connected def disconnect(self) -> None: self.bus_right.disconnect() self.bus_left.disconnect() logger.info(f"{self} disconnected.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/openarm_mini/openarm_mini.py", "license": "Apache License 2.0", "lines": 241, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/motors/robstride/robstride.py
# Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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. # TODO(Virgile) : Robustify mode control , only the MIT protocole is implemented for now import logging import time from contextlib import contextmanager from copy import deepcopy from functools import cached_property from types import SimpleNamespace from typing import TYPE_CHECKING, Any, TypedDict from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from lerobot.utils.import_utils import _can_available if TYPE_CHECKING or _can_available: import can else: can = SimpleNamespace(Message=object, interface=None) import numpy as np from lerobot.utils.errors import DeviceNotConnectedError from lerobot.utils.utils import enter_pressed, move_cursor_up from ..motors_bus import Motor, MotorCalibration, MotorsBusBase, NameOrID, Value from .tables import ( AVAILABLE_BAUDRATES, CAN_CMD_CLEAR_FAULT, CAN_CMD_DISABLE, CAN_CMD_ENABLE, CAN_CMD_SET_ZERO, DEFAULT_BAUDRATE, DEFAULT_TIMEOUT_MS, MODEL_RESOLUTION, MOTOR_LIMIT_PARAMS, NORMALIZED_DATA, PARAM_TIMEOUT, RUNNING_TIMEOUT, STATE_CACHE_TTL_S, ControlMode, MotorType, ) logger = logging.getLogger(__name__) class MotorState(TypedDict): position: float velocity: float torque: float temp_mos: float temp_rotor: float class RobstrideMotorsBus(MotorsBusBase): """ The Robstride implementation for a MotorsBus using CAN bus communication. This class uses python-can for CAN bus communication with Robstride motors. The motors need to be switched to MIT control mode to be compatible with this implementation. More details on the protocol can be found in the documentation links below: - python-can documentation: https://python-can.readthedocs.io/en/stable/ - Robstride CAN protocol: https://github.com/RobStride/MotorStudio """ # CAN-specific settings available_baudrates = deepcopy(AVAILABLE_BAUDRATES) default_baudrate = DEFAULT_BAUDRATE default_timeout = DEFAULT_TIMEOUT_MS # Motor configuration model_resolution_table = deepcopy(MODEL_RESOLUTION) normalized_data = deepcopy(NORMALIZED_DATA) def __init__( self, port: str, motors: dict[str, Motor], calibration: dict[str, MotorCalibration] | None = None, can_interface: str = "auto", use_can_fd: bool = True, bitrate: int = 1000000, data_bitrate: int | None = 5000000, ): """ Initialize the Robstride motors bus. Args: port: CAN interface name (e.g., "can0" for Linux, "/dev/cu.usbmodem*" for macOS) motors: Dictionary mapping motor names to Motor objects calibration: Optional calibration data can_interface: CAN interface type - "auto" (default), "socketcan" (Linux), or "slcan" (macOS/serial) use_can_fd: Whether to use CAN FD mode (default: True for OpenArms) bitrate: Nominal bitrate in bps (default: 1000000 = 1 Mbps) data_bitrate: Data bitrate for CAN FD in bps (default: 5000000 = 5 Mbps), ignored if use_can_fd is False """ super().__init__(port, motors, calibration) self.port = port self.can_interface = can_interface self.use_can_fd = use_can_fd self.bitrate = bitrate self.data_bitrate = data_bitrate self.canbus: can.BusABC | None = None self._is_connected = False # Map motor names to CAN IDs self._motor_can_ids: dict[str, int] = {} self._recv_id_to_motor: dict[int, str] = {} # Store motor types and recv IDs self._motor_types: dict[str, MotorType] = {} # Dynamic gains storage (Damiao-style update path via write/sync_write) self._gains: dict[str, dict[str, float]] = {} for name, motor in self.motors.items(): if motor.motor_type_str is not None: self._motor_types[name] = getattr(MotorType, motor.motor_type_str.upper()) else: # Default to O0if not specified self._motor_types[name] = MotorType.O0 # Damiao-style defaults: fixed gains at startup for every motor. self._gains[name] = {"kp": 10.0, "kd": 0.5} # Map recv_id to motor name for filtering responses if motor.recv_id is not None: self._recv_id_to_motor[motor.recv_id] = name # Motor Mode self.enabled: dict[str, bool] = {} self.operation_mode: dict[str, ControlMode] = {} self._last_known_states: dict[str, MotorState] = { name: { "position": 0.0, "velocity": 0.0, "torque": 0.0, "temp_mos": 0.0, "temp_rotor": 0.0, } for name in self.motors } self.last_feedback_time: dict[str, float | None] = {} self._id_to_name: dict[int, str] = {} for name in self.motors: self.enabled[name] = False self.operation_mode[name] = ControlMode.MIT # default mode self.last_feedback_time[name] = None for name, motor in self.motors.items(): key = motor.recv_id if motor.recv_id is not None else motor.id self._id_to_name[key] = name @property def is_connected(self) -> bool: """Check if the CAN bus is connected.""" return self._is_connected and self.canbus is not None def _bus(self) -> can.BusABC: if self.canbus is None: raise DeviceNotConnectedError(f"{self.__class__.__name__}('{self.port}') is not connected.") return self.canbus @check_if_already_connected def connect(self, handshake: bool = True) -> None: """ Open the CAN bus and initialize communication. Args: handshake: If True, ping all motors to verify they're present """ try: # Auto-detect interface type based on port name if self.can_interface == "auto": if self.port.startswith("/dev/"): self.can_interface = "slcan" logger.info(f"Auto-detected slcan interface for port {self.port}") else: self.can_interface = "socketcan" logger.info(f"Auto-detected socketcan interface for port {self.port}") kwargs = { "channel": self.port, "bitrate": self.bitrate, "interface": self.can_interface, } if self.can_interface == "socketcan" and self.use_can_fd and self.data_bitrate is not None: kwargs.update({"data_bitrate": self.data_bitrate, "fd": True}) logger.info( f"Connected to {self.port} with CAN FD (bitrate={self.bitrate}, data_bitrate={self.data_bitrate})" ) else: logger.info(f"Connected to {self.port} with {self.can_interface} (bitrate={self.bitrate})") self.canbus = can.interface.Bus(**kwargs) self._is_connected = True if handshake: self._handshake() logger.debug(f"{self.__class__.__name__} connected via {self.can_interface}.") except Exception as e: self._is_connected = False raise ConnectionError(f"Failed to connect to CAN bus: {e}") from e def _query_status_via_clear_fault(self, motor: NameOrID) -> tuple[bool, can.Message | None]: motor_name = self._get_motor_name(motor) motor_id = self._get_motor_id(motor_name) recv_id = self._get_motor_recv_id(motor_name) data = [0xFF] * 7 + [CAN_CMD_CLEAR_FAULT] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) return self._recv_status_via_clear_fault(expected_recv_id=recv_id) def _recv_status_via_clear_fault( self, expected_recv_id: int | None = None, timeout: float = RUNNING_TIMEOUT ) -> tuple[bool, can.Message | None]: """ Poll the bus for a response to a fault-clear request. Args: expected_recv_id: Only accept frames from this CAN ID when provided. timeout: Maximum time spent polling the bus in seconds. Returns: Tuple where the first element is True if a fault frame was received, and the second element is the CAN message (or None on timeout). """ start_time = time.time() while time.time() - start_time < timeout: msg = self._bus().recv(timeout=RUNNING_TIMEOUT / 10) if not msg: continue if expected_recv_id is not None and msg.data[0] != expected_recv_id: continue # Fault-status frame heuristic (doc-based) fault_bits = int.from_bytes(msg.data[1:5], "little") if fault_bits != 0 and msg.data[5] == msg.data[6] == msg.data[7] == 0: logger.error( f"Motor fault received from CAN ID 0x{msg.arbitration_id:02X}: " f"fault_bits=0x{fault_bits:08X}" ) return True, msg # Otherwise: valid normal response return False, msg return False, None def update_motor_state(self, motor: NameOrID) -> bool: has_fault, msg = self._query_status_via_clear_fault(motor) if msg is None: logger.warning(f"No response received from motor '{motor}' during state update.") raise ConnectionError(f"No response received from motor '{motor}' during state update.") if has_fault: logger.error(f"Fault reported by motor '{motor}' during state update. msg={msg.data.hex()}") raise RuntimeError(f"Fault reported by motor '{motor}' during state update.") self._decode_motor_state(msg.data) # updates cache return True def _handshake(self) -> None: logger.info("Starting handshake with motors...") missing_motors = [] faulted_motors = [] for motor_name in self.motors: has_fault, msg = self._query_status_via_clear_fault(motor_name) if msg is None: missing_motors.append(motor_name) elif has_fault: faulted_motors.append(motor_name) else: # CLEAR_FAULT responses are not guaranteed to always match the MIT feedback layout # on all firmware versions. Handshake should not fail just because cache warm-up fails. try: self._decode_motor_state(msg.data) except Exception as e: logger.debug( "Handshake cache warm-up decode failed for motor '%s': %s", motor_name, e, ) time.sleep(0.01) if missing_motors or faulted_motors: details = [] if missing_motors: details.append(f"did not respond: {missing_motors}") if faulted_motors: details.append(f"reported fault: {faulted_motors}") raise ConnectionError("Handshake failed. " + "; ".join(details)) logger.info("Handshake successful. All motors ready.") def _switch_operation_mode(self, motor: NameOrID, mode: ControlMode) -> None: """Switch the operation mode of a motor.""" motor_name = self._get_motor_name(motor) motor_id = self._get_motor_id(motor_name) recv_id = self._get_motor_recv_id(motor_name) data = [0xFF] * 8 data[6] = mode.value data[7] = 0xFC msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) msg = self._recv_motor_response(expected_recv_id=recv_id, timeout=PARAM_TIMEOUT) if msg is not None: self.operation_mode[motor_name] = mode @check_if_not_connected def disconnect(self, disable_torque: bool = True) -> None: """ Close the CAN bus connection. Args: disable_torque: If True, disable torque on all motors before disconnecting """ if disable_torque: try: self.disable_torque() except Exception as e: logger.warning(f"Failed to disable torque during disconnect: {e}") if self.canbus: self.canbus.shutdown() self.canbus = None self._is_connected = False logger.debug(f"{self.__class__.__name__} disconnected.") def configure_motors(self) -> None: """Configure all motors with default settings.""" # Robstride motors don't require much configuration in MIT mode # Just ensure they're enabled for motor in self.motors: self._enable_motor(self._get_motor_name(motor)) self._switch_operation_mode(motor, ControlMode.MIT) time.sleep(0.01) def switch_to_mode(self, mode: ControlMode) -> None: """Switch operation mode on selected motors.""" for motor in self.motors: self._switch_operation_mode(motor, mode) time.sleep(0.01) def _enable_motor(self, motor: NameOrID) -> None: """Enable a single motor.""" motor_id = self._get_motor_id(motor) recv_id = self._get_motor_recv_id(motor) data = [0xFF] * 7 + [CAN_CMD_ENABLE] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) self._recv_motor_response(expected_recv_id=recv_id, timeout=PARAM_TIMEOUT) def _disable_motor(self, motor: NameOrID) -> None: """Disable a single motor.""" motor_id = self._get_motor_id(motor) recv_id = self._get_motor_recv_id(motor) data = [0xFF] * 7 + [CAN_CMD_DISABLE] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) self._recv_motor_response(expected_recv_id=recv_id) def enable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None: """Enable torque on selected motors.""" motors = self._get_motors_list(motors) for motor in motors: for _ in range(num_retry + 1): try: self._get_motor_name(motor) self._enable_motor(self._get_motor_name(motor)) break except Exception as e: if _ == num_retry: raise e time.sleep(0.01) def disable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None: """Disable torque on selected motors.""" motors = self._get_motors_list(motors) for motor in motors: for _ in range(num_retry + 1): try: self._disable_motor(self._get_motor_name(motor)) break except Exception as e: if _ == num_retry: raise e time.sleep(0.01) @contextmanager def torque_disabled(self, motors: str | list[str] | None = None): """ Context manager that guarantees torque is re-enabled. This helper is useful to temporarily disable torque when configuring motors. Examples: >>> with bus.torque_disabled(): ... # Safe operations here with torque disabled ... pass """ self.disable_torque(motors) try: yield finally: self.enable_torque(motors) def set_zero_position(self, motors: str | list[str] | None = None) -> None: """Set current position as zero for selected motors.""" motors = self._get_motors_list(motors) for motor in motors: motor_id = self._get_motor_id(motor) recv_id = self._get_motor_recv_id(motor) data = [0xFF] * 7 + [CAN_CMD_SET_ZERO] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) self._recv_motor_response(expected_recv_id=recv_id) time.sleep(0.01) def _recv_motor_response( self, expected_recv_id: int | None = None, timeout: float = 0.001 ) -> can.Message | None: """ Receive a response from a motor. Args: expected_recv_id: If provided, only return messages from this CAN ID timeout: Timeout in seconds (default: 1ms for high-speed operation) Returns: CAN message if received, None otherwise """ try: start_time = time.time() messages_seen = [] while time.time() - start_time < timeout: msg = self._bus().recv(timeout=RUNNING_TIMEOUT / 10) # 100us timeout for fast polling if msg: messages_seen.append(f"0x{msg.arbitration_id:02X}") # If no filter specified, return any message if expected_recv_id is None: return msg # Otherwise, only return if it matches the expected recv_id if msg.data[0] == expected_recv_id: return msg else: logger.debug( f"Ignoring message from CAN ID 0x{msg.arbitration_id:02X}, expected 0x{expected_recv_id:02X}" ) # Only log warnings if we're in debug mode to reduce overhead if logger.isEnabledFor(logging.DEBUG): if messages_seen: logger.debug( f"Received {len(messages_seen)} message(s) from IDs {set(messages_seen)}, but expected 0x{expected_recv_id:02X}" ) else: logger.debug(f"No CAN messages received (expected from 0x{expected_recv_id:02X})") except Exception as e: logger.debug(f"Failed to receive CAN message: {e}") return None def _recv_all_responses( self, expected_recv_ids: list[int], timeout: float = 0.002 ) -> dict[int, can.Message]: """ Efficiently receive responses from multiple motors at once. Uses the OpenArms pattern: collect all available messages within timeout. Args: expected_recv_ids: List of CAN IDs we expect responses from timeout: Total timeout in seconds (default: 2ms) Returns: Dictionary mapping recv_id to CAN message """ responses: dict[int, can.Message] = {} expected_set = set(expected_recv_ids) start_time = time.time() try: while len(responses) < len(expected_recv_ids) and (time.time() - start_time) < timeout: msg = self._bus().recv(timeout=RUNNING_TIMEOUT / 10) # 100us poll timeout if msg and msg.data[0] in expected_set: responses[msg.data[0]] = msg if len(responses) == len(expected_recv_ids): break # Got all responses, exit early except Exception as e: logger.debug(f"Error receiving responses: {e}") return responses def _speed_control( self, motor: NameOrID, velocity_deg_per_sec: float, current_limit_a: float, ) -> None: """ Send a Velocity Mode Control Command (Command 11) to a single motor. Args: motor: Motor name or CAN ID. velocity_rad_per_sec: Target speed in rad/s (32-bit float). current_limit_a: Current limit in A (32-bit float). """ if not self.is_connected: raise DeviceNotConnectedError(f"{self} is not connected.") motor_id = self._get_motor_id(motor) motor_name = self._get_motor_name(motor) # Optional: ensure the motor is in velocity control mode if self.operation_mode[motor_name] != ControlMode.VEL: raise RuntimeError(f"Motor '{motor_name}' is not in velocity control mode.") # Convert to rad/s to match protocol specification velocity_rad_per_sec = np.radians(velocity_deg_per_sec) # Encode float32 little-endian without struct (byte list) def _float32_to_le_bytes(x: float) -> list[int]: b = np.float32(x).tobytes() # 4 bytes, little-endian return [b[0], b[1], b[2], b[3]] speed_bytes = _float32_to_le_bytes(velocity_rad_per_sec) limit_bytes = _float32_to_le_bytes(current_limit_a) data = speed_bytes + limit_bytes # 8 octets : [0–3]=speed, [4–7]=current limit msg = can.Message( arbitration_id=motor_id, data=data, is_extended_id=False, ) self._bus().send(msg) # Si le proto renvoie une réponse type état, on peut la décoder comme pour MIT recv_id = self._get_motor_recv_id(motor) if recv_id is not None: resp = self._recv_motor_response(expected_recv_id=recv_id) if resp: self._decode_motor_state(resp.data) def _mit_control( self, motor: NameOrID, kp: float, kd: float, position_degrees: float, velocity_deg_per_sec: float, torque: float, *, wait_for_response: bool = True, ) -> None: """ Send MIT control command to a motor. Args: motor: Motor name or ID kp: Position gain kd: Velocity gain position_degrees: Target position (degrees) velocity_deg_per_sec: Target velocity (degrees/s) torque: Target torque (N·m) """ motor_name = self._get_motor_name(motor) motor_type = self._motor_types[motor_name] if self.operation_mode[motor_name] != ControlMode.MIT: raise RuntimeError(f"Motor '{motor_name}' is not in MIT control mode.") motor_id = self._get_motor_id(motor) data = self._encode_mit_packet(motor_type, kp, kd, position_degrees, velocity_deg_per_sec, torque) msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) if wait_for_response: recv_id = self._get_motor_recv_id(motor) msg = self._recv_motor_response(expected_recv_id=recv_id) if msg: self._process_response(motor_name, msg) def _encode_mit_packet( self, motor_type: MotorType, kp: float, kd: float, position_degrees: float, velocity_deg_per_sec: float, torque: float, ) -> list[int]: """Encode an MIT control command payload from physical units.""" position_rad = np.radians(position_degrees) velocity_rad_per_sec = np.radians(velocity_deg_per_sec) pmax, vmax, tmax = MOTOR_LIMIT_PARAMS[motor_type] kp_uint = self._float_to_uint(kp, 0, 500, 12) kd_uint = self._float_to_uint(kd, 0, 5, 12) q_uint = self._float_to_uint(position_rad, -pmax, pmax, 16) dq_uint = self._float_to_uint(velocity_rad_per_sec, -vmax, vmax, 12) tau_uint = self._float_to_uint(torque, -tmax, tmax, 12) data = [0] * 8 data[0] = (q_uint >> 8) & 0xFF data[1] = q_uint & 0xFF data[2] = dq_uint >> 4 data[3] = ((dq_uint & 0xF) << 4) | ((kp_uint >> 8) & 0xF) data[4] = kp_uint & 0xFF data[5] = kd_uint >> 4 data[6] = ((kd_uint & 0xF) << 4) | ((tau_uint >> 8) & 0xF) data[7] = tau_uint & 0xFF return data def _mit_control_batch( self, commands: dict[NameOrID, tuple[float, float, float, float, float]], ) -> None: """Send MIT commands in batch and update cache from collected responses.""" if not commands: return recv_id_to_motor: dict[int, str] = {} for motor, (kp, kd, position_degrees, velocity_deg_per_sec, torque) in commands.items(): motor_name = self._get_motor_name(motor) if self.operation_mode[motor_name] != ControlMode.MIT: raise RuntimeError(f"Motor '{motor_name}' is not in MIT control mode.") motor_id = self._get_motor_id(motor) motor_type = self._motor_types[motor_name] data = self._encode_mit_packet(motor_type, kp, kd, position_degrees, velocity_deg_per_sec, torque) msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) recv_id_to_motor[self._get_motor_recv_id(motor)] = motor_name responses = self._recv_all_responses(list(recv_id_to_motor.keys()), timeout=RUNNING_TIMEOUT) for recv_id, motor_name in recv_id_to_motor.items(): if msg := responses.get(recv_id): self._process_response(motor_name, msg) def _float_to_uint(self, x: float, x_min: float, x_max: float, bits: int) -> int: """Convert float to unsigned integer for CAN transmission.""" x = max(x_min, min(x_max, x)) # Clamp to range span = x_max - x_min data_norm = (x - x_min) / span return int(data_norm * ((1 << bits) - 1)) def _uint_to_float(self, x: int, x_min: float, x_max: float, bits: int) -> float: """Convert unsigned integer from CAN to float.""" span = x_max - x_min data_norm = float(x) / ((1 << bits) - 1) return data_norm * span + x_min def _decode_motor_state(self, data: bytearray | bytes) -> tuple[float, float, float, float]: """ Decode motor state from CAN data. Returns: Tuple of (position_degrees, velocity_deg_per_sec, torque, temp_mos) """ if len(data) < 8: raise ValueError("Invalid motor state data") # Extract encoded values motor_id = data[0] motor_name = self._id_to_name[motor_id] q_uint = (data[1] << 8) | data[2] dq_uint = (data[3] << 4) | (data[4] >> 4) tau_uint = ((data[4] & 0x0F) << 8) | data[5] t_mos = (data[6] << 8) | data[7] motor_type = self._motor_types[motor_name] # Get motor limits pmax, vmax, tmax = MOTOR_LIMIT_PARAMS[motor_type] # Decode to physical values (radians) position_rad = self._uint_to_float(q_uint, -pmax, pmax, 16) velocity_rad_per_sec = self._uint_to_float(dq_uint, -vmax, vmax, 12) torque = self._uint_to_float(tau_uint, -tmax, tmax, 12) # Convert to degrees position_degrees = np.degrees(position_rad) velocity_deg_per_sec = np.degrees(velocity_rad_per_sec) # Update cached state self.last_feedback_time[motor_name] = time.time() self._last_known_states[motor_name] = { "position": position_degrees, "velocity": velocity_deg_per_sec, "torque": torque, "temp_mos": t_mos / 10, # Not available in Robstride MIT feedback. "temp_rotor": 0.0, } return position_degrees, velocity_deg_per_sec, torque, t_mos / 10 def _process_response(self, motor: str, msg: can.Message) -> None: """Decode a feedback frame and update the cache for one motor.""" try: self._decode_motor_state(msg.data) except Exception as e: logger.warning(f"Failed to decode response from {motor}: {e}") def _get_cached_value(self, motor: str, data_name: str) -> Value: """Retrieve a specific value from the state cache.""" state = self._last_known_states[motor] mapping: dict[str, Any] = { "Present_Position": state["position"], "Present_Velocity": state["velocity"], "Present_Torque": state["torque"], "Temperature_MOS": state["temp_mos"], } if data_name == "Temperature_Rotor": raise NotImplementedError("Rotor temperature reading not accessible.") if data_name not in mapping: raise ValueError(f"Unknown data_name: {data_name}") return mapping[data_name] @check_if_not_connected def read( self, data_name: str, motor: str, ) -> Value: """Read a value from a single motor. Positions are always in degrees.""" # Refresh motor to get latest state t_init = time.time() if ( self.last_feedback_time[motor] is None or t_init - (self.last_feedback_time[motor] or 0) > STATE_CACHE_TTL_S ): self.update_motor_state(motor) return self._get_cached_value(motor, data_name) @check_if_not_connected def write( self, data_name: str, motor: str, value: Value, ) -> None: """Write a value to a single motor. Positions are always in degrees.""" motor_name = self._get_motor_name(motor) if data_name in ("Kp", "Kd"): self._gains[motor_name][data_name.lower()] = float(value) elif data_name == "Goal_Position": # Use MIT control with position in degrees kp = self._gains[motor_name]["kp"] kd = self._gains[motor_name]["kd"] self._mit_control(motor, kp, kd, value, 0, 0) elif data_name == "Goal_Velocity": # Use Velocity control mode if self.operation_mode[motor_name] != ControlMode.VEL: raise RuntimeError(f"Motor '{motor_name}' is not in velocity control mode.") current_limit_a = 5.0 # Example current limit / not specified in doc. This mode is rarely used and primarily intended for diagnostics self._speed_control(motor, value, current_limit_a) else: raise ValueError(f"Writing {data_name} not supported in MIT mode") def sync_read( self, data_name: str, motors: str | list[str] | None = None, ) -> dict[str, Value]: """ Read the same value from multiple motors simultaneously. Uses batched operations: sends all refresh commands, then collects all responses. This is MUCH faster than sequential reads (OpenArms pattern). """ target_motors = self._get_motors_list(motors) self._batch_refresh(target_motors) return {motor: self._get_cached_value(motor, data_name) for motor in target_motors} @check_if_not_connected def sync_write( self, data_name: str, values: dict[str, Value], ) -> None: """ Write different values to multiple motors simultaneously. Positions are always in degrees. Uses batched operations: sends all commands first, then collects responses when MIT mode is used, otherwise send cmd and wait for response for each motor). """ if data_name in ("Kp", "Kd"): key = data_name.lower() for motor, val in values.items(): motor_name = self._get_motor_name(motor) self._gains[motor_name][key] = float(val) elif data_name == "Goal_Position": commands: dict[NameOrID, tuple[float, float, float, float, float]] = {} for motor, value_degrees in values.items(): motor_name = self._get_motor_name(motor) commands[motor] = ( self._gains[motor_name]["kp"], self._gains[motor_name]["kd"], float(value_degrees), 0.0, 0.0, ) self._mit_control_batch(commands) else: # Fall back to individual writes for other data types for motor, value in values.items(): self.write(data_name, motor, value) def sync_read_all_states( self, motors: str | list[str] | None = None, *, num_retry: int = 0, ) -> dict[str, MotorState]: """ Read ALL motor states (position, velocity, torque) with Robstride TTL refresh policy. """ target_motors = self._get_motors_list(motors) self._batch_refresh(target_motors) return {motor: self._last_known_states[motor].copy() for motor in target_motors} def _batch_refresh(self, motors: list[str]) -> None: """Refresh a set of motors and update the feedback cache.""" init_time = time.time() updated_motors: list[str] = [] for motor in motors: if ( self.last_feedback_time[motor] is not None and (init_time - (self.last_feedback_time[motor] or 0)) < STATE_CACHE_TTL_S ): continue motor_id = self._get_motor_id(motor) data = [0xFF] * 7 + [CAN_CMD_CLEAR_FAULT] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False) self._bus().send(msg) updated_motors.append(motor) expected_recv_ids = [self._get_motor_recv_id(motor) for motor in updated_motors] responses = self._recv_all_responses(expected_recv_ids, timeout=RUNNING_TIMEOUT) for response in responses.values(): payload_motor_name = self._recv_id_to_motor.get(response.data[0]) if payload_motor_name is not None: self._process_response(payload_motor_name, response) else: # Fallback: still attempt to decode based on payload byte0 mapping. self._decode_motor_state(response.data) for motor in updated_motors: recv_id = self._get_motor_recv_id(motor) if recv_id not in responses: logger.warning(f"Packet drop: {motor} (ID: 0x{recv_id:02X}). Using last known state.") def read_calibration(self) -> dict[str, MotorCalibration]: """Read calibration data from motors.""" # Robstride motors don't store calibration internally # Return existing calibration or empty dict return self.calibration if self.calibration else {} def write_calibration(self, calibration_dict: dict[str, MotorCalibration], cache: bool = True) -> None: """Write calibration data to motors.""" # Robstride motors don't store calibration internally # Just cache it in memory if cache: self.calibration = calibration_dict def record_ranges_of_motion( self, motors: str | list[str] | None = None, display_values: bool = True ) -> tuple[dict[str, Value], dict[str, Value]]: """ Interactively record the min/max values of each motor in degrees. Move the joints by hand (with torque disabled) while the method streams live positions. Press Enter to finish. """ target_motors = self._get_motors_list(motors) # Disable torque for manual movement self.disable_torque(target_motors) time.sleep(0.1) # Get initial positions (already in degrees) start_positions = self.sync_read("Present_Position", target_motors) mins = start_positions.copy() maxes = start_positions.copy() print("\nMove joints through their full range of motion. Press ENTER when done.") user_pressed_enter = False while not user_pressed_enter: positions = self.sync_read("Present_Position", target_motors) for motor in target_motors: if motor in positions: mins[motor] = int( min( positions[motor], mins.get(motor, positions[motor]), ) ) maxes[motor] = int( max( positions[motor], maxes.get(motor, positions[motor]), ) ) if display_values: print("\n" + "=" * 50) print(f"{'MOTOR':<20} | {'MIN (deg)':>12} | {'POS (deg)':>12} | {'MAX (deg)':>12}") print("-" * 50) for motor in target_motors: if motor in positions: print( f"{motor:<20} | {mins[motor]:>12.1f} | {positions[motor]:>12.1f} | {maxes[motor]:>12.1f}" ) if enter_pressed(): user_pressed_enter = True if display_values and not user_pressed_enter: # Move cursor up to overwrite the previous output move_cursor_up(len(target_motors) + 4) time.sleep(0.05) # Re-enable torque self.enable_torque(target_motors) # Validate ranges for motor in target_motors: if (motor in mins) and (motor in maxes) and (abs(maxes[motor] - mins[motor]) < 5.0): raise ValueError(f"Motor {motor} has insufficient range of motion (< 5 degrees)") return mins, maxes def _get_motors_list(self, motors: str | list[str] | None) -> list[str]: """Convert motor specification to list of motor names.""" if motors is None: return list(self.motors.keys()) elif isinstance(motors, str): return [motors] elif isinstance(motors, list): return motors else: raise TypeError(f"Invalid motors type: {type(motors)}") def _get_motor_id(self, motor: NameOrID) -> int: """Get CAN ID for a motor.""" if isinstance(motor, str): if motor in self.motors: return self.motors[motor].id else: raise ValueError(f"Unknown motor: {motor}") else: return motor def _get_motor_name(self, motor: NameOrID) -> str: """Get motor name from name or ID.""" if isinstance(motor, str): return motor else: for name, m in self.motors.items(): if m.id == motor: return name raise ValueError(f"Unknown motor ID: {motor}") def _get_motor_recv_id(self, motor: NameOrID) -> int: """Return the expected ID found in feedback payload byte0 for this motor. Robstride MIT feedback frames encode an ID in data[0]. Some setups expose it as `motor.recv_id`; otherwise we fall back to the configured `motor.id`. """ motor_name = self._get_motor_name(motor) motor_obj = self.motors[motor_name] recv_id = getattr(motor_obj, "recv_id", None) if recv_id is None: logger.debug( "Motor '%s' has no recv_id; falling back to motor.id=%s for feedback demux.", motor_name, motor_obj.id, ) return motor_obj.id return recv_id @cached_property def is_calibrated(self) -> bool: """Check if motors are calibrated.""" return bool(self.calibration)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/motors/robstride/robstride.py", "license": "Apache License 2.0", "lines": 866, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/motors/robstride/tables.py
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Configuration tables for Damiao motors.""" from enum import IntEnum # Motor type definitions class MotorType(IntEnum): O0 = 0 O1 = 1 O2 = 2 O3 = 3 O4 = 4 O5 = 5 ELO5 = 6 O6 = 7 class CommMode(IntEnum): PrivateProtocole = 0 CANopen = 1 MIT = 2 # Control modes class ControlMode(IntEnum): MIT = 0 POS_VEL = 1 VEL = 2 # Motor limit parameters [PMAX, VMAX, TMAX] # PMAX: Maximum position (rad) # VMAX: Maximum velocity (rad/s) # TMAX: Maximum torque (N·m) MOTOR_LIMIT_PARAMS: dict[MotorType, tuple[float, float, float]] = { MotorType.O0: (12.57, 33, 14), MotorType.O1: (12.57, 44, 17), MotorType.O2: (12.57, 33, 20), MotorType.O3: (12.57, 33, 60), MotorType.O4: (12.57, 33, 120), MotorType.O5: (12.57, 50, 5.5), MotorType.ELO5: (12.57, 50, 6), MotorType.O6: (112.5, 50, 36), } # Motor model names MODEL_NAMES = { MotorType.O0: "O0", MotorType.O1: "O1", MotorType.O2: "O2", MotorType.O3: "O3", MotorType.O4: "O4", MotorType.O5: "O5", MotorType.ELO5: "ELO5", MotorType.O6: "O6", } # Motor resolution table (encoder counts per revolution) MODEL_RESOLUTION = { "O0": 65536, "O1": 65536, "O2": 65536, "O3": 65536, "O4": 65536, "O5": 65536, "ELO5": 65536, "O6": 65536, } # CAN baudrates supported by Robstride motors AVAILABLE_BAUDRATES = [ 1000000, # 4: 1 mbps (default) ] DEFAULT_BAUDRATE = 1000000 # Default timeout in milliseconds DEFAULT_TIMEOUT_MS = 0 # disabled by default, otherwise 20000 is 1s # Data that should be normalized NORMALIZED_DATA = ["Present_Position", "Goal_Position"] # MIT control parameter ranges MIT_KP_RANGE = (0.0, 500.0) MIT_KD_RANGE = (0.0, 5.0) # CAN frame command IDs CAN_CMD_ENABLE = 0xFC CAN_CMD_DISABLE = 0xFD CAN_CMD_SET_ZERO = 0xFE CAN_CMD_CLEAR_FAULT = 0xFB CAN_CMD_QUERY_PARAM = 0x33 CAN_CMD_WRITE_PARAM = 0x55 CAN_CMD_SAVE_PARAM = 0xAA # CAN ID for parameter operations CAN_PARAM_ID = 0x7FF RUNNING_TIMEOUT = 0.001 PARAM_TIMEOUT = 0.01 STATE_CACHE_TTL_S = 0.02
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/motors/robstride/tables.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/datasets/test_streaming_video_encoder.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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. """Tests for streaming video encoding and hardware-accelerated encoding.""" import queue import threading from unittest.mock import patch import av import numpy as np import pytest from lerobot.datasets.video_utils import ( VALID_VIDEO_CODECS, StreamingVideoEncoder, _CameraEncoderThread, _get_codec_options, detect_available_hw_encoders, resolve_vcodec, ) from lerobot.utils.constants import OBS_IMAGES # ─── _get_codec_options tests ─── class TestGetCodecOptions: def test_libsvtav1_defaults(self): opts = _get_codec_options("libsvtav1") assert opts["g"] == "2" assert opts["crf"] == "30" assert opts["preset"] == "12" def test_libsvtav1_custom_preset(self): opts = _get_codec_options("libsvtav1", preset=8) assert opts["preset"] == "8" def test_h264_options(self): opts = _get_codec_options("h264", g=10, crf=23) assert opts["g"] == "10" assert opts["crf"] == "23" assert "preset" not in opts def test_videotoolbox_options(self): opts = _get_codec_options("h264_videotoolbox", g=2, crf=30) assert opts["g"] == "2" # CRF 30 maps to quality = max(1, min(100, 100 - 30*2)) = 40 assert opts["q:v"] == "40" assert "crf" not in opts def test_nvenc_options(self): opts = _get_codec_options("h264_nvenc", g=2, crf=25) assert opts["rc"] == "constqp" assert opts["qp"] == "25" assert "crf" not in opts # NVENC doesn't support g assert "g" not in opts def test_vaapi_options(self): opts = _get_codec_options("h264_vaapi", crf=28) assert opts["qp"] == "28" def test_qsv_options(self): opts = _get_codec_options("h264_qsv", crf=25) assert opts["global_quality"] == "25" def test_no_g_no_crf(self): opts = _get_codec_options("h264", g=None, crf=None) assert "g" not in opts assert "crf" not in opts # ─── HW encoder detection tests ─── class TestHWEncoderDetection: def test_detect_available_hw_encoders_returns_list(self): result = detect_available_hw_encoders() assert isinstance(result, list) def test_detect_available_hw_encoders_only_valid(self): from lerobot.datasets.video_utils import HW_ENCODERS result = detect_available_hw_encoders() for encoder in result: assert encoder in HW_ENCODERS def test_resolve_vcodec_passthrough(self): assert resolve_vcodec("libsvtav1") == "libsvtav1" assert resolve_vcodec("h264") == "h264" def test_resolve_vcodec_auto_fallback(self): """When no HW encoders are available, auto should fall back to libsvtav1.""" with patch("lerobot.datasets.video_utils.detect_available_hw_encoders", return_value=[]): assert resolve_vcodec("auto") == "libsvtav1" def test_resolve_vcodec_auto_picks_hw(self): """When a HW encoder is available, auto should pick it.""" with patch( "lerobot.datasets.video_utils.detect_available_hw_encoders", return_value=["h264_videotoolbox"], ): assert resolve_vcodec("auto") == "h264_videotoolbox" def test_resolve_vcodec_auto_returns_valid(self): """Test that resolve_vcodec('auto') returns a known valid codec.""" result = resolve_vcodec("auto") assert result in VALID_VIDEO_CODECS def test_hw_encoder_names_accepted_in_validation(self): """Test that HW encoder names pass validation in VALID_VIDEO_CODECS.""" assert "auto" in VALID_VIDEO_CODECS assert "h264_videotoolbox" in VALID_VIDEO_CODECS assert "h264_nvenc" in VALID_VIDEO_CODECS def test_resolve_vcodec_invalid_raises(self): """Test that resolve_vcodec raises ValueError for invalid codecs.""" with pytest.raises(ValueError, match="Invalid vcodec"): resolve_vcodec("not_a_real_codec") # ─── _CameraEncoderThread tests ─── class TestCameraEncoderThread: def test_encodes_valid_mp4(self, tmp_path): """Test that the encoder thread creates a valid MP4 file with correct frame count.""" num_frames = 30 height, width = 64, 96 fps = 30 video_path = tmp_path / "test_output" / "test.mp4" frame_queue: queue.Queue = queue.Queue(maxsize=60) result_queue: queue.Queue = queue.Queue(maxsize=1) stop_event = threading.Event() encoder_thread = _CameraEncoderThread( video_path=video_path, fps=fps, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, preset=13, frame_queue=frame_queue, result_queue=result_queue, stop_event=stop_event, ) encoder_thread.start() # Feed frames (HWC uint8) for _ in range(num_frames): frame = np.random.randint(0, 255, (height, width, 3), dtype=np.uint8) frame_queue.put(frame) # Send sentinel frame_queue.put(None) encoder_thread.join(timeout=60) assert not encoder_thread.is_alive() # Check result status, data = result_queue.get(timeout=5) assert status == "ok" assert data is not None # Stats should be returned assert "mean" in data assert "std" in data assert "min" in data assert "max" in data assert "count" in data # Verify the MP4 file is valid assert video_path.exists() with av.open(str(video_path)) as container: stream = container.streams.video[0] # The frame count should match total_frames = sum(1 for _ in container.decode(stream)) assert total_frames == num_frames def test_handles_chw_input(self, tmp_path): """Test that CHW format input is handled correctly.""" num_frames = 5 fps = 30 video_path = tmp_path / "test_chw" / "test.mp4" frame_queue: queue.Queue = queue.Queue(maxsize=60) result_queue: queue.Queue = queue.Queue(maxsize=1) stop_event = threading.Event() encoder_thread = _CameraEncoderThread( video_path=video_path, fps=fps, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, preset=13, frame_queue=frame_queue, result_queue=result_queue, stop_event=stop_event, ) encoder_thread.start() # Feed CHW frames for _ in range(num_frames): frame = np.random.randint(0, 255, (3, 64, 96), dtype=np.uint8) frame_queue.put(frame) frame_queue.put(None) encoder_thread.join(timeout=60) status, _ = result_queue.get(timeout=5) assert status == "ok" assert video_path.exists() def test_stop_event_cancellation(self, tmp_path): """Test that setting the stop event causes the thread to exit.""" fps = 30 video_path = tmp_path / "test_cancel" / "test.mp4" frame_queue: queue.Queue = queue.Queue(maxsize=60) result_queue: queue.Queue = queue.Queue(maxsize=1) stop_event = threading.Event() encoder_thread = _CameraEncoderThread( video_path=video_path, fps=fps, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, preset=13, frame_queue=frame_queue, result_queue=result_queue, stop_event=stop_event, ) encoder_thread.start() # Feed a few frames for _ in range(3): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) frame_queue.put(frame) # Signal stop instead of sending sentinel stop_event.set() encoder_thread.join(timeout=10) assert not encoder_thread.is_alive() # ─── StreamingVideoEncoder tests ─── class TestStreamingVideoEncoder: def test_single_camera_episode(self, tmp_path): """Test encoding a single camera episode.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, preset=13) video_keys = [f"{OBS_IMAGES}.laptop"] encoder.start_episode(video_keys, tmp_path) num_frames = 20 for _ in range(num_frames): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.laptop", frame) results = encoder.finish_episode() assert f"{OBS_IMAGES}.laptop" in results mp4_path, stats = results[f"{OBS_IMAGES}.laptop"] assert mp4_path.exists() assert stats is not None # Verify frame count with av.open(str(mp4_path)) as container: stream = container.streams.video[0] total_frames = sum(1 for _ in container.decode(stream)) assert total_frames == num_frames encoder.close() def test_multi_camera_episode(self, tmp_path): """Test encoding multiple cameras simultaneously.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30) video_keys = [f"{OBS_IMAGES}.laptop", f"{OBS_IMAGES}.phone"] encoder.start_episode(video_keys, tmp_path) num_frames = 15 for _ in range(num_frames): frame0 = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) frame1 = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(video_keys[0], frame0) encoder.feed_frame(video_keys[1], frame1) results = encoder.finish_episode() for key in video_keys: assert key in results mp4_path, stats = results[key] assert mp4_path.exists() assert stats is not None encoder.close() def test_sequential_episodes(self, tmp_path): """Test that multiple sequential episodes work correctly.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30) video_keys = [f"{OBS_IMAGES}.cam"] for ep in range(3): encoder.start_episode(video_keys, tmp_path) num_frames = 10 + ep * 5 for _ in range(num_frames): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.cam", frame) results = encoder.finish_episode() mp4_path, stats = results[f"{OBS_IMAGES}.cam"] assert mp4_path.exists() with av.open(str(mp4_path)) as container: stream = container.streams.video[0] total_frames = sum(1 for _ in container.decode(stream)) assert total_frames == num_frames encoder.close() def test_cancel_episode(self, tmp_path): """Test that canceling an episode cleans up properly.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30) video_keys = [f"{OBS_IMAGES}.cam"] encoder.start_episode(video_keys, tmp_path) for _ in range(5): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.cam", frame) encoder.cancel_episode() # Should be able to start a new episode after cancel encoder.start_episode(video_keys, tmp_path) for _ in range(5): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.cam", frame) results = encoder.finish_episode() assert f"{OBS_IMAGES}.cam" in results encoder.close() def test_feed_without_start_raises(self, tmp_path): """Test that feeding frames without starting an episode raises.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p") with pytest.raises(RuntimeError, match="No active episode"): encoder.feed_frame("cam", np.zeros((64, 96, 3), dtype=np.uint8)) encoder.close() def test_finish_without_start_raises(self, tmp_path): """Test that finishing without starting raises.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p") with pytest.raises(RuntimeError, match="No active episode"): encoder.finish_episode() encoder.close() def test_close_is_idempotent(self, tmp_path): """Test that close() can be called multiple times safely.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p") encoder.close() encoder.close() # Should not raise def test_video_duration_matches_frame_count(self, tmp_path): """Test that encoded video duration matches num_frames / fps.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, preset=13) video_keys = [f"{OBS_IMAGES}.cam"] encoder.start_episode(video_keys, tmp_path) num_frames = 90 # 3 seconds at 30fps for _ in range(num_frames): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.cam", frame) results = encoder.finish_episode() mp4_path, _ = results[f"{OBS_IMAGES}.cam"] expected_duration = num_frames / 30.0 # 3.0 seconds with av.open(str(mp4_path)) as container: stream = container.streams.video[0] total_frames = sum(1 for _ in container.decode(stream)) if stream.duration is not None: actual_duration = float(stream.duration * stream.time_base) else: actual_duration = float(container.duration / av.time_base) assert total_frames == num_frames # Allow small tolerance for duration due to codec framing assert abs(actual_duration - expected_duration) < 0.5, ( f"Video duration {actual_duration:.2f}s != expected {expected_duration:.2f}s" ) encoder.close() def test_multi_camera_start_episode_called_once(self, tmp_path): """Test that with multiple cameras, no frames are lost due to double start_episode.""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30) video_keys = [f"{OBS_IMAGES}.cam1", f"{OBS_IMAGES}.cam2"] encoder.start_episode(video_keys, tmp_path) num_frames = 30 for _ in range(num_frames): frame0 = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) frame1 = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(video_keys[0], frame0) encoder.feed_frame(video_keys[1], frame1) results = encoder.finish_episode() # Both cameras should have all frames for key in video_keys: mp4_path, stats = results[key] assert mp4_path.exists() with av.open(str(mp4_path)) as container: stream = container.streams.video[0] total_frames = sum(1 for _ in container.decode(stream)) assert total_frames == num_frames, ( f"Camera {key}: expected {num_frames} frames, got {total_frames}" ) encoder.close() def test_encoder_threads_passed_to_thread(self, tmp_path): """Test that encoder_threads is stored and passed through to encoder threads.""" encoder = StreamingVideoEncoder( fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, encoder_threads=2 ) assert encoder.encoder_threads == 2 video_keys = [f"{OBS_IMAGES}.cam"] encoder.start_episode(video_keys, tmp_path) # Verify the thread received the encoder_threads value thread = encoder._threads[f"{OBS_IMAGES}.cam"] assert thread.encoder_threads == 2 # Feed some frames and finish to ensure it works end-to-end num_frames = 10 for _ in range(num_frames): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.cam", frame) results = encoder.finish_episode() mp4_path, stats = results[f"{OBS_IMAGES}.cam"] assert mp4_path.exists() assert stats is not None with av.open(str(mp4_path)) as container: stream = container.streams.video[0] total_frames = sum(1 for _ in container.decode(stream)) assert total_frames == num_frames encoder.close() def test_encoder_threads_none_by_default(self, tmp_path): """Test that encoder_threads defaults to None (codec auto-detect).""" encoder = StreamingVideoEncoder(fps=30, vcodec="libsvtav1", pix_fmt="yuv420p") assert encoder.encoder_threads is None encoder.close() def test_graceful_frame_dropping(self, tmp_path): """Test that full queue drops frames instead of crashing.""" encoder = StreamingVideoEncoder( fps=30, vcodec="libsvtav1", pix_fmt="yuv420p", g=2, crf=30, preset=13, queue_maxsize=1 ) video_keys = [f"{OBS_IMAGES}.cam"] encoder.start_episode(video_keys, tmp_path) # Feed many frames quickly - with queue_maxsize=1, some will be dropped num_frames = 50 for _ in range(num_frames): frame = np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8) encoder.feed_frame(f"{OBS_IMAGES}.cam", frame) # Should not raise - frames are dropped gracefully results = encoder.finish_episode() assert f"{OBS_IMAGES}.cam" in results mp4_path, _ = results[f"{OBS_IMAGES}.cam"] assert mp4_path.exists() # Some frames should have been dropped (queue was tiny) dropped = encoder._dropped_frames.get(f"{OBS_IMAGES}.cam", 0) # We can't guarantee drops but can verify no crash occurred assert dropped >= 0 encoder.close() # ─── Integration tests with LeRobotDataset ─── class TestStreamingEncoderIntegration: def test_add_frame_save_episode_streaming(self, tmp_path): """Full integration test: add_frame -> save_episode with streaming encoding.""" from lerobot.datasets.lerobot_dataset import LeRobotDataset features = { "observation.images.cam": { "dtype": "video", "shape": (64, 96, 3), "names": ["height", "width", "channels"], }, "action": {"dtype": "float32", "shape": (6,), "names": ["j1", "j2", "j3", "j4", "j5", "j6"]}, } dataset = LeRobotDataset.create( repo_id="test/streaming", fps=30, features=features, root=tmp_path / "streaming_test", use_videos=True, streaming_encoding=True, ) assert dataset._streaming_encoder is not None num_frames = 20 for _ in range(num_frames): frame = { "observation.images.cam": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "action": np.random.randn(6).astype(np.float32), "task": "test task", } dataset.add_frame(frame) dataset.save_episode() # Verify dataset metadata assert dataset.meta.total_episodes == 1 assert dataset.meta.total_frames == num_frames # Verify stats exist for the video key assert dataset.meta.stats is not None assert "observation.images.cam" in dataset.meta.stats assert "action" in dataset.meta.stats dataset.finalize() def test_streaming_disabled_creates_pngs(self, tmp_path): """Test that disabling streaming encoding falls back to PNG path.""" from lerobot.datasets.lerobot_dataset import LeRobotDataset features = { "observation.images.cam": { "dtype": "video", "shape": (64, 96, 3), "names": ["height", "width", "channels"], }, "action": {"dtype": "float32", "shape": (6,), "names": ["j1", "j2", "j3", "j4", "j5", "j6"]}, } dataset = LeRobotDataset.create( repo_id="test/no_streaming", fps=30, features=features, root=tmp_path / "no_streaming_test", use_videos=True, streaming_encoding=False, ) assert dataset._streaming_encoder is None num_frames = 5 for _ in range(num_frames): frame = { "observation.images.cam": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "action": np.random.randn(6).astype(np.float32), "task": "test task", } dataset.add_frame(frame) # With streaming disabled, PNG files should be written images_dir = dataset.root / "images" assert images_dir.exists() dataset.save_episode() dataset.finalize() def test_multi_episode_streaming(self, tmp_path): """Test recording multiple episodes with streaming encoding.""" from lerobot.datasets.lerobot_dataset import LeRobotDataset features = { "observation.images.cam": { "dtype": "video", "shape": (64, 96, 3), "names": ["height", "width", "channels"], }, "action": {"dtype": "float32", "shape": (2,), "names": ["j1", "j2"]}, } dataset = LeRobotDataset.create( repo_id="test/multi_ep", fps=30, features=features, root=tmp_path / "multi_ep_test", use_videos=True, streaming_encoding=True, ) for ep in range(3): num_frames = 10 + ep * 5 for _ in range(num_frames): frame = { "observation.images.cam": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "action": np.random.randn(2).astype(np.float32), "task": f"task_{ep}", } dataset.add_frame(frame) dataset.save_episode() assert dataset.meta.total_episodes == 3 assert dataset.meta.total_frames == 10 + 15 + 20 dataset.finalize() def test_clear_episode_buffer_cancels_streaming(self, tmp_path): """Test that clearing episode buffer cancels streaming encoding.""" from lerobot.datasets.lerobot_dataset import LeRobotDataset features = { "observation.images.cam": { "dtype": "video", "shape": (64, 96, 3), "names": ["height", "width", "channels"], }, "action": {"dtype": "float32", "shape": (2,), "names": ["j1", "j2"]}, } dataset = LeRobotDataset.create( repo_id="test/cancel", fps=30, features=features, root=tmp_path / "cancel_test", use_videos=True, streaming_encoding=True, ) # Add some frames for _ in range(5): frame = { "observation.images.cam": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "action": np.random.randn(2).astype(np.float32), "task": "task", } dataset.add_frame(frame) # Cancel and re-record dataset.clear_episode_buffer() # Record a new episode for _ in range(10): frame = { "observation.images.cam": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "action": np.random.randn(2).astype(np.float32), "task": "task", } dataset.add_frame(frame) dataset.save_episode() assert dataset.meta.total_episodes == 1 assert dataset.meta.total_frames == 10 dataset.finalize() def test_multi_camera_add_frame_streaming(self, tmp_path): """Test that start_episode is called once with multiple video keys.""" from lerobot.datasets.lerobot_dataset import LeRobotDataset features = { "observation.images.cam1": { "dtype": "video", "shape": (64, 96, 3), "names": ["height", "width", "channels"], }, "observation.images.cam2": { "dtype": "video", "shape": (64, 96, 3), "names": ["height", "width", "channels"], }, "action": {"dtype": "float32", "shape": (2,), "names": ["j1", "j2"]}, } dataset = LeRobotDataset.create( repo_id="test/multi_cam", fps=30, features=features, root=tmp_path / "multi_cam_test", use_videos=True, streaming_encoding=True, ) num_frames = 15 for _ in range(num_frames): frame = { "observation.images.cam1": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "observation.images.cam2": np.random.randint(0, 255, (64, 96, 3), dtype=np.uint8), "action": np.random.randn(2).astype(np.float32), "task": "test task", } dataset.add_frame(frame) dataset.save_episode() assert dataset.meta.total_episodes == 1 assert dataset.meta.total_frames == num_frames dataset.finalize()
{ "repo_id": "huggingface/lerobot", "file_path": "tests/datasets/test_streaming_video_encoder.py", "license": "Apache License 2.0", "lines": 585, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/scripts/test_edit_dataset_parsing.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 draccus import pytest from lerobot.scripts.lerobot_edit_dataset import ( ConvertImageToVideoConfig, DeleteEpisodesConfig, EditDatasetConfig, InfoConfig, MergeConfig, ModifyTasksConfig, OperationConfig, RemoveFeatureConfig, SplitConfig, _validate_config, ) def parse_cfg(cli_args: list[str]) -> EditDatasetConfig: """Helper to parse CLI args into an EditDatasetConfig via draccus.""" return draccus.parse(EditDatasetConfig, args=cli_args) class TestOperationTypeParsing: """Test that --operation.type correctly selects the right config subclass.""" @pytest.mark.parametrize( "type_name, expected_cls", [ ("delete_episodes", DeleteEpisodesConfig), ("split", SplitConfig), ("merge", MergeConfig), ("remove_feature", RemoveFeatureConfig), ("modify_tasks", ModifyTasksConfig), ("convert_image_to_video", ConvertImageToVideoConfig), ("info", InfoConfig), ], ) def test_operation_type_resolves_correct_class(self, type_name, expected_cls): cfg = parse_cfg( ["--repo_id", "test/repo", "--new_repo_id", "test/merged", "--operation.type", type_name] ) assert isinstance(cfg.operation, expected_cls), ( f"Expected {expected_cls.__name__}, got {type(cfg.operation).__name__}" ) def test_merge_requires_new_repo_id(self): cfg = parse_cfg(["--operation.type", "merge"]) with pytest.raises(ValueError, match="--new_repo_id is required for merge"): _validate_config(cfg) def test_non_merge_requires_repo_id(self): cfg = parse_cfg(["--operation.type", "delete_episodes"]) with pytest.raises(ValueError, match="--repo_id is required for delete_episodes"): _validate_config(cfg) @pytest.mark.parametrize( "type_name, expected_cls", [ ("delete_episodes", DeleteEpisodesConfig), ("split", SplitConfig), ("merge", MergeConfig), ("remove_feature", RemoveFeatureConfig), ("modify_tasks", ModifyTasksConfig), ("convert_image_to_video", ConvertImageToVideoConfig), ("info", InfoConfig), ], ) def test_get_choice_name_roundtrips(self, type_name, expected_cls): cfg = parse_cfg( ["--repo_id", "test/repo", "--new_repo_id", "test/merged", "--operation.type", type_name] ) resolved_name = OperationConfig.get_choice_name(type(cfg.operation)) assert resolved_name == type_name
{ "repo_id": "huggingface/lerobot", "file_path": "tests/scripts/test_edit_dataset_parsing.py", "license": "Apache License 2.0", "lines": 78, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/datasets/test_subtask_dataset.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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. """ Tests for subtask functionality in LeRobotDataset. These tests verify that: - Subtask information is correctly loaded from datasets that have subtask data - The __getitem__ method correctly adds subtask strings to returned items - Subtask handling gracefully handles missing data """ import pandas as pd import pytest import torch from lerobot.datasets.lerobot_dataset import LeRobotDataset class TestSubtaskDataset: """Tests for subtask handling in LeRobotDataset.""" @pytest.fixture def subtask_dataset(self): """Load the test subtask dataset from the hub.""" # Use lerobot/pusht-subtask dataset with episode 1 return LeRobotDataset( repo_id="lerobot/pusht-subtask", episodes=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], ) def test_subtask_dataset_loads(self, subtask_dataset): """Test that the subtask dataset loads successfully.""" assert subtask_dataset is not None assert len(subtask_dataset) > 0 def test_subtask_metadata_loaded(self, subtask_dataset): """Test that subtask metadata is loaded when present in dataset.""" # The dataset should have subtasks metadata loaded assert subtask_dataset.meta.subtasks is not None assert isinstance(subtask_dataset.meta.subtasks, pd.DataFrame) def test_subtask_index_in_features(self, subtask_dataset): """Test that subtask_index is a feature when dataset has subtasks.""" assert "subtask_index" in subtask_dataset.features def test_getitem_returns_subtask_string(self, subtask_dataset): """Test that __getitem__ correctly adds subtask string to returned item.""" item = subtask_dataset[0] # Subtask should be present in the returned item assert "subtask" in item assert isinstance(item["subtask"], str) assert len(item["subtask"]) > 0 # Should not be empty def test_getitem_has_subtask_index(self, subtask_dataset): """Test that __getitem__ includes subtask_index.""" item = subtask_dataset[0] assert "subtask_index" in item assert isinstance(item["subtask_index"], torch.Tensor) def test_subtask_index_maps_to_valid_subtask(self, subtask_dataset): """Test that subtask_index correctly maps to a subtask in metadata.""" item = subtask_dataset[0] subtask_idx = item["subtask_index"].item() subtask_from_metadata = subtask_dataset.meta.subtasks.iloc[subtask_idx].name assert item["subtask"] == subtask_from_metadata def test_all_items_have_subtask(self, subtask_dataset): """Test that all items in the dataset have subtask information.""" for i in range(min(len(subtask_dataset), 5)): # Check first 5 items item = subtask_dataset[i] assert "subtask" in item assert isinstance(item["subtask"], str) def test_task_and_subtask_coexist(self, subtask_dataset): """Test that both task and subtask are present in returned items.""" item = subtask_dataset[0] # Both task and subtask should be present assert "task" in item assert "subtask" in item assert isinstance(item["task"], str) assert isinstance(item["subtask"], str) class TestSubtaskDatasetMissing: """Tests for graceful handling when subtask data is missing.""" @pytest.fixture def dataset_without_subtasks(self, tmp_path, empty_lerobot_dataset_factory): """Create a dataset without subtask information.""" features = {"state": {"dtype": "float32", "shape": (2,), "names": None}} dataset = empty_lerobot_dataset_factory(root=tmp_path / "no_subtask", features=features) # Add some frames and save for _ in range(5): dataset.add_frame({"state": torch.randn(2), "task": "Test task"}) dataset.save_episode() dataset.finalize() # Reload the dataset return LeRobotDataset(dataset.repo_id, root=dataset.root) def test_no_subtask_in_features(self, dataset_without_subtasks): """Test that subtask_index is not in features when not provided.""" assert "subtask_index" not in dataset_without_subtasks.features def test_getitem_without_subtask(self, dataset_without_subtasks): """Test that __getitem__ works when subtask is not present.""" item = dataset_without_subtasks[0] # Item should still be retrievable assert item is not None assert "state" in item assert "task" in item # Subtask should NOT be present assert "subtask" not in item def test_subtasks_metadata_is_none(self, dataset_without_subtasks): """Test that subtasks metadata is None when not present.""" assert dataset_without_subtasks.meta.subtasks is None class TestSubtaskEdgeCases: """Edge case tests for subtask handling.""" def test_subtask_with_multiple_episodes(self): """Test subtask handling with multiple episodes if available.""" try: dataset = LeRobotDataset( repo_id="lerobot/pusht-subtask", episodes=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], ) except Exception: pytest.skip("Could not load test-subtask dataset") # Check first and last items have valid subtasks first_item = dataset[0] last_item = dataset[len(dataset) - 1] assert "subtask" in first_item assert "subtask" in last_item assert isinstance(first_item["subtask"], str) assert isinstance(last_item["subtask"], str) def test_subtask_index_consistency(self): """Test that same subtask_index returns same subtask string.""" try: dataset = LeRobotDataset( repo_id="lerobot/pusht-subtask", episodes=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], ) except Exception: pytest.skip("Could not load test-subtask dataset") if len(dataset) < 2: pytest.skip("Dataset too small for this test") # Collect subtask_index to subtask mappings subtask_map = {} for i in range(min(len(dataset), 10)): item = dataset[i] idx = item["subtask_index"].item() subtask = item["subtask"] if idx in subtask_map: # Same index should always return same subtask assert subtask_map[idx] == subtask, ( f"Inconsistent subtask for index {idx}: '{subtask_map[idx]}' vs '{subtask}'" ) else: subtask_map[idx] = subtask
{ "repo_id": "huggingface/lerobot", "file_path": "tests/datasets/test_subtask_dataset.py", "license": "Apache License 2.0", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:src/lerobot/robots/bi_openarm_follower/bi_openarm_follower.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 logging from functools import cached_property from lerobot.processor import RobotAction, RobotObservation from lerobot.robots.openarm_follower import OpenArmFollower, OpenArmFollowerConfig from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..robot import Robot from .config_bi_openarm_follower import BiOpenArmFollowerConfig logger = logging.getLogger(__name__) class BiOpenArmFollower(Robot): """ Bimanual OpenArm Follower Arms """ config_class = BiOpenArmFollowerConfig name = "bi_openarm_follower" def __init__(self, config: BiOpenArmFollowerConfig): super().__init__(config) self.config = config left_arm_config = OpenArmFollowerConfig( id=f"{config.id}_left" if config.id else None, calibration_dir=config.calibration_dir, port=config.left_arm_config.port, disable_torque_on_disconnect=config.left_arm_config.disable_torque_on_disconnect, max_relative_target=config.left_arm_config.max_relative_target, cameras=config.left_arm_config.cameras, side=config.left_arm_config.side, can_interface=config.left_arm_config.can_interface, use_can_fd=config.left_arm_config.use_can_fd, can_bitrate=config.left_arm_config.can_bitrate, can_data_bitrate=config.left_arm_config.can_data_bitrate, motor_config=config.left_arm_config.motor_config, position_kd=config.left_arm_config.position_kd, position_kp=config.left_arm_config.position_kp, joint_limits=config.left_arm_config.joint_limits, ) right_arm_config = OpenArmFollowerConfig( id=f"{config.id}_right" if config.id else None, calibration_dir=config.calibration_dir, port=config.right_arm_config.port, disable_torque_on_disconnect=config.right_arm_config.disable_torque_on_disconnect, max_relative_target=config.right_arm_config.max_relative_target, cameras=config.right_arm_config.cameras, side=config.right_arm_config.side, can_interface=config.right_arm_config.can_interface, use_can_fd=config.right_arm_config.use_can_fd, can_bitrate=config.right_arm_config.can_bitrate, can_data_bitrate=config.right_arm_config.can_data_bitrate, motor_config=config.right_arm_config.motor_config, position_kd=config.right_arm_config.position_kd, position_kp=config.right_arm_config.position_kp, joint_limits=config.right_arm_config.joint_limits, ) self.left_arm = OpenArmFollower(left_arm_config) self.right_arm = OpenArmFollower(right_arm_config) # Only for compatibility with other parts of the codebase that expect a `robot.cameras` attribute self.cameras = {**self.left_arm.cameras, **self.right_arm.cameras} @property def _motors_ft(self) -> dict[str, type]: left_arm_motors_ft = self.left_arm._motors_ft right_arm_motors_ft = self.right_arm._motors_ft return { **{f"left_{k}": v for k, v in left_arm_motors_ft.items()}, **{f"right_{k}": v for k, v in right_arm_motors_ft.items()}, } @property def _cameras_ft(self) -> dict[str, tuple]: left_arm_cameras_ft = self.left_arm._cameras_ft right_arm_cameras_ft = self.right_arm._cameras_ft return { **{f"left_{k}": v for k, v in left_arm_cameras_ft.items()}, **{f"right_{k}": v for k, v in right_arm_cameras_ft.items()}, } @cached_property def observation_features(self) -> dict[str, type | tuple]: return {**self._motors_ft, **self._cameras_ft} @cached_property def action_features(self) -> dict[str, type]: return self._motors_ft @property def is_connected(self) -> bool: return self.left_arm.is_connected and self.right_arm.is_connected @check_if_already_connected def connect(self, calibrate: bool = True) -> None: self.left_arm.connect(calibrate) self.right_arm.connect(calibrate) @property def is_calibrated(self) -> bool: return self.left_arm.is_calibrated and self.right_arm.is_calibrated def calibrate(self) -> None: self.left_arm.calibrate() self.right_arm.calibrate() def configure(self) -> None: self.left_arm.configure() self.right_arm.configure() def setup_motors(self) -> None: raise NotImplementedError( "Motor ID configuration is typically done via manufacturer tools for CAN motors." ) @check_if_not_connected def get_observation(self) -> RobotObservation: obs_dict = {} # Add "left_" prefix left_obs = self.left_arm.get_observation() obs_dict.update({f"left_{key}": value for key, value in left_obs.items()}) # Add "right_" prefix right_obs = self.right_arm.get_observation() obs_dict.update({f"right_{key}": value for key, value in right_obs.items()}) return obs_dict @check_if_not_connected def send_action( self, action: RobotAction, custom_kp: dict[str, float] | None = None, custom_kd: dict[str, float] | None = None, ) -> RobotAction: # Remove "left_" prefix left_action = { key.removeprefix("left_"): value for key, value in action.items() if key.startswith("left_") } # Remove "right_" prefix right_action = { key.removeprefix("right_"): value for key, value in action.items() if key.startswith("right_") } sent_action_left = self.left_arm.send_action(left_action, custom_kp, custom_kd) sent_action_right = self.right_arm.send_action(right_action, custom_kp, custom_kd) # Add prefixes back prefixed_sent_action_left = {f"left_{key}": value for key, value in sent_action_left.items()} prefixed_sent_action_right = {f"right_{key}": value for key, value in sent_action_right.items()} return {**prefixed_sent_action_left, **prefixed_sent_action_right} @check_if_not_connected def disconnect(self): self.left_arm.disconnect() self.right_arm.disconnect()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/bi_openarm_follower/bi_openarm_follower.py", "license": "Apache License 2.0", "lines": 146, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/bi_openarm_follower/config_bi_openarm_follower.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass from lerobot.robots.openarm_follower import OpenArmFollowerConfigBase from ..config import RobotConfig @RobotConfig.register_subclass("bi_openarm_follower") @dataclass class BiOpenArmFollowerConfig(RobotConfig): """Configuration class for Bi OpenArm Follower robots.""" left_arm_config: OpenArmFollowerConfigBase right_arm_config: OpenArmFollowerConfigBase
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/bi_openarm_follower/config_bi_openarm_follower.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/bi_openarm_leader/bi_openarm_leader.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 logging from functools import cached_property from lerobot.processor import RobotAction from lerobot.teleoperators.openarm_leader import OpenArmLeaderConfig from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..openarm_leader import OpenArmLeader from ..teleoperator import Teleoperator from .config_bi_openarm_leader import BiOpenArmLeaderConfig logger = logging.getLogger(__name__) class BiOpenArmLeader(Teleoperator): """ Bimanual OpenArm Leader Arms """ config_class = BiOpenArmLeaderConfig name = "bi_openarm_leader" def __init__(self, config: BiOpenArmLeaderConfig): super().__init__(config) self.config = config left_arm_config = OpenArmLeaderConfig( id=f"{config.id}_left" if config.id else None, calibration_dir=config.calibration_dir, port=config.left_arm_config.port, can_interface=config.left_arm_config.can_interface, use_can_fd=config.left_arm_config.use_can_fd, can_bitrate=config.left_arm_config.can_bitrate, can_data_bitrate=config.left_arm_config.can_data_bitrate, motor_config=config.left_arm_config.motor_config, manual_control=config.left_arm_config.manual_control, position_kd=config.left_arm_config.position_kd, position_kp=config.left_arm_config.position_kp, ) right_arm_config = OpenArmLeaderConfig( id=f"{config.id}_right" if config.id else None, calibration_dir=config.calibration_dir, port=config.right_arm_config.port, can_interface=config.right_arm_config.can_interface, use_can_fd=config.right_arm_config.use_can_fd, can_bitrate=config.right_arm_config.can_bitrate, can_data_bitrate=config.right_arm_config.can_data_bitrate, motor_config=config.right_arm_config.motor_config, manual_control=config.right_arm_config.manual_control, position_kd=config.right_arm_config.position_kd, position_kp=config.right_arm_config.position_kp, ) self.left_arm = OpenArmLeader(left_arm_config) self.right_arm = OpenArmLeader(right_arm_config) @cached_property def action_features(self) -> dict[str, type]: left_arm_features = self.left_arm.action_features right_arm_features = self.right_arm.action_features return { **{f"left_{k}": v for k, v in left_arm_features.items()}, **{f"right_{k}": v for k, v in right_arm_features.items()}, } @cached_property def feedback_features(self) -> dict[str, type]: return {} @property def is_connected(self) -> bool: return self.left_arm.is_connected and self.right_arm.is_connected @check_if_already_connected def connect(self, calibrate: bool = True) -> None: self.left_arm.connect(calibrate) self.right_arm.connect(calibrate) @property def is_calibrated(self) -> bool: return self.left_arm.is_calibrated and self.right_arm.is_calibrated def calibrate(self) -> None: self.left_arm.calibrate() self.right_arm.calibrate() def configure(self) -> None: self.left_arm.configure() self.right_arm.configure() def setup_motors(self) -> None: raise NotImplementedError( "Motor ID configuration is typically done via manufacturer tools for CAN motors." ) @check_if_not_connected def get_action(self) -> RobotAction: action_dict = {} # Add "left_" prefix left_action = self.left_arm.get_action() action_dict.update({f"left_{key}": value for key, value in left_action.items()}) # Add "right_" prefix right_action = self.right_arm.get_action() action_dict.update({f"right_{key}": value for key, value in right_action.items()}) return action_dict def send_feedback(self, feedback: dict[str, float]) -> None: # TODO: Implement force feedback raise NotImplementedError @check_if_not_connected def disconnect(self) -> None: self.left_arm.disconnect() self.right_arm.disconnect()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/bi_openarm_leader/bi_openarm_leader.py", "license": "Apache License 2.0", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/bi_openarm_leader/config_bi_openarm_leader.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass from lerobot.teleoperators.openarm_leader import OpenArmLeaderConfigBase from ..config import TeleoperatorConfig @TeleoperatorConfig.register_subclass("bi_openarm_leader") @dataclass class BiOpenArmLeaderConfig(TeleoperatorConfig): """Configuration class for Bi OpenArm Follower robots.""" left_arm_config: OpenArmLeaderConfigBase right_arm_config: OpenArmLeaderConfigBase
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/bi_openarm_leader/config_bi_openarm_leader.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/unitree_g1/robot_kinematic_processor.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 logging import os import sys import numpy as np logger = logging.getLogger(__name__) parent2_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(parent2_dir) class WeightedMovingFilter: def __init__(self, weights, data_size=14): self._window_size = len(weights) self._weights = np.array(weights) self._data_size = data_size self._filtered_data = np.zeros(self._data_size) self._data_queue = [] def _apply_filter(self): if len(self._data_queue) < self._window_size: return self._data_queue[-1] data_array = np.array(self._data_queue) temp_filtered_data = np.zeros(self._data_size) for i in range(self._data_size): temp_filtered_data[i] = np.convolve(data_array[:, i], self._weights, mode="valid")[-1] return temp_filtered_data def add_data(self, new_data): assert len(new_data) == self._data_size if len(self._data_queue) > 0 and np.array_equal( new_data, self._data_queue[-1] ): # skip duplicate data return if len(self._data_queue) >= self._window_size: self._data_queue.pop(0) self._data_queue.append(new_data) self._filtered_data = self._apply_filter() @property def filtered_data(self): return self._filtered_data class G1_29_ArmIK: # noqa: N801 def __init__(self, unit_test=False): import casadi import pinocchio as pin from huggingface_hub import snapshot_download from pinocchio import casadi as cpin self._pin = pin np.set_printoptions(precision=5, suppress=True, linewidth=200) self.unit_test = unit_test self.repo_path = snapshot_download("lerobot/unitree-g1-mujoco") urdf_path = os.path.join(self.repo_path, "assets", "g1_body29_hand14.urdf") mesh_dir = os.path.join(self.repo_path, "assets") self.robot = self._pin.RobotWrapper.BuildFromURDF(urdf_path, mesh_dir) self.mixed_jointsToLockIDs = [ "left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint", "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint", "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint", "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_hand_thumb_0_joint", "left_hand_thumb_1_joint", "left_hand_thumb_2_joint", "left_hand_middle_0_joint", "left_hand_middle_1_joint", "left_hand_index_0_joint", "left_hand_index_1_joint", "right_hand_thumb_0_joint", "right_hand_thumb_1_joint", "right_hand_thumb_2_joint", "right_hand_index_0_joint", "right_hand_index_1_joint", "right_hand_middle_0_joint", "right_hand_middle_1_joint", ] self.reduced_robot = self.robot.buildReducedRobot( list_of_joints_to_lock=self.mixed_jointsToLockIDs, reference_configuration=np.array([0.0] * self.robot.model.nq), ) # Arm joint names in G1 motor order (G1_29_JointArmIndex) self._arm_joint_names_g1 = [ "left_shoulder_pitch_joint", "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint", "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint", "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint", "right_wrist_pitch_joint", "right_wrist_yaw_joint", ] # Pinocchio uses its own joint order in q; build index mapping. self._arm_joint_names_pin = sorted( self._arm_joint_names_g1, key=lambda name: self.reduced_robot.model.idx_qs[self.reduced_robot.model.getJointId(name)], ) logger.info(f"Pinocchio arm joint order: {self._arm_joint_names_pin}") self._arm_reorder_g1_to_pin = [ self._arm_joint_names_g1.index(name) for name in self._arm_joint_names_pin ] # Inverse mapping to return tau in G1 motor order. self._arm_reorder_pin_to_g1 = np.argsort(self._arm_reorder_g1_to_pin) self.reduced_robot.model.addFrame( self._pin.Frame( "L_ee", self.reduced_robot.model.getJointId("left_wrist_yaw_joint"), self._pin.SE3(np.eye(3), np.array([0.05, 0, 0]).T), self._pin.FrameType.OP_FRAME, ) ) self.reduced_robot.model.addFrame( self._pin.Frame( "R_ee", self.reduced_robot.model.getJointId("right_wrist_yaw_joint"), self._pin.SE3(np.eye(3), np.array([0.05, 0, 0]).T), self._pin.FrameType.OP_FRAME, ) ) # Creating Casadi models and data for symbolic computing self.cmodel = cpin.Model(self.reduced_robot.model) self.cdata = self.cmodel.createData() # Creating symbolic variables self.cq = casadi.SX.sym("q", self.reduced_robot.model.nq, 1) self.cTf_l = casadi.SX.sym("tf_l", 4, 4) self.cTf_r = casadi.SX.sym("tf_r", 4, 4) cpin.framesForwardKinematics(self.cmodel, self.cdata, self.cq) # Get the hand joint ID and define the error function self.L_hand_id = self.reduced_robot.model.getFrameId("L_ee") self.R_hand_id = self.reduced_robot.model.getFrameId("R_ee") self.translational_error = casadi.Function( "translational_error", [self.cq, self.cTf_l, self.cTf_r], [ casadi.vertcat( self.cdata.oMf[self.L_hand_id].translation - self.cTf_l[:3, 3], self.cdata.oMf[self.R_hand_id].translation - self.cTf_r[:3, 3], ) ], ) self.rotational_error = casadi.Function( "rotational_error", [self.cq, self.cTf_l, self.cTf_r], [ casadi.vertcat( cpin.log3(self.cdata.oMf[self.L_hand_id].rotation @ self.cTf_l[:3, :3].T), cpin.log3(self.cdata.oMf[self.R_hand_id].rotation @ self.cTf_r[:3, :3].T), ) ], ) # Defining the optimization problem self.opti = casadi.Opti() self.var_q = self.opti.variable(self.reduced_robot.model.nq) self.var_q_last = self.opti.parameter(self.reduced_robot.model.nq) # for smooth self.param_tf_l = self.opti.parameter(4, 4) self.param_tf_r = self.opti.parameter(4, 4) self.translational_cost = casadi.sumsqr( self.translational_error(self.var_q, self.param_tf_l, self.param_tf_r) ) self.rotation_cost = casadi.sumsqr( self.rotational_error(self.var_q, self.param_tf_l, self.param_tf_r) ) self.regularization_cost = casadi.sumsqr(self.var_q) self.smooth_cost = casadi.sumsqr(self.var_q - self.var_q_last) # Setting optimization constraints and goals self.opti.subject_to( self.opti.bounded( self.reduced_robot.model.lowerPositionLimit, self.var_q, self.reduced_robot.model.upperPositionLimit, ) ) self.opti.minimize( 50 * self.translational_cost + self.rotation_cost + 0.02 * self.regularization_cost + 0.1 * self.smooth_cost ) opts = { "ipopt": {"print_level": 0, "max_iter": 50, "tol": 1e-6}, "print_time": False, # print or not "calc_lam_p": False, # https://github.com/casadi/casadi/wiki/FAQ:-Why-am-I-getting-%22NaN-detected%22in-my-optimization%3F } self.opti.solver("ipopt", opts) self.init_data = np.zeros(self.reduced_robot.model.nq) self.smooth_filter = WeightedMovingFilter(np.array([0.4, 0.3, 0.2, 0.1]), 14) def solve_ik(self, left_wrist, right_wrist, current_lr_arm_motor_q=None, current_lr_arm_motor_dq=None): if current_lr_arm_motor_q is not None: self.init_data = current_lr_arm_motor_q self.opti.set_initial(self.var_q, self.init_data) self.opti.set_value(self.param_tf_l, left_wrist) self.opti.set_value(self.param_tf_r, right_wrist) self.opti.set_value(self.var_q_last, self.init_data) # for smooth try: self.opti.solve() sol_q = self.opti.value(self.var_q) self.smooth_filter.add_data(sol_q) sol_q = self.smooth_filter.filtered_data if current_lr_arm_motor_dq is not None: v = current_lr_arm_motor_dq * 0.0 else: v = (sol_q - self.init_data) * 0.0 self.init_data = sol_q sol_tauff = self._pin.rnea( self.reduced_robot.model, self.reduced_robot.data, sol_q, v, np.zeros(self.reduced_robot.model.nv), ) return sol_q, sol_tauff except Exception as e: logger.error(f"ERROR in convergence, plotting debug info.{e}") sol_q = self.opti.debug.value(self.var_q) self.smooth_filter.add_data(sol_q) sol_q = self.smooth_filter.filtered_data if current_lr_arm_motor_dq is not None: v = current_lr_arm_motor_dq * 0.0 else: v = (sol_q - self.init_data) * 0.0 self.init_data = sol_q logger.error( f"sol_q:{sol_q} \nmotorstate: \n{current_lr_arm_motor_q} \nleft_pose: \n{left_wrist} \nright_pose: \n{right_wrist}" ) return current_lr_arm_motor_q, np.zeros(self.reduced_robot.model.nv) def solve_tau(self, current_lr_arm_motor_q=None, current_lr_arm_motor_dq=None): try: q_g1 = np.array(current_lr_arm_motor_q, dtype=float) if q_g1.shape[0] != len(self._arm_joint_names_g1): raise ValueError(f"Expected {len(self._arm_joint_names_g1)} arm joints, got {q_g1.shape[0]}") q_pin = q_g1[self._arm_reorder_g1_to_pin] sol_tauff = self._pin.rnea( self.reduced_robot.model, self.reduced_robot.data, q_pin, np.zeros(self.reduced_robot.model.nv), np.zeros(self.reduced_robot.model.nv), ) return sol_tauff[self._arm_reorder_pin_to_g1] except Exception as e: logger.error(f"ERROR in convergence, plotting debug info.{e}") return np.zeros(self.reduced_robot.model.nv)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/unitree_g1/robot_kinematic_processor.py", "license": "Apache License 2.0", "lines": 264, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/unitree_g1/config_unitree_g1.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from ..config import TeleoperatorConfig @dataclass class ExoskeletonArmPortConfig: """Serial port configuration for individual exoskeleton arm.""" port: str = "" baud_rate: int = 115200 @TeleoperatorConfig.register_subclass("unitree_g1") @dataclass class UnitreeG1TeleoperatorConfig(TeleoperatorConfig): left_arm_config: ExoskeletonArmPortConfig = field(default_factory=ExoskeletonArmPortConfig) right_arm_config: ExoskeletonArmPortConfig = field(default_factory=ExoskeletonArmPortConfig) # Frozen joints (comma-separated joint names that won't be moved by IK) frozen_joints: str = ""
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/unitree_g1/config_unitree_g1.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/unitree_g1/exo_calib.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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. """ This module handles calibration of hall effect sensors used in the exoskeleton. Each joint has a pair of ADC channels outputting sin and cos values that trace an ellipse as the joint rotates due to imprecision in magnet/sensor placement. We fit this ellipse to a unit circle, and calculate arctan2 of the unit circle to get the joint angle. We then store the ellipse parameters and the zero offset for each joint to be used at runtime. """ import json import logging import time from collections import deque from dataclasses import dataclass, field from pathlib import Path import numpy as np import serial logger = logging.getLogger(__name__) # exoskeleton joint names -> ADC channel pairs. TODO: add wrist pitch and wrist yaw JOINTS = { "shoulder_pitch": (0, 1), "shoulder_yaw": (2, 3), "shoulder_roll": (4, 5), "elbow_flex": (6, 7), "wrist_roll": (14, 15), } @dataclass class ExoskeletonJointCalibration: name: str # joint name center_fit: list[float] # center of the ellipse T: list[list[float]] # 2x2 transformation matrix zero_offset: float = 0.0 # angle at neutral pose @dataclass class ExoskeletonCalibration: """Full calibration data for an exoskeleton arm.""" version: int = 2 side: str = "" adc_max: int = 2**12 - 1 joints: list[ExoskeletonJointCalibration] = field(default_factory=list) def to_dict(self) -> dict: return { "version": self.version, "side": self.side, "adc_max": self.adc_max, "joints": [ { "name": j.name, "center_fit": j.center_fit, "T": j.T, "zero_offset": j.zero_offset, } for j in self.joints ], } @classmethod def from_dict(cls, data: dict) -> "ExoskeletonCalibration": joints = [ ExoskeletonJointCalibration( name=j["name"], center_fit=j["center_fit"], T=j["T"], zero_offset=j.get("zero_offset", 0.0), ) for j in data.get("joints", []) ] return cls( version=data.get("version", 2), side=data.get("side", ""), adc_max=data.get("adc_max", 2**12 - 1), joints=joints, ) @dataclass(frozen=True) class CalibParams: fit_every: float = 0.15 min_fit_points: int = 60 fit_window: int = 900 max_fit_points: int = 300 trim_low: float = 0.05 trim_high: float = 0.95 median_window: int = 5 history: int = 3500 draw_hz: float = 120.0 sample_count: int = 50 def normalize_angle(angle: float) -> float: while angle > np.pi: angle -= 2 * np.pi while angle < -np.pi: angle += 2 * np.pi return angle def joint_z_and_angle(raw16: list[int], j: ExoskeletonJointCalibration) -> tuple[np.ndarray, float]: """ Applies calibration to each joint: raw → centered → ellipse-to-circle → angle. """ pair = JOINTS[j.name] s, c = raw16[pair[0]], raw16[pair[1]] # get sin and cos p = np.array([float(c) - (2**12 - 1) / 2, float(s) - (2**12 - 1) / 2]) # center the raw values z = np.asarray(j.T) @ ( p - np.asarray(j.center_fit) ) # center the ellipse and invert the transformation matrix to get unit circle coords ang = float(np.arctan2(z[1], z[0])) - j.zero_offset # calculate the anvgle and apply the zero offset return z, normalize_angle(-ang) # ensure range is [-pi, pi] def exo_raw_to_angles(raw16: list[int], calib: ExoskeletonCalibration) -> dict[str, float]: """Convert raw sensor readings to joint angles using calibration.""" return {j.name: joint_z_and_angle(raw16, j)[1] for j in calib.joints} def run_exo_calibration( ser: serial.Serial, side: str, save_path: Path, params: CalibParams | None = None, ) -> ExoskeletonCalibration: """ Run interactive calibration for an exoskeleton arm. """ try: import cv2 import matplotlib.pyplot as plt except ImportError as e: raise ImportError( "Calibration requires matplotlib and opencv-python. " "Install with: pip install matplotlib opencv-python" ) from e from .exo_serial import read_raw_from_serial params = params or CalibParams() joint_list = list(JOINTS.items()) # Convert dict to list for indexing logger.info(f"Starting calibration for {side} exoskeleton arm") def running_median(win: deque) -> float: return float(np.median(np.fromiter(win, dtype=float))) def read_joint_point(raw16: list[int], pair: tuple[int, int]): s, c = raw16[pair[0]], raw16[pair[1]] return float(c) - (2**12 - 1) / 2, float(s) - (2**12 - 1) / 2, float(s), float(c) def select_fit_subset(xs, ys): """Select and filter points for ellipse fitting. Trims outliers by radius and downsamples.""" n = min(params.fit_window, len(xs)) if n <= 0: return None, None x = np.asarray(list(xs)[-n:], dtype=float) # most recent n samples y = np.asarray(list(ys)[-n:], dtype=float) r = np.sqrt(x * x + y * y) # radius from origin if len(r) >= 20: lo, hi = np.quantile(r, params.trim_low), np.quantile(r, params.trim_high) # outlier bounds keep = (r >= lo) & (r <= hi) x, y = x[keep], y[keep] # remove outliers if len(x) > params.max_fit_points: idx = np.linspace(0, len(x) - 1, params.max_fit_points).astype(int) # downsample evenly x, y = x[idx], y[idx] return x, y def fit_ellipse_opencv(x, y): """Fit ellipse to (x,y) points using OpenCV. Returns center, axes, rotation matrix, and outline.""" x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float) if len(x) < 5: return None pts = np.stack([x, y], axis=1).astype(np.float32).reshape(-1, 1, 2) try: (xc, yc), (w, h), angle_deg = cv2.fitEllipse(pts) # returns center, axes, rotation in degrees except cv2.error: return None a, b = float(w) * 0.5, float(h) * 0.5 # get ellipse major and minor semi-axes phi = np.deg2rad(float(angle_deg)) # to rad if b > a: # ensure major axis is a a, b = b, a phi += np.pi / 2.0 if not np.isfinite(a) or not np.isfinite(b) or a <= 1e-6 or b <= 1e-6: return None cp, sp = float(np.cos(phi)), float(np.sin(phi)) # rot = np.array([[cp, -sp], [sp, cp]], dtype=float) # 2x2 rotation matrix center = np.array([float(xc), float(yc)], dtype=float) # offset vector tt = np.linspace(0, 2 * np.pi, 360) outline = (rot @ np.stack([a * np.cos(tt), b * np.sin(tt)])).T + center # for viz return {"center": center, "a": a, "b": b, "R": rot, "ex": outline[:, 0], "ey": outline[:, 1]} # Setup matplotlib plt.ion() fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12, 6)) ax0.set_xlabel("cos - center") ax0.set_ylabel("sin - center") ax0.grid(True, alpha=0.25) ax0.set_aspect("equal", adjustable="box") ax1.set_title("Unit circle + angle") ax1.set_xlabel("x") ax1.set_ylabel("y") ax1.grid(True, alpha=0.25) ax1.set_aspect("equal", adjustable="box") tt = np.linspace(0, 2 * np.pi, 360) ax1.plot(np.cos(tt), np.sin(tt), "k-", linewidth=1) ax0.set_xlim(-2200, 2200) ax0.set_ylim(-2200, 2200) ax1.set_xlim(-1.4, 1.4) ax1.set_ylim(-1.4, 1.4) sc0 = ax0.scatter([], [], s=6, animated=True) (ell_line,) = ax0.plot([], [], "r-", linewidth=2, animated=True) sc1 = ax1.scatter([], [], s=6, animated=True) (radius_line,) = ax1.plot([], [], "g-", linewidth=2, animated=True) angle_text = ax1.text( 0.02, 0.98, "", transform=ax1.transAxes, va="top", ha="left", fontsize=12, animated=True ) fig.canvas.draw() bg0 = fig.canvas.copy_from_bbox(ax0.bbox) bg1 = fig.canvas.copy_from_bbox(ax1.bbox) # State joints_out = [] joint_idx = 0 phase = "ellipse" advance_requested = False zero_samples = [] def on_key(event): nonlocal advance_requested if event.key in ("n", "N", "enter", " "): advance_requested = True fig.canvas.mpl_connect("key_press_event", on_key) def reset_state(): return { "xs": deque(maxlen=params.history), "ys": deque(maxlen=params.history), "xu": deque(maxlen=params.history), "yu": deque(maxlen=params.history), "win_s": deque(maxlen=params.median_window), "win_c": deque(maxlen=params.median_window), "ellipse_cache": None, "T": None, "center_fit": None, "have_transform": False, "latest_z": None, "last_fit": 0.0, } state = reset_state() last_draw = 0.0 name, pair = joint_list[joint_idx] fig.canvas.manager.set_window_title(f"[{joint_idx + 1}/{len(joint_list)}] {name} - ELLIPSE") ax0.set_title(f"{name} raw (filtered)") logger.info(f"[{joint_idx + 1}/{len(joint_list)}] Calibrating {name}") logger.info("Step 1: Move joint around to map ellipse, then press 'n'") try: while plt.fignum_exists(fig.number): name, pair = joint_list[joint_idx] # Handles calibration GUI state: ellipse → zero_pose → next joint -> ellipse -> ... if phase == "ellipse" and advance_requested and state["have_transform"]: joints_out.append( { "name": name, "center_fit": state["center_fit"].tolist(), "T": state["T"].tolist(), } ) logger.info(f" -> Ellipse saved for {name}") phase, zero_samples, advance_requested = "zero_pose", [], False fig.canvas.manager.set_window_title(f"[{joint_idx + 1}/{len(joint_list)}] {name} - ZERO POSE") ax0.set_title(f"{name} - hold zero pose") fig.canvas.draw() bg0, bg1 = fig.canvas.copy_from_bbox(ax0.bbox), fig.canvas.copy_from_bbox(ax1.bbox) logger.info(f"Step 2: Hold {name} in zero position, then press 'n'") elif phase == "ellipse" and advance_requested and not state["have_transform"]: logger.info(" (Need valid fit first - keep moving the joint)") advance_requested = False elif phase == "zero_pose" and advance_requested: if len(zero_samples) >= params.sample_count: zero_offset = float(np.mean(zero_samples[-params.sample_count :])) joints_out[-1]["zero_offset"] = zero_offset logger.info(f" -> {name} zero: {zero_offset:+.3f} rad ({np.degrees(zero_offset):+.1f}°)") joint_idx += 1 advance_requested = False if joint_idx >= len(joint_list): # All joints done calib = ExoskeletonCalibration( version=2, side=side, adc_max=2**12 - 1, joints=[ ExoskeletonJointCalibration( name=j["name"], center_fit=j["center_fit"], T=j["T"], zero_offset=j.get("zero_offset", 0.0), ) for j in joints_out ], ) save_path.parent.mkdir(parents=True, exist_ok=True) with open(save_path, "w") as f: json.dump(calib.to_dict(), f, indent=2) logger.info(f"Saved calibration to {save_path}") logger.info("Calibration complete!") plt.close(fig) return calib # Next joint phase, state = "ellipse", reset_state() name, pair = joint_list[joint_idx] fig.canvas.manager.set_window_title( f"[{joint_idx + 1}/{len(joint_list)}] {name} - ELLIPSE" ) ax0.set_title(f"{name} raw (filtered)") fig.canvas.draw() bg0, bg1 = fig.canvas.copy_from_bbox(ax0.bbox), fig.canvas.copy_from_bbox(ax1.bbox) logger.info(f"[{joint_idx + 1}/{len(joint_list)}] Calibrating {name}") logger.info("Step 1: Move joint around to map ellipse, then press 'n'") else: logger.info( f" (Collecting samples: {len(zero_samples)}/{params.sample_count} - hold still)" ) advance_requested = False # Read sensor raw16 = read_raw_from_serial(ser) if raw16 is not None: x_raw, y_raw, s_raw, c_raw = read_joint_point(raw16, pair) if phase == "ellipse": if state["have_transform"]: z = state["T"] @ (np.array([x_raw, y_raw]) - state["center_fit"]) state["xu"].append(float(z[0])) state["yu"].append(float(z[1])) state["latest_z"] = (float(z[0]), float(z[1])) state["win_s"].append(s_raw) state["win_c"].append(c_raw) if len(state["win_s"]) >= max(3, params.median_window): state["ys"].append(running_median(state["win_s"]) - (2**12 - 1) / 2) state["xs"].append(running_median(state["win_c"]) - (2**12 - 1) / 2) else: jdata = joints_out[-1] z = np.array(jdata["T"]) @ (np.array([x_raw, y_raw]) - np.array(jdata["center_fit"])) zero_samples.append(float(np.arctan2(z[1], z[0]))) state["latest_z"] = (float(z[0]), float(z[1])) # Ellipse fitting t = time.time() if ( phase == "ellipse" and (t - state["last_fit"]) >= params.fit_every and len(state["xs"]) >= params.min_fit_points ): xfit, yfit = select_fit_subset(state["xs"], state["ys"]) if xfit is not None and len(xfit) >= params.min_fit_points: fit = fit_ellipse_opencv(xfit, yfit) if fit is not None: state["center_fit"] = fit["center"] state["T"] = np.diag([1.0 / fit["a"], 1.0 / fit["b"]]) @ fit["R"].T state["ellipse_cache"] = (fit["ex"], fit["ey"]) state["have_transform"] = True state["last_fit"] = t # Drawing if (t - last_draw) >= 1.0 / params.draw_hz: fig.canvas.restore_region(bg0) fig.canvas.restore_region(bg1) if phase == "ellipse": sc0.set_offsets(np.c_[state["xs"], state["ys"]] if state["xs"] else np.empty((0, 2))) ax0.draw_artist(sc0) ell_line.set_data(*state["ellipse_cache"] if state["ellipse_cache"] else ([], [])) ax0.draw_artist(ell_line) sc1.set_offsets(np.c_[state["xu"], state["yu"]] if state["xu"] else np.empty((0, 2))) ax1.draw_artist(sc1) if state["latest_z"]: zx, zy = state["latest_z"] radius_line.set_data([0.0, zx], [0.0, zy]) ang = float(np.arctan2(zy, zx)) angle_text.set_text( f"angle: {ang:+.3f} rad ({np.degrees(ang):+.1f}°)\nmove {name}, press 'n' to advance" ) else: radius_line.set_data([], []) angle_text.set_text("(waiting for fit)") else: sc0.set_offsets(np.empty((0, 2))) ax0.draw_artist(sc0) ell_line.set_data([], []) ax0.draw_artist(ell_line) if state["latest_z"]: zx, zy = state["latest_z"] sc1.set_offsets([[zx, zy]]) radius_line.set_data([0.0, zx], [0.0, zy]) ang = float(np.arctan2(zy, zx)) angle_text.set_text( f"Zero pose for {name}\nangle: {ang:+.3f} rad\nsamples: {len(zero_samples)}/{params.sample_count}\nhold still, press 'n'" ) else: sc1.set_offsets(np.empty((0, 2))) radius_line.set_data([], []) angle_text.set_text("(waiting for data)") ax1.draw_artist(sc1) ax1.draw_artist(radius_line) ax1.draw_artist(angle_text) fig.canvas.blit(ax0.bbox) fig.canvas.blit(ax1.bbox) fig.canvas.flush_events() last_draw = t plt.pause(0.001) finally: plt.close(fig)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/unitree_g1/exo_calib.py", "license": "Apache License 2.0", "lines": 394, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/unitree_g1/exo_ik.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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. """ IK helper for exoskeleton-to-G1 teleoperation. We map Exoskeleton joint angles to end-effector pose in world frame, visualizing the result in meshcat after calibration. """ import logging import os from dataclasses import dataclass import numpy as np from lerobot.robots.unitree_g1.g1_utils import G1_29_JointArmIndex from lerobot.robots.unitree_g1.robot_kinematic_processor import G1_29_ArmIK from .exo_calib import JOINTS logger = logging.getLogger(__name__) def _frame_id(model, name: str) -> int | None: try: fid = model.getFrameId(name) return fid if 0 <= fid < model.nframes else None except Exception: return None @dataclass class ArmCfg: side: str # "left" | "right" urdf: str # exo_left.urdf / exo_right.urdf root: str # "exo_left" / "exo_right" g1_ee: str # "l_ee" / "r_ee" offset: np.ndarray # world offset for viz + target marker_prefix: str # "left" / "right" class Markers: """Creates meshcat visualization primitives, showing end-effector frames of exoskeleton and G1""" def __init__(self, viewer): self.v = viewer def sphere(self, path: str, r: float, rgba: tuple[float, float, float, float]): import meshcat.geometry as mg c = (int(rgba[0] * 255) << 16) | (int(rgba[1] * 255) << 8) | int(rgba[2] * 255) self.v[path].set_object( mg.Sphere(r), mg.MeshPhongMaterial(color=c, opacity=rgba[3], transparent=rgba[3] < 1.0), ) def axes(self, path: str, axis_len: float = 0.1, axis_w: int = 6): import meshcat.geometry as mg pts = np.array( [[0, 0, 0], [axis_len, 0, 0], [0, 0, 0], [0, axis_len, 0], [0, 0, 0], [0, 0, axis_len]], dtype=np.float32, ).T cols = np.array( [[1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=np.float32, ).T self.v[path].set_object( mg.LineSegments( mg.PointsGeometry(position=pts, color=cols), mg.LineBasicMaterial(linewidth=axis_w, vertexColors=True), ) ) def tf(self, path: str, mat: np.ndarray): self.v[path].set_transform(mat) class ExoskeletonIKHelper: """ - Loads G1 robot and exoskeleton URDF models via Pinocchio - Computes forward kinematics on exoskeleton to get end-effector poses - Solves inverse kinematics on G1 to match those poses - Provides meshcat visualization showing both robots and targets Args: frozen_joints: List of G1 joint names to exclude from IK (kept at neutral). """ def __init__(self, frozen_joints: list[str] | None = None): try: import pinocchio as pin except ImportError as e: raise ImportError("ik mode needs pinocchio: pip install pin") from e self.pin = pin self.frozen_joints = frozen_joints or [] self.g1_ik = G1_29_ArmIK() self.robot_g1 = self.g1_ik.reduced_robot self.robot_g1.data = self.robot_g1.model.createData() self.q_g1 = pin.neutral(self.robot_g1.model) assets_dir = os.path.join(self.g1_ik.repo_path, "assets") self.frozen_idx = self._frozen_joint_indices() self.arms = [ ArmCfg( side="left", urdf=os.path.join(assets_dir, "exo_left.urdf"), root="exo_left", g1_ee="L_ee", offset=np.array([0.6, 0.3, 0.0]), marker_prefix="left", ), ArmCfg( side="right", urdf=os.path.join(assets_dir, "exo_right.urdf"), root="exo_right", g1_ee="R_ee", offset=np.array([0.6, -0.3, 0.0]), marker_prefix="right", ), ] self.exo = {} # side -> pin.RobotWrapper self.q_exo = {} # side -> q self.ee_id_exo = {} # side -> frame id self.qmap = {} # side -> {joint_name: q_idx} self.ee_id_g1 = {} # side -> frame id self._load_exo_models(assets_dir) for a in self.arms: self.ee_id_g1[a.side] = _frame_id(self.robot_g1.model, a.g1_ee) self.viewer = None self.markers: Markers | None = None self.viz_g1 = None self.viz_exo = {} # side -> viz def _frozen_joint_indices(self) -> dict[str, int]: out = {} m = self.robot_g1.model for name in self.frozen_joints: if name in m.names: jid = m.getJointId(name) out[name] = m.idx_qs[jid] logger.info(f"freezing joint: {name} (q_idx={out[name]})") return out def _find_exo_ee(self, model, ee_name: str = "ee") -> int: ee = _frame_id(model, ee_name) if ee is not None: return ee for fid in reversed(range(model.nframes)): if model.frames[fid].type == self.pin.FrameType.BODY: return fid return 0 def _build_joint_map(self, robot) -> dict[str, int]: m = robot.model return {n: m.idx_qs[m.getJointId(n)] for n in JOINTS if n in m.names} def _load_exo_models(self, assets_dir: str): pin = self.pin for a in self.arms: if not os.path.exists(a.urdf): logger.warning(f"{a.side} exo urdf not found: {a.urdf}") continue r = pin.RobotWrapper.BuildFromURDF(a.urdf, assets_dir) self.exo[a.side] = r self.q_exo[a.side] = pin.neutral(r.model) self.ee_id_exo[a.side] = self._find_exo_ee(r.model) self.qmap[a.side] = self._build_joint_map(r) logger.info(f"loaded {a.side} exo urdf: {a.urdf}") def init_visualization(self): """ Creates a browser-based visualization of exoskeleton and G1 robot, highlighting end-effector frames and target positions. """ try: from pinocchio.visualize import MeshcatVisualizer except ImportError as e: logger.warning(f"meshcat viz unavailable: {e}") return # g1 self.viz_g1 = MeshcatVisualizer( self.robot_g1.model, self.robot_g1.collision_model, self.robot_g1.visual_model ) self.viz_g1.initViewer(open=True) self.viz_g1.loadViewerModel("g1") self.viz_g1.display(self.q_g1) self.viewer = self.viz_g1.viewer self.markers = Markers(self.viewer) # exos for a in self.arms: if a.side not in self.exo: continue r = self.exo[a.side] v = MeshcatVisualizer(r.model, r.collision_model, r.visual_model) v.initViewer(open=False) v.viewer = self.viewer v.loadViewerModel(a.root) offset_tf = np.eye(4) offset_tf[:3, 3] = a.offset self.viewer[a.root].set_transform(offset_tf) v.display(self.q_exo[a.side]) self.viz_exo[a.side] = v # markers for a in self.arms: p = a.marker_prefix self.markers.sphere(f"markers/{p}_exo_ee", 0.012, (0.2, 1.0, 0.2, 0.9)) self.markers.sphere(f"markers/{p}_g1_ee", 0.015, (1.0, 0.2, 0.2, 0.9)) self.markers.sphere(f"markers/{p}_ik_target", 0.015, (0.1, 0.3, 1.0, 0.9)) self.markers.axes(f"markers/{p}_exo_axes", 0.06) self.markers.axes(f"markers/{p}_g1_axes", 0.08) logger.info(f"meshcat viz initialized: {self.viewer.url()}") print(f"\nmeshcat url: {self.viewer.url()}\n") def _fk_target_world(self, side: str, angles: dict[str, float]) -> np.ndarray | None: """returns wrist frame target to be used for G1 IK in 4x4 homogeneous transform. Takes offset into account.""" if side not in self.exo or not angles: return None pin = self.pin q = self.q_exo[side] qmap = self.qmap[side] for name, ang in angles.items(): idx = qmap.get(name) if idx is not None: q[idx] = float(ang) r = self.exo[side] pin.forwardKinematics(r.model, r.data, q) pin.updateFramePlacements(r.model, r.data) ee = r.data.oMf[self.ee_id_exo[side]] target = np.eye(4) target[:3, :3] = ee.rotation # offset gets applied in world space cfg = next(a for a in self.arms if a.side == side) target[:3, 3] = cfg.offset + ee.translation return target def update_visualization(self): if self.viewer is None or self.markers is None: return pin = self.pin # g1 if self.viz_g1 is not None: self.viz_g1.display(self.q_g1) pin.forwardKinematics(self.robot_g1.model, self.robot_g1.data, self.q_g1) pin.updateFramePlacements(self.robot_g1.model, self.robot_g1.data) for a in self.arms: fid = self.ee_id_g1.get(a.side) if fid is None: continue ee_tf = self.robot_g1.data.oMf[fid].homogeneous p = a.marker_prefix self.markers.tf(f"markers/{p}_g1_ee", ee_tf) self.markers.tf(f"markers/{p}_g1_axes", ee_tf) # exos for a in self.arms: side = a.side v = self.viz_exo.get(side) if v is None: continue v.display(self.q_exo[side]) r = self.exo[side] pin.forwardKinematics(r.model, r.data, self.q_exo[side]) pin.updateFramePlacements(r.model, r.data) ee = r.data.oMf[self.ee_id_exo[side]] world_tf = (pin.SE3(np.eye(3), a.offset) * ee).homogeneous p = a.marker_prefix self.markers.tf(f"markers/{p}_exo_ee", world_tf) self.markers.tf(f"markers/{p}_exo_axes", world_tf) target_tf = np.eye(4) target_tf[:3, :3] = ee.rotation target_tf[:3, 3] = a.offset + ee.translation self.markers.tf(f"markers/{p}_ik_target", target_tf) def compute_g1_joints_from_exo( self, left_angles: dict[str, float], right_angles: dict[str, float], ) -> dict[str, float]: """ Performs FK on exoskeleton to get end-effector poses in world frame, after which it solves IK on G1 to return joint angles matching those poses in G1 motor order. """ pin = self.pin targets = { "left": self._fk_target_world("left", left_angles), "right": self._fk_target_world("right", right_angles), } # fallback to current g1 ee pose if missing target pin.forwardKinematics(self.robot_g1.model, self.robot_g1.data, self.q_g1) pin.updateFramePlacements(self.robot_g1.model, self.robot_g1.data) for a in self.arms: if targets[a.side] is not None: continue fid = self.ee_id_g1.get(a.side) if fid is not None: targets[a.side] = self.robot_g1.data.oMf[fid].homogeneous if targets["left"] is None or targets["right"] is None: logger.warning("missing ik targets, returning current pose") return {} frozen_vals = {n: self.q_g1[i] for n, i in self.frozen_idx.items()} self.q_g1, _ = self.g1_ik.solve_ik( targets["left"], targets["right"], current_lr_arm_motor_q=self.q_g1 ) for n, i in self.frozen_idx.items(): self.q_g1[i] = frozen_vals[n] return { f"{j.name}.q": float(self.q_g1[i]) for i, j in enumerate(G1_29_JointArmIndex) if i < len(self.q_g1) }
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/unitree_g1/exo_ik.py", "license": "Apache License 2.0", "lines": 290, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/unitree_g1/exo_serial.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 json import logging from dataclasses import dataclass from pathlib import Path import serial from .exo_calib import ExoskeletonCalibration, exo_raw_to_angles, run_exo_calibration logger = logging.getLogger(__name__) def parse_raw16(line: bytes) -> list[int] | None: try: parts = line.decode("utf-8", errors="ignore").split() if len(parts) < 16: return None return [int(x) for x in parts[:16]] except Exception: return None def read_raw_from_serial(ser) -> list[int] | None: """Read latest sample from serial; if buffer is backed up, keep only the newest.""" last = None while ser.in_waiting > 0: b = ser.readline() if not b: break raw16 = parse_raw16(b) if raw16 is not None: last = raw16 if last is None: b = ser.readline() if b: last = parse_raw16(b) return last @dataclass class ExoskeletonArm: port: str calibration_fpath: Path side: str baud_rate: int = 115200 _ser: serial.Serial | None = None calibration: ExoskeletonCalibration | None = None def __post_init__(self): if self.calibration_fpath.is_file(): self._load_calibration() @property def is_connected(self) -> bool: return self._ser is not None and getattr(self._ser, "is_open", False) @property def is_calibrated(self) -> bool: return self.calibration is not None def connect(self, calibrate: bool = True) -> None: if self.is_connected: return try: self._ser = serial.Serial(self.port, self.baud_rate, timeout=0.02) self._ser.reset_input_buffer() logger.info(f"connected: {self.port}") except serial.SerialException as e: raise ConnectionError(f"failed to connect to {self.port}: {e}") from e if calibrate and not self.is_calibrated: self.calibrate() def disconnect(self) -> None: if self._ser: try: self._ser.close() finally: self._ser = None def _load_calibration(self) -> None: try: data = json.loads(self.calibration_fpath.read_text()) self.calibration = ExoskeletonCalibration.from_dict(data) logger.info(f"loaded calibration: {self.calibration_fpath}") except Exception as e: logger.warning(f"failed to load calibration: {e}") def read_raw(self) -> list[int] | None: if not self._ser: return None return read_raw_from_serial(self._ser) def get_angles(self) -> dict[str, float]: if not self.calibration: raise RuntimeError("exoskeleton not calibrated") raw = self.read_raw() return {} if raw is None else exo_raw_to_angles(raw, self.calibration) def calibrate(self) -> None: ser = self._ser self.calibration = run_exo_calibration(ser, self.side, self.calibration_fpath)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/unitree_g1/exo_serial.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/unitree_g1/unitree_g1.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 logging import time from functools import cached_property from lerobot.robots.unitree_g1.g1_utils import G1_29_JointIndex from lerobot.utils.constants import HF_LEROBOT_CALIBRATION, TELEOPERATORS from ..teleoperator import Teleoperator from .config_unitree_g1 import UnitreeG1TeleoperatorConfig from .exo_ik import ExoskeletonIKHelper from .exo_serial import ExoskeletonArm logger = logging.getLogger(__name__) class UnitreeG1Teleoperator(Teleoperator): """ Bimanual exoskeleton arms teleoperator for Unitree G1 arms. Uses inverse kinematics: exoskeleton FK computes end-effector pose, G1 IK solves for joint angles. """ config_class = UnitreeG1TeleoperatorConfig name = "unitree_g1" def __init__(self, config: UnitreeG1TeleoperatorConfig): super().__init__(config) self.config = config # Setup calibration directory self.calibration_dir = ( config.calibration_dir if config.calibration_dir else HF_LEROBOT_CALIBRATION / TELEOPERATORS / self.name ) self.calibration_dir.mkdir(parents=True, exist_ok=True) left_id = f"{config.id}_left" if config.id else "left" right_id = f"{config.id}_right" if config.id else "right" # Create exoskeleton arm instances self.left_arm = ExoskeletonArm( port=config.left_arm_config.port, baud_rate=config.left_arm_config.baud_rate, calibration_fpath=self.calibration_dir / f"{left_id}.json", side="left", ) self.right_arm = ExoskeletonArm( port=config.right_arm_config.port, baud_rate=config.right_arm_config.baud_rate, calibration_fpath=self.calibration_dir / f"{right_id}.json", side="right", ) self.ik_helper: ExoskeletonIKHelper | None = None @cached_property def action_features(self) -> dict[str, type]: return {f"{name}.q": float for name in self._g1_joint_names} @cached_property def feedback_features(self) -> dict[str, type]: return {} @property def is_connected(self) -> bool: return self.left_arm.is_connected and self.right_arm.is_connected @property def is_calibrated(self) -> bool: return self.left_arm.is_calibrated and self.right_arm.is_calibrated def connect(self, calibrate: bool = True) -> None: self.left_arm.connect(calibrate) self.right_arm.connect(calibrate) frozen_joints = [j.strip() for j in self.config.frozen_joints.split(",") if j.strip()] self.ik_helper = ExoskeletonIKHelper(frozen_joints=frozen_joints) logger.info("IK helper initialized") def calibrate(self) -> None: if not self.left_arm.is_calibrated: logger.info("Starting calibration for left arm...") self.left_arm.calibrate() else: logger.info("Left arm already calibrated. Skipping.") if not self.right_arm.is_calibrated: logger.info("Starting calibration for right arm...") self.right_arm.calibrate() else: logger.info("Right arm already calibrated. Skipping.") logger.info("Starting visualization to verify calibration...") self.run_visualization_loop() def configure(self) -> None: pass def get_action(self) -> dict[str, float]: left_angles = self.left_arm.get_angles() right_angles = self.right_arm.get_angles() return self.ik_helper.compute_g1_joints_from_exo(left_angles, right_angles) def send_feedback(self, feedback: dict[str, float]) -> None: raise NotImplementedError("Exoskeleton arms do not support feedback") def disconnect(self) -> None: self.left_arm.disconnect() self.right_arm.disconnect() def run_visualization_loop(self): """Run interactive Meshcat visualization loop to verify tracking.""" if self.ik_helper is None: frozen_joints = [j.strip() for j in self.config.frozen_joints.split(",") if j.strip()] self.ik_helper = ExoskeletonIKHelper(frozen_joints=frozen_joints) self.ik_helper.init_visualization() print("\n" + "=" * 60) print("Visualization running! Move the exoskeletons to test tracking.") print("Press Ctrl+C to exit.") print("=" * 60 + "\n") try: while True: left_angles = self.left_arm.get_angles() right_angles = self.right_arm.get_angles() self.ik_helper.compute_g1_joints_from_exo(left_angles, right_angles) self.ik_helper.update_visualization() time.sleep(0.01) except KeyboardInterrupt: print("\n\nVisualization stopped.") @cached_property def _g1_joint_names(self) -> list[str]: return [joint.name for joint in G1_29_JointIndex]
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/unitree_g1/unitree_g1.py", "license": "Apache License 2.0", "lines": 122, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/openarm_follower/config_openarm_follower.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from lerobot.cameras import CameraConfig from ..config import RobotConfig LEFT_DEFAULT_JOINTS_LIMITS: dict[str, tuple[float, float]] = { "joint_1": (-75.0, 75.0), "joint_2": (-90.0, 9.0), "joint_3": (-85.0, 85.0), "joint_4": (0.0, 135.0), "joint_5": (-85.0, 85.0), "joint_6": (-40.0, 40.0), "joint_7": (-80.0, 80.0), "gripper": (-65.0, 0.0), } RIGHT_DEFAULT_JOINTS_LIMITS: dict[str, tuple[float, float]] = { "joint_1": (-75.0, 75.0), "joint_2": (-9.0, 90.0), "joint_3": (-85.0, 85.0), "joint_4": (0.0, 135.0), "joint_5": (-85.0, 85.0), "joint_6": (-40.0, 40.0), "joint_7": (-80.0, 80.0), "gripper": (-65.0, 0.0), } @dataclass class OpenArmFollowerConfigBase: """Base configuration for the OpenArms follower robot with Damiao motors.""" # CAN interfaces - one per arm # arm CAN interface (e.g., "can1") # Linux: "can0", "can1", etc. port: str # side of the arm: "left" or "right". If "None" default values will be used side: str | None = None # CAN interface type: "socketcan" (Linux), "slcan" (serial), or "auto" (auto-detect) can_interface: str = "socketcan" # CAN FD settings (OpenArms uses CAN FD by default) use_can_fd: bool = True can_bitrate: int = 1000000 # Nominal bitrate (1 Mbps) can_data_bitrate: int = 5000000 # Data bitrate for CAN FD (5 Mbps) # Whether to disable torque when disconnecting disable_torque_on_disconnect: bool = True # Safety limit for relative target positions # Set to a positive scalar for all motors, or a dict mapping motor names to limits max_relative_target: float | dict[str, float] | None = None # Camera configurations cameras: dict[str, CameraConfig] = field(default_factory=dict) # Motor configuration for OpenArms (7 DOF per arm) # Maps motor names to (send_can_id, recv_can_id, motor_type) # Based on: https://docs.openarm.dev/software/setup/configure-test # OpenArms uses 4 types of motors: # - DM8009 (DM-J8009P-2EC) for shoulders (high torque) # - DM4340P and DM4340 for shoulder rotation and elbow # - DM4310 (DM-J4310-2EC V1.1) for wrist and gripper motor_config: dict[str, tuple[int, int, str]] = field( default_factory=lambda: { "joint_1": (0x01, 0x11, "dm8009"), # J1 - Shoulder pan (DM8009) "joint_2": (0x02, 0x12, "dm8009"), # J2 - Shoulder lift (DM8009) "joint_3": (0x03, 0x13, "dm4340"), # J3 - Shoulder rotation (DM4340) "joint_4": (0x04, 0x14, "dm4340"), # J4 - Elbow flex (DM4340) "joint_5": (0x05, 0x15, "dm4310"), # J5 - Wrist roll (DM4310) "joint_6": (0x06, 0x16, "dm4310"), # J6 - Wrist pitch (DM4310) "joint_7": (0x07, 0x17, "dm4310"), # J7 - Wrist rotation (DM4310) "gripper": (0x08, 0x18, "dm4310"), # J8 - Gripper (DM4310) } ) # MIT control parameters for position control (used in send_action) # List of 8 values: [joint_1, joint_2, joint_3, joint_4, joint_5, joint_6, joint_7, gripper] position_kp: list[float] = field( default_factory=lambda: [240.0, 240.0, 240.0, 240.0, 24.0, 31.0, 25.0, 25.0] ) position_kd: list[float] = field(default_factory=lambda: [5.0, 5.0, 3.0, 5.0, 0.3, 0.3, 0.3, 0.3]) # Values for joint limits. Can be overridden via CLI (for custom values) or by setting config.side to either 'left' or 'right'. # If config.side is left set to None and no CLI values are passed, the default joint limit values are small for safety. joint_limits: dict[str, tuple[float, float]] = field( default_factory=lambda: { "joint_1": (-5.0, 5.0), "joint_2": (-5.0, 5.0), "joint_3": (-5.0, 5.0), "joint_4": (0.0, 5.0), "joint_5": (-5.0, 5.0), "joint_6": (-5.0, 5.0), "joint_7": (-5.0, 5.0), "gripper": (-5.0, 0.0), } ) @RobotConfig.register_subclass("openarm_follower") @dataclass class OpenArmFollowerConfig(RobotConfig, OpenArmFollowerConfigBase): pass
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/openarm_follower/config_openarm_follower.py", "license": "Apache License 2.0", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/openarm_follower/openarm_follower.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 logging import time from functools import cached_property from typing import Any from lerobot.cameras.utils import make_cameras_from_configs from lerobot.motors import Motor, MotorCalibration, MotorNormMode from lerobot.motors.damiao import DamiaoMotorsBus from lerobot.processor import RobotAction, RobotObservation from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..robot import Robot from ..utils import ensure_safe_goal_position from .config_openarm_follower import ( LEFT_DEFAULT_JOINTS_LIMITS, RIGHT_DEFAULT_JOINTS_LIMITS, OpenArmFollowerConfig, ) logger = logging.getLogger(__name__) class OpenArmFollower(Robot): """ OpenArms Follower Robot which uses CAN bus communication to control 7 DOF arm with a gripper. The arm uses Damiao motors in MIT control mode. """ config_class = OpenArmFollowerConfig name = "openarm_follower" def __init__(self, config: OpenArmFollowerConfig): super().__init__(config) self.config = config # Arm motors motors: dict[str, Motor] = {} for motor_name, (send_id, recv_id, motor_type_str) in config.motor_config.items(): motor = Motor( send_id, motor_type_str, MotorNormMode.DEGREES ) # Always use degrees for Damiao motors motor.recv_id = recv_id motor.motor_type_str = motor_type_str motors[motor_name] = motor self.bus = DamiaoMotorsBus( port=self.config.port, motors=motors, calibration=self.calibration, can_interface=self.config.can_interface, use_can_fd=self.config.use_can_fd, bitrate=self.config.can_bitrate, data_bitrate=self.config.can_data_bitrate if self.config.use_can_fd else None, ) if config.side is not None: if config.side == "left": config.joint_limits = LEFT_DEFAULT_JOINTS_LIMITS elif config.side == "right": config.joint_limits = RIGHT_DEFAULT_JOINTS_LIMITS else: raise ValueError( "config.side must be either 'left', 'right' (for default values) or 'None' (for CLI values)" ) else: logger.info( "Set config.side to either 'left' or 'right' to use pre-configured values for joint limits." ) logger.info(f"Values used for joint limits: {config.joint_limits}.") # Initialize cameras self.cameras = make_cameras_from_configs(config.cameras) @property def _motors_ft(self) -> dict[str, type]: """Motor features for observation and action spaces.""" features: dict[str, type] = {} for motor in self.bus.motors: features[f"{motor}.pos"] = float features[f"{motor}.vel"] = float # Add this features[f"{motor}.torque"] = float # Add this return features @property def _cameras_ft(self) -> dict[str, tuple]: """Camera features for observation space.""" return { cam: (self.config.cameras[cam].height, self.config.cameras[cam].width, 3) for cam in self.cameras } @cached_property def observation_features(self) -> dict[str, type | tuple]: """Combined observation features from motors and cameras.""" return {**self._motors_ft, **self._cameras_ft} @cached_property def action_features(self) -> dict[str, type]: """Action features.""" return self._motors_ft @property def is_connected(self) -> bool: """Check if robot is connected.""" return self.bus.is_connected and all(cam.is_connected for cam in self.cameras.values()) @check_if_already_connected def connect(self, calibrate: bool = True) -> None: """ Connect to the robot and optionally calibrate. We assume that at connection time, the arms are in a safe rest position, and torque can be safely disabled to run calibration if needed. """ # Connect to CAN bus logger.info(f"Connecting arm on {self.config.port}...") self.bus.connect() # Run calibration if needed if not self.is_calibrated and calibrate: logger.info( "Mismatch between calibration values in the motor and the calibration file or no calibration file found" ) self.calibrate() for cam in self.cameras.values(): cam.connect() self.configure() if self.is_calibrated: self.bus.set_zero_position() self.bus.enable_torque() logger.info(f"{self} connected.") @property def is_calibrated(self) -> bool: """Check if robot is calibrated.""" return self.bus.is_calibrated def calibrate(self) -> None: """ Run calibration procedure for OpenArms robot. The calibration procedure: 1. Disable torque 2. Ask user to position arms in hanging position with grippers closed 3. Set this as zero position 4. Record range of motion for each joint 5. Save calibration """ if self.calibration: # Calibration file exists, ask user whether to use it or run new calibration user_input = input( f"Press ENTER to use provided calibration file associated with the id {self.id}, or type 'c' and press ENTER to run calibration: " ) if user_input.strip().lower() != "c": logger.info(f"Writing calibration file associated with the id {self.id} to the motors") self.bus.write_calibration(self.calibration) return logger.info(f"\nRunning calibration for {self}") self.bus.disable_torque() # Step 1: Set zero position input( "\nCalibration: Set Zero Position)\n" "Position the arm in the following configuration:\n" " - Arm hanging straight down\n" " - Gripper closed\n" "Press ENTER when ready..." ) # Set current position as zero for all motors self.bus.set_zero_position() logger.info("Arm zero position set.") logger.info("Setting range: -90° to +90° for safety by default for all joints") for motor_name, motor in self.bus.motors.items(): self.calibration[motor_name] = MotorCalibration( id=motor.id, drive_mode=0, homing_offset=0, range_min=-90, range_max=90, ) self.bus.write_calibration(self.calibration) self._save_calibration() print(f"Calibration saved to {self.calibration_fpath}") def configure(self) -> None: """Configure motors with appropriate settings.""" # TODO(Steven, Pepijn): Slightly different from what it is happening in the leader with self.bus.torque_disabled(): self.bus.configure_motors() def setup_motors(self) -> None: raise NotImplementedError( "Motor ID configuration is typically done via manufacturer tools for CAN motors." ) @check_if_not_connected def get_observation(self) -> RobotObservation: """ Get current observation from robot including position, velocity, and torque. Reads all motor states (pos/vel/torque) in one CAN refresh cycle instead of 3 separate reads. """ start = time.perf_counter() obs_dict: dict[str, Any] = {} states = self.bus.sync_read_all_states() for motor in self.bus.motors: state = states.get(motor, {}) obs_dict[f"{motor}.pos"] = state.get("position", 0.0) obs_dict[f"{motor}.vel"] = state.get("velocity", 0.0) obs_dict[f"{motor}.torque"] = state.get("torque", 0.0) # Capture images from cameras for cam_key, cam in self.cameras.items(): start = time.perf_counter() obs_dict[cam_key] = cam.read_latest() dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} read {cam_key}: {dt_ms:.1f}ms") dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} get_observation took: {dt_ms:.1f}ms") return obs_dict @check_if_not_connected def send_action( self, action: RobotAction, custom_kp: dict[str, float] | None = None, custom_kd: dict[str, float] | None = None, ) -> RobotAction: """ Send action command to robot. The action magnitude may be clipped based on safety limits. Args: action: Dictionary with motor positions (e.g., "joint_1.pos", "joint_2.pos") custom_kp: Optional custom kp gains per motor (e.g., {"joint_1": 120.0, "joint_2": 150.0}) custom_kd: Optional custom kd gains per motor (e.g., {"joint_1": 1.5, "joint_2": 2.0}) Returns: The action actually sent (potentially clipped) """ goal_pos = {key.removesuffix(".pos"): val for key, val in action.items() if key.endswith(".pos")} # Apply joint limit clipping to arm for motor_name, position in goal_pos.items(): if motor_name in self.config.joint_limits: min_limit, max_limit = self.config.joint_limits[motor_name] clipped_position = max(min_limit, min(max_limit, position)) if clipped_position != position: logger.debug(f"Clipped {motor_name} from {position:.2f}° to {clipped_position:.2f}°") goal_pos[motor_name] = clipped_position # Cap goal position when too far away from present position. # /!\ Slower fps expected due to reading from the follower. if self.config.max_relative_target is not None: present_pos = self.bus.sync_read("Present_Position") goal_present_pos = {key: (g_pos, present_pos[key]) for key, g_pos in goal_pos.items()} goal_pos = ensure_safe_goal_position(goal_present_pos, self.config.max_relative_target) # TODO(Steven, Pepijn): Refactor writing # Motor name to index mapping for gains motor_index = { "joint_1": 0, "joint_2": 1, "joint_3": 2, "joint_4": 3, "joint_5": 4, "joint_6": 5, "joint_7": 6, "gripper": 7, } # Use batch MIT control for arm (sends all commands, then collects responses) commands = {} for motor_name, position_degrees in goal_pos.items(): idx = motor_index.get(motor_name, 0) # Use custom gains if provided, otherwise use config defaults if custom_kp is not None and motor_name in custom_kp: kp = custom_kp[motor_name] else: kp = ( self.config.position_kp[idx] if isinstance(self.config.position_kp, list) else self.config.position_kp ) if custom_kd is not None and motor_name in custom_kd: kd = custom_kd[motor_name] else: kd = ( self.config.position_kd[idx] if isinstance(self.config.position_kd, list) else self.config.position_kd ) commands[motor_name] = (kp, kd, position_degrees, 0.0, 0.0) self.bus._mit_control_batch(commands) return {f"{motor}.pos": val for motor, val in goal_pos.items()} @check_if_not_connected def disconnect(self): """Disconnect from robot.""" # Disconnect CAN bus self.bus.disconnect(self.config.disable_torque_on_disconnect) # Disconnect cameras for cam in self.cameras.values(): cam.disconnect() logger.info(f"{self} disconnected.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/openarm_follower/openarm_follower.py", "license": "Apache License 2.0", "lines": 283, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/openarm_leader/config_openarm_leader.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from ..config import TeleoperatorConfig @dataclass class OpenArmLeaderConfigBase: """Base configuration for the OpenArms leader/teleoperator with Damiao motors.""" # CAN interfaces - one per arm # Arm CAN interface (e.g., "can3") # Linux: "can0", "can1", etc. port: str # CAN interface type: "socketcan" (Linux), "slcan" (serial), or "auto" (auto-detect) can_interface: str = "socketcan" # CAN FD settings (OpenArms uses CAN FD by default) use_can_fd: bool = True can_bitrate: int = 1000000 # Nominal bitrate (1 Mbps) can_data_bitrate: int = 5000000 # Data bitrate for CAN FD (5 Mbps) # Motor configuration for OpenArms (7 DOF per arm) # Maps motor names to (send_can_id, recv_can_id, motor_type) # Based on: https://docs.openarm.dev/software/setup/configure-test # OpenArms uses 4 types of motors: # - DM8009 (DM-J8009P-2EC) for shoulders (high torque) # - DM4340P and DM4340 for shoulder rotation and elbow # - DM4310 (DM-J4310-2EC V1.1) for wrist and gripper motor_config: dict[str, tuple[int, int, str]] = field( default_factory=lambda: { "joint_1": (0x01, 0x11, "dm8009"), # J1 - Shoulder pan (DM8009) "joint_2": (0x02, 0x12, "dm8009"), # J2 - Shoulder lift (DM8009) "joint_3": (0x03, 0x13, "dm4340"), # J3 - Shoulder rotation (DM4340) "joint_4": (0x04, 0x14, "dm4340"), # J4 - Elbow flex (DM4340) "joint_5": (0x05, 0x15, "dm4310"), # J5 - Wrist roll (DM4310) "joint_6": (0x06, 0x16, "dm4310"), # J6 - Wrist pitch (DM4310) "joint_7": (0x07, 0x17, "dm4310"), # J7 - Wrist rotation (DM4310) "gripper": (0x08, 0x18, "dm4310"), # J8 - Gripper (DM4310) } ) # Torque mode settings for manual control # When enabled, motors have torque disabled for manual movement manual_control: bool = True # TODO(Steven, Pepijn): Not used ... ? # MIT control parameters (used when manual_control=False for torque control) # List of 8 values: [joint_1, joint_2, joint_3, joint_4, joint_5, joint_6, joint_7, gripper] position_kp: list[float] = field( default_factory=lambda: [240.0, 240.0, 240.0, 240.0, 24.0, 31.0, 25.0, 16.0] ) position_kd: list[float] = field(default_factory=lambda: [3.0, 3.0, 3.0, 3.0, 0.2, 0.2, 0.2, 0.2]) @TeleoperatorConfig.register_subclass("openarm_leader") @dataclass class OpenArmLeaderConfig(TeleoperatorConfig, OpenArmLeaderConfigBase): pass
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/openarm_leader/config_openarm_leader.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/openarm_leader/openarm_leader.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 logging import time from typing import Any from lerobot.motors import Motor, MotorCalibration, MotorNormMode from lerobot.motors.damiao import DamiaoMotorsBus from lerobot.processor import RobotAction from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..teleoperator import Teleoperator from .config_openarm_leader import OpenArmLeaderConfig logger = logging.getLogger(__name__) class OpenArmLeader(Teleoperator): """ OpenArm Leader/Teleoperator Arm with Damiao motors. This teleoperator uses CAN bus communication to read positions from Damiao motors that are manually moved (torque disabled). """ config_class = OpenArmLeaderConfig name = "openarm_leader" def __init__(self, config: OpenArmLeaderConfig): super().__init__(config) self.config = config # Arm motors motors: dict[str, Motor] = {} for motor_name, (send_id, recv_id, motor_type_str) in config.motor_config.items(): motor = Motor( send_id, motor_type_str, MotorNormMode.DEGREES ) # Always use degrees for Damiao motors motor.recv_id = recv_id motor.motor_type_str = motor_type_str motors[motor_name] = motor self.bus = DamiaoMotorsBus( port=self.config.port, motors=motors, calibration=self.calibration, can_interface=self.config.can_interface, use_can_fd=self.config.use_can_fd, bitrate=self.config.can_bitrate, data_bitrate=self.config.can_data_bitrate if self.config.use_can_fd else None, ) @property def action_features(self) -> dict[str, type]: """Features produced by this teleoperator.""" features: dict[str, type] = {} for motor in self.bus.motors: features[f"{motor}.pos"] = float features[f"{motor}.vel"] = float features[f"{motor}.torque"] = float return features @property def feedback_features(self) -> dict[str, type]: """Feedback features (not implemented for OpenArms).""" return {} @property def is_connected(self) -> bool: """Check if teleoperator is connected.""" return self.bus.is_connected @check_if_already_connected def connect(self, calibrate: bool = True) -> None: """ Connect to the teleoperator. For manual control, we disable torque after connecting so the arm can be moved by hand. """ # Connect to CAN bus logger.info(f"Connecting arm on {self.config.port}...") self.bus.connect() # Run calibration if needed if not self.is_calibrated and calibrate: logger.info( "Mismatch between calibration values in the motor and the calibration file or no calibration file found" ) self.calibrate() self.configure() if self.is_calibrated: self.bus.set_zero_position() logger.info(f"{self} connected.") @property def is_calibrated(self) -> bool: """Check if teleoperator is calibrated.""" return self.bus.is_calibrated def calibrate(self) -> None: """ Run calibration procedure for OpenArms leader. The calibration procedure: 1. Disable torque (if not already disabled) 2. Ask user to position arm in zero position (hanging with gripper closed) 3. Set this as zero position 4. Record range of motion for each joint 5. Save calibration """ if self.calibration: # Calibration file exists, ask user whether to use it or run new calibration user_input = input( f"Press ENTER to use provided calibration file associated with the id {self.id}, or type 'c' and press ENTER to run calibration: " ) if user_input.strip().lower() != "c": logger.info(f"Writing calibration file associated with the id {self.id} to the motors") self.bus.write_calibration(self.calibration) return logger.info(f"\nRunning calibration for {self}") self.bus.disable_torque() # Step 1: Set zero position input( "\nCalibration: Set Zero Position)\n" "Position the arm in the following configuration:\n" " - Arm hanging straight down\n" " - Gripper closed\n" "Press ENTER when ready..." ) # Set current position as zero for all motors self.bus.set_zero_position() logger.info("Arm zero position set.") logger.info("Setting range: -90° to +90° by default for all joints") # TODO(Steven, Pepijn): Check if MotorCalibration is actually needed here given that we only use Degrees for motor_name, motor in self.bus.motors.items(): self.calibration[motor_name] = MotorCalibration( id=motor.id, drive_mode=0, homing_offset=0, range_min=-90, range_max=90, ) self.bus.write_calibration(self.calibration) self._save_calibration() print(f"Calibration saved to {self.calibration_fpath}") def configure(self) -> None: """ Configure motors for manual teleoperation. For manual control, we disable torque so the arm can be moved by hand. """ return self.bus.disable_torque() if self.config.manual_control else self.bus.configure_motors() def setup_motors(self) -> None: raise NotImplementedError( "Motor ID configuration is typically done via manufacturer tools for CAN motors." ) @check_if_not_connected def get_action(self) -> RobotAction: """ Get current action from the leader arm. This is the main method for teleoperators - it reads the current state of the leader arm and returns it as an action that can be sent to a follower. Reads all motor states (pos/vel/torque) in one CAN refresh cycle. """ start = time.perf_counter() action_dict: dict[str, Any] = {} # Use sync_read_all_states to get pos/vel/torque in one go states = self.bus.sync_read_all_states() for motor in self.bus.motors: state = states.get(motor, {}) action_dict[f"{motor}.pos"] = state.get("position") action_dict[f"{motor}.vel"] = state.get("velocity") action_dict[f"{motor}.torque"] = state.get("torque") dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} read state: {dt_ms:.1f}ms") return action_dict def send_feedback(self, feedback: dict[str, float]) -> None: raise NotImplementedError("Feedback is not yet implemented for OpenArm leader.") @check_if_not_connected def disconnect(self) -> None: """Disconnect from teleoperator.""" # Disconnect CAN bus # For manual control, ensure torque is disabled before disconnecting self.bus.disconnect(disable_torque=self.config.manual_control) logger.info(f"{self} disconnected.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/openarm_leader/openarm_leader.py", "license": "Apache License 2.0", "lines": 178, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/motors/damiao/damiao.py
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. # Portions of this file are derived from DM_Control_Python by cmjang. # Licensed under the MIT License; see `LICENSE` for the full text: # https://github.com/cmjang/DM_Control_Python import logging import time from contextlib import contextmanager from copy import deepcopy from functools import cached_property from typing import TYPE_CHECKING, Any, TypedDict from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from lerobot.utils.import_utils import _can_available if TYPE_CHECKING or _can_available: import can else: class can: # noqa: N801 Message = object interface = None import numpy as np from lerobot.utils.robot_utils import precise_sleep from lerobot.utils.utils import enter_pressed, move_cursor_up from ..motors_bus import Motor, MotorCalibration, MotorsBusBase, NameOrID, Value from .tables import ( AVAILABLE_BAUDRATES, CAN_CMD_DISABLE, CAN_CMD_ENABLE, CAN_CMD_REFRESH, CAN_CMD_SET_ZERO, CAN_PARAM_ID, DEFAULT_BAUDRATE, DEFAULT_TIMEOUT_MS, MIT_KD_RANGE, MIT_KP_RANGE, MOTOR_LIMIT_PARAMS, MotorType, ) logger = logging.getLogger(__name__) LONG_TIMEOUT_SEC = 0.1 MEDIUM_TIMEOUT_SEC = 0.01 SHORT_TIMEOUT_SEC = 0.001 PRECISE_TIMEOUT_SEC = 0.0001 class MotorState(TypedDict): position: float velocity: float torque: float temp_mos: float temp_rotor: float class DamiaoMotorsBus(MotorsBusBase): """ The Damiao implementation for a MotorsBus using CAN bus communication. This class uses python-can for CAN bus communication with Damiao motors. For more info, see: - python-can documentation: https://python-can.readthedocs.io/en/stable/ - Seedstudio documentation: https://wiki.seeedstudio.com/damiao_series/ - DM_Control_Python repo: https://github.com/cmjang/DM_Control_Python """ # CAN-specific settings available_baudrates = deepcopy(AVAILABLE_BAUDRATES) default_baudrate = DEFAULT_BAUDRATE default_timeout = DEFAULT_TIMEOUT_MS def __init__( self, port: str, motors: dict[str, Motor], calibration: dict[str, MotorCalibration] | None = None, can_interface: str = "auto", use_can_fd: bool = True, bitrate: int = 1000000, data_bitrate: int | None = 5000000, ): """ Initialize the Damiao motors bus. Args: port: CAN interface name (e.g., "can0" for Linux, "/dev/cu.usbmodem*" for macOS) motors: Dictionary mapping motor names to Motor objects calibration: Optional calibration data can_interface: CAN interface type - "auto" (default), "socketcan" (Linux), or "slcan" (macOS/serial) use_can_fd: Whether to use CAN FD mode (default: True for OpenArms) bitrate: Nominal bitrate in bps (default: 1000000 = 1 Mbps) data_bitrate: Data bitrate for CAN FD in bps (default: 5000000 = 5 Mbps), ignored if use_can_fd is False """ super().__init__(port, motors, calibration) self.port = port self.can_interface = can_interface self.use_can_fd = use_can_fd self.bitrate = bitrate self.data_bitrate = data_bitrate self.canbus: can.interface.Bus | None = None self._is_connected = False # Map motor names to CAN IDs self._motor_can_ids: dict[str, int] = {} self._recv_id_to_motor: dict[int, str] = {} self._motor_types: dict[str, MotorType] = {} for name, motor in self.motors.items(): if motor.motor_type_str is None: raise ValueError(f"Motor '{name}' is missing required 'motor_type'") self._motor_types[name] = getattr(MotorType, motor.motor_type_str.upper().replace("-", "_")) # Map recv_id to motor name for filtering responses if motor.recv_id is not None: self._recv_id_to_motor[motor.recv_id] = name # State cache for handling packet drops safely self._last_known_states: dict[str, MotorState] = { name: { "position": 0.0, "velocity": 0.0, "torque": 0.0, "temp_mos": 0.0, "temp_rotor": 0.0, } for name in self.motors } # Dynamic gains storage # Defaults: Kp=10.0 (Stiffness), Kd=0.5 (Damping) self._gains: dict[str, dict[str, float]] = {name: {"kp": 10.0, "kd": 0.5} for name in self.motors} @property def is_connected(self) -> bool: """Check if the CAN bus is connected.""" return self._is_connected and self.canbus is not None @check_if_already_connected def connect(self, handshake: bool = True) -> None: """ Open the CAN bus and initialize communication. Args: handshake: If True, ping all motors to verify they're present """ try: # Auto-detect interface type based on port name if self.can_interface == "auto": if self.port.startswith("/dev/"): self.can_interface = "slcan" logger.info(f"Auto-detected slcan interface for port {self.port}") else: self.can_interface = "socketcan" logger.info(f"Auto-detected socketcan interface for port {self.port}") # Connect to CAN bus kwargs = { "channel": self.port, "bitrate": self.bitrate, "interface": self.can_interface, } if self.can_interface == "socketcan" and self.use_can_fd and self.data_bitrate is not None: kwargs.update({"data_bitrate": self.data_bitrate, "fd": True}) logger.info( f"Connected to {self.port} with CAN FD (bitrate={self.bitrate}, data_bitrate={self.data_bitrate})" ) else: logger.info(f"Connected to {self.port} with {self.can_interface} (bitrate={self.bitrate})") self.canbus = can.interface.Bus(**kwargs) self._is_connected = True if handshake: self._handshake() logger.debug(f"{self.__class__.__name__} connected via {self.can_interface}.") except Exception as e: self._is_connected = False raise ConnectionError(f"Failed to connect to CAN bus: {e}") from e def _handshake(self) -> None: """ Verify all motors are present and populate initial state cache. Raises ConnectionError if any motor fails to respond. """ logger.info("Starting handshake with motors...") # Drain any pending messages if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") while self.canbus.recv(timeout=0.01): pass missing_motors = [] for motor_name in self.motors: motor_id = self._get_motor_id(motor_name) recv_id = self._get_motor_recv_id(motor_name) # Send enable command data = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, CAN_CMD_ENABLE] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False, is_fd=self.use_can_fd) self.canbus.send(msg) # Wait for response with longer timeout response = None start_time = time.time() while time.time() - start_time < 0.1: response = self.canbus.recv(timeout=0.1) if response and response.arbitration_id == recv_id: break response = None if response is None: missing_motors.append(motor_name) else: self._process_response(motor_name, msg) time.sleep(MEDIUM_TIMEOUT_SEC) if missing_motors: raise ConnectionError( f"Handshake failed. The following motors did not respond: {missing_motors}. " "Check power (24V) and CAN wiring." ) logger.info("Handshake successful. All motors ready.") @check_if_not_connected def disconnect(self, disable_torque: bool = True) -> None: """ Close the CAN bus connection. Args: disable_torque: If True, disable torque on all motors before disconnecting """ if disable_torque: try: self.disable_torque() except Exception as e: logger.warning(f"Failed to disable torque during disconnect: {e}") if self.canbus: self.canbus.shutdown() self.canbus = None self._is_connected = False logger.debug(f"{self.__class__.__name__} disconnected.") def configure_motors(self) -> None: """Configure all motors with default settings.""" # Damiao motors don't require much configuration in MIT mode # Just ensure they're enabled for motor in self.motors: self._send_simple_command(motor, CAN_CMD_ENABLE) time.sleep(MEDIUM_TIMEOUT_SEC) def _send_simple_command(self, motor: NameOrID, command_byte: int) -> None: """Helper to send simple 8-byte commands (Enable, Disable, Zero).""" motor_id = self._get_motor_id(motor) motor_name = self._get_motor_name(motor) recv_id = self._get_motor_recv_id(motor) data = [0xFF] * 7 + [command_byte] msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False, is_fd=self.use_can_fd) if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") self.canbus.send(msg) if msg := self._recv_motor_response(expected_recv_id=recv_id): self._process_response(motor_name, msg) else: logger.debug(f"No response from {motor_name} after command 0x{command_byte:02X}") def enable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None: """Enable torque on selected motors.""" target_motors = self._get_motors_list(motors) for motor in target_motors: for _ in range(num_retry + 1): try: self._send_simple_command(motor, CAN_CMD_ENABLE) break except Exception as e: if _ == num_retry: raise e time.sleep(MEDIUM_TIMEOUT_SEC) def disable_torque(self, motors: str | list[str] | None = None, num_retry: int = 0) -> None: """Disable torque on selected motors.""" target_motors = self._get_motors_list(motors) for motor in target_motors: for _ in range(num_retry + 1): try: self._send_simple_command(motor, CAN_CMD_DISABLE) break except Exception as e: if _ == num_retry: raise e time.sleep(MEDIUM_TIMEOUT_SEC) @contextmanager def torque_disabled(self, motors: str | list[str] | None = None): """ Context manager that guarantees torque is re-enabled. This helper is useful to temporarily disable torque when configuring motors. """ self.disable_torque(motors) try: yield finally: self.enable_torque(motors) def set_zero_position(self, motors: str | list[str] | None = None) -> None: """Set current position as zero for selected motors.""" target_motors = self._get_motors_list(motors) for motor in target_motors: self._send_simple_command(motor, CAN_CMD_SET_ZERO) time.sleep(MEDIUM_TIMEOUT_SEC) def _refresh_motor(self, motor: NameOrID) -> can.Message | None: """Refresh motor status and return the response.""" motor_id = self._get_motor_id(motor) recv_id = self._get_motor_recv_id(motor) data = [motor_id & 0xFF, (motor_id >> 8) & 0xFF, CAN_CMD_REFRESH, 0, 0, 0, 0, 0] msg = can.Message(arbitration_id=CAN_PARAM_ID, data=data, is_extended_id=False, is_fd=self.use_can_fd) if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") self.canbus.send(msg) return self._recv_motor_response(expected_recv_id=recv_id) def _recv_motor_response( self, expected_recv_id: int | None = None, timeout: float = 0.001 ) -> can.Message | None: """ Receive a response from a motor. Args: expected_recv_id: If provided, only return messages from this CAN ID timeout: Timeout in seconds (default: 1ms for high-speed operation) Returns: CAN message if received, None otherwise """ if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") try: start_time = time.time() messages_seen = [] while time.time() - start_time < timeout: msg = self.canbus.recv(timeout=PRECISE_TIMEOUT_SEC) if msg: messages_seen.append(f"0x{msg.arbitration_id:02X}") if expected_recv_id is None or msg.arbitration_id == expected_recv_id: return msg logger.debug( f"Ignoring message from 0x{msg.arbitration_id:02X}, expected 0x{expected_recv_id:02X}" ) if logger.isEnabledFor(logging.DEBUG): if messages_seen: logger.debug( f"Received {len(messages_seen)} msgs from {set(messages_seen)}, expected 0x{expected_recv_id:02X}" ) else: logger.debug(f"No CAN messages received (expected 0x{expected_recv_id:02X})") except Exception as e: logger.debug(f"Failed to receive CAN message: {e}") return None def _recv_all_responses( self, expected_recv_ids: list[int], timeout: float = 0.002 ) -> dict[int, can.Message]: """ Efficiently receive responses from multiple motors at once. Uses the OpenArms pattern: collect all available messages within timeout. Args: expected_recv_ids: List of CAN IDs we expect responses from timeout: Total timeout in seconds (default: 2ms) Returns: Dictionary mapping recv_id to CAN message """ responses: dict[int, can.Message] = {} expected_set = set(expected_recv_ids) start_time = time.time() if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") try: while len(responses) < len(expected_recv_ids) and (time.time() - start_time) < timeout: # 100us poll timeout msg = self.canbus.recv(timeout=PRECISE_TIMEOUT_SEC) if msg and msg.arbitration_id in expected_set: responses[msg.arbitration_id] = msg if len(responses) == len(expected_recv_ids): break except Exception as e: logger.debug(f"Error receiving responses: {e}") return responses def _encode_mit_packet( self, motor_type: MotorType, kp: float, kd: float, position_degrees: float, velocity_deg_per_sec: float, torque: float, ) -> list[int]: """Helper to encode control parameters into 8 bytes for MIT mode.""" # Convert degrees to radians position_rad = np.radians(position_degrees) velocity_rad_per_sec = np.radians(velocity_deg_per_sec) # Get motor limits pmax, vmax, tmax = MOTOR_LIMIT_PARAMS[motor_type] # Encode parameters kp_uint = self._float_to_uint(kp, *MIT_KP_RANGE, 12) kd_uint = self._float_to_uint(kd, *MIT_KD_RANGE, 12) q_uint = self._float_to_uint(position_rad, -pmax, pmax, 16) dq_uint = self._float_to_uint(velocity_rad_per_sec, -vmax, vmax, 12) tau_uint = self._float_to_uint(torque, -tmax, tmax, 12) # Pack data data = [0] * 8 data[0] = (q_uint >> 8) & 0xFF data[1] = q_uint & 0xFF data[2] = dq_uint >> 4 data[3] = ((dq_uint & 0xF) << 4) | ((kp_uint >> 8) & 0xF) data[4] = kp_uint & 0xFF data[5] = kd_uint >> 4 data[6] = ((kd_uint & 0xF) << 4) | ((tau_uint >> 8) & 0xF) data[7] = tau_uint & 0xFF return data def _mit_control( self, motor: NameOrID, kp: float, kd: float, position_degrees: float, velocity_deg_per_sec: float, torque: float, ) -> None: """Send MIT control command to a motor.""" motor_id = self._get_motor_id(motor) motor_name = self._get_motor_name(motor) motor_type = self._motor_types[motor_name] if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") data = self._encode_mit_packet(motor_type, kp, kd, position_degrees, velocity_deg_per_sec, torque) msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False, is_fd=self.use_can_fd) self.canbus.send(msg) recv_id = self._get_motor_recv_id(motor) if msg := self._recv_motor_response(expected_recv_id=recv_id): self._process_response(motor_name, msg) else: logger.debug(f"No response from {motor_name} after MIT control command") def _mit_control_batch( self, commands: dict[NameOrID, tuple[float, float, float, float, float]], ) -> None: """ Send MIT control commands to multiple motors in batch. Sends all commands first, then collects responses. Args: commands: Dict mapping motor name/ID to (kp, kd, position_deg, velocity_deg/s, torque) Example: {'joint_1': (10.0, 0.5, 45.0, 0.0, 0.0), ...} """ if not commands: return recv_id_to_motor: dict[int, str] = {} if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") # Step 1: Send all MIT control commands for motor, (kp, kd, position_degrees, velocity_deg_per_sec, torque) in commands.items(): motor_id = self._get_motor_id(motor) motor_name = self._get_motor_name(motor) motor_type = self._motor_types[motor_name] data = self._encode_mit_packet(motor_type, kp, kd, position_degrees, velocity_deg_per_sec, torque) msg = can.Message(arbitration_id=motor_id, data=data, is_extended_id=False, is_fd=self.use_can_fd) self.canbus.send(msg) recv_id_to_motor[self._get_motor_recv_id(motor)] = motor_name # Step 2: Collect responses and update state cache responses = self._recv_all_responses(list(recv_id_to_motor.keys()), timeout=SHORT_TIMEOUT_SEC) for recv_id, motor_name in recv_id_to_motor.items(): if msg := responses.get(recv_id): self._process_response(motor_name, msg) def _float_to_uint(self, x: float, x_min: float, x_max: float, bits: int) -> int: """Convert float to unsigned integer for CAN transmission.""" x = max(x_min, min(x_max, x)) # Clamp to range span = x_max - x_min data_norm = (x - x_min) / span return int(data_norm * ((1 << bits) - 1)) def _uint_to_float(self, x: int, x_min: float, x_max: float, bits: int) -> float: """Convert unsigned integer from CAN to float.""" span = x_max - x_min data_norm = float(x) / ((1 << bits) - 1) return data_norm * span + x_min def _decode_motor_state( self, data: bytearray | bytes, motor_type: MotorType ) -> tuple[float, float, float, int, int]: """ Decode motor state from CAN data. Returns: (position_deg, velocity_deg_s, torque, temp_mos, temp_rotor) """ if len(data) < 8: raise ValueError("Invalid motor state data") # Extract encoded values q_uint = (data[1] << 8) | data[2] dq_uint = (data[3] << 4) | (data[4] >> 4) tau_uint = ((data[4] & 0x0F) << 8) | data[5] t_mos = data[6] t_rotor = data[7] # Get motor limits pmax, vmax, tmax = MOTOR_LIMIT_PARAMS[motor_type] # Decode to physical values position_rad = self._uint_to_float(q_uint, -pmax, pmax, 16) velocity_rad_per_sec = self._uint_to_float(dq_uint, -vmax, vmax, 12) torque = self._uint_to_float(tau_uint, -tmax, tmax, 12) return np.degrees(position_rad), np.degrees(velocity_rad_per_sec), torque, t_mos, t_rotor def _process_response(self, motor: str, msg: can.Message) -> None: """Decode a message and update the motor state cache.""" try: motor_type = self._motor_types[motor] pos, vel, torque, t_mos, t_rotor = self._decode_motor_state(msg.data, motor_type) self._last_known_states[motor] = { "position": pos, "velocity": vel, "torque": torque, "temp_mos": float(t_mos), "temp_rotor": float(t_rotor), } except Exception as e: logger.warning(f"Failed to decode response from {motor}: {e}") @check_if_not_connected def read(self, data_name: str, motor: str) -> Value: """Read a value from a single motor. Positions are always in degrees.""" # Refresh motor to get latest state msg = self._refresh_motor(motor) if msg is None: motor_id = self._get_motor_id(motor) recv_id = self._get_motor_recv_id(motor) raise ConnectionError( f"No response from motor '{motor}' (send ID: 0x{motor_id:02X}, recv ID: 0x{recv_id:02X}). " f"Check that: 1) Motor is powered (24V), 2) CAN wiring is correct, " f"3) Motor IDs are configured correctly using Damiao Debugging Tools" ) self._process_response(motor, msg) return self._get_cached_value(motor, data_name) def _get_cached_value(self, motor: str, data_name: str) -> Value: """Retrieve a specific value from the cache.""" state = self._last_known_states[motor] mapping: dict[str, Any] = { "Present_Position": state["position"], "Present_Velocity": state["velocity"], "Present_Torque": state["torque"], "Temperature_MOS": state["temp_mos"], "Temperature_Rotor": state["temp_rotor"], } if data_name not in mapping: raise ValueError(f"Unknown data_name: {data_name}") return mapping[data_name] @check_if_not_connected def write( self, data_name: str, motor: str, value: Value, ) -> None: """ Write a value to a single motor. Positions are always in degrees. Can write 'Goal_Position', 'Kp', or 'Kd'. """ if data_name in ("Kp", "Kd"): self._gains[motor][data_name.lower()] = float(value) elif data_name == "Goal_Position": kp = self._gains[motor]["kp"] kd = self._gains[motor]["kd"] self._mit_control(motor, kp, kd, float(value), 0.0, 0.0) else: raise ValueError(f"Writing {data_name} not supported in MIT mode") def sync_read( self, data_name: str, motors: str | list[str] | None = None, ) -> dict[str, Value]: """ Read the same value from multiple motors simultaneously. """ target_motors = self._get_motors_list(motors) self._batch_refresh(target_motors) result = {} for motor in target_motors: result[motor] = self._get_cached_value(motor, data_name) return result def sync_read_all_states( self, motors: str | list[str] | None = None, *, num_retry: int = 0, ) -> dict[str, MotorState]: """ Read ALL motor states (position, velocity, torque) from multiple motors in ONE refresh cycle. Returns: Dictionary mapping motor names to state dicts with keys: 'position', 'velocity', 'torque' Example: {'joint_1': {'position': 45.2, 'velocity': 1.3, 'torque': 0.5}, ...} """ target_motors = self._get_motors_list(motors) self._batch_refresh(target_motors) result = {} for motor in target_motors: result[motor] = self._last_known_states[motor].copy() return result def _batch_refresh(self, motors: list[str]) -> None: """Internal helper to refresh a list of motors and update cache.""" if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") # Send refresh commands for motor in motors: motor_id = self._get_motor_id(motor) data = [motor_id & 0xFF, (motor_id >> 8) & 0xFF, CAN_CMD_REFRESH, 0, 0, 0, 0, 0] msg = can.Message( arbitration_id=CAN_PARAM_ID, data=data, is_extended_id=False, is_fd=self.use_can_fd ) self.canbus.send(msg) # Collect responses expected_recv_ids = [self._get_motor_recv_id(m) for m in motors] responses = self._recv_all_responses(expected_recv_ids, timeout=MEDIUM_TIMEOUT_SEC) # Update cache for motor in motors: recv_id = self._get_motor_recv_id(motor) msg = responses.get(recv_id) if msg: self._process_response(motor, msg) else: logger.warning(f"Packet drop: {motor} (ID: 0x{recv_id:02X}). Using last known state.") @check_if_not_connected def sync_write(self, data_name: str, values: dict[str, Value]) -> None: """ Write values to multiple motors simultaneously. Positions are always in degrees. """ if data_name in ("Kp", "Kd"): key = data_name.lower() for motor, val in values.items(): self._gains[motor][key] = float(val) elif data_name == "Goal_Position": # Step 1: Send all MIT control commands recv_id_to_motor: dict[int, str] = {} if self.canbus is None: raise RuntimeError("CAN bus is not initialized.") for motor, value_degrees in values.items(): motor_id = self._get_motor_id(motor) motor_name = self._get_motor_name(motor) motor_type = self._motor_types[motor_name] kp = self._gains[motor]["kp"] kd = self._gains[motor]["kd"] data = self._encode_mit_packet(motor_type, kp, kd, float(value_degrees), 0.0, 0.0) msg = can.Message( arbitration_id=motor_id, data=data, is_extended_id=False, is_fd=self.use_can_fd ) self.canbus.send(msg) precise_sleep(PRECISE_TIMEOUT_SEC) recv_id_to_motor[self._get_motor_recv_id(motor)] = motor_name # Step 2: Collect responses and update state cache responses = self._recv_all_responses(list(recv_id_to_motor.keys()), timeout=MEDIUM_TIMEOUT_SEC) for recv_id, motor_name in recv_id_to_motor.items(): if msg := responses.get(recv_id): self._process_response(motor_name, msg) else: # Fall back to individual writes for motor, value in values.items(): self.write(data_name, motor, value) def read_calibration(self) -> dict[str, MotorCalibration]: """Read calibration data from motors.""" # Damiao motors don't store calibration internally # Return existing calibration or empty dict return self.calibration if self.calibration else {} def write_calibration(self, calibration_dict: dict[str, MotorCalibration], cache: bool = True) -> None: """Write calibration data to motors.""" # Damiao motors don't store calibration internally # Just cache it in memory if cache: self.calibration = calibration_dict def record_ranges_of_motion( self, motors: str | list[str] | None = None, display_values: bool = True, ) -> tuple[dict[str, Value], dict[str, Value]]: """ Interactively record the min/max values of each motor in degrees. Move the joints by hand (with torque disabled) while the method streams live positions. Press Enter to finish. """ target_motors = self._get_motors_list(motors) self.disable_torque(target_motors) time.sleep(LONG_TIMEOUT_SEC) start_positions = self.sync_read("Present_Position", target_motors) mins = start_positions.copy() maxes = start_positions.copy() print("\nMove joints through their full range of motion. Press ENTER when done.") user_pressed_enter = False while not user_pressed_enter: positions = self.sync_read("Present_Position", target_motors) for motor in target_motors: if motor in positions: mins[motor] = min(positions[motor], mins.get(motor, positions[motor])) maxes[motor] = max(positions[motor], maxes.get(motor, positions[motor])) if display_values: print("\n" + "=" * 50) print(f"{'MOTOR':<20} | {'MIN (deg)':>12} | {'POS (deg)':>12} | {'MAX (deg)':>12}") print("-" * 50) for motor in target_motors: if motor in positions: print( f"{motor:<20} | {mins[motor]:>12.1f} | {positions[motor]:>12.1f} | {maxes[motor]:>12.1f}" ) if enter_pressed(): user_pressed_enter = True if display_values and not user_pressed_enter: move_cursor_up(len(target_motors) + 4) time.sleep(LONG_TIMEOUT_SEC) self.enable_torque(target_motors) for motor in target_motors: if (motor in mins) and (motor in maxes) and (int(abs(maxes[motor] - mins[motor])) < 5): raise ValueError(f"Motor {motor} has insufficient range of motion (< 5 degrees)") return mins, maxes def _get_motors_list(self, motors: str | list[str] | None) -> list[str]: """Convert motor specification to list of motor names.""" if motors is None: return list(self.motors.keys()) elif isinstance(motors, str): return [motors] elif isinstance(motors, list): return motors else: raise TypeError(f"Invalid motors type: {type(motors)}") def _get_motor_id(self, motor: NameOrID) -> int: """Get CAN ID for a motor.""" if isinstance(motor, str): if motor in self.motors: return self.motors[motor].id else: raise ValueError(f"Unknown motor: {motor}") else: return motor def _get_motor_name(self, motor: NameOrID) -> str: """Get motor name from name or ID.""" if isinstance(motor, str): return motor else: for name, m in self.motors.items(): if m.id == motor: return name raise ValueError(f"Unknown motor ID: {motor}") def _get_motor_recv_id(self, motor: NameOrID) -> int: """Get motor recv_id from name or ID.""" motor_name = self._get_motor_name(motor) motor_obj = self.motors.get(motor_name) if motor_obj and motor_obj.recv_id is not None: return motor_obj.recv_id else: raise ValueError(f"Motor {motor_obj} doesn't have a valid recv_id (None).") @cached_property def is_calibrated(self) -> bool: """Check if motors are calibrated.""" return bool(self.calibration)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/motors/damiao/damiao.py", "license": "Apache License 2.0", "lines": 721, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/motors/damiao/tables.py
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Configuration tables for Damiao motors.""" from enum import IntEnum # Motor type definitions class MotorType(IntEnum): DM3507 = 0 DM4310 = 1 DM4310_48V = 2 DM4340 = 3 DM4340_48V = 4 DM6006 = 5 DM8006 = 6 DM8009 = 7 DM10010L = 8 DM10010 = 9 DMH3510 = 10 DMH6215 = 11 DMG6220 = 12 # Control modes class ControlMode(IntEnum): MIT = 1 POS_VEL = 2 VEL = 3 TORQUE_POS = 4 # Motor variable IDs (RID) class MotorVariable(IntEnum): UV_VALUE = 0 KT_VALUE = 1 OT_VALUE = 2 OC_VALUE = 3 ACC = 4 DEC = 5 MAX_SPD = 6 MST_ID = 7 ESC_ID = 8 TIMEOUT = 9 CTRL_MODE = 10 DAMP = 11 INERTIA = 12 HW_VER = 13 SW_VER = 14 SN = 15 NPP = 16 RS = 17 LS = 18 FLUX = 19 GR = 20 PMAX = 21 VMAX = 22 TMAX = 23 I_BW = 24 KP_ASR = 25 KI_ASR = 26 KP_APR = 27 KI_APR = 28 OV_VALUE = 29 GREF = 30 DETA = 31 V_BW = 32 IQ_C1 = 33 VL_C1 = 34 CAN_BR = 35 SUB_VER = 36 U_OFF = 50 V_OFF = 51 K1 = 52 K2 = 53 M_OFF = 54 DIR = 55 P_M = 80 XOUT = 81 # Motor limit parameters [PMAX, VMAX, TMAX] # PMAX: Maximum position (rad) # VMAX: Maximum velocity (rad/s) # TMAX: Maximum torque (N·m) MOTOR_LIMIT_PARAMS = { MotorType.DM3507: (12.5, 30, 10), MotorType.DM4310: (12.5, 30, 10), MotorType.DM4310_48V: (12.5, 50, 10), MotorType.DM4340: (12.5, 8, 28), MotorType.DM4340_48V: (12.5, 10, 28), MotorType.DM6006: (12.5, 45, 20), MotorType.DM8006: (12.5, 45, 40), MotorType.DM8009: (12.5, 45, 54), MotorType.DM10010L: (12.5, 25, 200), MotorType.DM10010: (12.5, 20, 200), MotorType.DMH3510: (12.5, 280, 1), MotorType.DMH6215: (12.5, 45, 10), MotorType.DMG6220: (12.5, 45, 10), } # Motor model names MODEL_NAMES = { MotorType.DM3507: "dm3507", MotorType.DM4310: "dm4310", MotorType.DM4310_48V: "dm4310_48v", MotorType.DM4340: "dm4340", MotorType.DM4340_48V: "dm4340_48v", MotorType.DM6006: "dm6006", MotorType.DM8006: "dm8006", MotorType.DM8009: "dm8009", MotorType.DM10010L: "dm10010l", MotorType.DM10010: "dm10010", MotorType.DMH3510: "dmh3510", MotorType.DMH6215: "dmh6215", MotorType.DMG6220: "dmg6220", } # Motor resolution table (encoder counts per revolution) MODEL_RESOLUTION = { "dm3507": 65536, "dm4310": 65536, "dm4310_48v": 65536, "dm4340": 65536, "dm4340_48v": 65536, "dm6006": 65536, "dm8006": 65536, "dm8009": 65536, "dm10010l": 65536, "dm10010": 65536, "dmh3510": 65536, "dmh6215": 65536, "dmg6220": 65536, } # CAN baudrates supported by Damiao motors AVAILABLE_BAUDRATES = [ 125000, # 0: 125 kbps 200000, # 1: 200 kbps 250000, # 2: 250 kbps 500000, # 3: 500 kbps 1000000, # 4: 1 mbps (default for OpenArms) 2000000, # 5: 2 mbps 2500000, # 6: 2.5 mbps 3200000, # 7: 3.2 mbps 4000000, # 8: 4 mbps 5000000, # 9: 5 mbps ] DEFAULT_BAUDRATE = 1000000 # 1 Mbps is standard for OpenArms # Default timeout in milliseconds DEFAULT_TIMEOUT_MS = 1000 # OpenArms specific configurations # Based on: https://docs.openarm.dev/software/setup/configure-test # OpenArms has 7 DOF per arm (14 total for dual arm) OPENARMS_ARM_MOTOR_IDS = { "joint_1": {"send": 0x01, "recv": 0x11}, # J1 - Shoulder pan "joint_2": {"send": 0x02, "recv": 0x12}, # J2 - Shoulder lift "joint_3": {"send": 0x03, "recv": 0x13}, # J3 - Elbow flex "joint_4": {"send": 0x04, "recv": 0x14}, # J4 - Wrist flex "joint_5": {"send": 0x05, "recv": 0x15}, # J5 - Wrist roll "joint_6": {"send": 0x06, "recv": 0x16}, # J6 - Wrist pitch "joint_7": {"send": 0x07, "recv": 0x17}, # J7 - Wrist rotation } OPENARMS_GRIPPER_MOTOR_IDS = { "gripper": {"send": 0x08, "recv": 0x18}, # J8 - Gripper } # Default motor types for OpenArms OPENARMS_DEFAULT_MOTOR_TYPES = { "joint_1": MotorType.DM8009, # Shoulder pan - high torque "joint_2": MotorType.DM8009, # Shoulder lift - high torque "joint_3": MotorType.DM4340, # Shoulder rotation "joint_4": MotorType.DM4340, # Elbow flex "joint_5": MotorType.DM4310, # Wrist roll "joint_6": MotorType.DM4310, # Wrist pitch "joint_7": MotorType.DM4310, # Wrist rotation "gripper": MotorType.DM4310, # Gripper } # MIT control parameter ranges MIT_KP_RANGE = (0.0, 500.0) MIT_KD_RANGE = (0.0, 5.0) # CAN frame command IDs CAN_CMD_ENABLE = 0xFC CAN_CMD_DISABLE = 0xFD CAN_CMD_SET_ZERO = 0xFE CAN_CMD_REFRESH = 0xCC CAN_CMD_QUERY_PARAM = 0x33 CAN_CMD_WRITE_PARAM = 0x55 CAN_CMD_SAVE_PARAM = 0xAA # CAN ID for parameter operations CAN_PARAM_ID = 0x7FF
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/motors/damiao/tables.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/scripts/lerobot_setup_can.py
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ Setup and debug CAN interfaces for Damiao motors (e.g., OpenArms). Examples: Setup CAN interfaces with CAN FD: ```shell lerobot-setup-can --mode=setup --interfaces=can0,can1,can2,can3 ``` Test motors on a single interface: ```shell lerobot-setup-can --mode=test --interfaces=can0 ``` Test motors on all interfaces: ```shell lerobot-setup-can --mode=test --interfaces=can0,can1,can2,can3 ``` Speed test: ```shell lerobot-setup-can --mode=speed --interfaces=can0 ``` """ import subprocess import sys import time from dataclasses import dataclass, field import draccus from lerobot.utils.import_utils import _can_available MOTOR_NAMES = { 0x01: "joint_1", 0x02: "joint_2", 0x03: "joint_3", 0x04: "joint_4", 0x05: "joint_5", 0x06: "joint_6", 0x07: "joint_7", 0x08: "gripper", } @dataclass class CANSetupConfig: mode: str = "test" interfaces: str = "can0" # Comma-separated, e.g. "can0,can1,can2,can3" bitrate: int = 1000000 data_bitrate: int = 5000000 use_fd: bool = True motor_ids: list[int] = field(default_factory=lambda: list(range(0x01, 0x09))) timeout: float = 1.0 speed_iterations: int = 100 def get_interfaces(self) -> list[str]: return [i.strip() for i in self.interfaces.split(",") if i.strip()] def check_interface_status(interface: str) -> tuple[bool, str, bool]: """Check if CAN interface is UP and configured.""" try: result = subprocess.run(["ip", "link", "show", interface], capture_output=True, text=True) # nosec B607 if result.returncode != 0: return False, "Interface not found", False output = result.stdout is_up = "UP" in output is_fd = "fd on" in output.lower() or "canfd" in output.lower() status = "UP" if is_up else "DOWN" if is_fd: status += " (CAN FD)" return is_up, status, is_fd except FileNotFoundError: return False, "ip command not found", False def setup_interface(interface: str, bitrate: int, data_bitrate: int, use_fd: bool) -> bool: """Configure a CAN interface.""" try: subprocess.run(["sudo", "ip", "link", "set", interface, "down"], check=False, capture_output=True) # nosec B607 cmd = ["sudo", "ip", "link", "set", interface, "type", "can", "bitrate", str(bitrate)] if use_fd: cmd.extend(["dbitrate", str(data_bitrate), "fd", "on"]) result = subprocess.run(cmd, capture_output=True, text=True) # nosec B607 if result.returncode != 0: print(f" ✗ Failed to configure: {result.stderr}") return False result = subprocess.run( # nosec B607 ["sudo", "ip", "link", "set", interface, "up"], capture_output=True, text=True ) if result.returncode != 0: print(f" ✗ Failed to bring up: {result.stderr}") return False return True except Exception as e: print(f" ✗ Error: {e}") return False def test_motor(bus, motor_id: int, timeout: float, use_fd: bool): """Test a single motor and return responses.""" import can enable_msg = can.Message( arbitration_id=motor_id, data=[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC], is_extended_id=False, is_fd=use_fd, ) try: bus.send(enable_msg) except Exception as e: return None, f"Send error: {e}" responses = [] start_time = time.time() while time.time() - start_time < timeout: msg = bus.recv(timeout=0.1) if msg: responses.append((msg.arbitration_id, msg.data.hex(), getattr(msg, "is_fd", False))) disable_msg = can.Message( arbitration_id=motor_id, data=[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD], is_extended_id=False, is_fd=use_fd, ) try: bus.send(disable_msg) bus.recv(timeout=0.1) # Clear any pending responses except Exception: print(f"Error sending message to motor 0x{motor_id:02X}") return responses, None def test_interface(cfg: CANSetupConfig, interface: str): """Test all motors on a CAN interface.""" import can is_up, status, _ = check_interface_status(interface) print(f"\n{interface}: {status}") if not is_up: print(f" ⚠ Interface is not UP. Run: lerobot-setup-can --mode=setup --interfaces {interface}") return {} try: kwargs = {"channel": interface, "interface": "socketcan", "bitrate": cfg.bitrate} if cfg.use_fd: kwargs.update({"data_bitrate": cfg.data_bitrate, "fd": True}) bus = can.interface.Bus(**kwargs) except Exception as e: print(f" ✗ Connection failed: {e}") return {} results = {} try: while bus.recv(timeout=0.01): pass for motor_id in cfg.motor_ids: motor_name = MOTOR_NAMES.get(motor_id, f"motor_0x{motor_id:02X}") responses, error = test_motor(bus, motor_id, cfg.timeout, cfg.use_fd) if error: print(f" Motor 0x{motor_id:02X} ({motor_name}): ✗ {error}") results[motor_id] = {"found": False, "error": error} elif responses: print(f" Motor 0x{motor_id:02X} ({motor_name}): ✓ FOUND") for resp_id, data, is_fd in responses: fd_flag = " [FD]" if is_fd else "" print(f" → Response 0x{resp_id:02X}{fd_flag}: {data}") results[motor_id] = {"found": True, "responses": responses} else: print(f" Motor 0x{motor_id:02X} ({motor_name}): ✗ No response") results[motor_id] = {"found": False} time.sleep(0.05) finally: bus.shutdown() found = sum(1 for r in results.values() if r.get("found")) print(f"\n Summary: {found}/{len(cfg.motor_ids)} motors found") return results def speed_test(cfg: CANSetupConfig, interface: str): """Test communication speed with motors.""" import can is_up, status, _ = check_interface_status(interface) if not is_up: print(f"{interface}: {status} - skipping") return print(f"\n{interface}: Running speed test ({cfg.speed_iterations} iterations)...") try: kwargs = {"channel": interface, "interface": "socketcan", "bitrate": cfg.bitrate} if cfg.use_fd: kwargs.update({"data_bitrate": cfg.data_bitrate, "fd": True}) bus = can.interface.Bus(**kwargs) except Exception as e: print(f" ✗ Connection failed: {e}") return responding_motor = None for motor_id in cfg.motor_ids: responses, _ = test_motor(bus, motor_id, 0.5, cfg.use_fd) if responses: responding_motor = motor_id break if not responding_motor: print(" ✗ No responding motors found") bus.shutdown() return print(f" Testing with motor 0x{responding_motor:02X}...") latencies = [] for _ in range(cfg.speed_iterations): start = time.perf_counter() msg = can.Message( arbitration_id=responding_motor, data=[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC], is_extended_id=False, is_fd=cfg.use_fd, ) bus.send(msg) resp = bus.recv(timeout=0.1) if resp: latencies.append((time.perf_counter() - start) * 1000) bus.shutdown() if latencies: avg_latency = sum(latencies) / len(latencies) hz = 1000.0 / avg_latency if avg_latency > 0 else 0 print(f" ✓ Success rate: {len(latencies)}/{cfg.speed_iterations}") print(f" ✓ Avg latency: {avg_latency:.2f} ms") print(f" ✓ Max frequency: {hz:.1f} Hz") else: print(" ✗ No successful responses") def run_setup(cfg: CANSetupConfig): """Setup CAN interfaces.""" print("=" * 50) print("CAN Interface Setup") print("=" * 50) print(f"Mode: {'CAN FD' if cfg.use_fd else 'CAN 2.0'}") print(f"Bitrate: {cfg.bitrate / 1_000_000:.1f} Mbps") if cfg.use_fd: print(f"Data bitrate: {cfg.data_bitrate / 1_000_000:.1f} Mbps") print() interfaces = cfg.get_interfaces() for interface in interfaces: print(f"Configuring {interface}...") if setup_interface(interface, cfg.bitrate, cfg.data_bitrate, cfg.use_fd): is_up, status, _ = check_interface_status(interface) print(f" ✓ {interface}: {status}") else: print(f" ✗ {interface}: Failed") print("\nSetup complete!") print("\nNext: Test motors with:") print(f" lerobot-setup-can --mode=test --interfaces {','.join(interfaces)}") def run_test(cfg: CANSetupConfig): """Test motors on CAN interfaces.""" print("=" * 50) print("CAN Motor Test") print("=" * 50) print(f"Testing motors 0x{min(cfg.motor_ids):02X}-0x{max(cfg.motor_ids):02X}") print(f"Mode: {'CAN FD' if cfg.use_fd else 'CAN 2.0'}") print() interfaces = cfg.get_interfaces() all_results = {} for interface in interfaces: all_results[interface] = test_interface(cfg, interface) total_found = sum(sum(1 for r in res.values() if r.get("found")) for res in all_results.values()) print("\n" + "=" * 50) print("Summary") print("=" * 50) print(f"Total motors found: {total_found}") if total_found == 0: print("\n⚠ No motors found! Check:") print(" 1. Motors are powered (24V)") print(" 2. CAN wiring (CANH, CANL, GND)") print(" 3. Motor timeout parameter > 0 (use Damiao tools)") print(" 4. 120Ω termination at both cable ends") print(f" 5. Interface configured: lerobot-setup-can --mode=setup --interfaces {interfaces[0]}") def run_speed(cfg: CANSetupConfig): """Run speed tests on CAN interfaces.""" print("=" * 50) print("CAN Speed Test") print("=" * 50) for interface in cfg.get_interfaces(): speed_test(cfg, interface) @draccus.wrap() def setup_can(cfg: CANSetupConfig): if not _can_available: print("Error: python-can not installed. Install with: pip install python-can") sys.exit(1) if cfg.mode == "setup": run_setup(cfg) elif cfg.mode == "test": run_test(cfg) elif cfg.mode == "speed": run_speed(cfg) else: print(f"Unknown mode: {cfg.mode}") print("Available modes: setup, test, speed") sys.exit(1) def main(): setup_can() if __name__ == "__main__": main()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/scripts/lerobot_setup_can.py", "license": "Apache License 2.0", "lines": 289, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/motors/test_damiao.py
"""Minimal test script for Damiao motor with ID 3.""" import pytest from lerobot.utils.import_utils import _can_available if not _can_available: pytest.skip("python-can not available", allow_module_level=True) from lerobot.motors import Motor from lerobot.motors.damiao import DamiaoMotorsBus @pytest.mark.skip(reason="Requires physical Damiao motor and CAN interface") def test_damiao_motor(): motors = { "joint_3": Motor( id=0x03, model="damiao", norm_mode="degrees", motor_type_str="dm4310", recv_id=0x13, ), } bus = DamiaoMotorsBus(port="can0", motors=motors) try: print("Connecting...") bus.connect() print("✓ Connected") print("Enabling torque...") bus.enable_torque() print("✓ Torque enabled") print("Reading all states...") states = bus.sync_read_all_states() print(f"✓ States: {states}") print("Reading position...") positions = bus.sync_read("Present_Position") print(f"✓ Position: {positions}") print("Testing MIT control batch...") current_pos = states["joint_3"]["position"] commands = {"joint_3": (10.0, 0.5, current_pos, 0.0, 0.0)} bus._mit_control_batch(commands) print("✓ MIT control batch sent") print("Disabling torque...") bus.disable_torque() print("✓ Torque disabled") print("Setting zero position...") bus.set_zero_position() print("✓ Zero position set") finally: print("Disconnecting...") bus.disconnect(disable_torque=True) print("✓ Disconnected") if __name__ == "__main__": test_damiao_motor()
{ "repo_id": "huggingface/lerobot", "file_path": "tests/motors/test_damiao.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:src/lerobot/utils/decorators.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 functools import wraps from lerobot.utils.errors import DeviceAlreadyConnectedError, DeviceNotConnectedError def check_if_not_connected(func): @wraps(func) def wrapper(self, *args, **kwargs): if not self.is_connected: raise DeviceNotConnectedError( f"{self.__class__.__name__} is not connected. Run `.connect()` first." ) return func(self, *args, **kwargs) return wrapper def check_if_already_connected(func): @wraps(func) def wrapper(self, *args, **kwargs): if self.is_connected: raise DeviceAlreadyConnectedError(f"{self.__class__.__name__} is already connected.") return func(self, *args, **kwargs) return wrapper
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/utils/decorators.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/cameras/zmq/camera_zmq.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ ZMQCamera - Captures frames from remote cameras via ZeroMQ using JSON protocol in the following format: { "timestamps": {"camera_name": float}, "images": {"camera_name": "<base64-jpeg>"} } """ import base64 import json import logging import time from threading import Event, Lock, Thread from typing import Any import cv2 import numpy as np from numpy.typing import NDArray from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from lerobot.utils.errors import DeviceNotConnectedError from ..camera import Camera from ..configs import ColorMode from .configuration_zmq import ZMQCameraConfig logger = logging.getLogger(__name__) class ZMQCamera(Camera): """ Manages camera interactions via ZeroMQ for receiving frames from a remote server. This class connects to a ZMQ Publisher, subscribes to frame topics, and decodes incoming JSON messages containing Base64 encoded images. It supports both synchronous and asynchronous frame reading patterns. Example usage: ```python from lerobot.cameras.zmq import ZMQCamera, ZMQCameraConfig config = ZMQCameraConfig(server_address="192.168.123.164", port=5555, camera_name="head_camera") camera = ZMQCamera(config) camera.connect() # Read 1 frame synchronously (blocking) color_image = camera.read() # Read 1 frame asynchronously (waits for new frame with a timeout) async_image = camera.async_read() # Get the latest frame immediately (no wait, returns timestamp) latest_image, timestamp = camera.read_latest() camera.disconnect() ``` """ def __init__(self, config: ZMQCameraConfig): super().__init__(config) import zmq self.config = config self.server_address = config.server_address self.port = config.port self.camera_name = config.camera_name self.color_mode = config.color_mode self.timeout_ms = config.timeout_ms # ZMQ Context and Socket self.context: zmq.Context | None = None self.socket: zmq.Socket | None = None self._connected = False # Threading resources self.thread: Thread | None = None self.stop_event: Event | None = None self.frame_lock: Lock = Lock() self.latest_frame: NDArray[Any] | None = None self.latest_timestamp: float | None = None self.new_frame_event: Event = Event() def __str__(self) -> str: return f"ZMQCamera({self.camera_name}@{self.server_address}:{self.port})" @property def is_connected(self) -> bool: """Checks if the ZMQ socket is initialized and connected.""" return self._connected and self.context is not None and self.socket is not None @check_if_already_connected def connect(self, warmup: bool = True) -> None: """Connect to ZMQ camera server. Args: warmup (bool): If True, waits for the camera to provide at least one valid frame before returning. Defaults to True. """ logger.info(f"Connecting to {self}...") try: import zmq self.context = zmq.Context() self.socket = self.context.socket(zmq.SUB) self.socket.setsockopt_string(zmq.SUBSCRIBE, "") self.socket.setsockopt(zmq.RCVTIMEO, self.timeout_ms) self.socket.setsockopt(zmq.CONFLATE, True) self.socket.connect(f"tcp://{self.server_address}:{self.port}") self._connected = True # Auto-detect resolution if not provided if self.width is None or self.height is None: # Read directly from hardware because the thread isn't running yet temp_frame = self._read_from_hardware() h, w = temp_frame.shape[:2] self.height = h self.width = w logger.info(f"{self} resolution detected: {w}x{h}") self._start_read_thread() logger.info(f"{self} connected.") if warmup: # Ensure we have captured at least one frame via the thread start_time = time.time() while time.time() - start_time < (self.config.warmup_s): # Wait a bit more than timeout self.async_read(timeout_ms=self.config.warmup_s * 1000) time.sleep(0.1) with self.frame_lock: if self.latest_frame is None: raise ConnectionError(f"{self} failed to capture frames during warmup.") except Exception as e: self._cleanup() raise RuntimeError(f"Failed to connect to {self}: {e}") from e def _cleanup(self): """Clean up ZMQ resources.""" self._connected = False if self.socket: self.socket.close() self.socket = None if self.context: self.context.term() self.context = None @staticmethod def find_cameras() -> list[dict[str, Any]]: """ Detection not implemented for ZMQ cameras. These cameras require manual configuration (server address/port). """ raise NotImplementedError("Camera detection is not implemented for ZMQ cameras.") def _read_from_hardware(self) -> NDArray[Any]: """ Reads a single frame directly from the ZMQ socket. """ if not self.is_connected or self.socket is None: raise DeviceNotConnectedError(f"{self} is not connected.") try: message = self.socket.recv_string() except Exception as e: # Check for ZMQ timeout (EAGAIN/Again) without requiring global zmq import if type(e).__name__ == "Again": raise TimeoutError(f"{self} timeout after {self.timeout_ms}ms") from e raise # Decode JSON message data = json.loads(message) if "images" not in data: raise RuntimeError(f"{self} invalid message: missing 'images' key") images = data["images"] # Get image by camera name or first available if self.camera_name in images: img_b64 = images[self.camera_name] elif images: img_b64 = next(iter(images.values())) else: raise RuntimeError(f"{self} no images in message") # Decode base64 JPEG img_bytes = base64.b64decode(img_b64) frame = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR) if frame is None: raise RuntimeError(f"{self} failed to decode image") return frame @check_if_not_connected def read(self, color_mode: ColorMode | None = None) -> NDArray[Any]: """ Reads a single frame synchronously from the camera. This is a blocking call. It waits for the next available frame from the camera background thread. Returns: np.ndarray: Decoded frame (height, width, 3) """ start_time = time.perf_counter() if color_mode is not None: logger.warning( f"{self} read() color_mode parameter is deprecated and will be removed in future versions." ) if self.thread is None or not self.thread.is_alive(): raise RuntimeError(f"{self} read thread is not running.") self.new_frame_event.clear() frame = self.async_read(timeout_ms=10000) read_duration_ms = (time.perf_counter() - start_time) * 1e3 logger.debug(f"{self} read took: {read_duration_ms:.1f}ms") return frame def _read_loop(self) -> None: """ Internal loop run by the background thread for asynchronous reading. """ if self.stop_event is None: raise RuntimeError(f"{self}: stop_event is not initialized.") failure_count = 0 while not self.stop_event.is_set(): try: frame = self._read_from_hardware() capture_time = time.perf_counter() with self.frame_lock: self.latest_frame = frame self.latest_timestamp = capture_time self.new_frame_event.set() failure_count = 0 except DeviceNotConnectedError: break except (TimeoutError, Exception) as e: if failure_count <= 10: failure_count += 1 logger.warning(f"Read error: {e}") else: raise RuntimeError(f"{self} exceeded maximum consecutive read failures.") from e def _start_read_thread(self) -> None: if self.stop_event is not None: self.stop_event.set() if self.thread is not None and self.thread.is_alive(): self.thread.join(timeout=2.0) with self.frame_lock: self.latest_frame = None self.latest_timestamp = None self.new_frame_event.clear() self.stop_event = Event() self.thread = Thread(target=self._read_loop, daemon=True, name=f"{self}_read_loop") self.thread.start() time.sleep(0.1) def _stop_read_thread(self) -> None: if self.stop_event is not None: self.stop_event.set() if self.thread is not None and self.thread.is_alive(): self.thread.join(timeout=2.0) self.thread = None self.stop_event = None with self.frame_lock: self.latest_frame = None self.latest_timestamp = None self.new_frame_event.clear() @check_if_not_connected def async_read(self, timeout_ms: float = 200) -> NDArray[Any]: """ Reads the latest available frame asynchronously. Args: timeout_ms (float): Maximum time in milliseconds to wait for a frame to become available. Defaults to 200ms. Returns: np.ndarray: The latest captured frame. Raises: DeviceNotConnectedError: If the camera is not connected. TimeoutError: If no frame data becomes available within the specified timeout. RuntimeError: If the background thread is not running. """ if self.thread is None or not self.thread.is_alive(): raise RuntimeError(f"{self} read thread is not running.") if not self.new_frame_event.wait(timeout=timeout_ms / 1000.0): raise TimeoutError(f"{self} async_read timeout after {timeout_ms}ms") with self.frame_lock: frame = self.latest_frame self.new_frame_event.clear() if frame is None: raise RuntimeError(f"{self} no frame available") return frame @check_if_not_connected def read_latest(self, max_age_ms: int = 1000) -> NDArray[Any]: """Return the most recent frame captured immediately (Peeking). This method is non-blocking and returns whatever is currently in the memory buffer. The frame may be stale, meaning it could have been captured a while ago (hanging camera scenario e.g.). Returns: NDArray[Any]: The frame image (numpy array). Raises: TimeoutError: If the latest frame is older than `max_age_ms`. DeviceNotConnectedError: If the camera is not connected. RuntimeError: If the camera is connected but has not captured any frames yet. """ if self.thread is None or not self.thread.is_alive(): raise RuntimeError(f"{self} read thread is not running.") with self.frame_lock: frame = self.latest_frame timestamp = self.latest_timestamp if frame is None or timestamp is None: raise RuntimeError(f"{self} has not captured any frames yet.") age_ms = (time.perf_counter() - timestamp) * 1e3 if age_ms > max_age_ms: raise TimeoutError( f"{self} latest frame is too old: {age_ms:.1f} ms (max allowed: {max_age_ms} ms)." ) return frame def disconnect(self) -> None: """Disconnect from ZMQ camera.""" if not self.is_connected and self.thread is None: raise DeviceNotConnectedError(f"{self} not connected.") if self.thread is not None: self._stop_read_thread() self._cleanup() with self.frame_lock: self.latest_frame = None self.latest_timestamp = None self.new_frame_event.clear() logger.info(f"{self} disconnected.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/cameras/zmq/camera_zmq.py", "license": "Apache License 2.0", "lines": 300, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/cameras/zmq/configuration_zmq.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass from ..configs import CameraConfig, ColorMode __all__ = ["ZMQCameraConfig", "ColorMode"] @CameraConfig.register_subclass("zmq") @dataclass class ZMQCameraConfig(CameraConfig): server_address: str port: int = 5555 camera_name: str = "zmq_camera" color_mode: ColorMode = ColorMode.RGB timeout_ms: int = 5000 warmup_s: int = 1 def __post_init__(self) -> None: self.color_mode = ColorMode(self.color_mode) if self.timeout_ms <= 0: raise ValueError(f"`timeout_ms` must be positive, but {self.timeout_ms} is provided.") if not self.server_address: raise ValueError("`server_address` cannot be empty.") if self.port <= 0 or self.port > 65535: raise ValueError(f"`port` must be between 1 and 65535, but {self.port} is provided.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/cameras/zmq/configuration_zmq.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/cameras/zmq/image_server.py
#!/usr/bin/env python # Copyright 2026 The HuggingFace Inc. team. All rights reserved. # # 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. """ Streams camera images over ZMQ. Uses lerobot's OpenCVCamera for capture, encodes images to base64 and sends them over ZMQ. """ import base64 import contextlib import json import logging import time from collections import deque import cv2 import numpy as np import zmq from lerobot.cameras.configs import ColorMode from lerobot.cameras.opencv import OpenCVCamera, OpenCVCameraConfig logger = logging.getLogger(__name__) def encode_image(image: np.ndarray, quality: int = 80) -> str: """Encode RGB image to base64 JPEG string.""" _, buffer = cv2.imencode(".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) return base64.b64encode(buffer).decode("utf-8") class ImageServer: def __init__(self, config: dict, port: int = 5555): self.fps = config.get("fps", 30) self.cameras: dict[str, OpenCVCamera] = {} for name, cfg in config.get("cameras", {}).items(): shape = cfg.get("shape", [480, 640]) cam_config = OpenCVCameraConfig( index_or_path=cfg.get("device_id", 0), fps=self.fps, width=shape[1], height=shape[0], color_mode=ColorMode.RGB, ) camera = OpenCVCamera(cam_config) camera.connect() self.cameras[name] = camera logger.info(f"Camera {name}: {shape[1]}x{shape[0]}") # ZMQ PUB socket self.context = zmq.Context() self.socket = self.context.socket(zmq.PUB) self.socket.setsockopt(zmq.SNDHWM, 20) self.socket.setsockopt(zmq.LINGER, 0) self.socket.bind(f"tcp://*:{port}") logger.info(f"ImageServer running on port {port}") def run(self): frame_count = 0 frame_times = deque(maxlen=60) try: while True: t0 = time.time() # Build message message = {"timestamps": {}, "images": {}} for name, cam in self.cameras.items(): frame = cam.read() # Returns RGB message["timestamps"][name] = time.time() message["images"][name] = encode_image(frame) # Send as JSON string (suppress if buffer full) with contextlib.suppress(zmq.Again): self.socket.send_string(json.dumps(message), zmq.NOBLOCK) frame_count += 1 frame_times.append(time.time() - t0) if frame_count % 60 == 0: logger.debug(f"FPS: {len(frame_times) / sum(frame_times):.1f}") sleep = (1.0 / self.fps) - (time.time() - t0) if sleep > 0: time.sleep(sleep) except KeyboardInterrupt: pass finally: for cam in self.cameras.values(): cam.disconnect() self.socket.close() self.context.term() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) config = {"fps": 30, "cameras": {"head_camera": {"device_id": 4, "shape": [480, 640]}}} ImageServer(config, port=5555).run()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/cameras/zmq/image_server.py", "license": "Apache License 2.0", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/pi0_fast/configuration_pi0_fast.py
#!/usr/bin/env python # Copyright 2025 Physical Intelligence and The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from lerobot.configs.policies import PreTrainedConfig from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature from lerobot.optim.optimizers import AdamWConfig from lerobot.optim.schedulers import CosineDecayWithWarmupSchedulerConfig from lerobot.policies.rtc.configuration_rtc import RTCConfig from lerobot.utils.constants import ACTION, OBS_IMAGES, OBS_STATE DEFAULT_IMAGE_SIZE = 224 @PreTrainedConfig.register_subclass("pi0_fast") @dataclass class PI0FastConfig(PreTrainedConfig): paligemma_variant: str = "gemma_2b" action_expert_variant: str = "gemma_300m" dtype: str = "float32" # Options: "bfloat16", "float32" chunk_size: int = 50 # Number of action steps to predict, in openpi called "action_horizon" n_action_steps: int = 50 # Number of action steps to execute # Shorter state and action vectors will be padded to these dimensions max_state_dim: int = 32 max_action_dim: int = 32 max_action_tokens: int = 256 # Real-Time Chunking (RTC) configuration rtc_config: RTCConfig | None = None image_resolution: tuple[int, int] = ( DEFAULT_IMAGE_SIZE, DEFAULT_IMAGE_SIZE, ) # see openpi `preprocessing_pytorch.py` # Add empty images. Used to add empty cameras when no image features are present. empty_cameras: int = 0 tokenizer_max_length: int = 200 # see openpi `__post_init__` text_tokenizer_name: str = "google/paligemma-3b-pt-224" action_tokenizer_name: str = "lerobot/fast-action-tokenizer" temperature: float = 0.0 max_decoding_steps: int = 256 fast_skip_tokens: int = 128 # Whether to validate that decoded action tokens start with "Action: " prefix validate_action_token_prefix: bool = True # Whether to use KV cache for faster autoregressive decoding use_kv_cache: bool = True normalization_mapping: dict[str, NormalizationMode] = field( default_factory=lambda: { "VISUAL": NormalizationMode.IDENTITY, "STATE": NormalizationMode.MEAN_STD, # Pi0Fast uses quantiles for state "ACTION": NormalizationMode.MEAN_STD, # Pi0Fast uses quantiles for action } ) # Training settings gradient_checkpointing: bool = False # Enable gradient checkpointing for memory optimization compile_model: bool = False # Whether to use torch.compile for model optimization compile_mode: str = "max-autotune" # Torch compile mode device: str | None = None # Device to use for the model (None = auto-detect) # Optimizer settings: see openpi `AdamW` optimizer_lr: float = 2.5e-5 # see openpi `CosineDecaySchedule: peak_lr` optimizer_betas: tuple[float, float] = (0.9, 0.95) optimizer_eps: float = 1e-8 optimizer_weight_decay: float = 0.01 optimizer_grad_clip_norm: float = 1.0 # Scheduler settings: see openpi `CosineDecaySchedule` # Note: These will auto-scale if --steps < scheduler_decay_steps # For example, --steps=3000 will scale warmup to 100 and decay to 3000 scheduler_warmup_steps: int = 1_000 scheduler_decay_steps: int = 30_000 scheduler_decay_lr: float = 2.5e-6 def __post_init__(self): super().__post_init__() # Validate configuration if self.n_action_steps > self.chunk_size: raise ValueError( f"n_action_steps ({self.n_action_steps}) cannot be greater than chunk_size ({self.chunk_size})" ) if self.paligemma_variant not in ["gemma_300m", "gemma_2b"]: raise ValueError(f"Invalid paligemma_variant: {self.paligemma_variant}") if self.dtype not in ["bfloat16", "float32"]: raise ValueError(f"Invalid dtype: {self.dtype}") def validate_features(self) -> None: """Validate and set up input/output features.""" for i in range(self.empty_cameras): key = OBS_IMAGES + f".empty_camera_{i}" empty_camera = PolicyFeature( type=FeatureType.VISUAL, shape=(3, *self.image_resolution), # Use configured image resolution ) self.input_features[key] = empty_camera if OBS_STATE not in self.input_features: state_feature = PolicyFeature( type=FeatureType.STATE, shape=(self.max_state_dim,), # Padded to max_state_dim ) self.input_features[OBS_STATE] = state_feature if ACTION not in self.output_features: action_feature = PolicyFeature( type=FeatureType.ACTION, shape=(self.max_action_dim,), # Padded to max_action_dim ) self.output_features[ACTION] = action_feature def get_optimizer_preset(self) -> AdamWConfig: return AdamWConfig( lr=self.optimizer_lr, betas=self.optimizer_betas, eps=self.optimizer_eps, weight_decay=self.optimizer_weight_decay, grad_clip_norm=self.optimizer_grad_clip_norm, ) def get_scheduler_preset(self): return CosineDecayWithWarmupSchedulerConfig( peak_lr=self.optimizer_lr, decay_lr=self.scheduler_decay_lr, num_warmup_steps=self.scheduler_warmup_steps, num_decay_steps=self.scheduler_decay_steps, ) @property def observation_delta_indices(self) -> None: return None @property def action_delta_indices(self) -> list: return list(range(self.chunk_size)) @property def reward_delta_indices(self) -> None: return None
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/pi0_fast/configuration_pi0_fast.py", "license": "Apache License 2.0", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/pi0_fast/modeling_pi0_fast.py
#!/usr/bin/env python # Copyright 2025 Physical Intelligence and The HuggingFace Inc. team. All rights reserved. # # 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 builtins import logging import math from collections import deque from pathlib import Path from typing import TYPE_CHECKING, Literal, TypedDict, Unpack import numpy as np import torch import torch.nn.functional as F # noqa: N812 from torch import Tensor, nn from lerobot.utils.import_utils import _scipy_available, _transformers_available # Conditional import for type checking and lazy loading if TYPE_CHECKING or _scipy_available: from scipy.fftpack import idct else: idct = None if TYPE_CHECKING or _transformers_available: from transformers import AutoTokenizer from transformers.models.auto import CONFIG_MAPPING from lerobot.policies.pi_gemma import ( PaliGemmaForConditionalGenerationWithPiGemma, PiGemmaModel, ) else: CONFIG_MAPPING = None AutoTokenizer = None PiGemmaModel = None PaliGemmaForConditionalGenerationWithPiGemma = None from lerobot.configs.policies import PreTrainedConfig from lerobot.policies.pi0_fast.configuration_pi0_fast import PI0FastConfig from lerobot.policies.pretrained import PreTrainedPolicy, T from lerobot.policies.rtc.modeling_rtc import RTCProcessor from lerobot.utils.constants import ( ACTION, ACTION_TOKEN_MASK, ACTION_TOKENS, OBS_LANGUAGE_ATTENTION_MASK, OBS_LANGUAGE_TOKENS, OPENPI_ATTENTION_MASK_VALUE, ) class ActionSelectKwargs(TypedDict, total=False): temperature: float | None def pad_vector(vector, new_dim): """Pad the last dimension of a vector to new_dim with zeros. Can be (batch_size x sequence_length x features_dimension) or (batch_size x features_dimension) """ if vector.shape[-1] >= new_dim: return vector return F.pad(vector, (0, new_dim - vector.shape[-1])) def resize_with_pad_torch( # see openpi `resize_with_pad_torch` (exact copy) images: torch.Tensor, height: int, width: int, mode: str = "bilinear", ) -> torch.Tensor: """PyTorch version of resize_with_pad. Resizes an image to a target height and width without distortion by padding with black. If the image is float32, it must be in the range [-1, 1]. Args: images: Tensor of shape [*b, h, w, c] or [*b, c, h, w] height: Target height width: Target width mode: Interpolation mode ('bilinear', 'nearest', etc.) Returns: Resized and padded tensor with same shape format as input """ # Check if input is in channels-last format [*b, h, w, c] or channels-first [*b, c, h, w] if images.shape[-1] <= 4: # Assume channels-last format channels_last = True if images.dim() == 3: images = images.unsqueeze(0) # Add batch dimension images = images.permute(0, 3, 1, 2) # [b, h, w, c] -> [b, c, h, w] else: channels_last = False if images.dim() == 3: images = images.unsqueeze(0) # Add batch dimension batch_size, channels, cur_height, cur_width = images.shape # Calculate resize ratio ratio = max(cur_width / width, cur_height / height) resized_height = int(cur_height / ratio) resized_width = int(cur_width / ratio) # Resize resized_images = F.interpolate( images, size=(resized_height, resized_width), mode=mode, align_corners=False if mode == "bilinear" else None, ) # Handle dtype-specific clipping if images.dtype == torch.uint8: resized_images = torch.round(resized_images).clamp(0, 255).to(torch.uint8) elif images.dtype == torch.float32: resized_images = resized_images.clamp(0.0, 1.0) else: raise ValueError(f"Unsupported image dtype: {images.dtype}") # Calculate padding pad_h0, remainder_h = divmod(height - resized_height, 2) pad_h1 = pad_h0 + remainder_h pad_w0, remainder_w = divmod(width - resized_width, 2) pad_w1 = pad_w0 + remainder_w # Pad constant_value = 0 if images.dtype == torch.uint8 else 0.0 padded_images = F.pad( resized_images, (pad_w0, pad_w1, pad_h0, pad_h1), # left, right, top, bottom mode="constant", value=constant_value, ) # Convert back to original format if needed if channels_last: padded_images = padded_images.permute(0, 2, 3, 1) # [b, c, h, w] -> [b, h, w, c] return padded_images class GemmaConfig: # see openpi `gemma.py: Config` """Configuration for Gemma model variants.""" def __init__(self, width, depth, mlp_dim, num_heads, num_kv_heads, head_dim): self.width = width self.depth = depth self.mlp_dim = mlp_dim self.num_heads = num_heads self.num_kv_heads = num_kv_heads self.head_dim = head_dim def get_gemma_config(variant: str) -> GemmaConfig: # see openpi `gemma.py: get_config` """Returns config for specified gemma variant.""" if variant == "gemma_300m": return GemmaConfig( width=1024, depth=18, mlp_dim=4096, num_heads=8, num_kv_heads=1, head_dim=256, ) elif variant == "gemma_2b": return GemmaConfig( width=2048, depth=18, mlp_dim=16_384, num_heads=8, num_kv_heads=1, head_dim=256, ) else: raise ValueError(f"Unknown variant: {variant}") class PI0FastPaliGemma(nn.Module): """PaliGemma model for PI0Fast""" def __init__( self, vlm_config, use_adarms=None, precision: Literal["bfloat16", "float32"] = "bfloat16", ): if use_adarms is None: use_adarms = [False, False] super().__init__() vlm_config_hf = CONFIG_MAPPING["paligemma"]() vlm_config_hf._vocab_size = 257152 # noqa: SLF001 vlm_config_hf.image_token_index = 257152 vlm_config_hf.text_config.hidden_size = vlm_config.width vlm_config_hf.text_config.intermediate_size = vlm_config.mlp_dim vlm_config_hf.text_config.num_attention_heads = vlm_config.num_heads vlm_config_hf.text_config.head_dim = vlm_config.head_dim vlm_config_hf.text_config.num_hidden_layers = vlm_config.depth vlm_config_hf.text_config.num_key_value_heads = vlm_config.num_kv_heads vlm_config_hf.text_config.hidden_activation = "gelu_pytorch_tanh" vlm_config_hf.text_config.dtype = "float32" vlm_config_hf.text_config.vocab_size = 257152 vlm_config_hf.text_config.use_adarms = use_adarms[0] vlm_config_hf.text_config.adarms_cond_dim = vlm_config.width if use_adarms[0] else None vlm_config_hf.vision_config.intermediate_size = 4304 vlm_config_hf.vision_config.projection_dim = 2048 vlm_config_hf.vision_config.projector_hidden_act = "gelu_fast" vlm_config_hf.vision_config.dtype = "float32" self.paligemma = PaliGemmaForConditionalGenerationWithPiGemma(config=vlm_config_hf) # Use PI Gemma (AdaRMS) as language model when use_adarms[0] is True so that # forward(..., adarms_cond=...) is supported (same as pi0/pi05). if use_adarms[0]: text_config = self.paligemma.config.text_config self.paligemma.model.language_model = PiGemmaModel(text_config) self.to_bfloat16_for_selected_params(precision) def to_bfloat16_for_selected_params(self, precision: Literal["bfloat16", "float32"] = "bfloat16"): if precision == "bfloat16": self.to(dtype=torch.bfloat16) elif precision == "float32": self.to(dtype=torch.float32) return else: raise ValueError(f"Invalid precision: {precision}") # Keep full vision path in float32 so we never toggle (toggle causes optimizer # "same dtype" error). Align with PI05. params_to_keep_float32 = [ "vision_tower", "multi_modal_projector", "input_layernorm", "post_attention_layernorm", "model.norm", ] for name, param in self.named_parameters(): if any(selector in name for selector in params_to_keep_float32): param.data = param.data.to(dtype=torch.float32) def embed_image(self, image: torch.Tensor): # Vision tower and multi_modal_projector are kept in float32 (params_to_keep_float32). Align with PI05. out_dtype = image.dtype if image.dtype != torch.float32: image = image.to(torch.float32) image_outputs = self.paligemma.model.get_image_features(image) features = image_outputs.pooler_output * self.paligemma.config.text_config.hidden_size**0.5 if features.dtype != out_dtype: features = features.to(out_dtype) return features def embed_language_tokens(self, tokens: torch.Tensor): return self.paligemma.model.language_model.embed_tokens(tokens) def forward( self, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: list[torch.FloatTensor] | None = None, use_cache: bool | None = None, adarms_cond: list[torch.Tensor] | None = None, ): if adarms_cond is None: adarms_cond = [None, None] if inputs_embeds[1] is None: prefix_output = self.paligemma.model.language_model.forward( inputs_embeds=inputs_embeds[0], attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, adarms_cond=adarms_cond[0] if adarms_cond is not None else None, ) prefix_past_key_values = prefix_output.past_key_values # prefix_output to be used for the language head # shape: [batch_size, seq_len, hidden_size] with hidden_size = 2048 prefix_output = prefix_output.last_hidden_state suffix_output = None return [prefix_output, suffix_output], prefix_past_key_values class PI0FastPytorch(nn.Module): # see openpi `PI0Pytorch` """Core PI0Fast PyTorch model.""" def __init__( self, config: PI0FastConfig, rtc_processor: RTCProcessor | None = None, paligemma_tokenizer: "AutoTokenizer | None" = None, ): super().__init__() self.config = config self.rtc_processor = rtc_processor self._paligemma_tokenizer = paligemma_tokenizer paligemma_config = get_gemma_config(config.paligemma_variant) self.paligemma_with_expert = PI0FastPaliGemma( paligemma_config, use_adarms=[False, True], precision=config.dtype, ) # Initialize gradient checkpointing flag self.gradient_checkpointing_enabled = False # Compile model if requested if config.compile_model: torch.set_float32_matmul_precision("high") self.sample_actions_fast = torch.compile(self.sample_actions_fast, mode=config.compile_mode) self.forward = torch.compile(self.forward, mode=config.compile_mode) def gradient_checkpointing_enable(self): """Enable gradient checkpointing for memory optimization.""" self.gradient_checkpointing_enabled = True # Call the proper gradient_checkpointing_enable() method with use_reentrant=False for better memory efficiency self.paligemma_with_expert.paligemma.model.language_model.gradient_checkpointing_enable( gradient_checkpointing_kwargs={"use_reentrant": False} ) self.paligemma_with_expert.paligemma.model.vision_tower.gradient_checkpointing_enable( gradient_checkpointing_kwargs={"use_reentrant": False} ) logging.info("Enabled gradient checkpointing for PI0FastPytorch model") def gradient_checkpointing_disable(self): """Disable gradient checkpointing.""" self.gradient_checkpointing_enabled = False # Call the proper gradient_checkpointing_disable() method self.paligemma_with_expert.paligemma.model.language_model.gradient_checkpointing_disable() self.paligemma_with_expert.paligemma.model.vision_tower.gradient_checkpointing_disable() logging.info("Disabled gradient checkpointing for PI0FastPytorch model") def _apply_checkpoint(self, func, *args, **kwargs): """Helper method to apply gradient checkpointing if enabled.""" if self.gradient_checkpointing_enabled and self.training: return torch.utils.checkpoint.checkpoint( func, *args, use_reentrant=False, preserve_rng_state=False, **kwargs ) return func(*args, **kwargs) def _prepare_attention_masks_4d(self, att_2d_masks, dtype=None): """Helper method to prepare 4D attention masks for transformer.""" att_2d_masks_4d = att_2d_masks[:, None, :, :] result = torch.where(att_2d_masks_4d, 0.0, OPENPI_ATTENTION_MASK_VALUE) if dtype is not None: result = result.to(dtype=dtype) return result def embed_prefix_fast( self, images, img_masks, tokens, masks, fast_action_tokens=None, fast_action_masks=None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, int]: """Embed images, language tokens, and FAST action tokens. Attention pattern: - Images + Language: bidirectional among themselves - FAST: attend to images + language, causal among themselves Args: images: List of image tensors img_masks: List of image masks tokens: Language instruction tokens masks: Attention masks for tokens fast_action_tokens: FAST action tokens (discrete token IDs) fast_action_masks: Padding masks for FAST action tokens Returns: embs: Concatenated embeddings [images, tokens, fast_action_tokens] pad_masks: Padding masks att_masks: 2D attention mask total_T_images: Total number of image tokens num_fast_embs: Number of FAST action token embeddings """ embs = [] pad_masks = [] att_mask_segments = [] total_t_images = 0 num_fast_embs = 0 # Process images for img, img_mask in zip(images, img_masks, strict=True): def image_embed_func(img): return self.paligemma_with_expert.embed_image(img) img_emb = self._apply_checkpoint(image_embed_func, img) bsize, num_img_embs = img_emb.shape[:2] embs.append(img_emb) pad_masks.append(img_mask[:, None].expand(bsize, num_img_embs)) att_mask_segments.append(("image", num_img_embs)) total_t_images += num_img_embs # Process language instruction tokens def lang_embed_func(tokens): lang_emb = self.paligemma_with_expert.embed_language_tokens(tokens) lang_emb_dim = lang_emb.shape[-1] return lang_emb * math.sqrt(lang_emb_dim) lang_emb = self._apply_checkpoint(lang_embed_func, tokens) embs.append(lang_emb) pad_masks.append(masks) num_lang_embs = lang_emb.shape[1] att_mask_segments.append(("language", num_lang_embs)) # Process FAST action tokens (discrete token IDs) if fast_action_tokens is not None: def fast_action_embed_func(fast_action_tokens): fast_emb = self.paligemma_with_expert.embed_language_tokens(fast_action_tokens) fast_emb_dim = fast_emb.shape[-1] return fast_emb * math.sqrt(fast_emb_dim) fast_action_emb = self._apply_checkpoint(fast_action_embed_func, fast_action_tokens) embs.append(fast_action_emb) num_fast_embs = fast_action_tokens.shape[1] pad_masks.append(fast_action_masks) att_mask_segments.append(("fast", num_fast_embs)) embs = torch.cat(embs, dim=1) pad_masks = torch.cat(pad_masks, dim=1) # Create custom 2D attention mask: # - Images + Language: bidirectional among themselves # - FAST: attend to images + language, causal among themselves att_masks = self._create_custom_attention_mask_fast(att_mask_segments, pad_masks, bsize) return embs, pad_masks, att_masks, total_t_images, num_fast_embs def _create_custom_attention_mask_fast(self, att_mask_segments, pad_masks, bsize): """Create custom 2D attention mask. Attention rules: - Images + Language: bidirectional among themselves - FAST: attend to images + language, causal among themselves """ total_len = sum(length for _, length in att_mask_segments) device = pad_masks.device att_2d_masks = torch.zeros(bsize, total_len, total_len, dtype=torch.bool, device=device) positions = [] current_pos = 0 for seg_type, seg_len in att_mask_segments: positions.append((seg_type, current_pos, current_pos + seg_len)) current_pos += seg_len for _i, (query_type, query_start, query_end) in enumerate(positions): for _j, (key_type, key_start, key_end) in enumerate(positions): # Images and Language can attend to each other bidirectionally if ( query_type in ["image", "language"] and key_type in ["image", "language"] or query_type == "fast" and key_type in ["image", "language"] ): att_2d_masks[:, query_start:query_end, key_start:key_end] = True # FAST tokens attend causally to themselves elif query_type == "fast" and key_type == "fast": fast_len = query_end - query_start causal_mask = torch.tril(torch.ones(fast_len, fast_len, dtype=torch.bool, device=device)) att_2d_masks[:, query_start:query_end, key_start:key_end] = causal_mask[None, :, :] # Apply padding masks pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None] att_2d_masks = att_2d_masks & pad_2d_masks return att_2d_masks def forward( self, images, img_masks, tokens, masks, fast_action_tokens, fast_action_masks, ) -> dict: """Forward pass for PI0Fast. This implements the Pi0FAST training objective: predict next action token using cross-entropy loss. Args: images: List of image tensors img_masks: List of image masks tokens: Language instruction tokens masks: Attention masks for tokens fast_action_tokens: Discrete action token IDs [B, max_action_tokens] fast_action_masks: Padding masks for fast action tokens [B, max_action_tokens] Returns: Dictionary with 'fast_loss' and 'loss' keys """ if fast_action_tokens is None or fast_action_masks is None: raise ValueError("fast_action_tokens and fast_action_masks are required for FAST-only mode") # Embed prefix with FAST tokens prefix_embs, prefix_pad_masks, prefix_att_masks, total_t_images, num_fast_embs = ( self.embed_prefix_fast( images, img_masks, tokens, masks, fast_action_tokens=fast_action_tokens, fast_action_masks=fast_action_masks, ) ) # Convert embeddings to bfloat16 if needed if ( self.paligemma_with_expert.paligemma.model.language_model.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16 ): prefix_embs = prefix_embs.to(dtype=torch.bfloat16) # for next-token prediction, input tokens [0:T-1] to predict tokens [1:T] input_embs = prefix_embs input_pad_masks = prefix_pad_masks input_att_masks = prefix_att_masks position_ids = torch.cumsum(input_pad_masks, dim=1) - 1 att_2d_4d = self._prepare_attention_masks_4d(input_att_masks, dtype=input_embs.dtype) # forward pass through paligemma (language model) (prefix_out, _), _ = self.paligemma_with_expert.forward( attention_mask=att_2d_4d, position_ids=position_ids, past_key_values=None, inputs_embeds=[input_embs, None], # No suffix/action expert use_cache=False, adarms_cond=[None, None], ) # Get logits for FAST action tokens using the FAST LM head # only compute logits for the positions that predict FAST tokens lm_head = self.paligemma_with_expert.paligemma.lm_head # Targets are the FAST action tokens fast_targets = fast_action_tokens # (B, num_fast_embs) # extract logits for FAST token prediction fast_hidden = prefix_out[:, -fast_targets.shape[1] :, :] fast_logits_for_pred = lm_head(fast_hidden) # (B, num_fast_embs, gemma_vocab_size) # Shift left for next-step prediction and shift target # logits[:, i] predicts targets[:, i+1] fast_logits_for_pred = fast_logits_for_pred[:, :-1, :] # shift logits left fast_targets = fast_targets[:, 1:] # shift targets right fast_action_masks = fast_action_masks[:, 1:] # shift masks to match targets # compute cross-entropy loss loss_fct = torch.nn.CrossEntropyLoss(reduction="none") fast_logits_flat = fast_logits_for_pred.reshape(-1, fast_logits_for_pred.size(-1)) fast_targets_flat = fast_targets.reshape(-1) fast_loss_per_token = loss_fct(fast_logits_flat, fast_targets_flat) fast_loss_per_token = fast_loss_per_token.reshape(fast_targets.shape) # apply mask and compute mean loss masked_fast_loss = fast_loss_per_token * fast_action_masks.float() fast_loss = masked_fast_loss.sum() / fast_action_masks.sum().clamp(min=1) return { "ce_loss": fast_loss, "loss": fast_loss, } @torch.no_grad() def sample_actions_fast( self, images, img_masks, tokens, masks, max_decoding_steps=None, temperature=0.0, ) -> torch.Tensor: """ Inefficient but safe autoregressive decoding for FAST tokens. Matches the pattern of _generate_subtask_tokens. TODO: jadechoghari, should we move this logic to PI0FastPolicy class? """ if max_decoding_steps is None: max_decoding_steps = self.config.max_action_tokens bsize = tokens.shape[0] device = tokens.device lm_head = self.paligemma_with_expert.paligemma.lm_head # add bos token after tokens bos_token = torch.full( (bsize, 1), self._paligemma_tokenizer.bos_token_id, dtype=torch.long, device=device ) tokens = torch.cat([tokens, bos_token], dim=1) masks = torch.cat([masks, torch.ones((bsize, 1), dtype=torch.bool, device=device)], dim=1) # 1. Initial Embedding (matches training prefix) # prefix_embs will include [Images, Language Prompt, BOS] prefix_embs, prefix_pad_masks, prefix_att_masks, total_t_images, _ = self.embed_prefix_fast( images, img_masks, tokens, masks, fast_action_tokens=None, fast_action_masks=None ) if ( self.paligemma_with_expert.paligemma.model.language_model.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16 ): prefix_embs = prefix_embs.to(dtype=torch.bfloat16) generated_action_tokens = torch.zeros((bsize, max_decoding_steps), dtype=torch.long, device=device) # 2. Decoding Loop (each step re-computes full sequence) for t in range(max_decoding_steps): # always re-calculate position IDs from the current pad mask position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1 att_4d = self._prepare_attention_masks_4d(prefix_att_masks, dtype=prefix_embs.dtype) # full forward pass (no kv cache) (prefix_out, _), _ = self.paligemma_with_expert.forward( attention_mask=att_4d, position_ids=position_ids, past_key_values=None, inputs_embeds=[prefix_embs, None], use_cache=False, adarms_cond=[None, None], ) # predict next token from the very last sequence position last_logits = lm_head(prefix_out[:, -1:, :]) # (B, 1, vocab_size) if temperature > 0: probs = torch.softmax(last_logits[:, -1] / temperature, dim=-1) next_token = torch.multinomial(probs, num_samples=1) else: next_token = torch.argmax(last_logits[:, -1], dim=-1, keepdim=True) generated_action_tokens[:, t] = next_token.squeeze(-1) # 3. Update sequence for next iteration (unless it's the last step) if t < max_decoding_steps - 1: # embed the newly generated token next_token_emb = self.paligemma_with_expert.embed_language_tokens(next_token) next_token_emb = next_token_emb * math.sqrt(next_token_emb.shape[-1]) if prefix_embs.dtype == torch.bfloat16: next_token_emb = next_token_emb.to(dtype=torch.bfloat16) # append to embeddings prefix_embs = torch.cat([prefix_embs, next_token_emb], dim=1) # update padding mask (new token is always valid/1) prefix_pad_masks = torch.cat( [prefix_pad_masks, torch.ones((bsize, 1), dtype=torch.bool, device=device)], dim=1 ) # update 2d attention mask: grow the matrix old_len = prefix_att_masks.shape[1] new_len = old_len + 1 new_att_masks = torch.zeros((bsize, new_len, new_len), dtype=torch.bool, device=device) new_att_masks[:, :old_len, :old_len] = prefix_att_masks # new token attends to all non-padding tokens in the updated sequence new_att_masks[:, -1, :] = prefix_pad_masks prefix_att_masks = new_att_masks return generated_action_tokens @torch.no_grad() def sample_actions_fast_kv_cache( self, images, img_masks, tokens, masks, max_decoding_steps=None, temperature=0.0, ) -> torch.Tensor: """ Optimized autoregressive decoding for FAST tokens using KV Caching. """ if max_decoding_steps is None: max_decoding_steps = self.config.max_action_tokens bsize = tokens.shape[0] device = tokens.device lm_head = self.paligemma_with_expert.paligemma.lm_head # --- 1. PREFILL PHASE --- # Process Images + Text Prompt + BOS token once to populate the KV cache. # Add BOS token to the prompt bos_token = torch.full( (bsize, 1), self._paligemma_tokenizer.bos_token_id, dtype=torch.long, device=device ) tokens_in = torch.cat([tokens, bos_token], dim=1) masks_in = torch.cat([masks, torch.ones((bsize, 1), dtype=torch.bool, device=device)], dim=1) # Embed prefix [Images, Language, BOS] # fast_action_tokens=None means we are just embedding the condition (images+text) prefix_embs, prefix_pad_masks, prefix_att_masks, total_t_images, _ = self.embed_prefix_fast( images, img_masks, tokens_in, masks_in, fast_action_tokens=None, fast_action_masks=None ) # Ensure correct precision (bfloat16/float32) if ( self.paligemma_with_expert.paligemma.model.language_model.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16 ): prefix_embs = prefix_embs.to(dtype=torch.bfloat16) # Create position IDs (cumsum of mask - 1) position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1 # Create 4D mask for the prefix att_4d = self._prepare_attention_masks_4d(prefix_att_masks, dtype=prefix_embs.dtype) # Forward pass (Prefill) with use_cache=True # We only pass [prefix_embs, None] because we aren't using the suffix (expert) model yet (prefix_out, _), past_key_values = self.paligemma_with_expert.forward( attention_mask=att_4d, position_ids=position_ids, past_key_values=None, inputs_embeds=[prefix_embs, None], use_cache=True, # Enable caching adarms_cond=[None, None], ) # Sample the first action token from the last logit of the prefix last_logits = lm_head(prefix_out[:, -1:, :]) # (B, 1, V) if temperature > 0: probs = torch.softmax(last_logits[:, -1] / temperature, dim=-1) next_token = torch.multinomial(probs, num_samples=1) else: next_token = torch.argmax(last_logits[:, -1], dim=-1, keepdim=True) # Initialize storage for generated tokens generated_action_tokens = torch.zeros((bsize, max_decoding_steps), dtype=torch.long, device=device) generated_action_tokens[:, 0] = next_token.squeeze(-1) # Track valid tokens mask (0 for pad, 1 for valid) # We need this to tell the new token what it can attend to (images + text + past actions) current_pad_mask = prefix_pad_masks # --- 2. DECODING PHASE --- # Generate remaining tokens one by one using the cache. for t in range(1, max_decoding_steps): # Embed the single previous token # We use embed_language_tokens directly to avoid overhead of full prefix embedding next_token_emb = self.paligemma_with_expert.embed_language_tokens(next_token) next_token_emb = next_token_emb * math.sqrt(next_token_emb.shape[-1]) if prefix_embs.dtype == torch.bfloat16: next_token_emb = next_token_emb.to(dtype=torch.bfloat16) # Update Pad Mask: append 1s for the new valid token new_column = torch.ones((bsize, 1), dtype=torch.bool, device=device) current_pad_mask = torch.cat([current_pad_mask, new_column], dim=1) # Update Position IDs for the single new token current_position_ids = (torch.sum(current_pad_mask, dim=1, keepdim=True) - 1).long() # Create Attention Mask for the single new step # The new token attends to all valid tokens in history (captured by current_pad_mask). # Shape becomes (B, 1, 1, Total_Len) which works with HF's cache logic. step_att_mask = self._prepare_attention_masks_4d( current_pad_mask.unsqueeze(1), dtype=next_token_emb.dtype ) # Forward pass (Decoding step) # input_embeds is just the new token (B, 1, D) (step_out, _), past_key_values = self.paligemma_with_expert.forward( attention_mask=step_att_mask, position_ids=current_position_ids, past_key_values=past_key_values, # Pass updated cache inputs_embeds=[next_token_emb, None], use_cache=True, adarms_cond=[None, None], ) # Sample next token last_logits = lm_head(step_out[:, -1:, :]) if temperature > 0: probs = torch.softmax(last_logits[:, -1] / temperature, dim=-1) next_token = torch.multinomial(probs, num_samples=1) else: next_token = torch.argmax(last_logits[:, -1], dim=-1, keepdim=True) generated_action_tokens[:, t] = next_token.squeeze(-1) return generated_action_tokens class PI0FastPolicy(PreTrainedPolicy): """PI0Fast Policy for LeRobot.""" config_class = PI0FastConfig name = "pi0_fast" def __init__( self, config: PI0FastConfig, **kwargs, ): """ Args: config: Policy configuration class instance. """ super().__init__(config) config.validate_features() self.config = config # Load tokenizers first try: from transformers import AutoProcessor, AutoTokenizer # Load FAST tokenizer self.action_tokenizer = AutoProcessor.from_pretrained( config.action_tokenizer_name, trust_remote_code=True ) # Load PaliGemma tokenizer for token conversion self._paligemma_tokenizer = AutoTokenizer.from_pretrained( config.text_tokenizer_name, trust_remote_code=True, add_eos_token=True, add_bos_token=False ) logging.info("Loaded FAST tokenizer for action detokenization") except Exception as e: logging.error(f"Failed to load FAST tokenizer for action detokenization: {e}") logging.error("Tokenizer loading is required for proper policy initialization; aborting.") raise RuntimeError("Failed to load required tokenizers for PI0FastPolicy initialization") from e # Initialize the core PI0Fast model self.init_rtc_processor() self.model = PI0FastPytorch( config, rtc_processor=self.rtc_processor, paligemma_tokenizer=self._paligemma_tokenizer ) # Enable gradient checkpointing if requested if config.gradient_checkpointing: self.model.gradient_checkpointing_enable() self.model.to(config.device) self.reset() @classmethod def from_pretrained( cls: builtins.type[T], pretrained_name_or_path: str | Path, *, config: PreTrainedConfig | None = None, force_download: bool = False, resume_download: bool | None = None, proxies: dict | None = None, token: str | bool | None = None, cache_dir: str | Path | None = None, local_files_only: bool = False, revision: str | None = None, strict: bool = True, **kwargs, ) -> T: """Override the from_pretrained method to handle key remapping and display important disclaimer.""" print( "The PI0Fast model is a direct port of the OpenPI implementation. \n" "This implementation follows the original OpenPI structure for compatibility. \n" "Original implementation: https://github.com/Physical-Intelligence/openpi" ) if pretrained_name_or_path is None: raise ValueError("pretrained_name_or_path is required") # Use provided config if available, otherwise create default config if config is None: config = PreTrainedConfig.from_pretrained( pretrained_name_or_path=pretrained_name_or_path, force_download=force_download, resume_download=resume_download, proxies=proxies, token=token, cache_dir=cache_dir, local_files_only=local_files_only, revision=revision, **kwargs, ) # Initialize model without loading weights # Check if dataset_stats were provided in kwargs model = cls(config, **kwargs) # Load state dict (expects keys with "model." prefix) try: print(f"Loading model from: {pretrained_name_or_path}") try: from transformers.utils import cached_file resolved_file = cached_file( pretrained_name_or_path, "model.safetensors", cache_dir=kwargs.get("cache_dir"), force_download=kwargs.get("force_download", False), resume_download=kwargs.get("resume_download"), proxies=kwargs.get("proxies"), token=kwargs.get("token"), revision=kwargs.get("revision"), local_files_only=kwargs.get("local_files_only", False), ) from safetensors.torch import load_file original_state_dict = load_file(resolved_file) print("✓ Loaded state dict from model.safetensors") except Exception as e: print(f"Could not load state dict from remote files: {e}") print("Returning model without loading pretrained weights") return model # First, fix any key differences (see openpi model.py, _fix_pytorch_state_dict_keys) fixed_state_dict = model._fix_pytorch_state_dict_keys(original_state_dict, model.config) # Then add "model." prefix for all keys that don't already have it remapped_state_dict = {} remap_count = 0 for key, value in fixed_state_dict.items(): if not key.startswith("model."): new_key = f"model.{key}" remapped_state_dict[new_key] = value remap_count += 1 else: remapped_state_dict[key] = value if remap_count > 0: print(f"Remapped {remap_count} state dict keys") # Load the remapped state dict into the model missing_keys, unexpected_keys = model.load_state_dict(remapped_state_dict, strict=strict) if missing_keys: print(f"Missing keys when loading state dict: {len(missing_keys)} keys") if len(missing_keys) <= 5: for key in missing_keys: print(f" - {key}") else: for key in missing_keys[:5]: print(f" - {key}") print(f" ... and {len(missing_keys) - 5} more") if unexpected_keys: print(f"Unexpected keys when loading state dict: {len(unexpected_keys)} keys") if len(unexpected_keys) <= 5: for key in unexpected_keys: print(f" - {key}") else: for key in unexpected_keys[:5]: print(f" - {key}") print(f" ... and {len(unexpected_keys) - 5} more") if not missing_keys and not unexpected_keys: print("All keys loaded successfully!") except Exception as e: print(f"Warning: Could not load state dict: {e}") return model def _fix_pytorch_state_dict_keys( self, state_dict, model_config ): # see openpi `BaseModelConfig, _fix_pytorch_state_dict_keys` """Fix state dict keys to match current model architecture.""" fixed_state_dict = {} for key, value in state_dict.items(): new_key = key # Handle vision tower embedding layer potential differences if "patch_embedding" in key: # Some checkpoints might have this, but current model expects different structure logging.warning(f"Vision embedding key might need handling: {key}") if ( key == "model.paligemma_with_expert.paligemma.lm_head.weight" or key == "paligemma_with_expert.paligemma.lm_head.weight" ): fixed_state_dict[ "model.paligemma_with_expert.paligemma.model.language_model.embed_tokens.weight" ] = value.clone() fixed_state_dict[new_key] = value return fixed_state_dict def get_optim_params(self) -> dict: return self.parameters() def reset(self): """Reset internal state - called when environment resets.""" self._action_queue = deque(maxlen=self.config.n_action_steps) self._queues = { ACTION: deque(maxlen=self.config.n_action_steps), } def init_rtc_processor(self): """Initialize RTC processor if RTC is enabled in config.""" self.rtc_processor = None # Create processor if config provided # If RTC is not enabled - we can still track the denoising data if self.config.rtc_config is not None: self.rtc_processor = RTCProcessor(self.config.rtc_config) model_value = getattr(self, "model", None) if model_value is not None: model_value.rtc_processor = self.rtc_processor def _rtc_enabled(self) -> bool: return self.config.rtc_config is not None and self.config.rtc_config.enabled def _preprocess_images(self, batch: dict[str, Tensor]) -> tuple[list[Tensor], list[Tensor]]: """Preprocess images for the model. Images from LeRobot are typically in [B, C, H, W] format and normalized to [0, 1]. PaliGemma expects images in [B, C, H, W] format and normalized to [-1, 1]. """ images = [] img_masks = [] # Get device from model parameters device = next(self.parameters()).device present_img_keys = [key for key in self.config.image_features if key in batch] missing_img_keys = [key for key in self.config.image_features if key not in batch] if len(present_img_keys) == 0: raise ValueError( f"All image features are missing from the batch. At least one expected. " f"(batch: {batch.keys()}) (image_features: {self.config.image_features})" ) # Preprocess image features present in the batch for key in present_img_keys: img = batch[key] # Ensure tensor is on the same device as the model if img.device != device: img = img.to(device) # Ensure float32 dtype for consistency if img.dtype != torch.float32: img = img.to(torch.float32) # from openpi preprocess_observation_pytorch: Handle both [B, C, H, W] and [B, H, W, C] formats is_channels_first = img.shape[1] == 3 # Check if channels are in dimension 1 if is_channels_first: # Convert [B, C, H, W] to [B, H, W, C] for processing img = img.permute(0, 2, 3, 1) # from openpi preprocess_observation_pytorch: Resize with padding if needed if img.shape[1:3] != self.config.image_resolution: img = resize_with_pad_torch(img, *self.config.image_resolution) # Normalize from [0,1] to [-1,1] as expected by siglip img = img * 2.0 - 1.0 # from openpi preprocess_observation_pytorch: Convert back to [B, C, H, W] format if it was originally channels-first if is_channels_first: img = img.permute(0, 3, 1, 2) # [B, H, W, C] -> [B, C, H, W] images.append(img) # Create mask (all ones for real images) bsize = img.shape[0] mask = torch.ones(bsize, dtype=torch.bool, device=device) img_masks.append(mask) # Create image features not present in the batch as fully 0 padded images for _num_empty_cameras in range(len(missing_img_keys)): img = torch.ones_like(img) * -1 # Padded with -1 for SigLIP mask = torch.zeros_like(mask) # Mask is zero for empty cameras images.append(img) img_masks.append(mask) return images, img_masks def prepare_action(self, batch): """Pad action""" actions = pad_vector(batch[ACTION], self.config.max_action_dim) return actions def _paligemma_tokens_to_act_tokens(self, tokens: torch.Tensor) -> torch.Tensor: """ Converts PaliGemma tokens back to action tokens (inverse of _act_tokens_to_paligemma_tokens). Args: tokens: PaliGemma token IDs Returns: Action token IDs """ return self._paligemma_tokenizer.vocab_size - 1 - self.config.fast_skip_tokens - tokens def decode_actions_with_fast( self, token_ids: list[int], time_horizon: int, action_dim: int, relaxed_decoding: bool = True ) -> np.ndarray: """ Decodes action token IDs back to continuous action values using the FAST tokenizer. Args: token_ids: List of token IDs to decode. time_horizon: The number of timesteps for actions. action_dim: The dimensionality of each action. relaxed_decoding: Whether to use relaxed decoding (allows partial sequences). Returns: A numpy array representing the decoded actions. """ decoded_actions = [] for token in token_ids: try: decoded_tokens = self.action_tokenizer.bpe_tokenizer.decode(token) decoded_dct_coeff = np.array(list(map(ord, decoded_tokens))) + self.action_tokenizer.min_token if relaxed_decoding: # expected sequence length expected_seq_len = time_horizon * action_dim diff = expected_seq_len - decoded_dct_coeff.shape[0] # apply truncation if too long if diff < 0: decoded_dct_coeff = decoded_dct_coeff[:expected_seq_len] # truncate on the right # apply padding if too short elif diff > 0: decoded_dct_coeff = np.pad( decoded_dct_coeff, (0, diff), mode="constant", constant_values=0 ) decoded_dct_coeff = decoded_dct_coeff.reshape(-1, action_dim) assert decoded_dct_coeff.shape == ( time_horizon, action_dim, ), ( f"Decoded DCT coefficients have shape {decoded_dct_coeff.shape}, expected ({time_horizon}, {action_dim})" ) except Exception as e: logging.warning(f"Error decoding tokens: {e}") logging.warning(f"Tokens: {token}") decoded_dct_coeff = np.zeros((time_horizon, action_dim)) decoded_actions.append( idct(decoded_dct_coeff / self.action_tokenizer.scale, axis=0, norm="ortho") ) return np.stack(decoded_actions) def detokenize_actions(self, tokens: torch.Tensor, action_horizon: int, action_dim: int) -> torch.Tensor: """ Detokenizes action tokens back to continuous actions. This method converts predicted action tokens from the model back to continuous action values using the FAST tokenizer. It handles the conversion from PaliGemma token space to action token space, then decodes the action tokens to continuous values using DCT decoding. Args: tokens: The input tensor of tokenized outputs. Shape: (B, seq_len) or (seq_len,) action_horizon: The number of timesteps for actions. action_dim: The dimensionality of each action. Returns: The continuous action tensor. Shape: (B, action_horizon, action_dim) or (action_horizon, action_dim) """ if self.action_tokenizer is None or self._paligemma_tokenizer is None: raise ValueError( "Action tokenizer not initialized. Make sure fast_only=True in config and tokenizers loaded successfully." ) # Handle single sample (add batch dimension) single_sample = tokens.dim() == 1 if single_sample: tokens = tokens.unsqueeze(0) # Convert token IDs to token strings decoded_tokens = [self._paligemma_tokenizer.convert_ids_to_tokens(seq.tolist()) for seq in tokens] # Get the token sequence for "Action: " to remove it action_prefix_ids = self._paligemma_tokenizer.encode("Action: ", add_special_tokens=False) action_prefix_tokens = self._paligemma_tokenizer.convert_ids_to_tokens(action_prefix_ids) action_prefix_len = len(action_prefix_tokens) # Clean tokens by removing everything after the first "|" (end-of-action marker) # and removing all occurrences of "Action: " token sequence # assert that beginning contain "Action: " if self.config.validate_action_token_prefix: for token_seq in decoded_tokens: assert len(token_seq) >= 2 and token_seq[0] == "Action" and token_seq[1] == ":", ( f"Token sequence does not start with ['Action', ':']: {token_seq}" ) cleaned_tokens = [] for token_seq in decoded_tokens: # Remove everything after "|" if "|" in token_seq: token_seq = token_seq[: token_seq.index("|")] # Remove all occurrences of "Action: " token sequence i = 0 while i <= len(token_seq) - action_prefix_len: if token_seq[i : i + action_prefix_len] == action_prefix_tokens: # Found a match, remove it token_seq = token_seq[:i] + token_seq[i + action_prefix_len :] else: i += 1 cleaned_tokens.append(token_seq) # Convert token strings back to IDs raw_action_tokens = [ torch.tensor( self._paligemma_tokenizer.convert_tokens_to_ids(token_seq), dtype=torch.long, device=tokens.device, ) for token_seq in cleaned_tokens ] # Convert PaliGemma tokens to action tokens action_tokens = [ self._paligemma_tokens_to_act_tokens(raw_action_token) for raw_action_token in raw_action_tokens ] # Decode action tokens to continuous actions actions = self.decode_actions_with_fast( action_tokens, time_horizon=action_horizon, action_dim=action_dim ) # Convert to tensor and return actions_tensor = torch.tensor(actions, dtype=torch.float32, device=tokens.device) # Remove batch dimension if input was single sample if single_sample: actions_tensor = actions_tensor.squeeze(0) return actions_tensor @torch.no_grad() def select_action(self, batch: dict[str, Tensor]) -> Tensor: """Select a single action given environment observations.""" assert not self._rtc_enabled(), ( "RTC is not supported for select_action, use it with predict_action_chunk" ) self.eval() # Action queue logic for n_action_steps > 1 if len(self._action_queue) == 0: actions = self.predict_action_chunk(batch)[:, : self.config.n_action_steps] # Transpose to get shape (n_action_steps, batch_size, action_dim) self._action_queue.extend(actions.transpose(0, 1)) return self._action_queue.popleft() @torch.no_grad() def predict_action_chunk(self, batch: dict[str, Tensor], **kwargs: Unpack[ActionSelectKwargs]) -> Tensor: """Predict a chunk of actions given environment observations.""" self.eval() # Prepare inputs images, img_masks = self._preprocess_images(batch) # FAST-only mode: use autoregressive decoding tokens = batch[f"{OBS_LANGUAGE_TOKENS}"] masks = batch[f"{OBS_LANGUAGE_ATTENTION_MASK}"] # Get decoding parameters temperature = self.config.temperature max_decoding_steps = self.config.max_decoding_steps # Sample action tokens autoregressively if self.config.use_kv_cache: action_tokens = self.model.sample_actions_fast_kv_cache( images, img_masks, tokens, masks, max_decoding_steps=max_decoding_steps, temperature=temperature, ) else: action_tokens = self.model.sample_actions_fast( images, img_masks, tokens, masks, max_decoding_steps=max_decoding_steps, temperature=temperature, ) # Detokenize action tokens to continuous actions action_horizon = self.config.n_action_steps action_dim = self.config.output_features[ACTION].shape[0] continuous_actions = self.detokenize_actions( action_tokens, action_horizon=action_horizon, action_dim=action_dim ) return continuous_actions def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict]: """Run the batch through the model and compute the loss for training.""" # Prepare inputs images, img_masks = self._preprocess_images(batch) # Get FAST action tokens from batch fast_action_tokens = batch.get(ACTION_TOKENS) # (B, max_action_tokens) fast_action_masks = batch.get(ACTION_TOKEN_MASK) # (B, max_action_tokens) # Use full language tokens (no separation into high_level_task and subtask) tokens = batch.get(OBS_LANGUAGE_TOKENS) masks = batch.get(OBS_LANGUAGE_ATTENTION_MASK) if fast_action_tokens is None or fast_action_masks is None: raise ValueError( f"PI0Fast requires {ACTION_TOKENS} and {ACTION_TOKEN_MASK} to be present in the batch" ) loss_dict = self.model.forward( images, img_masks, tokens, masks, fast_action_tokens, fast_action_masks, ) loss = loss_dict["loss"] detailed_loss_dict = { "loss": loss.item(), "ce_loss": loss_dict["ce_loss"].item(), } return loss, detailed_loss_dict
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/pi0_fast/modeling_pi0_fast.py", "license": "Apache License 2.0", "lines": 1120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/pi0_fast/processor_pi0_fast.py
#!/usr/bin/env python # Copyright 2025 Physical Intelligence and The HuggingFace Inc. team. All rights reserved. # # 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 copy import deepcopy from dataclasses import dataclass from typing import Any import numpy as np import torch from lerobot.configs.types import PipelineFeatureType, PolicyFeature from lerobot.policies.pi0_fast.configuration_pi0_fast import PI0FastConfig from lerobot.processor import ( ActionTokenizerProcessorStep, AddBatchDimensionProcessorStep, DeviceProcessorStep, NormalizerProcessorStep, PolicyAction, PolicyProcessorPipeline, ProcessorStep, ProcessorStepRegistry, RenameObservationsProcessorStep, TokenizerProcessorStep, UnnormalizerProcessorStep, ) from lerobot.processor.converters import policy_action_to_transition, transition_to_policy_action from lerobot.processor.core import EnvTransition, TransitionKey from lerobot.utils.constants import ( OBS_STATE, POLICY_POSTPROCESSOR_DEFAULT_NAME, POLICY_PREPROCESSOR_DEFAULT_NAME, ) @ProcessorStepRegistry.register(name="pi0_fast_prepare_state_tokenizer_processor_step") @dataclass class Pi0FastPrepareStateAndLanguageTokenizerProcessorStep(ProcessorStep): """ Processor step to prepare the state and tokenize the language input. """ max_state_dim: int = 32 task_key: str = "task" def __call__(self, transition: EnvTransition) -> EnvTransition: transition = transition.copy() state = transition.get(TransitionKey.OBSERVATION, {}).get(OBS_STATE) if state is None: raise ValueError("State is required for PI0Fast") tasks = transition.get(TransitionKey.COMPLEMENTARY_DATA, {}).get(self.task_key) if tasks is None: raise ValueError("No task found in complementary data") # TODO: check if this necessary state = deepcopy(state) # State should already be normalized to [-1, 1] by the NormalizerProcessorStep that runs before this step # Discretize into 256 bins (see openpi `PaligemmaTokenizer.tokenize()`) state_np = state.cpu().numpy() discretized_states = np.digitize(state_np, bins=np.linspace(-1, 1, 256 + 1)[:-1]) - 1 full_prompts = [] for i, task in enumerate(tasks): cleaned_text = task.strip().replace("_", " ").replace("\n", " ") state_str = " ".join(map(str, discretized_states[i])) full_prompt = f"Task: {cleaned_text}, State: {state_str};\n" full_prompts.append(full_prompt) transition[TransitionKey.COMPLEMENTARY_DATA][self.task_key] = full_prompts # Normalize state to [-1, 1] range if needed (assuming it's already normalized by normalizer processor step!!) # Discretize into 256 bins (see openpi `PaligemmaTokenizer.tokenize()`) return transition def transform_features( self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]] ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]: """ This step does not alter the feature definitions. """ return features def make_pi0_fast_pre_post_processors( config: PI0FastConfig, dataset_stats: dict[str, dict[str, torch.Tensor]] | None = None, ) -> tuple[ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """ Constructs pre-processor and post-processor pipelines for the PI0Fast policy. The pre-processing pipeline prepares input data for the model by: 1. Renaming features to match pretrained configurations. 2. Normalizing input and output features based on dataset statistics. 3. Adding a batch dimension. 4. Appending a newline character to the task description for tokenizer compatibility. 5. Tokenizing the text prompt using the PaliGemma tokenizer. 6. Moving all data to the specified device. The post-processing pipeline handles the model's output by: 1. Moving data to the CPU. 2. Unnormalizing the output features to their original scale. Args: config: The configuration object for the PI0Fast policy. dataset_stats: A dictionary of statistics for normalization. preprocessor_kwargs: Additional arguments for the pre-processor pipeline. postprocessor_kwargs: Additional arguments for the post-processor pipeline. Returns: A tuple containing the configured pre-processor and post-processor pipelines. """ # Add remaining processors input_steps: list[ProcessorStep] = [ RenameObservationsProcessorStep(rename_map={}), # To mimic the same processor as pretrained one AddBatchDimensionProcessorStep(), # NOTE: NormalizerProcessorStep MUST come before Pi0FastPrepareStateAndLanguageTokenizerProcessorStep # because the tokenizer step expects normalized state in [-1, 1] range for discretization NormalizerProcessorStep( features={**config.input_features, **config.output_features}, norm_map=config.normalization_mapping, stats=dataset_stats, ), Pi0FastPrepareStateAndLanguageTokenizerProcessorStep(max_state_dim=config.max_state_dim), TokenizerProcessorStep( tokenizer_name=config.text_tokenizer_name, max_length=config.tokenizer_max_length, padding_side="right", padding="max_length", ), ActionTokenizerProcessorStep( action_tokenizer_name=config.action_tokenizer_name, max_action_tokens=config.max_action_tokens, fast_skip_tokens=config.fast_skip_tokens, paligemma_tokenizer_name=config.text_tokenizer_name, ), DeviceProcessorStep(device=config.device), ] output_steps: list[ProcessorStep] = [ UnnormalizerProcessorStep( features=config.output_features, norm_map=config.normalization_mapping, stats=dataset_stats ), DeviceProcessorStep(device="cpu"), ] return ( PolicyProcessorPipeline[dict[str, Any], dict[str, Any]]( steps=input_steps, name=POLICY_PREPROCESSOR_DEFAULT_NAME, ), PolicyProcessorPipeline[PolicyAction, PolicyAction]( steps=output_steps, name=POLICY_POSTPROCESSOR_DEFAULT_NAME, to_transition=policy_action_to_transition, to_output=transition_to_policy_action, ), )
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/pi0_fast/processor_pi0_fast.py", "license": "Apache License 2.0", "lines": 151, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/policies/pi0_fast/test_pi0_fast_original_vs_lerobot.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Test script to verify PI0Fast policy integration with LeRobot vs the original implementation""" # ruff: noqa: E402 import random from copy import deepcopy from typing import Any import numpy as np import pytest import torch pytest.importorskip("transformers") pytest.importorskip("scipy") from lerobot.policies.pi0_fast.configuration_pi0_fast import PI0FastConfig from lerobot.policies.pi0_fast.modeling_pi0_fast import PI0FastPolicy from lerobot.policies.pi0_fast.processor_pi0_fast import make_pi0_fast_pre_post_processors from lerobot.processor import PolicyAction, PolicyProcessorPipeline # noqa: E402 from lerobot.utils.constants import ( ACTION_TOKEN_MASK, ACTION_TOKENS, OBS_IMAGES, OBS_LANGUAGE_ATTENTION_MASK, OBS_LANGUAGE_TOKENS, OBS_STATE, ) # noqa: E402 from tests.utils import require_cuda, require_hf_token # noqa: E402 # Constants DUMMY_ACTION_DIM = 7 DUMMY_STATE_DIM = 20 IMAGE_HEIGHT = 224 IMAGE_WIDTH = 224 NUM_VIEWS = 2 # Number of camera views DEVICE = "cuda" MODEL_PATH_LEROBOT = "lerobot/pi0fast-base" # Expected action token shape: (batch_size, max_decoding_steps) EXPECTED_ACTION_TOKENS_SHAPE = (1, 2) # Expected first 5 action tokens (for reproducibility check) EXPECTED_ACTION_TOKENS_FIRST_5 = torch.tensor([255020, 255589]) # Expected actions after detokenization EXPECTED_ACTIONS_SHAPE = (1, 2, 32) # (batch_size, n_action_steps, action_dim) EXPECTED_ACTIONS_MEAN = 0.046403881162405014 EXPECTED_ACTIONS_STD = 0.2607129216194153 EXPECTED_ACTIONS_FIRST_5 = torch.tensor([0.0000, 0.3536, 0.0707, 0.0000, 0.0000]) @require_cuda @require_hf_token def set_seed_all(seed: int): """Set random seed for all RNG sources to ensure reproducibility.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Set deterministic behavior torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.use_deterministic_algorithms(True, warn_only=True) @require_cuda @require_hf_token def instantiate_lerobot_pi0_fast( from_pretrained: bool = False, model_path: str = MODEL_PATH_LEROBOT, ) -> tuple[ Any, # Policy PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """Instantiate LeRobot PI0Fast policy with preprocessor and postprocessor.""" if from_pretrained: policy = PI0FastPolicy.from_pretrained( pretrained_name_or_path=model_path, strict=True, ) policy.config.validate_action_token_prefix = False policy.config.max_action_tokens = 2 policy.config.max_decoding_steps = 2 policy.config.chunk_size = 2 policy.config.n_action_steps = 2 else: config = PI0FastConfig( n_action_steps=2, max_action_dim=DUMMY_ACTION_DIM, max_state_dim=DUMMY_STATE_DIM, device=DEVICE, validate_action_token_prefix=False, max_action_tokens=2, max_decoding_steps=2, chunk_size=2, ) policy = PI0FastPolicy(config) policy.to(DEVICE) policy.config.device = DEVICE preprocessor, postprocessor = make_pi0_fast_pre_post_processors( config=policy.config, dataset_stats=None, # Pass None for dataset_stats to disable normalization ) return policy, preprocessor, postprocessor @require_cuda @require_hf_token def create_dummy_data(device=DEVICE): """Create dummy data for testing both implementations.""" batch_size = 1 prompt = "Pick up the red block and place it in the bin" # Create random RGB images in [0, 255] uint8 range (as PIL images would be) # Then convert to [0, 1] float32 range for LeRobot def fake_rgb(h, w): arr = np.random.randint(0, 255, (h, w, 3), dtype=np.uint8) t = torch.from_numpy(arr).permute(2, 0, 1) # CHW return t batch = { f"{OBS_IMAGES}.base_0_rgb": torch.stack( [fake_rgb(IMAGE_HEIGHT, IMAGE_WIDTH) for _ in range(batch_size)] ).to(device), f"{OBS_IMAGES}.left_wrist_0_rgb": torch.stack( [fake_rgb(IMAGE_HEIGHT, IMAGE_WIDTH) for _ in range(batch_size)] ).to(device), f"{OBS_IMAGES}.right_wrist_0_rgb": torch.stack( [fake_rgb(IMAGE_HEIGHT, IMAGE_WIDTH) for _ in range(batch_size)] ).to(device), OBS_STATE: torch.randn(batch_size, DUMMY_STATE_DIM, dtype=torch.float32, device=device), "task": [prompt for _ in range(batch_size)], } return batch # Pytest fixtures @pytest.fixture(scope="module") @require_cuda @require_hf_token def pi0_fast_components(): """Fixture to instantiate and provide all PI0Fast components for tests.""" print(f"\nTesting with DEVICE='{DEVICE}'") print("\n[Setup] Instantiating LeRobot PI0Fast policy...") policy_obj, preprocessor_obj, postprocessor_obj = instantiate_lerobot_pi0_fast(from_pretrained=True) print("Model loaded successfully") return policy_obj, preprocessor_obj, postprocessor_obj @pytest.fixture(scope="module") @require_cuda @require_hf_token def policy(pi0_fast_components): """Fixture to provide the PI0Fast policy for tests.""" return pi0_fast_components[0] @pytest.fixture(scope="module") @require_cuda @require_hf_token def preprocessor(pi0_fast_components): """Fixture to provide the PI0Fast preprocessor for tests.""" return pi0_fast_components[1] @require_cuda @require_hf_token def test_pi0_fast_preprocessor_alignment(policy, preprocessor): """Test that LeRobot PI0Fast preprocessor produces expected outputs.""" print("\n" + "=" * 80) print("Test: PI0Fast Preprocessor Outputs") print("=" * 80) set_seed_all(42) print("\nCreating dummy data...") batch = create_dummy_data() print("\n[LeRobot] Preprocessing...") lerobot_observation = preprocessor(deepcopy(batch)) print("\nVerifying preprocessor outputs:") print("-" * 80) # Expected keys from PI0Fast preprocessing expected_keys = [ "observation.images.base_0_rgb", "observation.images.left_wrist_0_rgb", "observation.images.right_wrist_0_rgb", "observation.state", "observation.language_tokens", "observation.language_attention_mask", ] for key in expected_keys: if key in lerobot_observation: shape = tuple(lerobot_observation[key].shape) print(f"\nKey: {key}") print(f"Shape: {shape}") print(f"Dtype: {lerobot_observation[key].dtype}") else: print(f"\nKey '{key}' not found in inputs!") # Check language tokens shape if "observation.language_tokens" in lerobot_observation: lang_tokens = lerobot_observation["observation.language_tokens"] print(f"\nLanguage tokens shape: {lang_tokens.shape}") # Should have batch dimension and max_length from tokenizer assert lang_tokens.dim() == 2, f"Expected 2D tensor, got {lang_tokens.dim()}D" print("\nPreprocessor outputs verified!") @require_cuda @require_hf_token def test_pi0_fast_action_generation(policy, preprocessor): """Test PI0Fast LeRobot implementation generates expected actions.""" print("\n" + "=" * 80) print("Test: PI0Fast Action Generation Against Expected Values") print("=" * 80) set_seed_all(42) print("\nCreating dummy data...") batch = create_dummy_data() print("\n[LeRobot] Running inference...") lerobot_observation = preprocessor(deepcopy(batch)) # Reset seed for inference torch.manual_seed(42) with torch.no_grad(): lerobot_actions = policy.predict_action_chunk(lerobot_observation) lerobot_actions = lerobot_actions.float().cpu() print(f"LeRobot actions shape: {lerobot_actions.shape}") print(f"LeRobot actions mean: {lerobot_actions.mean().item():.6f}") print(f"LeRobot actions std: {lerobot_actions.std().item():.6f}") print(f"LeRobot actions first 5: {lerobot_actions[0, 0, :5]}") print("\nExpected values (from original PI0Fast):") print(f"Expected actions shape: {EXPECTED_ACTIONS_SHAPE}") print(f"Expected actions mean: {EXPECTED_ACTIONS_MEAN:.6f}") print(f"Expected actions std: {EXPECTED_ACTIONS_STD:.6f}") print(f"Expected actions first 5: {EXPECTED_ACTIONS_FIRST_5}") print("\nAction Comparison:") print("-" * 80) # Compare shapes actual_shape = tuple(lerobot_actions.shape) print(f"Actual shape: {actual_shape}") assert actual_shape == EXPECTED_ACTIONS_SHAPE, ( f"Shape mismatch: {actual_shape} vs {EXPECTED_ACTIONS_SHAPE}" ) print(f"Shape matches: {actual_shape}") # Compare statistics actual_mean = lerobot_actions.mean().item() actual_std = lerobot_actions.std().item() print(f"\nMean: {actual_mean:.6f} (expected: {EXPECTED_ACTIONS_MEAN:.6f})") print(f"Std: {actual_std:.6f} (expected: {EXPECTED_ACTIONS_STD:.6f})") # Compare first 5 actions actual_first_5 = lerobot_actions[0, 0, :5] print("\nFirst 5 actions comparison:") print(f" Actual: {actual_first_5}") print(f" Expected: {EXPECTED_ACTIONS_FIRST_5}") first_5_diff = torch.abs(actual_first_5 - EXPECTED_ACTIONS_FIRST_5) print(f" Max diff: {first_5_diff.max().item():.6e}") print(f" Mean diff: {first_5_diff.mean().item():.6e}") # Check with different tolerances tolerances = [1e-5, 1e-4, 1e-3, 1e-2] for tol in tolerances: is_close = torch.allclose(actual_first_5, EXPECTED_ACTIONS_FIRST_5, atol=tol) status = "Success" if is_close else "Failure" print(f"{status}: First 5 actions close (atol={tol}): {is_close}") # Assert with reasonable tolerance tolerance = 1e-3 assert torch.allclose(actual_first_5, EXPECTED_ACTIONS_FIRST_5, atol=tolerance), ( f"First 5 actions differ by more than tolerance ({tolerance})" ) print(f"\nSuccess: Actions match expected values within tolerance ({tolerance})!") print("\nAction generation test completed (values printed for reference)!") @require_cuda @require_hf_token def test_pi0_fast_inference_reproducibility(policy, preprocessor): """Test that PI0Fast inference is reproducible with the same seed.""" print("\n" + "=" * 80) print("Test: PI0Fast Inference Reproducibility") print("=" * 80) print("\nCreating dummy data...") batch = create_dummy_data() # First inference print("\n[Run 1] Running inference...") set_seed_all(42) lerobot_observation = preprocessor(deepcopy(batch)) with torch.no_grad(): actions_1 = policy.predict_action_chunk(lerobot_observation) actions_1 = actions_1.float().cpu() # Second inference with same seed print("\n[Run 2] Running inference with same seed...") set_seed_all(42) lerobot_observation = preprocessor(deepcopy(batch)) with torch.no_grad(): actions_2 = policy.predict_action_chunk(lerobot_observation) actions_2 = actions_2.float().cpu() print("\nComparing two runs:") print("-" * 80) if torch.allclose(actions_1, actions_2, atol=1e-8): print("Inference is perfectly reproducible!") else: diff = torch.abs(actions_1 - actions_2) print("Small differences detected:") print(f" Max diff: {diff.max().item():.6e}") print(f" Mean diff: {diff.mean().item():.6e}") assert torch.allclose(actions_1, actions_2, atol=1e-6), "Inference should be reproducible!" print("\nInference is reproducible!") @require_cuda @require_hf_token def test_pi0_fast_forward_pass_logits(policy, preprocessor): """Test PI0Fast forward pass and compare logits against expected values.""" print("\n" + "=" * 80) print("Test: PI0Fast Forward Pass Logits") print("=" * 80) set_seed_all(42) print("\nCreating dummy data with action tokens...") batch = create_dummy_data() # Preprocess the batch lerobot_observation = preprocessor(deepcopy(batch)) # For forward pass, we need action tokens # Create dummy action tokens for testing batch_size = 1 max_action_tokens = policy.config.max_action_tokens # Create dummy action tokens (in practice, these come from the FAST tokenizer) dummy_action_tokens = torch.randint( 0, 1000, (batch_size, max_action_tokens), dtype=torch.long, device=DEVICE ) dummy_action_masks = torch.ones(batch_size, max_action_tokens, dtype=torch.bool, device=DEVICE) # Add action tokens to the observation lerobot_observation[ACTION_TOKENS] = dummy_action_tokens lerobot_observation[ACTION_TOKEN_MASK] = dummy_action_masks print("\n[LeRobot] Running forward pass...") policy.train() with torch.no_grad(): loss, loss_dict = policy.forward(lerobot_observation) print(f"Loss: {loss.item():.6f}") print(f"FAST Loss: {loss_dict['ce_loss']:.6f}") print("\nForward pass completed successfully!") print(f"Loss value: {loss.item():.6f}") # The loss should be a positive value assert loss.item() > 0, "Loss should be positive" assert not torch.isnan(loss), "Loss should not be NaN" assert not torch.isinf(loss), "Loss should not be infinite" print("\nForward pass test passed!") @require_cuda @require_hf_token def test_pi0_fast_action_token_sampling(policy, preprocessor): """Test PI0Fast action token sampling (autoregressive decoding).""" print("\n" + "=" * 80) print("Test: PI0Fast Action Token Sampling") print("=" * 80) set_seed_all(42) print("\nCreating dummy data...") batch = create_dummy_data() print("\n[LeRobot] Preprocessing...") lerobot_observation = preprocessor(deepcopy(batch)) # Prepare inputs for model images, img_masks = policy._preprocess_images(lerobot_observation) tokens = lerobot_observation[OBS_LANGUAGE_TOKENS] masks = lerobot_observation[OBS_LANGUAGE_ATTENTION_MASK] print("\n[LeRobot] Sampling action tokens...") torch.manual_seed(42) with torch.no_grad(): action_tokens = policy.model.sample_actions_fast( images, img_masks, tokens, masks, max_decoding_steps=2, temperature=0.0, # Greedy decoding for reproducibility ) print(f"Action tokens shape: {action_tokens.shape}") print(f"Action tokens first 10: {action_tokens[0, :10].tolist()}") print("\nExpected values (from original PI0Fast):") print(f"Expected shape: {EXPECTED_ACTION_TOKENS_SHAPE}") print(f"Expected first 5: {EXPECTED_ACTION_TOKENS_FIRST_5.tolist()}") # Verify shape actual_shape = tuple(action_tokens.shape) print(f"\nActual shape: {actual_shape}") assert actual_shape == EXPECTED_ACTION_TOKENS_SHAPE, ( f"Shape mismatch: {actual_shape} vs {EXPECTED_ACTION_TOKENS_SHAPE}" ) # Compare first 5 tokens actual_first_5 = action_tokens[0, :5].cpu() assert torch.equal(actual_first_5, EXPECTED_ACTION_TOKENS_FIRST_5), ( f"First 5 tokens mismatch: {actual_first_5} vs {EXPECTED_ACTION_TOKENS_FIRST_5}" ) print("\nAction token sampling test completed!") @require_cuda @require_hf_token def test_pi0_fast_detokenization(policy, preprocessor): """Test PI0Fast action detokenization (FAST decoding).""" print("\n" + "=" * 80) print("Test: PI0Fast Action Detokenization") print("=" * 80) set_seed_all(42) print("\nCreating dummy data...") batch = create_dummy_data() print("\n[LeRobot] Preprocessing...") lerobot_observation = preprocessor(deepcopy(batch)) # Prepare inputs for model images, img_masks = policy._preprocess_images(lerobot_observation) tokens = lerobot_observation[OBS_LANGUAGE_TOKENS] masks = lerobot_observation[OBS_LANGUAGE_ATTENTION_MASK] print("\n[LeRobot] Sampling action tokens...") torch.manual_seed(42) with torch.no_grad(): action_tokens = policy.model.sample_actions_fast( images, img_masks, tokens, masks, max_decoding_steps=2, temperature=0.0, ) print(f"Action tokens shape: {action_tokens.shape}") # Detokenize print("\n[LeRobot] Detokenizing action tokens...") action_horizon = policy.config.n_action_steps action_dim = policy.config.output_features["action"].shape[0] try: continuous_actions = policy.detokenize_actions( action_tokens, action_horizon=action_horizon, action_dim=action_dim ) print(f"Continuous actions shape: {continuous_actions.shape}") print(f"Continuous actions mean: {continuous_actions.mean().item():.6f}") print(f"Continuous actions std: {continuous_actions.std().item():.6f}") print(f"Continuous actions first 5: {continuous_actions[0, 0, :5]}") print("\nDetokenization successful!") except Exception as e: print(f"\nDetokenization failed with error: {e}") print("This may be expected if the action tokens are not valid FAST tokens.") print("The test will pass as long as the sampling works correctly.")
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/pi0_fast/test_pi0_fast_original_vs_lerobot.py", "license": "Apache License 2.0", "lines": 416, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:examples/unitree_g1/holosoma_locomotion.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 argparse import json import logging import time import numpy as np import onnx import onnxruntime as ort from huggingface_hub import hf_hub_download from lerobot.robots.unitree_g1.config_unitree_g1 import UnitreeG1Config from lerobot.robots.unitree_g1.g1_utils import G1_29_JointIndex from lerobot.robots.unitree_g1.unitree_g1 import UnitreeG1 logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) DEFAULT_ANGLES = np.zeros(29, dtype=np.float32) DEFAULT_ANGLES[[0, 6]] = -0.312 # Hip pitch DEFAULT_ANGLES[[3, 9]] = 0.669 # Knee DEFAULT_ANGLES[[4, 10]] = -0.363 # Ankle pitch DEFAULT_ANGLES[[15, 22]] = 0.2 # Shoulder pitch DEFAULT_ANGLES[16] = 0.2 # Left shoulder roll DEFAULT_ANGLES[23] = -0.2 # Right shoulder roll DEFAULT_ANGLES[[18, 25]] = 0.6 # Elbow MISSING_JOINTS = [] G1_MODEL = "g1_23" # Or "g1_29" if G1_MODEL == "g1_23": MISSING_JOINTS = [12, 14, 20, 21, 27, 28] # Waist yaw/pitch, wrist pitch/yaw # Control parameters ACTION_SCALE = 0.25 CONTROL_DT = 0.02 # 50Hz ANG_VEL_SCALE = 0.25 DOF_POS_SCALE = 1.0 DOF_VEL_SCALE = 0.05 GAIT_PERIOD = 1.0 DEFAULT_HOLOSOMA_REPO_ID = "nepyope/holosoma_locomotion" # Policy filename mapping POLICY_FILES = { "fastsac": "fastsac_g1_29dof.onnx", "ppo": "ppo_g1_29dof.onnx", } def load_policy( repo_id: str = DEFAULT_HOLOSOMA_REPO_ID, policy_type: str = "fastsac", ) -> tuple[ort.InferenceSession, np.ndarray, np.ndarray]: """Load Holosoma locomotion policy and extract KP/KD from metadata. Args: repo_id: Hugging Face Hub repo ID policy_type: Either "fastsac" (default) or "ppo" Returns: (policy, kp, kd) tuple """ if policy_type not in POLICY_FILES: raise ValueError(f"Unknown policy type: {policy_type}. Choose from: {list(POLICY_FILES.keys())}") filename = POLICY_FILES[policy_type] logger.info(f"Loading {policy_type.upper()} policy from: {repo_id}/{filename}") policy_path = hf_hub_download(repo_id=repo_id, filename=filename) policy = ort.InferenceSession(policy_path) logger.info(f"Policy loaded: {policy.get_inputs()[0].shape} → {policy.get_outputs()[0].shape}") # Extract KP/KD from ONNX metadata model = onnx.load(policy_path) metadata = {prop.key: prop.value for prop in model.metadata_props} if "kp" not in metadata or "kd" not in metadata: raise ValueError("ONNX model must contain 'kp' and 'kd' in metadata") kp = np.array(json.loads(metadata["kp"]), dtype=np.float32) kd = np.array(json.loads(metadata["kd"]), dtype=np.float32) logger.info(f"Loaded KP/KD from ONNX ({len(kp)} joints)") return policy, kp, kd class HolosomaLocomotionController: """Holosoma whole-body locomotion controller for Unitree G1.""" def __init__(self, policy, robot, kp: np.ndarray, kd: np.ndarray): self.policy = policy self.robot = robot # Override robot's PD gains with policy gains self.robot.kp = kp self.robot.kd = kd self.cmd = np.zeros(3, dtype=np.float32) # Robot state self.qj = np.zeros(29, dtype=np.float32) self.dqj = np.zeros(29, dtype=np.float32) self.obs = np.zeros(100, dtype=np.float32) self.last_action = np.zeros(29, dtype=np.float32) # Gait phase self.phase = np.array([[0.0, np.pi]], dtype=np.float32) self.phase_dt = 2 * np.pi / ((1.0 / CONTROL_DT) * GAIT_PERIOD) self.is_standing = True def run_step(self): # Get current observation obs = self.robot.get_observation() if not obs: return # Get command from remote controller ly = obs["remote.ly"] if abs(obs["remote.ly"]) > 0.1 else 0.0 lx = obs["remote.lx"] if abs(obs["remote.lx"]) > 0.1 else 0.0 rx = obs["remote.rx"] if abs(obs["remote.rx"]) > 0.1 else 0.0 self.cmd[:] = [ly, -lx, -rx] # Get joint positions and velocities for motor in G1_29_JointIndex: name = motor.name idx = motor.value self.qj[idx] = obs[f"{name}.q"] self.dqj[idx] = obs[f"{name}.dq"] # Adapt observation for g1_23dof for idx in MISSING_JOINTS: self.qj[idx] = 0.0 self.dqj[idx] = 0.0 # Express IMU data in gravity frame of reference quat = [obs["imu.quat.w"], obs["imu.quat.x"], obs["imu.quat.y"], obs["imu.quat.z"]] ang_vel = np.array([obs["imu.gyro.x"], obs["imu.gyro.y"], obs["imu.gyro.z"]], dtype=np.float32) gravity = self.robot.get_gravity_orientation(quat) # Scale joint positions and velocities before policy inference qj_obs = (self.qj - DEFAULT_ANGLES) * DOF_POS_SCALE dqj_obs = self.dqj * DOF_VEL_SCALE ang_vel_s = ang_vel * ANG_VEL_SCALE # Update gait phase if np.linalg.norm(self.cmd[:2]) < 0.01 and abs(self.cmd[2]) < 0.01: self.phase[0, :] = np.pi self.is_standing = True elif self.is_standing: self.phase = np.array([[0.0, np.pi]], dtype=np.float32) self.is_standing = False else: self.phase = np.fmod(self.phase + self.phase_dt + np.pi, 2 * np.pi) - np.pi sin_ph = np.sin(self.phase[0]) cos_ph = np.cos(self.phase[0]) # Build observations self.obs[0:29] = self.last_action self.obs[29:32] = ang_vel_s self.obs[32] = self.cmd[2] self.obs[33:35] = self.cmd[:2] self.obs[35:37] = cos_ph self.obs[37:66] = qj_obs self.obs[66:95] = dqj_obs self.obs[95:98] = gravity self.obs[98:100] = sin_ph # Run policy inference ort_in = {self.policy.get_inputs()[0].name: self.obs.reshape(1, -1).astype(np.float32)} raw_action = self.policy.run(None, ort_in)[0].squeeze() action = np.clip(raw_action, -100.0, 100.0) self.last_action = action.copy() # Transform action back to target joint positions target = DEFAULT_ANGLES + action * ACTION_SCALE # Build action dict action_dict = {} for motor in G1_29_JointIndex: action_dict[f"{motor.name}.q"] = float(target[motor.value]) # Zero out missing joints for g1_23dof for joint_idx in MISSING_JOINTS: motor_name = G1_29_JointIndex(joint_idx).name action_dict[f"{motor_name}.q"] = 0.0 # Send action to robot self.robot.send_action(action_dict) def run(repo_id: str = DEFAULT_HOLOSOMA_REPO_ID, policy_type: str = "fastsac") -> None: """Main function to run the Holosoma locomotion controller. Args: repo_id: Hugging Face Hub repository ID for Holosoma policies. policy_type: Policy type to use ('fastsac' or 'ppo'). """ # Load policy and gains policy, kp, kd = load_policy(repo_id=repo_id, policy_type=policy_type) # Initialize robot config = UnitreeG1Config() robot = UnitreeG1(config) robot.connect() holosoma_controller = HolosomaLocomotionController(policy, robot, kp, kd) try: robot.reset(CONTROL_DT, DEFAULT_ANGLES) logger.info("Use joystick: LY=fwd/back, LX=left/right, RX=rotate") logger.info("Press Ctrl+C to stop") # Run step while not robot._shutdown_event.is_set(): start_time = time.time() holosoma_controller.run_step() elapsed = time.time() - start_time sleep_time = max(0, CONTROL_DT - elapsed) time.sleep(sleep_time) except KeyboardInterrupt: logger.info("Stopping locomotion...") finally: if robot.is_connected: robot.disconnect() logger.info("Done!") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Holosoma Locomotion Controller for Unitree G1") parser.add_argument( "--repo-id", type=str, default=DEFAULT_HOLOSOMA_REPO_ID, help=f"Hugging Face Hub repo ID for Holosoma policies (default: {DEFAULT_HOLOSOMA_REPO_ID})", ) parser.add_argument( "--policy", type=str, choices=["fastsac", "ppo"], default="fastsac", help="Policy type to use: 'fastsac' (default) or 'ppo'", ) args = parser.parse_args() run(repo_id=args.repo_id, policy_type=args.policy)
{ "repo_id": "huggingface/lerobot", "file_path": "examples/unitree_g1/holosoma_locomotion.py", "license": "Apache License 2.0", "lines": 210, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/wall_x/configuration_wall_x.py
# Copyright 2025 HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from lerobot.configs.policies import PreTrainedConfig from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature from lerobot.optim.optimizers import AdamWConfig from lerobot.optim.schedulers import CosineDecayWithWarmupSchedulerConfig from lerobot.utils.constants import ACTION, OBS_STATE @PreTrainedConfig.register_subclass("wall_x") @dataclass class WallXConfig(PreTrainedConfig): """ Configuration class for Wall-X policy. Wall-X is based on Qwen2.5-VL with action prediction capabilities using flow matching. It supports cross-embodiment robotic control through unified action representations. This config supports multi-modal learning with vision, language, and action data. """ # ==================== Input / Output Structure ==================== n_obs_steps: int = 1 chunk_size: int = 32 # action_horizon in wall-x n_action_steps: int = 32 # Action dimension - wall-x uses 20 max_action_dim: int = 20 max_state_dim: int = 20 # For proprioception normalization_mapping: dict[str, NormalizationMode] = field( default_factory=lambda: { "VISUAL": NormalizationMode.IDENTITY, "STATE": NormalizationMode.MEAN_STD, "ACTION": NormalizationMode.MEAN_STD, } ) # ==================== Action Prediction ==================== # Pretrained model paths pretrained_name_or_path: str = "x-square-robot/wall-oss-flow" # Tokenizer settings action_tokenizer_path: str | None = "lerobot/fast-action-tokenizer" # Action prediction mode: "diffusion" or "fast" prediction_mode: str = "diffusion" # Attention Implementation, options: "eager", "flash_attention_2", "sdpa" # NOTE: flash-attn==2.7.4.post1 is required for flash_attention_2 implementation attn_implementation: str = "eager" # ==================== Optimizer Presets ==================== optimizer_lr: float = 2e-5 optimizer_betas: tuple[float, float] = (0.9, 0.95) optimizer_eps: float = 1e-8 optimizer_weight_decay: float = 0.01 optimizer_grad_clip_norm: float = 1.0 scheduler_warmup_steps: int = 1000 scheduler_decay_steps: int = 100000 scheduler_decay_lr: float = 1e-6 def __post_init__(self): super().__post_init__() # Input validation if self.n_action_steps > self.chunk_size: raise ValueError( f"The chunk size is the upper bound for the number of action steps per model invocation. Got " f"{self.n_action_steps} for `n_action_steps` and {self.chunk_size} for `chunk_size`." ) if self.prediction_mode not in ["diffusion", "fast"]: raise ValueError(f"prediction_mode must be 'diffusion' or 'fast', got {self.prediction_mode}") # Assign use_fast_tokenizer based on prediction_mode if self.prediction_mode == "fast": self.use_fast_tokenizer = True elif self.prediction_mode == "diffusion": self.use_fast_tokenizer = False self.action_tokenizer_path = None # disable action tokenizer for diffusion mode else: raise ValueError(f"prediction_mode must be 'diffusion' or 'fast', got {self.prediction_mode}") def validate_features(self) -> None: """Validate and set up input/output features.""" image_features = [key for key, feat in self.input_features.items() if feat.type == FeatureType.VISUAL] if not image_features: raise ValueError( "Wall-X policy requires at least one visual input feature. " "No features of type FeatureType.VISUAL found in input_features." ) if OBS_STATE not in self.input_features: state_feature = PolicyFeature( type=FeatureType.STATE, shape=(self.max_state_dim,), # Padded to max_state_dim ) self.input_features[OBS_STATE] = state_feature else: state_shape = self.input_features[OBS_STATE].shape state_dim = state_shape[0] if state_shape else 0 if state_dim > self.max_state_dim: raise ValueError( f"State dimension {state_dim} exceeds max_state_dim {self.max_state_dim}. " f"Either reduce state dimension or increase max_state_dim in config." ) if ACTION not in self.output_features: action_feature = PolicyFeature( type=FeatureType.ACTION, shape=(self.max_action_dim,), # Padded to max_action_dim ) self.output_features[ACTION] = action_feature else: action_shape = self.output_features[ACTION].shape action_dim = action_shape[0] if action_shape else 0 if action_dim > self.max_action_dim: raise ValueError( f"Action dimension {action_dim} exceeds max_action_dim {self.max_action_dim}. " f"Either reduce action dimension or increase max_action_dim in config." ) def get_optimizer_preset(self) -> AdamWConfig: return AdamWConfig( lr=self.optimizer_lr, betas=self.optimizer_betas, eps=self.optimizer_eps, weight_decay=self.optimizer_weight_decay, grad_clip_norm=self.optimizer_grad_clip_norm, ) def get_scheduler_preset(self): return CosineDecayWithWarmupSchedulerConfig( peak_lr=self.optimizer_lr, decay_lr=self.scheduler_decay_lr, num_warmup_steps=self.scheduler_warmup_steps, num_decay_steps=self.scheduler_decay_steps, ) @property def observation_delta_indices(self) -> list: return None @property def action_delta_indices(self) -> list: return list(range(self.chunk_size)) @property def reward_delta_indices(self) -> None: return None
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/configuration_wall_x.py", "license": "Apache License 2.0", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/wall_x/constant.py
#!/usr/bin/env python # Copyright 2025 HuggingFace Inc. team. All rights reserved. # # 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. """ Wall-X Constants and Configuration Data. """ CAMERA_NAME_MAPPING = { "face_view": "front view", "left_wrist_view": "left wrist view", "right_wrist_view": "right wrist view", "move1_view": "move view", "move2_view": "move view", "wall_view": "wall view", "top_view": "top view", } RESOLUTION = 256 # Parameters for preprocessing MAX_PIXELS = 16384 * 28 * 28 MIN_PIXELS = 4 * 28 * 28 IMAGE_FACTOR = 28 PRIORITY_ORDER = None GENERATE_SUBTASK_RATIO = 0.0 MODEL_TYPE = "qwen2_5" TOKENIZER_MAX_LENGTH = 768
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/constant.py", "license": "Apache License 2.0", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/wall_x/modeling_wall_x.py
#!/usr/bin/env python # Copyright 2025 HuggingFace Inc. team. All rights reserved. # # 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. """ Wall-X: Cross-embodiment robotic control using Qwen2.5-VL with flow matching. [Paper](https://github.com/x2-robot/wall-x) Install wall-x extra dependencies: ```bash pip install -e ".[wall_x]" ``` Example of finetuning a wall-x model: ```bash lerobot-train \ --policy.type=wall_x \ --dataset.repo_id=your/dataset \ --batch_size=32 \ --steps=100000 ``` """ import math from collections import deque from os import PathLike from typing import Any import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from peft import LoraConfig, get_peft_model from PIL import Image from qwen_vl_utils.vision_process import smart_resize from torch import Tensor from torch.distributions import Beta from torch.nn import CrossEntropyLoss from torchdiffeq import odeint from transformers import AutoProcessor, BatchFeature from transformers.cache_utils import ( StaticCache, ) from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VLForConditionalGeneration, ) from transformers.utils import is_torchdynamo_compiling, logging from lerobot.policies.pretrained import PreTrainedPolicy from lerobot.policies.utils import populate_queues from lerobot.policies.wall_x.configuration_wall_x import WallXConfig from lerobot.policies.wall_x.constant import ( GENERATE_SUBTASK_RATIO, IMAGE_FACTOR, MAX_PIXELS, MIN_PIXELS, MODEL_TYPE, PRIORITY_ORDER, RESOLUTION, TOKENIZER_MAX_LENGTH, ) from lerobot.policies.wall_x.qwen_model.configuration_qwen2_5_vl import Qwen2_5_VLConfig from lerobot.policies.wall_x.qwen_model.qwen2_5_vl_moe import ( Qwen2_5_VisionTransformerPretrainedModel, Qwen2_5_VLACausalLMOutputWithPast, Qwen2_5_VLMoEModel, ) from lerobot.policies.wall_x.utils import ( get_wallx_normal_text, preprocesser_call, process_grounding_points, replace_action_token, ) from lerobot.utils.constants import ACTION, OBS_STATE logger = logging.get_logger(__name__) class SinusoidalPosEmb(nn.Module): """Sinusoidal positional embedding for diffusion timesteps.""" def __init__(self, dim): super().__init__() self.dim = dim def forward(self, x): device = x.device half_dim = self.dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=device) * -emb) emb = x[:, None] * emb[None, :] emb = torch.cat((emb.sin(), emb.cos()), dim=-1) return emb class ActionHead(nn.Module): """ Action prediction head with flow matching. Implements Beta-distributed noise scheduling and temporal embeddings for action sequence prediction. """ def __init__(self, config): super().__init__() self.config = config self.action_dim = sum(config.dof_config.values()) self.propri_dim = sum(config.agent_pos_config.values()) self.hidden_size = config.hidden_size # Beta distribution for noise scheduling self.beta_alpha = 1.5 self.beta_beta = 1.0 self.s = 0.999 # Sinusoidal timestep embedding self.time_embed = SinusoidalPosEmb(config.hidden_size) # Action embedding network # *2 for action + DOF mask concatenation self.w1 = nn.Linear(self.action_dim * 2, self.hidden_size, bias=False) self.w2 = nn.Linear(self.hidden_size * 2, self.hidden_size, bias=False) # *2 for action + time self.w3 = nn.Linear(self.hidden_size, self.hidden_size, bias=False) self.act_fn = nn.SiLU() # Project back to action space self.action_proj_back = nn.Linear(self.hidden_size, self.action_dim, bias=False) # Proprioception projection self.propri_proj = nn.Linear(self.propri_dim * 2, self.hidden_size, bias=False) def sample_time(self, batch_size, device): """Sample timesteps using Beta distribution (always in float32 for numerical stability).""" beta_dist = Beta( torch.tensor(self.beta_alpha, dtype=torch.float32, device=device), torch.tensor(self.beta_beta, dtype=torch.float32, device=device), ) sample = beta_dist.sample([batch_size]) time = (1 - sample) * self.s return time def forward(self, action_chunk, dof_mask=None): """ Process action sequences with noise injection for training. Args: action_chunk: Action sequences [batch, seq_len, action_dim] dof_mask: DOF mask [batch, seq_len, action_dim] Returns: tuple: (action_embeddings, flow_target) """ batch_size = action_chunk.shape[0] device = action_chunk.device weight_dtype = self.w1.weight.dtype # Sample time outside of autocast (Beta distribution needs float32) time = self.sample_time(batch_size, device) t = time.unsqueeze(-1).unsqueeze(-1) # Noise and flow computation in float32 noise = torch.randn_like(action_chunk, dtype=torch.float32) action_chunk_f32 = action_chunk.to(torch.float32) noisy_action = (1 - t) * noise + t * action_chunk_f32 flow = action_chunk_f32 - noise # Project noisy actions if dof_mask is not None: noisy_action = torch.cat([noisy_action, dof_mask.to(torch.float32)], dim=-1) # Convert to weight dtype for linear layers noisy_action = noisy_action.to(dtype=weight_dtype) action_embed = self.w1(noisy_action) # Generate time embeddings and combine time_embed = self.time_embed(time) time_embed = time_embed.unsqueeze(1).repeat(1, action_embed.shape[1], 1) time_embed = time_embed.to(dtype=weight_dtype) concat_embed = torch.cat([action_embed, time_embed], dim=-1) concat_embed = self.w2(concat_embed) embed = self.w3(self.act_fn(concat_embed)) return embed, flow def step(self, timestep, noisy_action, dof_mask=None): """Single denoising step for inference.""" weight_dtype = self.w1.weight.dtype if dof_mask is not None: noisy_action = torch.cat([noisy_action, dof_mask], dim=-1) noisy_action = noisy_action.to(dtype=weight_dtype) time_embed = self.time_embed(timestep) action_embed = self.w1(noisy_action) time_embed = time_embed.unsqueeze(1).repeat(1, action_embed.shape[1], 1) time_embed = time_embed.to(device=noisy_action.device, dtype=weight_dtype) concat_embed = torch.cat([action_embed, time_embed], dim=-1) concat_embed = self.w2(concat_embed) embed = self.w3(self.act_fn(concat_embed)) return embed def flow_loss(self, action_hidden_states, flow, dof_mask=None): """Compute flow matching loss (all computations in float32 for stability).""" # Ensure all inputs are float32 action_hidden_states = action_hidden_states.to(torch.float32) flow = flow.to(torch.float32) action_pred = self.action_proj_back(action_hidden_states) loss = F.mse_loss(action_pred, flow, reduction="none") if dof_mask is not None: dof_mask = dof_mask.reshape(-1, dof_mask.shape[-1]).to(torch.float32) loss = loss * dof_mask return loss def proprioception_proj(self, proprioception, dof_mask=None, use_history=False): """Project proprioceptive data to hidden space.""" # Ensure proper device and dtype alignment proprioception = proprioception.to(device=self.propri_proj.weight.device).to( dtype=self.propri_proj.weight.dtype ) if dof_mask is not None: # Concatenate proprioception with DOF mask # TODO: Use variable-based dimension checking for better flexibility if use_history: proprioception = torch.cat([proprioception, dof_mask], dim=-1) else: proprioception = torch.cat([proprioception, dof_mask], dim=-1) proprioception = proprioception.to(device=self.propri_proj.weight.device).to( dtype=self.propri_proj.weight.dtype ) return self.propri_proj(proprioception) class Qwen2_5_VLMoEForAction(Qwen2_5_VLForConditionalGeneration): """ Qwen2.5 Vision-Language Mixture of Experts model for action processing. This model extends the base Qwen2.5 VL model with action token processing capabilities and optional LoRA fine-tuning support. """ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} config_class = Qwen2_5_VLConfig _no_split_modules = ["Qwen2_5_VLDecoderLayer_with_MoE", "Qwen2_5_VLVisionBlock"] def init_weights(self): if getattr(self.model, "language_model", None) is not None: return super().init_weights() @classmethod def from_pretrained( cls, pretrained_name_or_path, config=None, action_tokenizer_path=None, attn_implementation: str = "eager", cache_dir: str | PathLike | None = None, force_download: bool = False, local_files_only: bool = False, token: str | bool | None = None, revision: str = "main", strict: bool = False, **kwargs: Any, ): """ Load model from pretrained model path. Args: pretrained_model_path (str): Model directory path containing model.safetensors file config_path (str, optional): Configuration file path, if None will look for qwen25_config.json in pretrained_model_path action_tokenizer_path (str, optional): Action tokenizer path, if None will load from default config attn_implementation (str, optional): Attention implementation, if None will load from default config **kwargs: Additional arguments Returns: Qwen2_5_VLMoEForAction: Loaded model instance """ if config is None: config = cls.config_class.from_pretrained( pretrained_name_or_path, cache_dir=cache_dir, force_download=force_download, local_files_only=local_files_only, token=token, revision=revision, strict=strict, **kwargs, ) if attn_implementation is not None: config._attn_implementation = attn_implementation processor = AutoProcessor.from_pretrained(pretrained_name_or_path, use_fast=True) if action_tokenizer_path is not None: action_tokenizer = AutoProcessor.from_pretrained(action_tokenizer_path, trust_remote_code=True) processor.action_processor = action_tokenizer else: action_tokenizer = None # add pad_token_id to config config.pad_token_id = processor.tokenizer.pad_token_id config.text_config.pad_token_id = processor.tokenizer.pad_token_id # Initialize model with configuration and processor model = cls(config, processor=processor, action_tokenizer=action_tokenizer, **kwargs) # Resize token embeddings to match processor tokenizer vocabulary size model.resize_token_embeddings(len(processor.tokenizer)) # Try to load the model.safetensors file print(f"Loading model from: {pretrained_name_or_path}") try: from transformers.utils import cached_file # Try safetensors first resolved_file = cached_file( pretrained_name_or_path, "model.safetensors", cache_dir=kwargs.get("cache_dir"), force_download=kwargs.get("force_download", False), resume_download=kwargs.get("resume_download"), proxies=kwargs.get("proxies"), token=kwargs.get("token"), revision=kwargs.get("revision"), local_files_only=kwargs.get("local_files_only", False), ) from safetensors.torch import load_file sd = load_file(resolved_file) print("✓ Loaded state dict from model.safetensors") except Exception as e: print(f"Could not load state dict from remote files: {e}") print("Returning model without loading pretrained weights") return model state_dict = {} # filter normalizer statistic params del_keys = [] for key in sd.keys(): if "action_preprocessor.normalizer" in key: del_keys.append(key) for key in del_keys: del sd[key] state_dict.update(sd) model.load_state_dict(state_dict, strict=False) return model def __init__( self, config, use_fast_tokenizer=False, processor=None, action_tokenizer=None, action_mapper=None, flow_loss_weight=1.0, ): """ Initialize the Qwen2.5 VLMoE model for action processing. Args: config: Model configuration use_fast_tokenizer (bool): Whether to use fast tokenizer processor: Text and image processor action_tokenizer: Action-specific tokenizer action_mapper: Action mapping utility flow_loss_weight (float): Weight for flow loss computation """ super().__init__(config) # Initialize vision transformer and language model components self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(config.vision_config) self.model = Qwen2_5_VLMoEModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize loss function without reduction for channel-wise loss computation self.loss_fct = CrossEntropyLoss(reduction="none") self.flow_loss_weight = flow_loss_weight self.use_fast_tokenizer = use_fast_tokenizer self.processor = processor self.action_tokenizer = action_tokenizer # Define action token IDs self.define_action_token_id() # Cache for rope deltas self.rope_deltas = None # Initialize action preprocessor self.action_preprocessor = ActionHead(config) # Apply LoRA if specified in configuration if hasattr(config, "use_lora") and config.use_lora: self.add_lora( r=config.lora_r, lora_alpha=config.lora_alpha, target_modules=config.lora_target_modules, lora_dropout=config.lora_dropout, ) # Initialize weights and apply final processing self.post_init() def to_bfloat16_for_selected_params(self): self.to(dtype=torch.bfloat16) params_to_keep_float32 = [] for name, param in self.named_parameters(): if "input_layernorm" in name or "post_attention_layernorm" in name or "model.norm" in name: params_to_keep_float32.append(name) if "action_preprocessor" in name: params_to_keep_float32.append(name) for name, param in self.named_parameters(): if name in params_to_keep_float32: param.data = param.data.to(torch.float32) def define_action_token_id(self): """ Define action token IDs based on tokenizer configuration. Creates mappings for fast action tokens, proprioception tokens, and general action tokens. """ # Create list of fast action token IDs fast_action_token_list = [] if self.use_fast_tokenizer: for i in range(self.processor.tokenizer.init_kwargs["action_token_vocab_size"]): action_token_id = self.processor.tokenizer.convert_tokens_to_ids(f"<|action_token_{i}|>") fast_action_token_list.append(action_token_id) # Get special action token IDs action_token_id = self.processor.tokenizer.convert_tokens_to_ids("<|action|>") propri_token_id = self.processor.tokenizer.convert_tokens_to_ids("<|propri|>") # Store action token ID mappings self.action_token_id_set = { "fast_action_token_list": fast_action_token_list, "propri_token_id": propri_token_id, "action_token_id": action_token_id, } def add_lora(self, r=8, lora_alpha=32, target_modules=["q_proj", "v_proj"], lora_dropout=0.1): """ Add LoRA (Low-Rank Adaptation) adapters to the model. Args: r (int): Rank of adaptation lora_alpha (int): LoRA scaling parameter target_modules (list): List of module names to apply LoRA to lora_dropout (float): Dropout probability for LoRA layers """ config = LoraConfig( r=r, lora_alpha=lora_alpha, target_modules=target_modules, lora_dropout=lora_dropout, bias="none", task_type="CAUSAL_LM", ) self.model = get_peft_model(self.model, config) # Print information about trainable parameters self.model.print_trainable_parameters() def get_input_embeddings(self): """Get input embeddings layer.""" return self.model.embed_tokens def set_input_embeddings(self, value): """Set input embeddings layer.""" self.model.embed_tokens = value def get_output_embeddings(self): """Get output embeddings layer.""" return self.lm_head def set_output_embeddings(self, new_embeddings): """Set output embeddings layer.""" self.lm_head = new_embeddings def set_decoder(self, decoder): """Set the decoder model.""" self.model = decoder def get_decoder(self): """Get the decoder model.""" return self.model def get_rope_index( self, input_ids: torch.LongTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, second_per_grid_ts: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Calculate 3D RoPE (Rotary Position Embedding) indices for vision and text tokens. This method computes position embeddings that account for the temporal, height, and width dimensions of vision tokens (images/videos) while maintaining standard 1D position embeddings for text tokens. For vision tokens, 3D position embeddings are calculated based on: - Temporal dimension: Time patches in videos - Height dimension: Vertical patches in images/video frames - Width dimension: Horizontal patches in images/video frames For text tokens, standard 1D position embeddings are used, continuing from the maximum vision position ID plus 1. Args: input_ids (torch.LongTensor, optional): Input token IDs of shape (batch_size, sequence_length) image_grid_thw (torch.LongTensor, optional): Image grid dimensions (num_images, 3) for [temporal, height, width] video_grid_thw (torch.LongTensor, optional): Video grid dimensions (num_videos, 3) for [temporal, height, width] second_per_grid_ts (torch.Tensor, optional): Time interval per temporal grid (num_videos,) attention_mask (torch.Tensor, optional): Attention mask (batch_size, sequence_length) Returns: tuple: - position_ids (torch.LongTensor): 3D position IDs of shape (3, batch_size, sequence_length) - mrope_position_deltas (torch.Tensor): Position deltas for mRoPE of shape (batch_size, 1) """ spatial_merge_size = self.config.vision_config.spatial_merge_size image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id mrope_position_deltas = [] if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): total_input_ids = input_ids if attention_mask is None: attention_mask = torch.ones_like(total_input_ids) # Initialize 3D position IDs tensor position_ids = torch.ones( 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device, ) image_index, video_index = 0, 0 attention_mask = attention_mask.to(total_input_ids.device) # Process each sequence in the batch for i, input_ids in enumerate(total_input_ids): input_ids = input_ids[attention_mask[i] == 1] image_nums, video_nums = 0, 0 # Find vision tokens and count images/videos vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums # Process each vision token (image or video) for _ in range(image_nums + video_nums): # Find next image or video token if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 # Determine if processing image or video token if ed_image < ed_video: # Process image token t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) second_per_grid_t = 0 image_index += 1 remain_images -= 1 ed = ed_image else: # Process video token t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) if second_per_grid_ts is not None: second_per_grid_t = second_per_grid_ts[video_index] else: second_per_grid_t = 1.0 video_index += 1 remain_videos -= 1 ed = ed_video # Calculate grid dimensions after spatial merging llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st # Add position IDs for text tokens before vision token st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) # Calculate 3D position embeddings for vision tokens range_tensor = torch.arange(llm_grid_t).view(-1, 1) expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w) # Calculate temporal position IDs with time scaling time_tensor = ( expanded_range * second_per_grid_t * self.config.vision_config.tokens_per_second ) time_tensor_long = time_tensor.long() t_index = time_tensor_long.flatten() # Calculate spatial position IDs h_index = ( torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() ) w_index = ( torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() ) # Add 3D position IDs for vision tokens llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w # Add position IDs for remaining text tokens if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) # Concatenate all position IDs for this sequence llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device) mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) return position_ids, mrope_position_deltas else: # Handle case without vision tokens - use standard 1D position embeddings if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] else: position_ids = ( torch.arange(input_ids.shape[1], device=input_ids.device) .view(1, 1, -1) .expand(3, input_ids.shape[0], -1) ) mrope_position_deltas = torch.zeros( [input_ids.shape[0], 1], device=input_ids.device, dtype=input_ids.dtype, ) return position_ids, mrope_position_deltas def train_step_forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, moe_token_types: torch.LongTensor | None = None, # MoE token type assignments labels: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, pixel_values: torch.Tensor | None = None, pixel_values_videos: torch.FloatTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, action_chunk: torch.FloatTensor | None = None, # Action trajectory chunks proprioception: torch.FloatTensor | None = None, # Joint position/orientation data rope_deltas: torch.LongTensor | None = None, cache_position: torch.LongTensor | None = None, second_per_grid_ts: torch.Tensor | None = None, dof_mask: torch.FloatTensor | None = None, agent_pos_mask: torch.FloatTensor | None = None, **kwargs, ) -> tuple | Qwen2_5_VLACausalLMOutputWithPast: """ Forward pass for training with multi-modal inputs including vision, text, and action data. This method handles the complete forward pass during training, processing various input modalities including images, videos, text, proprioceptive data, and action sequences. It computes losses for both language modeling and action prediction using flow matching. Args: input_ids (torch.LongTensor, optional): Input token IDs attention_mask (torch.Tensor, optional): Attention mask for input tokens position_ids (torch.LongTensor, optional): Position IDs for tokens past_key_values (List[torch.FloatTensor], optional): Cached key-value pairs for generation inputs_embeds (torch.FloatTensor, optional): Pre-computed input embeddings moe_token_types (torch.LongTensor, optional): Token type assignments for MoE routing labels (torch.LongTensor, optional): Target labels for loss computation use_cache (bool, optional): Whether to use key-value caching output_attentions (bool, optional): Whether to return attention weights output_hidden_states (bool, optional): Whether to return hidden states return_dict (bool, optional): Whether to return structured output pixel_values (torch.Tensor, optional): Image pixel values pixel_values_videos (torch.FloatTensor, optional): Video pixel values image_grid_thw (torch.LongTensor, optional): Image grid dimensions (temporal, height, width) video_grid_thw (torch.LongTensor, optional): Video grid dimensions (temporal, height, width) action_chunk (torch.FloatTensor, optional): Action trajectory data chunks proprioception (torch.FloatTensor, optional): Proprioceptive sensor data (joint positions, etc.) rope_deltas (torch.LongTensor, optional): RoPE position deltas cache_position (torch.LongTensor, optional): Cache position indices second_per_grid_ts (torch.Tensor, optional): Time interval per temporal grid dof_mask (torch.FloatTensor, optional): Degrees of freedom mask for action tokens agent_pos_mask (torch.FloatTensor, optional): Agent position mask for proprioceptive data **kwargs: Additional keyword arguments Returns: Union[Tuple, Qwen2_5_VLACausalLMOutputWithPast]: Model outputs including losses, logits, and auxiliary information, or tuple if return_dict=False """ batch_size, seq_length = input_ids.shape # Set output configuration from model config if not specified output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # Calculate RoPE position IDs if not provided # Note: Cannot calculate rope deltas with 4D attention mask. TODO: Fix this limitation if position_ids is None and (attention_mask is None or attention_mask.ndim == 2): # Calculate RoPE index once per generation in the pre-fill stage only if ( (cache_position is not None and cache_position[0] == 0) or self.rope_deltas is None or (past_key_values is None or past_key_values.get_seq_length() == 0) ): position_ids, rope_deltas = self.get_rope_index( input_ids, image_grid_thw, video_grid_thw, second_per_grid_ts, attention_mask, ) self.rope_deltas = rope_deltas # Use previously calculated rope deltas to get correct position IDs else: delta = ( (cache_position[0] + self.rope_deltas).to(self.device) if cache_position is not None else 0 ) position_ids = torch.arange(seq_length, device=self.device) position_ids = position_ids.view(1, -1).expand(batch_size, -1) if cache_position is not None: # otherwise `deltas` is an int `0` delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0) position_ids = position_ids.add(delta) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1) # Process input embeddings with multi-modal data if inputs_embeds is None: inputs_embeds = self.model.embed_tokens(input_ids) # Process image embeddings if pixel_values is not None: pixel_values = pixel_values.type(self.visual.dtype) image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) mask = input_ids == self.config.image_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) image_mask = mask_expanded.to(inputs_embeds.device) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) # Process video embeddings if pixel_values_videos is not None: pixel_values_videos = pixel_values_videos.type(self.visual.dtype) video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tokens = (input_ids == self.config.video_token_id).sum().item() n_video_features = video_embeds.shape[0] # Validate video token and feature count match if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) mask = input_ids == self.config.video_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) video_mask = mask_expanded.to(inputs_embeds.device) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) # Process proprioceptive data (joint positions, orientations, etc.) if proprioception is not None: proprioception = proprioception.to(inputs_embeds.device).to(inputs_embeds.dtype) agent_pos_mask = agent_pos_mask.to(inputs_embeds.device).to(inputs_embeds.dtype) proprioception = self.action_preprocessor.proprioception_proj( proprioception, agent_pos_mask, use_history=proprioception.shape[1] > 1, ) mask = input_ids == self.action_token_id_set["propri_token_id"] mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) proprioception_mask = mask_expanded.to(inputs_embeds.device) proprioception = proprioception.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(proprioception_mask, proprioception) elif self.training: # Dummy forward pass to ensure gradient registration in DDP # This handles cases where one process has proprioception data while another doesn't # Without this, DDP would hang waiting for a gradient that will never be computed dummy_input = torch.randn( 2, self.action_preprocessor.propri_dim * 2, device=inputs_embeds.device, ) dummy_forward = self.action_preprocessor.proprioception_proj(dummy_input) dummy_loss = sum(p.sum() for p in dummy_forward) inputs_embeds = inputs_embeds + 0 * dummy_loss # Process action chunk data if action_chunk is not None: action_chunk = action_chunk.to(inputs_embeds.device).to(inputs_embeds.dtype) dof_mask = dof_mask.to(inputs_embeds.device).to(inputs_embeds.dtype) noisy_action_emb, flow = self.action_preprocessor(action_chunk, dof_mask) mask = input_ids == self.action_token_id_set["action_token_id"] mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) action_mask = mask_expanded.to(inputs_embeds.device) noisy_action_emb = noisy_action_emb.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(action_mask, noisy_action_emb) if attention_mask is not None: attention_mask = attention_mask.to(inputs_embeds.device) # Forward pass through the main model outputs = self.model( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, moe_token_types=moe_token_types, # Pass token types for MoE routing use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] hidden_states = hidden_states.to(self.lm_head.weight.dtype) logits = self.lm_head(hidden_states) # Initialize loss computation variables loss = None cross_entropy_loss, flow_loss = None, None channel_loss_dict = None channel_loss_count_dict = None # Compute losses if labels are provided if labels is not None: loss = torch.tensor(0.0, device=hidden_states.device, dtype=torch.float32) # Compute standard cross-entropy loss for language modeling shift_logits = logits[..., :-1, :].contiguous().to(torch.float32) shift_labels = labels[..., 1:].contiguous() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model parallelism by moving labels to correct device shift_labels = shift_labels.to(shift_logits.device) non_ignored_mask = shift_labels != -100 _cross_entropy_loss = self.loss_fct(shift_logits, shift_labels) cross_entropy_loss = ( _cross_entropy_loss[non_ignored_mask].mean() if non_ignored_mask.any() else torch.tensor(0.0, device=shift_logits.device, dtype=torch.float32) ) # Add cross-entropy loss to total loss if valid if not torch.isnan(cross_entropy_loss): loss = loss + cross_entropy_loss.to(torch.float32) else: with torch.no_grad(): cross_entropy_loss.detach() if action_chunk is not None: action_mask = input_ids == self.action_token_id_set["action_token_id"] if action_mask.any(): action_hidden_states = hidden_states[action_mask].to(torch.float32) flow = flow.reshape(-1, flow.shape[-1]).to(torch.float32) _flow_loss = self.action_preprocessor.flow_loss(action_hidden_states, flow, dof_mask) if isinstance(_flow_loss, torch.Tensor): flow_loss = _flow_loss.mean() if loss is not None: loss = loss + self.flow_loss_weight * flow_loss.to(torch.float32) else: loss = self.flow_loss_weight * flow_loss.to(torch.float32) _flow_loss = _flow_loss.view(dof_mask.shape[0], dof_mask.shape[1], dof_mask.shape[2]) # Return outputs based on return_dict setting if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return Qwen2_5_VLACausalLMOutputWithPast( loss=loss, cross_entropy_loss=(cross_entropy_loss.clone() if cross_entropy_loss is not None else None), flow_loss=flow_loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=self.rope_deltas, channel_loss_dict=channel_loss_dict, channel_loss_count_dict=channel_loss_count_dict, ) def predict_action(self, predict_mode: str, **kwargs): """ Predict actions using specified prediction mode. Args: predict_mode (str): Prediction mode, either "fast" or "diffusion" **kwargs: Additional arguments passed to the predict method Returns: tuple: (predicted_action, ground_truth_action) where ground_truth_action may be None """ assert predict_mode in ["fast", "diffusion"] output = self.predict(predict_mode=predict_mode, **kwargs) return output["predict_action"], output.get("gt_action", None) @torch.no_grad() def predict( self, predict_mode: str, pred_horizon: int | None = None, action_dim: int | None = None, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, moe_token_types: torch.LongTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, pixel_values: torch.Tensor | None = None, pixel_values_videos: torch.FloatTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, action_chunk: torch.FloatTensor | None = None, proprioception: torch.FloatTensor | None = None, rope_deltas: torch.LongTensor | None = None, cache_position: torch.LongTensor | None = None, second_per_grid_ts: torch.Tensor | None = None, num_inference_timesteps: int | None = 10, dof_mask: torch.FloatTensor | None = None, agent_pos_mask: torch.FloatTensor | None = None, re_generate: bool = False, **kwargs, ): """ Multi-modal prediction method supporting text generation, fast action prediction, and diffusion-based action prediction. This method handles three prediction modes: 1. "text": Pure text generation using autoregressive decoding 2. "fast": Fast action prediction using discrete action tokens 3. "diffusion": Continuous action prediction using diffusion/flow matching Args: predict_mode (str): Prediction mode ("text", "fast", or "diffusion") pred_horizon (int, optional): Prediction horizon for action sequences action_dim (int, optional): Dimensionality of action space input_ids (torch.LongTensor, optional): Input token IDs attention_mask (torch.Tensor, optional): Attention mask for input tokens position_ids (torch.LongTensor, optional): Position IDs for tokens past_key_values (List[torch.FloatTensor], optional): Cached key-value pairs inputs_embeds (torch.FloatTensor, optional): Pre-computed input embeddings moe_token_types (torch.LongTensor, optional): Token type assignments for MoE routing labels (torch.LongTensor, optional): Target labels for evaluation use_cache (bool, optional): Whether to use key-value caching output_attentions (bool, optional): Whether to return attention weights output_hidden_states (bool, optional): Whether to return hidden states return_dict (bool, optional): Whether to return structured output pixel_values (torch.Tensor, optional): Image pixel values pixel_values_videos (torch.FloatTensor, optional): Video pixel values image_grid_thw (torch.LongTensor, optional): Image grid dimensions video_grid_thw (torch.LongTensor, optional): Video grid dimensions action_chunk (torch.FloatTensor, optional): Ground truth action sequences proprioception (torch.FloatTensor, optional): Proprioceptive sensor data rope_deltas (torch.LongTensor, optional): RoPE position deltas cache_position (torch.LongTensor, optional): Cache position indices second_per_grid_ts (torch.Tensor, optional): Time interval per temporal grid num_inference_timesteps (int, optional): Number of diffusion inference steps dof_mask (torch.FloatTensor, optional): Degrees of freedom mask agent_pos_mask (torch.FloatTensor, optional): Agent position mask re_generate (bool, optional): Whether to use sampling for regeneration **kwargs: Additional keyword arguments Returns: dict: Dictionary containing prediction results with keys like: - 'predict_action': Predicted action sequences - 'gt_action': Ground truth actions (if available) - 'input_text': Input text (for text/fast modes) - 'predict_output_text': Generated text (for text/fast modes) - 'gt_output_text': Ground truth text (for text/fast modes) """ batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0] # Text and fast modes require batch size 1 for autoregressive generation if predict_mode in ["text", "fast"]: assert batch_size == 1, "predict only support batch size 1 for ar generation" # Set output configuration from model config if not specified output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # Process input embeddings with multi-modal data if inputs_embeds is None: inputs_embeds = self.model.embed_tokens(input_ids) # Process image embeddings if pixel_values is not None: pixel_values = pixel_values.type(self.visual.dtype) image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) n_image_tokens = (input_ids == self.config.image_token_id).sum().item() n_image_features = image_embeds.shape[0] # Validate image token and feature count match if n_image_tokens != n_image_features: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) mask = input_ids == self.config.image_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) image_mask = mask_expanded.to(inputs_embeds.device) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) # Process video embeddings if pixel_values_videos is not None: pixel_values_videos = pixel_values_videos.type(self.visual.dtype) video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tokens = (input_ids == self.config.video_token_id).sum().item() n_video_features = video_embeds.shape[0] # Validate video token and feature count match if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) mask = input_ids == self.config.video_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) video_mask = mask_expanded.to(inputs_embeds.device) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) # Process proprioceptive data if proprioception is not None: proprioception = proprioception.to(inputs_embeds.device).to(inputs_embeds.dtype) agent_pos_mask = agent_pos_mask.to(inputs_embeds.device).to(inputs_embeds.dtype) proprio_embed = self.action_preprocessor.proprioception_proj( proprioception, agent_pos_mask, use_history=proprioception.shape[1] > 1, ) proprioception_mask = input_ids == self.action_token_id_set["propri_token_id"] proprio_embed = proprio_embed.to(torch.bfloat16) inputs_embeds[proprioception_mask] = proprio_embed.reshape(-1, inputs_embeds.shape[-1]) if attention_mask is not None: attention_mask = attention_mask.to(inputs_embeds.device) # Calculate RoPE position IDs if not provided # Note: Cannot calculate rope deltas with 4D attention mask. TODO: Fix this limitation if position_ids is None and (attention_mask is None or attention_mask.ndim == 2): # Calculate RoPE index once per generation in the pre-fill stage only if ( (cache_position is not None and cache_position[0] == 0) or self.rope_deltas is None or (past_key_values is None or past_key_values.get_seq_length() == 0) ): position_ids, rope_deltas = self.get_rope_index( input_ids, image_grid_thw, video_grid_thw, second_per_grid_ts, attention_mask, ) self.rope_deltas = rope_deltas # Use previously calculated rope deltas to get correct position IDs else: batch_size, seq_length, _ = inputs_embeds.shape delta = ( (cache_position[0] + self.rope_deltas).to(inputs_embeds.device) if cache_position is not None else 0 ) position_ids = torch.arange(seq_length, device=inputs_embeds.device) position_ids = position_ids.view(1, -1).expand(batch_size, -1) if cache_position is not None: # otherwise `deltas` is an int `0` delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0) position_ids = position_ids.add(delta) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1) # Prepare action chunk data if provided if action_chunk is not None: action_chunk = action_chunk.to(inputs_embeds.device).to(torch.float32) output = {} # Split input sequence for text and fast modes (not needed for diffusion) if predict_mode == "text" or predict_mode == "fast": # Look for generation prompt tokens: <|im_start|>assistant generation_prompt_ids = torch.tensor( [151644, 77091], device=input_ids.device, dtype=input_ids.dtype ) matches = (input_ids[0, :-1] == generation_prompt_ids[0]) & ( input_ids[0, 1:] == generation_prompt_ids[1] ) if matches.any(): split_pos = torch.nonzero(matches, as_tuple=True)[0][0].item() # Extract ground truth output tokens (including newline) gt_output_ids = input_ids[:, split_pos + 3 :] # Remove output part from input, keeping prompt input_ids = input_ids[:, : split_pos + 3] inputs_embeds = inputs_embeds[:, : split_pos + 3, :] if attention_mask is not None: attention_mask = attention_mask[:, : split_pos + 3] if labels is not None: labels = labels[:, split_pos + 3 :] else: raise ValueError( "input_ids does not contain the generation prompt tokens <|im_start|>assistant" ) # Decode input text for output input_text = self.processor.batch_decode( input_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True ) output["input_text"] = input_text # Handle text and fast prediction modes using autoregressive generation if predict_mode == "text" or predict_mode == "fast": # Initialize MoE token types for generation moe_token_types = torch.zeros_like(input_ids) batch = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "moe_token_types": moe_token_types, "image_grid_thw": image_grid_thw, "dof_mask": dof_mask, "agent_pos_mask": agent_pos_mask, "proprioception": proprioception, } # Generate output tokens predict_output_ids = self.generate( **batch, max_new_tokens=100, eos_token_id=[self.processor.tokenizer.eos_token_id], use_cache=True, pad_token_id=self.processor.tokenizer.pad_token_id, temperature=(1.0 if not re_generate else 0.7), # Higher temperature for regeneration do_sample=(False if not re_generate else True), # Enable sampling for regeneration ) # Decode generated and ground truth text gt_output_text = self.processor.batch_decode( gt_output_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True, ) predict_output_text = self.processor.batch_decode( predict_output_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True, ) output["gt_output_text"] = gt_output_text output["predict_output_text"] = predict_output_text # Convert tokens to actions for fast prediction mode if predict_mode == "fast": action_id = [] # Extract action tokens from generated sequence for token_id_i in predict_output_ids[0]: if token_id_i.item() >= self.processor.tokenizer.init_kwargs["action_token_start_index"]: action_id.append( token_id_i.item() - self.processor.tokenizer.init_kwargs["action_token_start_index"] ) predict_action = self.processor.action_processor.decode( [action_id], time_horizon=pred_horizon, action_dim=action_dim ) # Handle action decoding errors if np.sum(predict_action) == 0: print("Error in decoding action, predict_action is None") output["predict_action"] = None else: # Convert discrete tokens to continuous actions predict_action = torch.tensor(predict_action, device=self.device) dof_mask = dof_mask.to(self.device).to(pixel_values.dtype) # removed unnormalization step for now predict_action = predict_action[:, :, dof_mask[0, 0, :].bool()] output["predict_action"] = predict_action # Process ground truth actions if available if action_chunk is not None: # Apply DOF mask to get ground truth actions # removed unnormalization step for now action_chunk = action_chunk[:, :, dof_mask[0, 0, :].bool()] output["gt_action"] = action_chunk else: output["gt_action"] = None # Handle diffusion-based action prediction if predict_mode == "diffusion": # Initialize with random noise noisy_action = torch.randn( size=(batch_size, pred_horizon, action_dim), dtype=torch.float32, device=inputs_embeds.device, ) dof_mask = dof_mask.to(inputs_embeds.device).to(torch.float32) def step(timestep, noisy_action): """ Single denoising step for diffusion process. Args: timestep: Current diffusion timestep noisy_action: Current noisy action estimate Returns: torch.Tensor: Predicted clean action """ action_mask = input_ids == self.action_token_id_set["action_token_id"] assert action_mask.any(), "No action token found in input_ids" # Prepare timestep for batch processing timestep = timestep.unsqueeze(0).repeat(noisy_action.shape[0]) action_embed = self.action_preprocessor.step( timestep=timestep, noisy_action=noisy_action, dof_mask=dof_mask ) action_embed = action_embed.reshape(-1, inputs_embeds.shape[-1]) # Ensure action_embed has the correct dtype and device before assignment action_embed = action_embed.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device) # Create temporary copy of embeddings (clone preserves dtype) temp_inputs_embeds = inputs_embeds.clone() temp_inputs_embeds[action_mask] = action_embed # Forward pass through transformer transformer_outputs = self.model( input_ids=None, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=temp_inputs_embeds, moe_token_types=moe_token_types, use_cache=True, output_attentions=False, output_hidden_states=False, return_dict=True, ) # Extract action predictions from hidden states hidden_states = transformer_outputs.last_hidden_state action_mask = input_ids == self.action_token_id_set["action_token_id"] action_hidden_states = hidden_states[action_mask].to(torch.float32) pred = self.action_preprocessor.action_proj_back(action_hidden_states) return pred.reshape(batch_size, pred_horizon, action_dim) # Perform ODE integration for diffusion sampling times = torch.linspace( 0, 1, num_inference_timesteps + 1, device=inputs_embeds.device, dtype=torch.float32, ) action_trajectory = odeint(step, noisy_action, times, method="euler") # Extract final predicted action # Removed unnormalization step for now predict_action = action_trajectory[-1] output["predict_action"] = predict_action # Process ground truth actions if available # removed unnormalization step for now if action_chunk is not None: output["gt_action"] = action_chunk[:, :, dof_mask[0, 0, :].bool()] return output def forward(self, mode: str | None = None, predict_mode: str | None = "text", **kwargs): """ Main forward pass dispatcher for different execution modes. This method routes execution to appropriate forward functions based on the specified mode: - No mode (None): Training step with gradient disabled - 'predict': Prediction/inference mode - 'train': Training mode with gradients enabled - 'validate': Validation mode with gradients disabled Args: mode (str, optional): Execution mode. If None, defaults to training step without gradients predict_mode (str, optional): Prediction mode for 'predict' mode ("text", "fast", or "diffusion") **kwargs: Additional arguments passed to the selected forward function Returns: Model outputs appropriate for the selected mode Todo: - Add support for distinguishing multi-modal data types in prediction mode """ if not mode: with torch.no_grad(): return self.train_step_forward(**kwargs) elif mode == "predict": return self.predict(predict_mode=predict_mode, **kwargs) elif mode == "train": return self.train_step_forward(use_cache=False, **kwargs) elif mode == "validate": with torch.no_grad(): return self.train_step_forward(use_cache=False, **kwargs) else: raise NotImplementedError("invalid key") def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, moe_token_types=None, cache_position=None, position_ids=None, use_cache=True, pixel_values=None, pixel_values_videos=None, image_grid_thw=None, video_grid_thw=None, second_per_grid_ts=None, proprioception=None, dof_mask=None, agent_pos_mask=None, **kwargs, ): """ Prepare inputs for autoregressive generation with multi-modal support. This method handles input preparation for generation, including proper slicing of inputs based on cache position, MoE token type management, and multi-modal data handling. Vision inputs are selectively forwarded only when needed during generation. Args: input_ids: Input token IDs past_key_values: Cached key-value pairs from previous generation steps attention_mask: Attention mask for input tokens inputs_embeds: Pre-computed input embeddings moe_token_types: Token type assignments for MoE routing cache_position: Current cache position for generation position_ids: Position IDs for tokens use_cache: Whether to use key-value caching pixel_values: Image pixel values pixel_values_videos: Video pixel values image_grid_thw: Image grid dimensions video_grid_thw: Video grid dimensions second_per_grid_ts: Time interval per temporal grid proprioception: Proprioceptive sensor data dof_mask: Degrees of freedom mask agent_pos_mask: Agent position mask **kwargs: Additional arguments Returns: dict: Prepared model inputs for generation step Todo: - Test this function thoroughly with various input configurations Note: This is an overridden method that handles specific cases for multi-modal generation: - Slices input_ids through cache_position to keep only unprocessed tokens - Handles special cases for input_embeds, generation methods, and GPU synchronization - Manages vision inputs to avoid unnecessary forward passes """ # Initialize MoE token types if not provided if moe_token_types is None: moe_token_types = torch.zeros_like( input_ids ) # FIXME: Handle case when input_embeds is used instead else: # Ensure moe_token_types length matches input_ids if moe_token_types.shape[1] < input_ids.shape[1]: # Calculate required padding length pad_length = input_ids.shape[1] - moe_token_types.shape[1] # Create padding tensor with default token type (0) pad_tensor = torch.zeros( (moe_token_types.shape[0], pad_length), dtype=moe_token_types.dtype, device=moe_token_types.device, ) # Concatenate padding to existing moe_token_types moe_token_types = torch.cat([moe_token_types, pad_tensor], dim=1) # Handle input slicing based on cache state and special cases if past_key_values is not None: if inputs_embeds is not None and input_ids.shape[1] == 0: # Exception 4: input_embeds case inputs_embeds = inputs_embeds[:, -cache_position.shape[0] :] moe_token_types = moe_token_types[:, -cache_position.shape[0] :] elif inputs_embeds is not None or ( # Exception 1: input_embeds provided is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1] ): # Exception 3: GPU sync edge case input_ids = input_ids[:, -cache_position.shape[0] :] moe_token_types = moe_token_types[:, -cache_position.shape[0] :] elif input_ids.shape[1] != cache_position.shape[0]: # Default case (Exception 2 is no-op) cache_pos = cache_position.clone() input_ids = input_ids[:, cache_pos] moe_token_types = moe_token_types[:, cache_pos] # Skip vision inputs for continuation steps (not initial generation) if cache_position[0] != 0: pixel_values = None pixel_values_videos = None # Determine whether to use inputs_embeds or input_ids for this generation step if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]: model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None} else: model_inputs = {"input_ids": input_ids, "inputs_embeds": None} # Prepare 4D causal attention mask for static cache if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2: if model_inputs["inputs_embeds"] is not None: batch_size, sequence_length, _ = inputs_embeds.shape device = inputs_embeds.device else: batch_size, sequence_length = input_ids.shape device = input_ids.device attention_mask = self.model._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=past_key_values.get_max_cache_shape(), dtype=self.lm_head.weight.dtype, device=device, cache_position=cache_position, batch_size=batch_size, config=self.config, past_key_values=past_key_values, ) # Assemble all model inputs for generation model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "moe_token_types": moe_token_types, "use_cache": use_cache, "attention_mask": attention_mask, "pixel_values": pixel_values, "pixel_values_videos": pixel_values_videos, "image_grid_thw": image_grid_thw, "video_grid_thw": video_grid_thw, "cache_position": cache_position, "second_per_grid_ts": second_per_grid_ts, "proprioception": proprioception, "dof_mask": dof_mask, "agent_pos_mask": agent_pos_mask, } ) return model_inputs def _get_image_nums_and_video_nums( self, input_ids: torch.LongTensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Get the number of images and videos for each sample to calculate tensor separation lengths. These parameters are computed directly from input_ids rather than being passed through the processor to avoid unpredictable impacts from interface modifications. Args: input_ids (torch.LongTensor): Input token IDs of shape (batch_size, sequence_length) Returns: tuple: - image_nums (torch.LongTensor): Number of images per sample - video_nums (torch.LongTensor): Number of videos per sample """ image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id # Find vision start tokens and their following tokens vision_start_mask = input_ids == vision_start_token_id vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1) image_mask = input_ids == image_token_id video_mask = input_ids == video_token_id # Count images and videos following vision start tokens image_nums = torch.sum(vision_first_mask & image_mask, dim=1) video_nums = torch.sum(vision_first_mask & video_mask, dim=1) return image_nums, video_nums def _expand_inputs_for_generation( self, expand_size: int = 1, is_encoder_decoder: bool = False, input_ids: torch.LongTensor | None = None, **model_kwargs, ) -> tuple[torch.LongTensor, dict[str, Any]]: """ Expand inputs for generation with support for multi-modal tensors. This is an overridden method that supports expanding tensors without a standard batch size dimension, specifically for vision-related tensors: - pixel_values.shape[0] = sum(sequence_lengths for all image samples) - image_grid_thw.shape[0] = sum(num_images for all samples) - Similar patterns for video tensors Args: expand_size (int): Factor by which to expand inputs (for beam search, etc.) is_encoder_decoder (bool): Whether using encoder-decoder architecture input_ids (torch.LongTensor, optional): Input token IDs **model_kwargs: Additional model arguments to expand Returns: tuple: (expanded_input_ids, expanded_model_kwargs) """ if expand_size == 1: return input_ids, model_kwargs # Define keys for vision-related tensors that need special handling visual_keys = [ "pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts", ] def _expand_dict_for_generation_visual(dict_to_expand): """Expand vision-related tensors based on image/video counts per sample.""" image_grid_thw = model_kwargs.get("image_grid_thw", None) video_grid_thw = model_kwargs.get("video_grid_thw", None) image_nums, video_nums = self._get_image_nums_and_video_nums(input_ids) def _repeat_interleave_samples(x, lengths, repeat_times): """Split tensor by lengths and repeat each sample.""" samples = torch.split(x, lengths) repeat_args = [repeat_times] + [1] * (x.dim() - 1) result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0) return result for key in dict_to_expand: if key == "pixel_values": # Split images into samples and compute sequence lengths samples = torch.split(image_grid_thw, list(image_nums)) lengths = [torch.prod(sample, dim=1).sum() for sample in samples] dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "image_grid_thw": # Expand based on number of images per sample lengths = list(image_nums) dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "pixel_values_videos": # Split videos into samples and compute sequence lengths samples = torch.split(video_grid_thw, list(video_nums)) lengths = [torch.prod(sample, dim=1).sum() for sample in samples] dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "video_grid_thw": # Expand based on number of videos per sample lengths = list(video_nums) dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "second_per_grid_ts": # Handle list-type temporal grid data if not isinstance(dict_to_expand[key], list): raise TypeError( f"Expected value for key '{key}' to be a list, but got {type(dict_to_expand[key])} instead." ) tensor = torch.tensor(dict_to_expand[key]) lengths = list(video_nums) tensor = _repeat_interleave_samples(tensor, lengths=lengths, repeat_times=expand_size) dict_to_expand[key] = tensor.tolist() return dict_to_expand def _expand_dict_for_generation(dict_to_expand): """Expand standard tensors using repeat_interleave.""" for key in dict_to_expand: if ( key != "cache_position" and dict_to_expand[key] is not None and isinstance(dict_to_expand[key], torch.Tensor) and key not in visual_keys ): dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0) return dict_to_expand # Expand visual inputs only if input_ids is available for counting images/videos # If input_ids is unavailable, visual inputs won't be used, so no expansion needed if input_ids is not None and input_ids.numel() != 0: model_kwargs = _expand_dict_for_generation_visual(model_kwargs) # Expand input_ids using standard repeat_interleave if input_ids is not None: input_ids = input_ids.repeat_interleave(expand_size, dim=0) # Expand all other model arguments model_kwargs = _expand_dict_for_generation(model_kwargs) # Handle encoder-decoder specific expansion if is_encoder_decoder: if model_kwargs.get("encoder_outputs") is None: raise ValueError( "If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined." ) model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"]) return input_ids, model_kwargs class WallXPolicy(PreTrainedPolicy): """ Wall-X policy for cross-embodiment robotic control. Integrates Qwen2.5-VL vision-language model with action prediction using flow matching for continuous action spaces. """ config_class = WallXConfig name = "wall_x" def __init__(self, config: WallXConfig, **kwargs): super().__init__(config) config.validate_features() self.config = config # Initialize the wall-x model self.model = Qwen2_5_VLMoEForAction.from_pretrained( pretrained_name_or_path=config.pretrained_name_or_path, action_tokenizer_path=config.action_tokenizer_path, attn_implementation=config.attn_implementation, ) self.model.to(config.device) self.model.to_bfloat16_for_selected_params() self.reset() def reset(self): """Reset action queue.""" self._queues = { ACTION: deque(maxlen=self.config.n_action_steps), } def get_optim_params(self): """Get parameters for optimization.""" return self.parameters() def preprocess_inputs( self, batch: dict[str, Any], ) -> BatchFeature: """ Convert a batch of LeRobot dataset items to Wall-X model input format. This processes a batched dictionary where tensors have batch dimension first. Args: batch: Dictionary with batched tensors: - "observation.state": (batch_size, state_dim) or (batch_size, n_obs_steps, state_dim) - "action": (batch_size, chunk_size, action_dim) - "observation.images.<key>": (batch_size, C, H, W) - "task": List[str] of length batch_size Returns: BatchFeature containing batched model inputs """ use_fast_tokenizer = self.config.use_fast_tokenizer # Get batch size from state tensor batch_size = batch[OBS_STATE].shape[0] # ==================== PROCESS ALL SAMPLES ==================== all_image_inputs = [] all_texts = [] # Find image keys in batch img_keys = [key for key in self.config.image_features if key in batch] for i in range(batch_size): # Vision preprocessing per sample processed_frames = [] orig_height, orig_width = None, None resized_height, resized_width = None, None for key in img_keys: current_obs = batch[key][i].clone() # (C, H, W) if current_obs.dim() == 3: current_obs = current_obs.permute(1, 2, 0) # (H, W, C) img_pil = Image.fromarray((current_obs * 255).to(torch.uint8).cpu().numpy()) orig_width, orig_height = img_pil.size target_size = RESOLUTION if target_size != -1: if orig_width > orig_height: new_width = target_size new_height = int(target_size * orig_height / orig_width) else: new_height = target_size new_width = int(target_size * orig_width / orig_height) img_pil = img_pil.resize((new_width, new_height)) current_width, current_height = img_pil.size resized_height, resized_width = smart_resize( current_height, current_width, factor=IMAGE_FACTOR, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS, ) resized_img = img_pil.resize((resized_width, resized_height)) processed_frames.append(resized_img) all_image_inputs.append(processed_frames) # Text preprocessing task_text = batch["task"][i] if isinstance(batch["task"], list) else batch["task"] instruction_info = {"instruction": task_text} frame_index = batch["frame_index"][i] if "frame_index" in batch else 0 complete_text, _ = get_wallx_normal_text( instruction_info, self.config.chunk_size, frame_index, PRIORITY_ORDER, img_keys, generate_subtask_ratio=GENERATE_SUBTASK_RATIO, ) text = process_grounding_points( complete_text, orig_height, orig_width, resized_height, resized_width, MODEL_TYPE ) all_texts.append(text) # ==================== PROCESS AGENT POS ==================== agent_pos = batch[OBS_STATE] # (batch_size, state_dim) if agent_pos.dim() == 2: agent_pos = agent_pos.unsqueeze(1) # (batch_size, 1, state_dim) agent_pos_mask = (~torch.isnan(agent_pos)).float() agent_pos = agent_pos.nan_to_num(nan=0.0) if agent_pos.shape[-1] != 20: pad_size = 20 - agent_pos.shape[-1] agent_pos = torch.cat( [ agent_pos, torch.zeros(agent_pos.shape[0], agent_pos.shape[1], pad_size, device=agent_pos.device), ], dim=-1, ) agent_pos_mask = torch.cat( [ agent_pos_mask, torch.zeros( agent_pos_mask.shape[0], agent_pos_mask.shape[1], pad_size, device=agent_pos_mask.device, ), ], dim=-1, ) # ==================== PROCESS ACTIONS ==================== action = batch.get(ACTION) # (batch_size, chunk_size, action_dim) if action is not None: if action.dim() == 2: action = action.unsqueeze(1) dof_mask = (~torch.isnan(action)).float() action = action.nan_to_num(nan=0.0) if action.shape[-1] != 20: pad_size = 20 - action.shape[-1] action = torch.cat( [action, torch.zeros(action.shape[0], action.shape[1], pad_size, device=action.device)], dim=-1, ) dof_mask = torch.cat( [ dof_mask, torch.zeros(dof_mask.shape[0], dof_mask.shape[1], pad_size, device=dof_mask.device), ], dim=-1, ) else: action_dim = self.config.output_features[ACTION].shape[0] dof_mask = torch.cat( [ torch.ones( batch_size, self.config.chunk_size, action_dim, device=batch[OBS_STATE].device ), torch.zeros( batch_size, self.config.chunk_size, 20 - action_dim, device=batch[OBS_STATE].device ), ], dim=-1, ) # ==================== ACTION TOKEN REPLACEMENT ==================== all_texts = replace_action_token( all_texts, action, self.model.action_tokenizer if use_fast_tokenizer else None, dof_mask, ) # ==================== TOKENIZATION ==================== inputs = preprocesser_call( processor=self.model.processor, text=all_texts, images=all_image_inputs, videos=None, padding=True, truncation=True, return_tensors="pt", max_length=TOKENIZER_MAX_LENGTH, ) # ==================== ADDITIONAL INPUTS ==================== action_token_id = self.model.processor.tokenizer.convert_tokens_to_ids("<|action|>") moe_token_types = inputs.input_ids == action_token_id inputs["proprioception"] = agent_pos inputs["agent_pos_mask"] = agent_pos_mask inputs["action_chunk"] = action inputs["dof_mask"] = dof_mask inputs["moe_token_types"] = moe_token_types inputs["frame_index"] = ( batch["frame_index"] if "frame_index" in batch else torch.zeros(batch_size, device=batch[OBS_STATE].device) ) # Move all tensors to the correct device device = self.config.device for key, value in inputs.items(): if isinstance(value, torch.Tensor): inputs[key] = value.to(device) return inputs def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict]: """ Training forward pass using Qwen2_5_VLMoEForAction. Args: batch: Dictionary containing preprocessed inputs from preprocess_inputs() Expected keys: input_ids, attention_mask, pixel_values, image_grid_thw, proprioception, agent_pos_mask, action_chunk, dof_mask, moe_token_types, etc. Returns: tuple: (loss, loss_dict) """ batch = self.preprocess_inputs( batch, ) # Call the underlying model's forward with mode="train" outputs = self.model(**batch, mode="train") # Extract losses from output loss = outputs.loss loss_dict = { "loss": loss.item() if loss is not None else 0.0, } if outputs.flow_loss is not None: loss_dict["flow_loss"] = outputs.flow_loss.item() if outputs.cross_entropy_loss is not None: loss_dict["cross_entropy_loss"] = outputs.cross_entropy_loss.item() # Add channel losses if available if outputs.channel_loss_dict is not None: for key, value in outputs.channel_loss_dict.items(): if isinstance(value, torch.Tensor): loss_dict[f"channel_{key}"] = value.item() return loss, loss_dict @torch.no_grad() def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor: """Predict action chunk for evaluation.""" self.eval() self._queues = populate_queues(self._queues, batch, exclude_keys=[ACTION]) batch = self.preprocess_inputs( batch, ) if self.config.prediction_mode == "diffusion": output = self.model( **batch, action_dim=self.config.max_action_dim, pred_horizon=self.config.chunk_size, mode="predict", predict_mode="diffusion", ) elif self.config.prediction_mode == "fast": output = self.model( **batch, action_dim=self.config.output_features[ACTION].shape[0], pred_horizon=self.config.chunk_size, mode="predict", predict_mode="fast", ) else: raise NotImplementedError(f"Prediction mode {self.config.prediction_mode} not implemented") # Extract action tensor from output dictionary actions = output["predict_action"] # Unpad actions to actual action dimension action_dim = self.config.output_features[ACTION].shape[0] actions = actions[:, :, :action_dim] return actions @torch.no_grad() def select_action(self, batch: dict[str, Tensor]) -> Tensor: """Select single action for environment execution.""" self.eval() self._queues = populate_queues(self._queues, batch, exclude_keys=[ACTION]) # Use action queue if len(self._queues[ACTION]) == 0: actions = self.predict_action_chunk(batch) self._queues[ACTION].extend(actions.transpose(0, 1)[: self.config.n_action_steps]) return self._queues[ACTION].popleft()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/modeling_wall_x.py", "license": "Apache License 2.0", "lines": 1739, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/wall_x/processor_wall_x.py
#!/usr/bin/env python # Copyright 2025 HuggingFace Inc. team. All rights reserved. # # 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 Any import torch from lerobot.configs.types import PipelineFeatureType, PolicyFeature from lerobot.policies.wall_x.configuration_wall_x import WallXConfig from lerobot.processor import ( AddBatchDimensionProcessorStep, ComplementaryDataProcessorStep, DeviceProcessorStep, NormalizerProcessorStep, PolicyAction, PolicyProcessorPipeline, ProcessorStepRegistry, RenameObservationsProcessorStep, UnnormalizerProcessorStep, ) from lerobot.processor.converters import policy_action_to_transition, transition_to_policy_action from lerobot.utils.constants import POLICY_POSTPROCESSOR_DEFAULT_NAME, POLICY_PREPROCESSOR_DEFAULT_NAME def make_wall_x_pre_post_processors( config: WallXConfig, dataset_stats: dict[str, dict[str, torch.Tensor]] | None = None, ) -> tuple[ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """ Constructs pre-processor and post-processor pipelines for the Wall-X policy. The pre-processing pipeline prepares input data for the model by: 1. Renaming features to match pretrained configurations 2. Adding a batch dimension 4. Normalizing input and output features based on dataset statistics 5. Moving all data to the specified device The post-processing pipeline handles the model's output by: 1. Unnormalizing the output actions to their original scale 2. Moving data to the CPU Args: config: The configuration object for the Wall-X policy dataset_stats: A dictionary of statistics for normalization Returns: A tuple containing the configured pre-processor and post-processor pipelines """ input_steps = [ RenameObservationsProcessorStep(rename_map={}), AddBatchDimensionProcessorStep(), WallXTaskProcessor(), # Process task description NormalizerProcessorStep( features={**config.input_features, **config.output_features}, norm_map=config.normalization_mapping, stats=dataset_stats, ), DeviceProcessorStep(device=config.device), ] output_steps = [ UnnormalizerProcessorStep( features=config.output_features, norm_map=config.normalization_mapping, stats=dataset_stats ), DeviceProcessorStep(device="cpu"), ] return ( PolicyProcessorPipeline[dict[str, Any], dict[str, Any]]( steps=input_steps, name=POLICY_PREPROCESSOR_DEFAULT_NAME, ), PolicyProcessorPipeline[PolicyAction, PolicyAction]( steps=output_steps, name=POLICY_POSTPROCESSOR_DEFAULT_NAME, to_transition=policy_action_to_transition, to_output=transition_to_policy_action, ), ) @ProcessorStepRegistry.register(name="wall_x_task_processor") class WallXTaskProcessor(ComplementaryDataProcessorStep): """ A processor step that ensures the task description is properly formatted for Wall-X. This step handles task preprocessing similar to Qwen-VL requirements. """ def complementary_data(self, complementary_data): if "task" not in complementary_data: return complementary_data task = complementary_data["task"] if task is None: # Provide default task if none specified complementary_data["task"] = "Execute the robot action." return complementary_data new_complementary_data = dict(complementary_data) # Handle both string and list of strings if isinstance(task, str): # Single string: ensure proper formatting if not task.endswith("."): new_complementary_data["task"] = f"{task}." elif isinstance(task, list) and all(isinstance(t, str) for t in task): # List of strings: format each new_complementary_data["task"] = [t if t.endswith(".") else f"{t}." for t in task] return new_complementary_data def transform_features( self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]] ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]: return features
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/processor_wall_x.py", "license": "Apache License 2.0", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/wall_x/qwen_model/configuration_qwen2_5_vl.py
from transformers.configuration_utils import PretrainedConfig from transformers.modeling_rope_utils import rope_config_validation class Qwen2_5_VLVisionConfig(PretrainedConfig): model_type = "qwen2_5_vl" base_config_key = "vision_config" def __init__( self, depth=32, hidden_size=3584, hidden_act="silu", intermediate_size=3420, num_heads=16, in_channels=3, patch_size=14, spatial_merge_size=2, temporal_patch_size=2, tokens_per_second=4, window_size=112, out_hidden_size=3584, fullatt_block_indexes=[7, 15, 23, 31], initializer_range=0.02, **kwargs, ): super().__init__(**kwargs) self.depth = depth self.hidden_size = hidden_size self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.num_heads = num_heads self.in_channels = in_channels self.patch_size = patch_size self.spatial_merge_size = spatial_merge_size self.temporal_patch_size = temporal_patch_size self.tokens_per_second = tokens_per_second self.window_size = window_size self.fullatt_block_indexes = fullatt_block_indexes self.out_hidden_size = out_hidden_size self.initializer_range = initializer_range class Qwen2_5_VLConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen2_5_VLModel`]. It is used to instantiate a Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of Qwen2-VL-7B-Instruct [Qwen/Qwen2-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct). Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 152064): Vocabulary size of the Qwen2_5_VL model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Qwen2_5_VLModel`] hidden_size (`int`, *optional*, defaults to 8192): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 29568): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 80): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 64): Number of attention heads for each attention layer in the Transformer encoder. num_key_value_heads (`int`, *optional*, defaults to 8): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 32768): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. rope_theta (`float`, *optional*, defaults to 1000000.0): The base period of the RoPE embeddings. use_sliding_window (`bool`, *optional*, defaults to `False`): Whether to use sliding window attention. sliding_window (`int`, *optional*, defaults to 4096): Sliding window attention (SWA) window size. If not specified, will default to `4096`. max_window_layers (`int`, *optional*, defaults to 80): The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. vision_config (`Dict`, *optional*): The config for the visual encoder initialization. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`List[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`List[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE ```python >>> from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLConfig >>> # Initializing a Qwen2_5_VL style configuration >>> configuration = Qwen2_5_VLConfig() >>> # Initializing a model from the Qwen2-VL-7B style configuration >>> model = Qwen2_5_VLForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "qwen2_5_vl" sub_configs = {"vision_config": Qwen2_5_VLVisionConfig} keys_to_ignore_at_inference = ["past_key_values"] # Default tensor parallel plan for base model `Qwen2_5_VL` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), } def __init__( self, vocab_size=152064, hidden_size=8192, intermediate_size=29568, num_hidden_layers=80, num_attention_heads=64, num_key_value_heads=8, hidden_act="silu", max_position_embeddings=32768, initializer_range=0.02, rms_norm_eps=1e-05, use_cache=True, tie_word_embeddings=False, rope_theta=1000000.0, use_sliding_window=False, sliding_window=4096, max_window_layers=80, attention_dropout=0.0, vision_config=None, rope_scaling=None, num_experts=4, experts=None, dof_config=None, noise_scheduler=None, dim_inputs=(1536, 1536), attention_moe=False, mlp_moe=False, **kwargs, ): if isinstance(vision_config, dict): self.vision_config = self.sub_configs["vision_config"](**vision_config) elif vision_config is None: self.vision_config = self.sub_configs["vision_config"]() self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window self.max_window_layers = max_window_layers self.layer_types = ["dense"] * num_hidden_layers # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.attention_dropout = attention_dropout self.rope_scaling = rope_scaling self.num_experts = num_experts self.experts = experts self.dof_config = dof_config self.noise_scheduler = noise_scheduler self.dim_inputs = tuple(dim_inputs) self.attention_moe = attention_moe self.mlp_moe = mlp_moe if self.rope_scaling is not None and "type" in self.rope_scaling: if self.rope_scaling["type"] == "mrope": self.rope_scaling["type"] = "default" self.rope_scaling["rope_type"] = self.rope_scaling["type"] rope_config_validation(self, ignore_keys={"mrope_section"}) super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs) @property def text_config(self): return self __all__ = ["Qwen2_5_VLConfig"]
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/qwen_model/configuration_qwen2_5_vl.py", "license": "Apache License 2.0", "lines": 226, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
huggingface/lerobot:src/lerobot/policies/wall_x/qwen_model/qwen2_5_vl_moe.py
import math from dataclasses import dataclass from typing import Any import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from transformers import AutoConfig from transformers.activations import ACT2FN from transformers.cache_utils import ( Cache, DynamicCache, StaticCache, ) from transformers.generation import GenerationMixin from transformers.modeling_attn_mask_utils import AttentionMaskConverter from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS from transformers.modeling_utils import PreTrainedModel from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, is_torchdynamo_compiling, logging, replace_return_docstrings, ) from .configuration_qwen2_5_vl import Qwen2_5_VLConfig, Qwen2_5_VLVisionConfig # TODO(Steven): SlidingWindowCache was removed in transformers v5. Define a placeholder so isinstance checks # always return False (which is the correct behavior when no sliding window cache is in use). class _SlidingWindowCachePlaceholder: pass SlidingWindowCache = _SlidingWindowCachePlaceholder if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.layers.rotary import apply_rotary_emb else: flash_attn_varlen_func = None apply_rotary_emb = None flash_attn_func = None if is_flash_attn_2_available(): pass else: flash_attn_varlen_func = None logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "Qwen2_5_VLConfig" class Qwen2_5_VLMLP(nn.Module): def __init__(self, config, bias: bool = False): super().__init__() self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=bias) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=bias) self.act_fn = ACT2FN[config.hidden_act] def forward(self, hidden_state): return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state)) class Qwen2_5_VisionPatchEmbed(nn.Module): def __init__( self, patch_size: int = 14, temporal_patch_size: int = 2, in_channels: int = 3, embed_dim: int = 1152, ) -> None: super().__init__() self.patch_size = patch_size self.temporal_patch_size = temporal_patch_size self.in_channels = in_channels self.embed_dim = embed_dim kernel_size = [temporal_patch_size, patch_size, patch_size] self.proj = nn.Conv3d( in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False, ) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: target_dtype = self.proj.weight.dtype hidden_states = hidden_states.view( -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size, ) hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim) return hidden_states class Qwen2_5_VisionRotaryEmbedding(nn.Module): def __init__(self, dim: int, theta: float = 10000.0) -> None: super().__init__() inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) def forward(self, seqlen: int) -> torch.Tensor: seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype) freqs = torch.outer(seq, self.inv_freq) return freqs class Qwen2RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Qwen2RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" class Qwen2_5_VLPatchMerger(nn.Module): def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None: super().__init__() self.hidden_size = context_dim * (spatial_merge_size**2) self.ln_q = Qwen2RMSNorm(context_dim, eps=1e-6) self.mlp = nn.Sequential( nn.Linear(self.hidden_size, self.hidden_size), nn.GELU(), nn.Linear(self.hidden_size, dim), ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.mlp(self.ln_q(x).view(-1, self.hidden_size)) return x def apply_rotary_pos_emb_flashatt( q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: cos = cos.chunk(2, dim=-1)[0].contiguous() sin = sin.chunk(2, dim=-1)[0].contiguous() q_embed = apply_rotary_emb(q.float(), cos.float(), sin.float()).type_as(q) k_embed = apply_rotary_emb(k.float(), cos.float(), sin.float()).type_as(k) return q_embed, k_embed class Qwen2_5_VLVisionFlashAttention2(nn.Module): def __init__(self, dim: int, num_heads: int = 16) -> None: super().__init__() self.num_heads = num_heads self.qkv = nn.Linear(dim, dim * 3, bias=True) self.proj = nn.Linear(dim, dim) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int | None = None, rotary_pos_emb: torch.Tensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> torch.Tensor: seq_length = hidden_states.shape[0] q, k, v = ( self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) ) if position_embeddings is None: logger.warning_once( "The attention layers in this model are transitioning from computing the RoPE embeddings internally " "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed " "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be " "removed and `position_embeddings` will be mandatory." ) emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) cos = emb.cos().float() sin = emb.sin().float() else: cos, sin = position_embeddings q, k = apply_rotary_pos_emb_flashatt(q.unsqueeze(0), k.unsqueeze(0), cos, sin) q = q.squeeze(0) k = k.squeeze(0) if max_seqlen is None: max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item() attn_output = flash_attn_varlen_func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen).reshape( seq_length, -1 ) attn_output = self.proj(attn_output) return attn_output def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb_vision( q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: orig_q_dtype = q.dtype orig_k_dtype = k.dtype q, k = q.float(), k.float() cos, sin = cos.unsqueeze(-2), sin.unsqueeze(-2) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) q_embed = q_embed.to(orig_q_dtype) k_embed = k_embed.to(orig_k_dtype) return q_embed, k_embed class Qwen2_5_VLVisionAttention(nn.Module): def __init__(self, dim: int, num_heads: int = 16) -> None: super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.qkv = nn.Linear(dim, dim * 3, bias=True) self.proj = nn.Linear(dim, dim) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int | None = None, rotary_pos_emb: torch.Tensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> torch.Tensor: seq_length = hidden_states.shape[0] q, k, v = ( self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) ) if position_embeddings is None: logger.warning_once( "The attention layers in this model are transitioning from computing the RoPE embeddings internally " "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed " "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be " "removed and `position_embeddings` will be mandatory." ) emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) cos = emb.cos().float() sin = emb.sin().float() else: cos, sin = position_embeddings q, k = apply_rotary_pos_emb_vision(q, k, cos, sin) attention_mask = torch.full( [1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype, ) for i in range(1, len(cu_seqlens)): attention_mask[ ..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i], ] = 0 q = q.transpose(0, 1) k = k.transpose(0, 1) v = v.transpose(0, 1) attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim) attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype) attn_output = torch.matmul(attn_weights, v) attn_output = attn_output.transpose(0, 1) attn_output = attn_output.reshape(seq_length, -1) attn_output = self.proj(attn_output) return attn_output class Qwen2_5_VLVisionSdpaAttention(nn.Module): def __init__(self, dim: int, num_heads: int = 16) -> None: super().__init__() self.num_heads = num_heads self.qkv = nn.Linear(dim, dim * 3, bias=True) self.proj = nn.Linear(dim, dim) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int | None = None, rotary_pos_emb: torch.Tensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> torch.Tensor: seq_length = hidden_states.shape[0] q, k, v = ( self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) ) if position_embeddings is None: logger.warning_once( "The attention layers in this model are transitioning from computing the RoPE embeddings internally " "through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed " "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be " "removed and `position_embeddings` will be mandatory." ) emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) cos = emb.cos().float() sin = emb.sin().float() else: cos, sin = position_embeddings q, k = apply_rotary_pos_emb_vision(q, k, cos, sin) attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool) for i in range(1, len(cu_seqlens)): attention_mask[ ..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i], ] = True q = q.transpose(0, 1) k = k.transpose(0, 1) v = v.transpose(0, 1) attn_output = F.scaled_dot_product_attention(q, k, v, attention_mask, dropout_p=0.0) attn_output = attn_output.transpose(0, 1) attn_output = attn_output.reshape(seq_length, -1) attn_output = self.proj(attn_output) return attn_output QWEN2_5_VL_VISION_ATTENTION_CLASSES = { "eager": Qwen2_5_VLVisionAttention, "flash_attention_2": Qwen2_5_VLVisionFlashAttention2, "sdpa": Qwen2_5_VLVisionSdpaAttention, } class Qwen2_5_VLVisionBlock(nn.Module): def __init__(self, config, attn_implementation: str = "sdpa") -> None: super().__init__() self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6) self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6) self.attn = QWEN2_5_VL_VISION_ATTENTION_CLASSES[attn_implementation]( config.hidden_size, num_heads=config.num_heads ) self.mlp = Qwen2_5_VLMLP(config, bias=True) def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int | None = None, rotary_pos_emb: torch.Tensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, ) -> torch.Tensor: hidden_states = hidden_states + self.attn( self.norm1(hidden_states), cu_seqlens=cu_seqlens, max_seqlen=max_seqlen, rotary_pos_emb=rotary_pos_emb, position_embeddings=position_embeddings, ) hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) return hidden_states Qwen2_5_VL_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`Qwen2_5_VLConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ @add_start_docstrings( "The bare Qwen2_5_VL Model outputting raw hidden-states without any specific head on top.", Qwen2_5_VL_START_DOCSTRING, ) class Qwen2_5_VLPreTrainedModel(PreTrainedModel): config_class = Qwen2_5_VLConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_sdpa = True _supports_cache_class = True _supports_static_cache = ( False # TODO (joao): fix. torch.compile failing probably due to `cache_positions` ) def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, (nn.Linear, nn.Conv3d)): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel): config_class = Qwen2_5_VLVisionConfig _no_split_modules = ["Qwen2_5_VLVisionBlock"] def __init__(self, config, *inputs, **kwargs) -> None: super().__init__(config, *inputs, **kwargs) self.spatial_merge_size = config.spatial_merge_size self.patch_size = config.patch_size self.fullatt_block_indexes = config.fullatt_block_indexes self.window_size = config.window_size self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size self.patch_embed = Qwen2_5_VisionPatchEmbed( patch_size=config.patch_size, temporal_patch_size=config.temporal_patch_size, in_channels=config.in_channels, embed_dim=config.hidden_size, ) head_dim = config.hidden_size // config.num_heads self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2) self.blocks = nn.ModuleList( [Qwen2_5_VLVisionBlock(config, config._attn_implementation) for _ in range(config.depth)] ) self.merger = Qwen2_5_VLPatchMerger( dim=config.out_hidden_size, context_dim=config.hidden_size, spatial_merge_size=config.spatial_merge_size, ) self.gradient_checkpointing = False def rot_pos_emb(self, grid_thw): pos_ids = [] for t, h, w in grid_thw: hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) hpos_ids = hpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) hpos_ids = hpos_ids.permute(0, 2, 1, 3) hpos_ids = hpos_ids.flatten() wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1) wpos_ids = wpos_ids.reshape( h // self.spatial_merge_size, self.spatial_merge_size, w // self.spatial_merge_size, self.spatial_merge_size, ) wpos_ids = wpos_ids.permute(0, 2, 1, 3) wpos_ids = wpos_ids.flatten() pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)) pos_ids = torch.cat(pos_ids, dim=0) max_grid_size = grid_thw[:, 1:].max() rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size) rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1) return rotary_pos_emb def get_window_index(self, grid_thw): window_index: list = [] cu_window_seqlens: list = [0] window_index_id = 0 vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size for grid_t, grid_h, grid_w in grid_thw: llm_grid_h, llm_grid_w = ( grid_h // self.spatial_merge_size, grid_w // self.spatial_merge_size, ) index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w) pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100) index_padded = index_padded.reshape( grid_t, num_windows_h, vit_merger_window_size, num_windows_w, vit_merger_window_size, ) index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape( grid_t, num_windows_h * num_windows_w, vit_merger_window_size, vit_merger_window_size, ) seqlens = (index_padded != -100).sum([2, 3]).reshape(-1) index_padded = index_padded.reshape(-1) index_new = index_padded[index_padded != -100] window_index.append(index_new + window_index_id) cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1] cu_window_seqlens.extend(cu_seqlens_tmp.tolist()) window_index_id += (grid_t * llm_grid_h * llm_grid_w).item() window_index = torch.cat(window_index, dim=0) return window_index, cu_window_seqlens def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor: """ Args: hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`): The final hidden states of the model. grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`): The temporal, height and width of feature shape of each image in LLM. Returns: `torch.Tensor`: hidden_states. """ hidden_states = self.patch_embed(hidden_states) rotary_pos_emb = self.rot_pos_emb(grid_thw) window_index, cu_window_seqlens = self.get_window_index(grid_thw) window_index = window_index.to(hidden_states.device) cu_window_seqlens = torch.tensor( cu_window_seqlens, device=hidden_states.device, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) hidden_states = hidden_states[window_index, :, :] hidden_states = hidden_states.reshape(seq_len, -1) rotary_pos_emb = rotary_pos_emb.reshape( seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1 ) rotary_pos_emb = rotary_pos_emb[window_index, :, :] rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) position_embeddings = (emb.cos(), emb.sin()) cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum( dim=0, # Select dtype based on the following factors: # - FA2 requires that cu_seqlens_q must have dtype int32 # - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw # See https://github.com/huggingface/transformers/pull/34852 for more information dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) max_seqlen_full = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item() max_seqlen_window = (cu_window_seqlens[1:] - cu_window_seqlens[:-1]).max().item() for layer_num, blk in enumerate(self.blocks): if layer_num in self.fullatt_block_indexes: cu_seqlens_now = cu_seqlens max_seqlen_now = max_seqlen_full else: cu_seqlens_now = cu_window_seqlens max_seqlen_now = max_seqlen_window if self.gradient_checkpointing and self.training: hidden_states = self._gradient_checkpointing_func( blk.__call__, hidden_states, cu_seqlens_now, None, position_embeddings, ) else: hidden_states = blk( hidden_states, cu_seqlens=cu_seqlens_now, max_seqlen=max_seqlen_now, position_embeddings=position_embeddings, ) hidden_states = self.merger(hidden_states) reverse_indices = torch.argsort(window_index) hidden_states = hidden_states[reverse_indices, :] return hidden_states def _compute_default_rope_parameters_qwen2_5_vl(config, device=None): """ compute default rope parameters for Qwen2_5_VL """ base = config.text_config.rope_parameters["rope_theta"] dim = config.hidden_size // config.num_attention_heads inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, 1.0 class Qwen2_5_VLRotaryEmbedding(nn.Module): def __init__(self, config: Qwen2_5_VLConfig, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and config.rope_scaling is not None: self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) elif hasattr(config, "rope_parameters") and config.rope_parameters is not None: self.rope_type = config.rope_parameters.get("rope_type", "default") else: self.rope_type = "default" self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config if self.rope_type == "default": self.rope_init_fn = _compute_default_rope_parameters_qwen2_5_vl self.rope_kwargs = {} else: rope_type_key = "linear" if self.rope_type == "linear" else self.rope_type self.rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type_key] self.rope_kwargs = {} inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = self.inv_freq def _dynamic_frequency_update(self, position_ids, device): """ dynamic RoPE layers should recompute `inv_freq` in the following situations: 1 - growing beyond the cached sequence length (allow scaling) 2 - the current sequence length is in the original scale (avoid losing precision with small sequences) """ seq_len = torch.max(position_ids) + 1 if seq_len > self.max_seq_len_cached: # growth inv_freq, self.attention_scaling = self.rope_init_fn( self.config, device, seq_len=seq_len, **self.rope_kwargs ) self.register_buffer( "inv_freq", inv_freq, persistent=False ) # TODO joao: may break with compilation self.max_seq_len_cached = seq_len if ( seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len ): # reset self.register_buffer("inv_freq", self.original_inv_freq, persistent=False) self.max_seq_len_cached = self.original_max_seq_len @torch.no_grad() def forward(self, x, position_ids): if "dynamic" in self.rope_type: self._dynamic_frequency_update(position_ids, device=x.device) # Core RoPE block. In contrast to other models, Qwen2_5_VL has different position ids for thw grids # So we expand the inv_freq to shape (3, ...) inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) # Force float32 (see https://github.com/huggingface/transformers/pull/29285) device_type = x.device.type device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() sin = emb.sin() # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention cos = cos * self.attention_scaling sin = sin * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) class Qwen2MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act] def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1): """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/). Explanation: Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately. Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding. For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal, height and width) of text embedding is always the same, so the text embedding rotary position embedding has no difference with modern LLMs. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. mrope_section(`List(int)`): Multimodal rope section is for channel dimension of temporal, height and width in rope calculation. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ mrope_section = mrope_section * 2 cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze( unsqueeze_dim ) sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze( unsqueeze_dim ) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) class Qwen2_5_VLAttention(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer and "Generating Long Sequences with Sparse Transformers". """ def __init__(self, config: Qwen2_5_VLConfig, layer_idx: int | None = None): super().__init__() self.config = config self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.hidden_size // self.num_heads self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.is_causal = True self.attention_dropout = config.attention_dropout self.rope_scaling = config.rope_scaling if (self.head_dim * self.num_heads) != self.hidden_size: raise ValueError( f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" f" and `num_heads`: {self.num_heads})." ) self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True) self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True) self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True) self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_value: Cache | None = None, output_attentions: bool = False, use_cache: bool = False, cache_position: torch.LongTensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # necessary, but kept here for BC ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_multimodal_rotary_pos_emb( query_states, key_states, cos, sin, self.rope_scaling["mrope_section"] ) if past_key_value is not None: cache_kwargs = { "sin": sin, "cos": cos, "cache_position": cache_position, } # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) # repeat k/v heads if n_kv_heads < n_heads key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) if attention_mask is not None: # no matter the length, we just slice it causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask # Fix precision issues in Qwen2-VL float16 inference # Replace inf values with zeros in attention weights to prevent NaN propagation if query_states.dtype == torch.float16: attn_weights = torch.where( torch.isinf(attn_weights), torch.zeros_like(attn_weights), attn_weights ) # upcast attention to fp32 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) attn_output = torch.matmul(attn_weights, value_states) if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, -1) attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value class Qwen2_5_VLFlashAttention2(Qwen2_5_VLAttention): """ Qwen2_5_VL flash attention module, following Qwen2_5_VL attention module. This module inherits from `Qwen2_5_VLAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom config.max_window_layers layers. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_value: Cache | None = None, output_attentions: bool = False, use_cache: bool = False, cache_position: torch.LongTensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # necessary, but kept here for BC ): bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) # Because the input can be padded, the absolute sequence length depends on the max position id. cos, sin = position_embeddings query_states, key_states = apply_multimodal_rotary_pos_emb( query_states, key_states, cos, sin, self.rope_scaling["mrope_section"] ) if past_key_value is not None: cache_kwargs = { "sin": sin, "cos": cos, "cache_position": cache_position, } # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) # repeat k/v heads if n_kv_heads < n_heads # key_states = repeat_kv(key_states, self.num_key_value_groups) # value_states = repeat_kv(value_states, self.num_key_value_groups) dropout_rate = 0.0 if not self.training else self.attention_dropout # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in float16 just to be sure everything works as expected. input_dtype = query_states.dtype if input_dtype == torch.float32: if torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) # Reashape to the expected shape for Flash Attention query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) attn_output = flash_attn_func( query_states, key_states, value_states, dropout_rate, softmax_scale=None, causal=self.is_causal, ) attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value class Qwen2_5_VLSdpaAttention(Qwen2_5_VLAttention): """ Qwen2 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from `Qwen2Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to SDPA API. """ # Adapted from Qwen2Attention.forward def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_value: Cache | None = None, output_attentions: bool = False, use_cache: bool = False, cache_position: torch.LongTensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # necessary, but kept here for BC ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: if output_attentions: # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. logger.warning_once( "Qwen2_5_VLModel is using Qwen2_5_VLSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' ) return super().forward( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, ) bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_multimodal_rotary_pos_emb( query_states, key_states, cos, sin, self.rope_scaling["mrope_section"] ) if past_key_value is not None: cache_kwargs = { "sin": sin, "cos": cos, "cache_position": cache_position, } # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) causal_mask = attention_mask if attention_mask is not None: # no matter the length, we just slice it causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, # Reference: https://github.com/pytorch/pytorch/issues/112577. if query_states.device.type == "cuda" and attention_mask is not None: query_states = query_states.contiguous() key_states = key_states.contiguous() value_states = value_states.contiguous() # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling. # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1. is_causal = True if causal_mask is None and q_len > 1 else False attn_output = torch.nn.functional.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=causal_mask, dropout_p=self.attention_dropout if self.training else 0.0, is_causal=is_causal, ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.view(bsz, q_len, self.hidden_size) attn_output = self.o_proj(attn_output) return attn_output, None, past_key_value QWEN2_5_VL_ATTENTION_CLASSES = { "eager": Qwen2_5_VLAttention, "flash_attention_2": Qwen2_5_VLFlashAttention2, "sdpa": Qwen2_5_VLSdpaAttention, } class Qwen2_5_VLDecoderLayer(nn.Module): def __init__(self, config: Qwen2_5_VLConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size if config.use_sliding_window and config._attn_implementation != "flash_attention_2": logger.warning_once( f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; " "unexpected results may be encountered." ) self.self_attn = QWEN2_5_VL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx) self.mlp = Qwen2MLP(config) self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_value: tuple[torch.Tensor] | None = None, output_attentions: bool | None = False, use_cache: bool | None = False, cache_position: torch.LongTensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, # necessary, but kept here for BC **kwargs, ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, sequence_length)` where padding elements are indicated by 0. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*): Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`, with `head_dim` being the embedding dimension of each attention head. kwargs (`dict`, *optional*): Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code into the model """ residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) if use_cache: outputs += (present_key_value,) return outputs @add_start_docstrings( "The bare Qwen2_5_VL Model outputting raw hidden-states without any specific head on top.", Qwen2_5_VL_START_DOCSTRING, ) class Qwen2_5_VLModel(Qwen2_5_VLPreTrainedModel): def __init__(self, config: Qwen2_5_VLConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Qwen2_5_VLDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self._attn_implementation = config._attn_implementation self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, cache_position: torch.LongTensor | None = None, ) -> tuple | BaseModelOutputWithPast: output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False # torch.jit.trace() doesn't support cache objects in the output if use_cache and past_key_values is None and not torch.jit.is_tracing(): past_key_values = DynamicCache() if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device, ) # the hard coded `3` is for temporal, height and width. if position_ids is None: position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1) elif position_ids.dim() == 2: position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions, ) hidden_states = inputs_embeds # create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids) # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = None for decoder_layer in self.layers: if output_hidden_states: all_hidden_states += (hidden_states,) if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, causal_mask, position_ids, past_key_values, output_attentions, use_cache, cache_position, position_embeddings, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = next_decoder_cache if use_cache else None if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) def _update_causal_mask( self, attention_mask: torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool, ): if self.config._attn_implementation == "flash_attention_2": if attention_mask is not None and past_key_values is not None: is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0] if is_padding_right: raise ValueError( "You are attempting to perform batched generation with padding_side='right'" " this may lead to unexpected behaviour for Flash Attention version of Qwen2_5_VL. Make sure to " " call `tokenizer.padding_side = 'left'` before tokenizing the input. " ) if attention_mask is not None and 0.0 in attention_mask: return attention_mask return None # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail # to infer the attention mask. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_static_cache = isinstance(past_key_values, StaticCache) using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache) # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward if ( self.config._attn_implementation == "sdpa" and not (using_static_cache or using_sliding_window_cache) and not output_attentions ): if AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask, inputs_embeds=input_tensor, past_key_values_length=past_seen_tokens, sliding_window=self.config.sliding_window, is_training=self.training, ): return None dtype, device = input_tensor.dtype, input_tensor.device min_dtype = torch.finfo(dtype).min sequence_length = input_tensor.shape[1] # SlidingWindowCache or StaticCache if using_sliding_window_cache or using_static_cache: target_length = past_key_values.get_max_cache_shape() # DynamicCache or no cache else: target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 ) # In case the provided `attention` mask is 2D, we generate a causal mask here (4D). causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, device=device, cache_position=cache_position, batch_size=input_tensor.shape[0], config=self.config, past_key_values=past_key_values, ) if ( self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type in ["cuda", "xpu"] and not output_attentions ): # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. # Details: https://github.com/pytorch/pytorch/issues/110213 causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) return causal_mask @staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, device: torch.device, cache_position: torch.Tensor, batch_size: int, config: Qwen2_5_VLConfig, past_key_values: Cache, ): """ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. Args: attention_mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`. sequence_length (`int`): The sequence length being processed. target_length (`int`): The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet. dtype (`torch.dtype`): The dtype to use for the 4D attention mask. device (`torch.device`): The device to place the 4D attention mask on. cache_position (`torch.Tensor`): Indices depicting the position of the input sequence tokens in the sequence. batch_size (`torch.Tensor`): Batch size. config (`Qwen2_5_VLConfig`): The model's configuration class past_key_values (`Cache`): The cache class that is being used currently to generate """ if attention_mask is not None and attention_mask.dim() == 4: # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min causal_mask = torch.full( (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device, ) diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) if config.sliding_window is not None: # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also # the check is needed to verify is current checkpoint was trained with sliding window or not if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length: sliding_attend_mask = torch.arange(target_length, device=device) <= ( cache_position.reshape(-1, 1) - config.sliding_window ) diagonal_attend_mask.bitwise_or_(sliding_attend_mask) causal_mask *= diagonal_attend_mask causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit if attention_mask.shape[-1] > target_length: attention_mask = attention_mask[:, :target_length] mask_length = attention_mask.shape[-1] padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to( causal_mask.device ) padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype ) return causal_mask @dataclass class Qwen2_5_VLCausalLMOutputWithPast(ModelOutput): """ Base class for Qwen2_5_VL causal language model (or autoregressive) outputs. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. """ loss: torch.FloatTensor | None = None logits: torch.FloatTensor = None past_key_values: list[torch.FloatTensor] | None = None hidden_states: tuple[torch.FloatTensor] | None = None attentions: tuple[torch.FloatTensor] | None = None rope_deltas: torch.LongTensor | None = None QWEN2_5_VL_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy. - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. pixel_values (`torch.FloatTensor` of shape `(seq_length, num_channels * image_size * image_size)): The tensors corresponding to the input images. Pixel values can be obtained using [`AutoImageProcessor`]. See [`Qwen2_5_VLImageProcessor.__call__`] for details. [`Qwen2_5_VLProcessor`] uses [`Qwen2_5_VLImageProcessor`] for processing images. pixel_values_videos (`torch.FloatTensor` of shape `(seq_length, num_channels * temporal_size * image_size * image_size)): The tensors corresponding to the input videos. Pixel values can be obtained using [`AutoImageProcessor`]. See [`Qwen2_5_VLImageProcessor.__call__`] for details. [`Qwen2_5_VLProcessor`] uses [`Qwen2_5_VLImageProcessor`] for processing videos. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*): The rope index difference between sequence length and multimodal rope. """ class Qwen2_5_VLForConditionalGeneration(Qwen2_5_VLPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} config_class = Qwen2_5_VLConfig _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"] def __init__(self, config): super().__init__(config) self.visual = Qwen2_5_VisionTransformerPretrainedModel._from_config(config.vision_config) self.model = Qwen2_5_VLModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.rope_deltas = None # cache rope_deltas here # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings def set_decoder(self, decoder): self.model = decoder def get_decoder(self): return self.model def get_rope_index( self, input_ids: torch.LongTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, second_per_grid_ts: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Calculate the 3D rope index based on image and video's temporal, height and width in LLM. Explanation: Each embedding sequence contains vision embedding and text embedding or just contains text embedding. For pure text embedding sequence, the rotary position embedding has no difference with modern LLMs. Examples: input_ids: [T T T T T], here T is for text. temporal position_ids: [0, 1, 2, 3, 4] height position_ids: [0, 1, 2, 3, 4] width position_ids: [0, 1, 2, 3, 4] For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part and 1D rotary position embedding for text part. Examples: Temporal (Time): 3 patches, representing different segments of the video in time. Height: 2 patches, dividing each frame vertically. Width: 2 patches, dividing each frame horizontally. We also have some important parameters: fps (Frames Per Second): The video's frame rate, set to 1. This means one frame is processed each second. tokens_per_second: This is a crucial parameter. It dictates how many "time-steps" or "temporal tokens" are conceptually packed into a one-second interval of the video. In this case, we have 25 tokens per second. So each second of the video will be represented with 25 separate time points. It essentially defines the temporal granularity. temporal_patch_size: The number of frames that compose one temporal patch. Here, it's 2 frames. interval: The step size for the temporal position IDs, calculated as tokens_per_second * temporal_patch_size / fps. In this case, 25 * 2 / 1 = 50. This means that each temporal patch will be have a difference of 50 in the temporal position IDs. input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. vision temporal position_ids: [0, 0, 0, 0, 50, 50, 50, 50, 100, 100, 100, 100] vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] text temporal position_ids: [101, 102, 103, 104, 105] text height position_ids: [101, 102, 103, 104, 105] text width position_ids: [101, 102, 103, 104, 105] Here we calculate the text start position_ids as the max vision position_ids plus 1. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. second_per_grid_ts (`torch.Tensor` of shape `(num_videos)`, *optional*): The time interval (in seconds) for each grid along the temporal dimension in the 3D position IDs. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. Returns: position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`) mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`) """ spatial_merge_size = self.config.vision_config.spatial_merge_size image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id mrope_position_deltas = [] if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): total_input_ids = input_ids if attention_mask is None: attention_mask = torch.ones_like(total_input_ids) position_ids = torch.ones( 3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device, ) image_index, video_index = 0, 0 attention_mask = attention_mask.to(total_input_ids.device) for i, input_ids in enumerate(total_input_ids): input_ids = input_ids[attention_mask[i] == 1] image_nums, video_nums = 0, 0 vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1) vision_tokens = input_ids[vision_start_indices + 1] image_nums = (vision_tokens == image_token_id).sum() video_nums = (vision_tokens == video_token_id).sum() input_tokens = input_ids.tolist() llm_pos_ids_list: list = [] st = 0 remain_images, remain_videos = image_nums, video_nums for _ in range(image_nums + video_nums): if image_token_id in input_tokens and remain_images > 0: ed_image = input_tokens.index(image_token_id, st) else: ed_image = len(input_tokens) + 1 if video_token_id in input_tokens and remain_videos > 0: ed_video = input_tokens.index(video_token_id, st) else: ed_video = len(input_tokens) + 1 if ed_image < ed_video: t, h, w = ( image_grid_thw[image_index][0], image_grid_thw[image_index][1], image_grid_thw[image_index][2], ) second_per_grid_t = 0 image_index += 1 remain_images -= 1 ed = ed_image else: t, h, w = ( video_grid_thw[video_index][0], video_grid_thw[video_index][1], video_grid_thw[video_index][2], ) if second_per_grid_ts is not None: second_per_grid_t = second_per_grid_ts[video_index] else: second_per_grid_t = 1.0 video_index += 1 remain_videos -= 1 ed = ed_video llm_grid_t, llm_grid_h, llm_grid_w = ( t.item(), h.item() // spatial_merge_size, w.item() // spatial_merge_size, ) text_len = ed - st st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) range_tensor = torch.arange(llm_grid_t).view(-1, 1) expanded_range = range_tensor.expand(-1, llm_grid_h * llm_grid_w) time_tensor = ( expanded_range * second_per_grid_t * self.config.vision_config.tokens_per_second ) time_tensor_long = time_tensor.long() t_index = time_tensor_long.flatten() h_index = ( torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() ) w_index = ( torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() ) llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) st = ed + llm_grid_t * llm_grid_h * llm_grid_w if st < len(input_tokens): st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 text_len = len(input_tokens) - st llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device) mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i])) mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1) return position_ids, mrope_position_deltas else: if attention_mask is not None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(attention_mask.device) max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0] mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1] else: position_ids = ( torch.arange(input_ids.shape[1], device=input_ids.device) .view(1, 1, -1) .expand(3, input_ids.shape[0], -1) ) mrope_position_deltas = torch.zeros( [input_ids.shape[0], 1], device=input_ids.device, dtype=input_ids.dtype, ) return position_ids, mrope_position_deltas @add_start_docstrings_to_model_forward(QWEN2_5_VL_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=Qwen2_5_VLCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, pixel_values: torch.Tensor | None = None, pixel_values_videos: torch.FloatTensor | None = None, image_grid_thw: torch.LongTensor | None = None, video_grid_thw: torch.LongTensor | None = None, rope_deltas: torch.LongTensor | None = None, cache_position: torch.LongTensor | None = None, second_per_grid_ts: torch.Tensor | None = None, ) -> tuple | Qwen2_5_VLCausalLMOutputWithPast: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: Example: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration >>> model = Qwen2_5_VLForConditionalGeneration.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct") >>> messages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "What is shown in this image?"}, ], }, ] >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) >>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos]) >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..." ```""" output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if inputs_embeds is None: inputs_embeds = self.model.embed_tokens(input_ids) if pixel_values is not None: pixel_values = pixel_values.type(self.visual.dtype) image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) n_image_tokens = (input_ids == self.config.image_token_id).sum().item() n_image_features = image_embeds.shape[0] if n_image_tokens != n_image_features: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) mask = input_ids == self.config.image_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) image_mask = mask_expanded.to(inputs_embeds.device) image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) if pixel_values_videos is not None: pixel_values_videos = pixel_values_videos.type(self.visual.dtype) video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw) n_video_tokens = (input_ids == self.config.video_token_id).sum().item() n_video_features = video_embeds.shape[0] if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) mask = input_ids == self.config.video_token_id mask_unsqueezed = mask.unsqueeze(-1) mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) video_mask = mask_expanded.to(inputs_embeds.device) video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) if attention_mask is not None: attention_mask = attention_mask.to(inputs_embeds.device) # if we get 4D attention mask we cannot calculate rope deltas anymore. TODO @raushan fixme if position_ids is None and (attention_mask is None or attention_mask.ndim == 2): # calculate RoPE index once per generation in the pre-fill stage only if ( (cache_position is not None and cache_position[0] == 0) or self.rope_deltas is None or (past_key_values is None or past_key_values.get_seq_length() == 0) ): position_ids, rope_deltas = self.get_rope_index( input_ids, image_grid_thw, video_grid_thw, second_per_grid_ts, attention_mask, ) self.rope_deltas = rope_deltas # then use the prev pre-calculated rope-deltas to get the correct position ids else: batch_size, seq_length, _ = inputs_embeds.shape delta = ( (cache_position[0] + self.rope_deltas).to(inputs_embeds.device) if cache_position is not None else 0 ) position_ids = torch.arange(seq_length, device=inputs_embeds.device) position_ids = position_ids.view(1, -1).expand(batch_size, -1) if cache_position is not None: # otherwise `deltas` is an int `0` delta = delta.repeat_interleave(batch_size // delta.shape[0], dim=0) position_ids = position_ids.add(delta) position_ids = position_ids.unsqueeze(0).expand(3, -1, -1) outputs = self.model( input_ids=None, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) loss = None if labels is not None: # Upcast to float if we need to compute the loss to avoid potential precision issues logits = logits.float() # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return Qwen2_5_VLCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, rope_deltas=self.rope_deltas, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, position_ids=None, use_cache=True, pixel_values=None, pixel_values_videos=None, image_grid_thw=None, video_grid_thw=None, second_per_grid_ts=None, **kwargs, ): # Overwritten -- in specific circumstances we don't want to forward image inputs to the model # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens # Exception 1: when passing input_embeds, input_ids may be missing entries # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case. # (we can't check exception 3 while compiling) # Exception 4: If input_embeds are passed then slice it through `cache_position`, to keep only the unprocessed tokens and # generate the first token for each sequence. Later use the generated Input ids for continuation. if past_key_values is not None: if inputs_embeds is not None and input_ids.shape[1] == 0: # Exception 4 inputs_embeds = inputs_embeds[:, -cache_position.shape[0] :] elif inputs_embeds is not None or ( # Exception 1 is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1] ): # Exception 3 input_ids = input_ids[:, -cache_position.shape[0] :] elif ( input_ids.shape[1] != cache_position.shape[0] ): # Default case (the "else", a no op, is Exception 2) input_ids = input_ids[:, cache_position] if cache_position[0] != 0: pixel_values = None pixel_values_videos = None # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]: model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None} else: model_inputs = {"input_ids": input_ids, "inputs_embeds": None} if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2: if model_inputs["inputs_embeds"] is not None: batch_size, sequence_length, _ = inputs_embeds.shape device = inputs_embeds.device else: batch_size, sequence_length = input_ids.shape device = input_ids.device attention_mask = self.model._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=past_key_values.get_max_cache_shape(), dtype=self.lm_head.weight.dtype, device=device, cache_position=cache_position, batch_size=batch_size, config=self.config, past_key_values=past_key_values, ) model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": use_cache, "attention_mask": attention_mask, "pixel_values": pixel_values, "pixel_values_videos": pixel_values_videos, "image_grid_thw": image_grid_thw, "video_grid_thw": video_grid_thw, "cache_position": cache_position, "second_per_grid_ts": second_per_grid_ts, } ) return model_inputs def _get_image_nums_and_video_nums( self, input_ids: torch.LongTensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Get the number of images and videos for each sample to calculate the separation length of the sample tensor. These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Returns: image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`) video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`) """ image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id vision_start_mask = input_ids == vision_start_token_id vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1) image_mask = input_ids == image_token_id video_mask = input_ids == video_token_id image_nums = torch.sum(vision_first_mask & image_mask, dim=1) video_nums = torch.sum(vision_first_mask & video_mask, dim=1) return image_nums, video_nums def _expand_inputs_for_generation( self, expand_size: int = 1, is_encoder_decoder: bool = False, input_ids: torch.LongTensor | None = None, **model_kwargs, ) -> tuple[torch.LongTensor, dict[str, Any]]: # Overwritten -- Support for expanding tensors without a batch size dimension # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t # pixel_values.shape[0] is sum(seqlen_images for samples) # image_grid_thw.shape[0] is sum(num_images for samples) if expand_size == 1: return input_ids, model_kwargs visual_keys = [ "pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts", ] def _expand_dict_for_generation_visual(dict_to_expand): image_grid_thw = model_kwargs.get("image_grid_thw", None) video_grid_thw = model_kwargs.get("video_grid_thw", None) image_nums, video_nums = self._get_image_nums_and_video_nums(input_ids) def _repeat_interleave_samples(x, lengths, repeat_times): samples = torch.split(x, lengths) repeat_args = [repeat_times] + [1] * (x.dim() - 1) result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0) return result for key in dict_to_expand: if key == "pixel_values": # split images into samples samples = torch.split(image_grid_thw, list(image_nums)) # compute the sequence length of images for each sample lengths = [torch.prod(sample, dim=1).sum() for sample in samples] dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "image_grid_thw": # get the num of images for each sample lengths = list(image_nums) dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "pixel_values_videos": samples = torch.split(video_grid_thw, list(video_nums)) lengths = [torch.prod(sample, dim=1).sum() for sample in samples] dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "video_grid_thw": lengths = list(video_nums) dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "second_per_grid_ts": if not isinstance(dict_to_expand[key], list): raise TypeError( f"Expected value for key '{key}' to be a list, but got {type(dict_to_expand[key])} instead." ) tensor = torch.tensor(dict_to_expand[key]) lengths = list(video_nums) tensor = _repeat_interleave_samples(tensor, lengths=lengths, repeat_times=expand_size) dict_to_expand[key] = tensor.tolist() return dict_to_expand def _expand_dict_for_generation(dict_to_expand): for key in dict_to_expand: if ( key != "cache_position" and dict_to_expand[key] is not None and isinstance(dict_to_expand[key], torch.Tensor) and key not in visual_keys ): dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0) return dict_to_expand # input_ids is required for expanding visual inputs # If input_ids is unavailable, visual inputs will not be used; therefore, there is no need to expand visual inputs. if input_ids is not None and input_ids.numel() != 0: model_kwargs = _expand_dict_for_generation_visual(model_kwargs) if input_ids is not None: input_ids = input_ids.repeat_interleave(expand_size, dim=0) model_kwargs = _expand_dict_for_generation(model_kwargs) if is_encoder_decoder: if model_kwargs.get("encoder_outputs") is None: raise ValueError( "If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined." ) model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"]) return input_ids, model_kwargs @dataclass class Qwen2_5_VLACausalLMOutputWithPast(ModelOutput): loss: torch.FloatTensor | None = None flow_loss: torch.FloatTensor | None = None cross_entropy_loss: torch.FloatTensor | None = None logits: torch.FloatTensor | None = None past_key_values: list[torch.FloatTensor] | None = None hidden_states: tuple[torch.FloatTensor] | None = None attentions: tuple[torch.FloatTensor] | None = None rope_deltas: torch.LongTensor | None = None channel_loss_dict: dict[torch.FloatTensor] | None = None channel_loss_count_dict: dict[torch.FloatTensor] | None = None class BlockSparseMLP(nn.Module): def __init__(self, config): super().__init__() self.hidden_size = config["hidden_size"] self.intermediate_size = config["intermediate_size"] self.hidden_act = config["hidden_act"] self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[self.hidden_act] def forward(self, hidden_state): return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state)) class SparseMoeBlock(nn.Module): def __init__(self, config, num_experts: int): super().__init__() self.num_experts = num_experts self.experts = nn.ModuleList([BlockSparseMLP(config.experts[i]) for i in range(num_experts)]) if not hasattr(config, "dim_inputs") or not config.dim_inputs: raise ValueError("Config must contain valid dim_inputs") self.dim_inputs = config.dim_inputs def forward(self, hidden_states: torch.Tensor, experts_indices: torch.Tensor) -> torch.Tensor: """ Route different hidden_states to corresponding experts for processing. Args: hidden_states (torch.Tensor): Tensor of shape (batch_size, seq_length, hidden_dim). experts_indices (torch.Tensor): Tensor of shape (batch_size, seq_length), indicating the expert index assigned to each token. Returns: output (torch.Tensor): Tensor of shape (batch_size, seq_length, hidden_dim). """ batch_size, seq_length, hidden_dim = hidden_states.size() output = torch.zeros_like(hidden_states) for expert_idx, expert in enumerate(self.experts): mask = experts_indices == expert_idx if mask.sum() == 0: continue dim_input = self.dim_inputs[expert_idx] selected_hidden = hidden_states[mask] processed_hidden = expert(selected_hidden[:, :dim_input]) batch_indices, seq_indices = torch.where(mask) output[batch_indices, seq_indices, :dim_input] = processed_hidden return output QWEN2_5_VL_ATTENTION_CLASSES = { "eager": Qwen2_5_VLAttention, "flash_attention_2": Qwen2_5_VLFlashAttention2, "sdpa": Qwen2_5_VLSdpaAttention, } class Qwen2_5_VLDecoderLayer_with_MoE(nn.Module): def __init__(self, config: Qwen2_5_VLConfig, layer_idx: int, num_experts: int): super().__init__() self.hidden_size = config.hidden_size if config.use_sliding_window and config._attn_implementation != "flash_attention_2": logger.warning_once( f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; " "unexpected results may be encountered." ) self.self_attn = QWEN2_5_VL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx) self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) if config.mlp_moe: self.moe = SparseMoeBlock(config, num_experts=num_experts) self.mlp = None else: self.mlp = Qwen2_5_VLMLP(config) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_value: tuple[torch.Tensor] | None = None, token_types=None, output_attentions: bool | None = False, use_cache: bool | None = False, cache_position: torch.LongTensor | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs, ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, sequence_length)` where padding elements are indicated by 0. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*): Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`, with `head_dim` being the embedding dimension of each attention head. kwargs (`dict`, *optional*): Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code into the model """ residual = hidden_states hidden_states = hidden_states.to(self.input_layernorm.weight.dtype) hidden_states = self.input_layernorm(hidden_states) hidden_states = hidden_states.to(self.self_attn.q_proj.weight.dtype) # Self Attention hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = hidden_states.to(self.post_attention_layernorm.weight.dtype) hidden_states = self.post_attention_layernorm(hidden_states) if self.mlp is None: # using moe mlp hidden_states = hidden_states.to(self.moe.experts[0].down_proj.weight.dtype) hidden_states = self.moe(hidden_states, token_types) else: hidden_states = hidden_states.to(self.mlp.down_proj.weight.dtype) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) if use_cache: outputs += (present_key_value,) return outputs class Qwen2_5_VLMoEModel(Qwen2_5_VLPreTrainedModel): """Qwen2.5-VL model with Mixture of Experts (MoE) architecture. This model extends the base Qwen2.5-VL model by incorporating MoE layers for improved scalability and specialization across different token types. """ @classmethod def from_pretrained( cls, pretrained_model_name_or_path: str, num_experts: int | None = None, *args, **kwargs, ): """Load a pretrained model with optional MoE configuration. Args: pretrained_model_name_or_path: Path or name of the pretrained model num_experts: Number of experts for MoE layers (if not in config) *args: Additional arguments passed to parent class **kwargs: Additional keyword arguments passed to parent class Returns: Initialized model instance with MoE configuration """ config = kwargs.get("config") if config is None: config = AutoConfig.from_pretrained(pretrained_model_name_or_path) # Override number of experts if specified if num_experts is not None: config.num_experts = num_experts kwargs["config"] = config return super().from_pretrained(pretrained_model_name_or_path, *args, **kwargs) def __init__(self, config: Qwen2_5_VLConfig): """Initialize the Qwen2.5-VL MoE model. Args: config: Model configuration containing architecture parameters """ super().__init__(config) # Basic model parameters self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size # Model components self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) # Decoder layers with MoE support self.layers = nn.ModuleList( [ Qwen2_5_VLDecoderLayer_with_MoE(config, layer_idx, config.num_experts) for layer_idx in range(config.num_hidden_layers) ] ) # Model configuration self._attn_implementation = config._attn_implementation self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Qwen2_5_VLRotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self) -> nn.Embedding: """Get the input embedding layer. Returns: The token embedding layer """ return self.embed_tokens def set_input_embeddings(self, value: nn.Embedding) -> None: """Set the input embedding layer. Args: value: New embedding layer to use """ self.embed_tokens = value def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, moe_token_types: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, cache_position: torch.LongTensor | None = None, **kwargs, ) -> tuple | BaseModelOutputWithPast: # Set default output options output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict # Validate inputs if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if moe_token_types is None: raise ValueError("moe_token_types must be provided for MoE routing") # Handle gradient checkpointing compatibility if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False # Initialize cache if needed if use_cache and past_key_values is None and not torch.jit.is_tracing(): past_key_values = DynamicCache() # Get input embeddings if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) # Set up cache position if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device, ) # Set up position IDs (hardcoded 3 dimensions for temporal, height, width) if position_ids is None: position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1) elif position_ids.dim() == 2: position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) # Create causal attention mask causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions, moe_token_types, ) hidden_states = inputs_embeds # Create position embeddings to be shared across decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids) # Initialize output collections all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = None # Process through decoder layers for decoder_layer in self.layers: if output_hidden_states: all_hidden_states += (hidden_states,) if self.gradient_checkpointing and self.training: # Use gradient checkpointing during training layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, causal_mask, position_ids, past_key_values, moe_token_types, output_attentions, use_cache, cache_position, position_embeddings, ) else: # Regular forward pass layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_value=past_key_values, token_types=moe_token_types, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, ) hidden_states = layer_outputs[0] # Update cache if using it if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1] # Collect attention weights if requested if output_attentions: all_self_attns += (layer_outputs[1],) # Apply final layer normalization hidden_states = self.norm(hidden_states) # Add final hidden states if collecting all states if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = next_decoder_cache if use_cache else None # Return outputs in requested format if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) def _update_causal_mask( self, attention_mask: torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool, moe_token_types: torch.LongTensor | None = None, ): """Update causal attention mask with support for bidirectional attention for specific token types. This method creates and modifies attention masks to support different attention patterns: - Standard causal (unidirectional) attention for most tokens - Bidirectional attention for specific token types (e.g., MoE routing tokens) Args: attention_mask: Input attention mask to avoid attending to padding tokens input_tensor: Input embeddings tensor for shape and device information cache_position: Position indices for caching mechanisms past_key_values: Cached key-value pairs from previous forward passes output_attentions: Whether attention weights will be returned moe_token_types: Optional tensor indicating token types for MoE routing (type 1 tokens will use bidirectional attention) Returns: Updated causal attention mask, or None if using Flash Attention 2 """ # Flash Attention 2 handles masking internally if self.config._attn_implementation == "flash_attention_2": return None # Calculate sequence lengths for cache management past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_static_cache = isinstance(past_key_values, StaticCache) using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache) # For SDPA (Scaled Dot Product Attention), use `is_causal` argument when possible # instead of explicit attention mask to enable Flash Attention 2 dispatch # Note: This optimization is not compatible with static cache if ( self.config._attn_implementation == "sdpa" and not (using_static_cache or using_sliding_window_cache) and not output_attentions ): # Check if we can ignore the causal mask and rely on SDPA's internal handling if AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask, inputs_embeds=input_tensor, past_key_values_length=past_seen_tokens, sliding_window=self.config.sliding_window, is_training=self.training, ): return None # Extract tensor properties for mask creation dtype, device = input_tensor.dtype, input_tensor.device min_dtype = torch.finfo(dtype).min sequence_length = input_tensor.shape[1] # Determine target length based on cache type if using_sliding_window_cache or using_static_cache: # Use maximum cache shape for sliding window or static caches target_length = past_key_values.get_max_cache_shape() else: # For dynamic cache or no cache, calculate based on attention mask or sequence length target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 ) # Generate 4D causal attention mask from 2D input mask if provided causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, device=device, cache_position=cache_position, batch_size=input_tensor.shape[0], config=self.config, past_key_values=past_key_values, ) # Modify mask to support bidirectional attention for specific token types if moe_token_types is not None: # Identify positions of type 1 tokens (MoE routing tokens) type1_tokens = (moe_token_types == 1).unsqueeze(1).unsqueeze(2) # Shape: [B, 1, 1, S] # Create bidirectional attention region for type 1 tokens # This allows type 1 tokens to attend to each other bidirectionally type1_mask = torch.zeros_like(causal_mask) # Shape: [B, num_heads, S, S] type1_region = type1_tokens & type1_tokens.transpose(-1, -2) # Shape: [B, 1, S, S] type1_mask = type1_mask.masked_fill(type1_region, 1.0).to(torch.bool) # Apply bidirectional attention: zero out causal constraints in type 1 regions causal_mask = torch.where( type1_mask, # Where type 1 tokens interact with each other torch.zeros_like(causal_mask), # Remove causal masking (allow bidirectional) causal_mask, # Keep original causal masking for other regions ) # Handle special case for SDPA with CUDA/XPU devices if ( self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type in ["cuda", "xpu"] and not output_attentions ): # Ensure attention to all tokens in fully masked rows for memory-efficient attention # This is required for F.scaled_dot_product_attention's memory-efficient path # when using left padding. See: https://github.com/pytorch/pytorch/issues/110213 causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) return causal_mask @staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, device: torch.device, cache_position: torch.Tensor, batch_size: int, config: Qwen2_5_VLConfig, past_key_values: Cache, ): """ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. Args: attention_mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`. sequence_length (`int`): The sequence length being processed. target_length (`int`): The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet. dtype (`torch.dtype`): The dtype to use for the 4D attention mask. device (`torch.device`): The device to place the 4D attention mask on. cache_position (`torch.Tensor`): Indices depicting the position of the input sequence tokens in the sequence. batch_size (`torch.Tensor`): Batch size. config (`Qwen2_5_VLConfig`): The model's configuration class past_key_values (`Cache`): The cache class that is being used currently to generate """ if attention_mask is not None and attention_mask.dim() == 4: # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min causal_mask = torch.full( (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device, ) diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) if config.sliding_window is not None: # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also # the check is needed to verify is current checkpoint was trained with sliding window or not if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length: sliding_attend_mask = torch.arange(target_length, device=device) <= ( cache_position.reshape(-1, 1) - config.sliding_window ) diagonal_attend_mask.bitwise_or_(sliding_attend_mask) causal_mask *= diagonal_attend_mask causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit if attention_mask.shape[-1] > target_length: attention_mask = attention_mask[:, :target_length] mask_length = attention_mask.shape[-1] padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to( causal_mask.device ) padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype ) return causal_mask __all__ = [ "Qwen2_5_VLForConditionalGeneration", "Qwen2_5_VLModel", "Qwen2_5_VLPreTrainedModel", "Qwen2_5_VLDecoderLayer_with_MoE", "Qwen2_5_VLMoEModel", ]
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/qwen_model/qwen2_5_vl_moe.py", "license": "Apache License 2.0", "lines": 2431, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
huggingface/lerobot:src/lerobot/policies/wall_x/utils.py
#!/usr/bin/env python # Copyright 2025 HuggingFace Inc. team. All rights reserved. # # 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. """ Wall-X Utility Functions. Contains data processing utilities, text formatting functions, and helper classes for the Wall-X cross-embodiment robotic control model. """ import random import re from collections import OrderedDict from dataclasses import dataclass, field from typing import Any import torch from transformers import BatchFeature from lerobot.policies.wall_x.constant import ( CAMERA_NAME_MAPPING, ) from lerobot.utils.constants import OBS_IMAGES @dataclass class X2RDataProcessingConfig: """Configuration class for X2R data processing pipeline. This class contains all the necessary parameters for processing robotic data including camera mappings, tactile sensor configurations, action predictions, and various processing options. """ # Action prediction configuration predict_action_keys: list[str] = field(default_factory=list) obs_action_keys: list[str] = field(default_factory=list) # Image resolution settings for different views resolution: dict[str, int] = field( default_factory=lambda: { "face_view": -1, "left_wrist_view": 128, "right_wrist_view": 128, } ) # Dataset splitting train_test_split: float = 0.9 split_seed: int = 42 # Instruction handling priority_order: dict[str, float] | None = None # Vision model parameters model_type: str = "qwen2_5" max_pixels: int = 16384 * 28 * 28 min_pixels: int = 4 * 28 * 28 image_factor: int = 28 generate_subtask_ratio: float = 0.0 def __post_init__(self): """Post-initialization validation and setup.""" # Validate train/test split if not 0 < self.train_test_split < 1: raise ValueError(f"train_test_split must be between 0 and 1, got {self.train_test_split}") def as_dict(self) -> dict: """Convert configuration to dictionary format. Returns: Dict: Configuration as dictionary """ return self.__dict__ def update(self, **kwargs) -> "X2RDataProcessingConfig": """Update configuration parameters. Args: **kwargs: Key-value pairs to update Returns: X2RDataProcessingConfig: Updated configuration instance """ for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) else: raise ValueError(f"Unknown configuration parameter: {key}") return self def preprocesser_call( processor, images: list | Any | None = None, text: str | list[str] | None = None, videos: list | Any | None = None, padding: bool | str = False, truncation: bool | None = None, max_length: int | None = None, return_tensors: str = "pt", ) -> BatchFeature: """Unified preprocessing function for Wall-X model handling text, image and video inputs. Processes inputs into format suitable for multimodal transformer models, including: - Text tokenization and special token handling - Image/video processing through image processor - Attention mask and label generation - Padding and truncation handling Args: processor: Multimodal processor containing tokenizer and image processor images: Input images (PIL, numpy arrays, or torch tensors) text: Text or list of texts to tokenize videos: Input videos (numpy arrays or torch tensors) padding: Whether to pad sequences to same length truncation: Whether to truncate sequences longer than max_length max_length: Maximum length for truncation/padding return_tensors: Format for returned tensors ('pt', 'np', etc.) Returns: BatchFeature containing processed inputs with keys: - input_ids: Tokenized text - attention_mask: Attention mask for text - pixel_values: Processed image pixels - pixel_values_videos: Processed video frames - image_grid_thw: Image grid dimensions for LLM - video_grid_thw: Video grid dimensions for LLM - labels: Training labels with masking """ # Process image inputs if images is not None and len(images) > 0: image_inputs = processor.image_processor(images=images, return_tensors=return_tensors) image_grid_thw = image_inputs["image_grid_thw"] else: image_inputs = {} image_grid_thw = None # Process video inputs if videos is not None: videos_inputs = processor.image_processor(videos=videos, return_tensors=return_tensors) video_grid_thw = videos_inputs["video_grid_thw"] else: videos_inputs = {} video_grid_thw = None # Ensure text input is in list format if not isinstance(text, list): text = [text] # Process image placeholder tokens in text if image_grid_thw is not None: merge_length = processor.image_processor.merge_size**2 index = 0 for i in range(len(text)): while "<|image_pad|>" in text[i]: # Add bounds checking to avoid index overflow if index >= len(image_grid_thw): print( f"Warning: Number of image placeholders ({index + 1}) " f"exceeds actual images ({len(image_grid_thw)}), " f"skipping remaining placeholder processing" ) break # Replace image placeholder with actual token count token_count = image_grid_thw[index].prod() // merge_length text[i] = text[i].replace("<|image_pad|>", "<|placeholder|>" * token_count, 1) index += 1 text[i] = text[i].replace("<|placeholder|>", "<|image_pad|>") # Process video placeholder tokens in text if video_grid_thw is not None: merge_length = processor.image_processor.merge_size**2 index = 0 for i in range(len(text)): while "<|video_pad|>" in text[i]: # Replace video placeholder with actual token count token_count = video_grid_thw[index].prod() // merge_length text[i] = text[i].replace("<|video_pad|>", "<|placeholder|>" * token_count, 1) index += 1 text[i] = text[i].replace("<|placeholder|>", "<|video_pad|>") # Tokenize complete input text text_inputs = processor.tokenizer( text, return_tensors=return_tensors, padding=padding, truncation=truncation, max_length=max_length, ) # Get pad token ID for label generation pad_token_id = processor.tokenizer.pad_token_id if pad_token_id is None: pad_token_id = processor.tokenizer.eos_token_id # Generate labels for multi-turn dialogue, keeping only assistant response loss labels = torch.full_like(text_inputs.input_ids, -100) assistant_marker = "<|im_start|>assistant\n" im_end_token_id = processor.tokenizer.convert_tokens_to_ids("<|im_end|>") assistant_tokens = processor.tokenizer("<|im_start|>assistant\n", add_special_tokens=False).input_ids for i in range(len(text)): assistant_regions = [] parts = text[i].split(assistant_marker) # Process each part to determine which tokens belong to assistant responses # Count left padding tokens num_left_pads = 0 for token_id in text_inputs.input_ids[i]: if token_id == pad_token_id: num_left_pads += 1 else: break current_pos = num_left_pads for j, part in enumerate(parts): part_tokens = processor.tokenizer(part, add_special_tokens=False).input_ids if j == 0: # First part is system prompt or user question, all labels are -100 current_pos += len(part_tokens) continue # From second part onwards, each part starts with assistant response for k in range(current_pos + 1, len(text_inputs.input_ids[i])): if text_inputs.input_ids[i][k] == im_end_token_id: assistant_regions.append((current_pos + len(assistant_tokens), k + 2)) break current_pos += len(part_tokens) + 3 # Set labels for assistant response regions for start, end in assistant_regions: labels[i][start:end] = text_inputs.input_ids[i][start:end] # Mask special action tokens in labels action_token_id = processor.tokenizer.encode("<|action|>")[0] propri_token_id = processor.tokenizer.encode("<|propri|>")[0] labels[labels == action_token_id] = -100 labels[labels == propri_token_id] = -100 labels[labels == processor.tokenizer.pad_token_id] = -100 # Set labels to None if all are invalid to skip cross entropy loss if (labels != -100).any().item(): text_inputs["labels"] = labels else: text_inputs["labels"] = None return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}) def process_grounding_points( text: str, orig_height: int, orig_width: int, resized_height: int, resized_width: int, model_type: str, ) -> str: """Process grounding point coordinates in text based on image resizing. Adjusts coordinate values in <point> tags to match resized image dimensions for different model types (qwen2, qwen2_5). Args: text: Input text containing <point> tags with coordinates orig_height: Original image height orig_width: Original image width resized_height: Resized image height resized_width: Resized image width model_type: Model type for coordinate processing ('qwen2' or 'qwen2_5') Returns: Text with adjusted coordinate values """ # Regex pattern to match <point> tags and their contents point_pattern = re.compile(r"<point>(.*?)</point>") def process_match(match): """Process a single point match and adjust coordinates.""" coords_str = match.group(1) try: # Extract coordinates from string coords = list(map(int, re.findall(r"\d+", coords_str))) # Calculate resize scale factors scale_w = resized_width / orig_width scale_h = resized_height / orig_height if len(coords) == 2: x, y = coords if model_type == "qwen2_5": # Qwen2.5 uses pixel coordinates new_x = max(0, min(round(x * scale_w), resized_width - 1)) new_y = max(0, min(round(y * scale_h), resized_height - 1)) elif model_type == "qwen2": # Qwen2 normalizes to [0, 1000) range new_x = max(0, min(999.999, (x / orig_width) * 1000)) new_y = max(0, min(999.999, (y / orig_height) * 1000)) else: raise ValueError(f"Unsupported model type: {model_type}") coords = [new_x, new_y] elif len(coords) == 4: x1, y1, x2, y2 = coords if model_type == "qwen2_5": new_x1 = max(0, min(round(x1 * scale_w), resized_width - 1)) new_y1 = max(0, min(round(y1 * scale_h), resized_height - 1)) new_x2 = max(0, min(round(x2 * scale_w), resized_width - 1)) new_y2 = max(0, min(round(y2 * scale_h), resized_height - 1)) elif model_type == "qwen2": new_x1 = max(0, min(999.999, (x1 / orig_width) * 1000)) new_y1 = max(0, min(999.999, (y1 / orig_height) * 1000)) new_x2 = max(0, min(999.999, (x2 / orig_width) * 1000)) new_y2 = max(0, min(999.999, (y2 / orig_height) * 1000)) else: raise ValueError(f"Unsupported model type: {model_type}") coords = [new_x1, new_y1, new_x2, new_y2] # Return processed point tag return f"<point>[{', '.join(map(str, coords))}]</point>" except (ValueError, TypeError): # Return original content if processing fails return match.group(0) # Replace all matching point tags processed_text = point_pattern.sub(process_match, text) return processed_text def get_frame_instruction( instruction_info: dict[str, Any], frame_idx: int | None = None, truncate_keys: list[str] | None = None, ) -> tuple[dict[str, Any], int | None]: """Extract frame-specific instruction from instruction dictionary. Args: instruction_info: Dictionary containing instruction components frame_idx: Current frame index truncate_keys: Keys that trigger truncation when found Returns: Tuple of (frame_instruction_dict, split_end_frame) """ if truncate_keys is None: truncate_keys = [ "subtask_generation", "distribute", "subtask_generation_zh", "distribute_zh", ] instruction_for_frame = {} split_end = None for key, value in instruction_info.items(): if isinstance(value, dict): # Handle frame-range specific instructions for frame_range, frame_instruction in value.items(): start_frame, end_frame = map(int, frame_range.split(" ")) if start_frame <= frame_idx < end_frame or (start_frame == frame_idx): instruction_for_frame[key] = frame_instruction if truncate_keys is not None and split_end is None and key in truncate_keys: split_end = end_frame + 1 break else: instruction_for_frame[key] = value return instruction_for_frame, split_end def get_task_instruction( frame_instruction_info: dict[str, Any], priority_order: OrderedDict | None = None ) -> str: """Construct task instruction from available instruction fields using priority sampling. Args: frame_instruction_info: Dictionary containing instruction fields priority_order: OrderedDict specifying sampling probability for each field Returns: Combined instruction string with priority components """ # Default priority settings default_priority_order = OrderedDict( { "subtask_generation": 0.25, "subtask_generation_zh": 0.25, "distribute": 0.25, "distribute_zh": 0.25, } ) if priority_order is not None: priority_order = OrderedDict(priority_order) else: priority_order = default_priority_order got_instruction = False task_instruction = "" # Sample instruction components based on priority probabilities for key, prob in priority_order.items(): if key in frame_instruction_info and frame_instruction_info[key] != "": if got_instruction: if random.random() >= prob: continue task_instruction += f"\n{frame_instruction_info[key]}" got_instruction = True break # Fall back to base instruction if no priority components found if not got_instruction: task_instruction = frame_instruction_info.get("instruction", "") return task_instruction def get_wallx_normal_text( instruction_info: dict[str, Any], action_chunk_size: int, frame_idx: int, priority_order: OrderedDict | None = None, img_keys: list[str] | None = None, generate_subtask_ratio: float = 0.0, ) -> tuple[str, bool]: """Construct complete multimodal prompt text for Wall-X model. Formats input using special tokens including: - System message - User observations (with image placeholders) - Task instructions - Proprioception prompts - Assistant responses (with action tokens) Args: instruction_info: Dictionary containing instruction components action_chunk_size: Number of action tokens to generate frame_idx: Current frame index priority_order: Priority order for instruction sampling img_keys: List of image keys generate_subtask_ratio: Probability of generating subtask instead of actions Returns: Tuple of (formatted_prompt_text, is_subtask_generation) """ # Special tokens for formatting role_start_symbol = "<|im_start|>" role_end_symbol = "<|im_end|>" vision_start_symbol = "<|vision_start|>" vision_end_symbol = "<|vision_end|>" image_pad_symbol = "<|image_pad|>" propri_symbol = "<|propri|>" action_symbol = "<|action|>" action_fast_symbol = "<|action_fast|>" # System prologue prologue = f"{role_start_symbol}system\nYou are a helpful assistant.{role_end_symbol}\n" # User request with observation user_request = f"{role_start_symbol}user\nObservation:" if img_keys: img_keys = img_key_mapping(img_keys) for key in img_keys: user_request += f" {key}: {vision_start_symbol}{image_pad_symbol}{vision_end_symbol}" user_request += "\nInstruction:" # Get frame-specific instruction frame_instruction_info, _ = get_frame_instruction(instruction_info, frame_idx=frame_idx) generate_subtask = False priority_keys = ["subtask_generation", "distribute"] # Decide whether to generate subtask or actions if ( bool(set(frame_instruction_info.keys()) & set(priority_keys)) and random.random() < generate_subtask_ratio ): # Generate subtask (equivalent to VQA task) instruction = frame_instruction_info.get("instruction", "") text_prompt = "\nPredict the next action in language.\n" user_message = f"{user_request} {instruction}{text_prompt}{role_end_symbol}\n" # Find output instruction from priority keys for key in priority_keys: if key in frame_instruction_info: output_instruction = frame_instruction_info[key] break assistant_output = f"{role_start_symbol}assistant\n{output_instruction}\n{role_end_symbol}" generate_subtask = True else: # Generate actions instruction = get_task_instruction(frame_instruction_info, priority_order=priority_order) text_prompt = f"\nPredict the next action in robot action.\nProprioception: {propri_symbol}\n" user_message = f"{user_request} {instruction}{text_prompt}{role_end_symbol}\n" assistant_output = f"{role_start_symbol}assistant\n{action_fast_symbol}{role_end_symbol}\n{action_symbol * action_chunk_size}" complete_text = prologue + user_message + assistant_output return complete_text, generate_subtask def img_key_mapping(img_keys: list[str]) -> list[str]: """Map image keys to camera names. Args: img_keys: List of image keys Returns: List of camera names """ processed_img_keys = [] for key in img_keys: key = key.replace(OBS_IMAGES + ".", "") if key in CAMERA_NAME_MAPPING: key = CAMERA_NAME_MAPPING[key] else: if "view" in key: key = key.replace("_", " ") else: key = key + " view" processed_img_keys.append(key) return processed_img_keys def get_action_tokens(normalized_actions: torch.Tensor | list, action_tokenizer) -> list[list[str]]: """Convert normalized actions to action token strings. Args: normalized_actions: Normalized action arrays/tensors action_tokenizer: Tokenizer for converting actions to tokens Returns: List of action token string lists for each sample """ if isinstance(normalized_actions, torch.Tensor): normalized_actions = normalized_actions.cpu().numpy() all_action_tokens = [] for i in range(len(normalized_actions)): if isinstance(normalized_actions[i], torch.Tensor): normalized_actions[i] = normalized_actions[i].cpu().numpy() token_id = action_tokenizer(normalized_actions[i]) action_tokens = [f"<|action_token_{j}|>" for j in token_id[0]] all_action_tokens.append(action_tokens) return all_action_tokens def pad_action_token_strs( actions_token_lists: list[list[str]], pad_token: str = "<|endoftext|>", # nosec B107 ) -> list[str]: """Pad action token lists to same length and join as strings. Args: actions_token_lists: List of action token lists for each sample pad_token: Token used for padding Returns: List of padded action token strings """ max_len = max(len(tokens) for tokens in actions_token_lists) padded_action_strs = [] for tokens in actions_token_lists: padded_tokens = tokens + ["<|im_end|>\n"] + [pad_token] * (max_len - len(tokens)) padded_action_strs.append("".join(padded_tokens)) return padded_action_strs def replace_action_token( text: list[str], norm_action: torch.Tensor | None, action_tokenizer, dof_masks: torch.Tensor | None = None, ) -> list[str]: """Replace action placeholders in text with actual action tokens. Args: text: List of text strings with action placeholders norm_action: Normalized action tensors action_tokenizer: Tokenizer for converting actions to tokens dof_masks: Masks for degrees of freedom Returns: List of text strings with action tokens replaced """ if action_tokenizer is not None and norm_action is not None: # Extract actions based on chunk sizes and DOF masks norm_action = [action[:32, dof_masks[i, 0].bool()] for i, action in enumerate(norm_action)] # Convert to action tokens and pad actions_fast_tokens = get_action_tokens(norm_action, action_tokenizer) actions_fast_token_strs = pad_action_token_strs(actions_fast_tokens) # Replace action placeholders with actual tokens actions_fast_token_idx = 0 for i in range(len(text)): if "<|action_fast|>" in text[i]: text[i] = text[i].replace( "<|action_fast|><|im_end|>\n", actions_fast_token_strs[actions_fast_token_idx], ) actions_fast_token_idx += 1 # Remove remaining action placeholders text = [t.replace("<|action|>", "") for t in text] else: # Remove action placeholders when no tokenizer available text = [t.replace("<|action_fast|><|im_end|>\n", "") for t in text] return text
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/wall_x/utils.py", "license": "Apache License 2.0", "lines": 523, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/policies/wall_x/test_wallx.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Test script to verify Wall-X policy integration with LeRobot""" import pytest import torch # Skip if required dependencies are not available pytest.importorskip("peft") pytest.importorskip("transformers") pytest.importorskip("torchdiffeq") from lerobot.policies.factory import make_policy_config # noqa: E402 from lerobot.policies.wall_x import WallXConfig # noqa: E402 from lerobot.policies.wall_x.modeling_wall_x import WallXPolicy # noqa: E402 from lerobot.policies.wall_x.processor_wall_x import make_wall_x_pre_post_processors # noqa: E402 from lerobot.utils.random_utils import set_seed # noqa: E402 from tests.utils import require_cuda, require_hf_token # noqa: E402 @require_cuda @require_hf_token def test_policy_instantiation(): # Create config set_seed(42) config = WallXConfig(device="cuda") # Set up input_features and output_features in the config from lerobot.configs.types import FeatureType, PolicyFeature config.input_features = { "observation.state": PolicyFeature( type=FeatureType.STATE, shape=(7,), ), "observation.images.face_view": PolicyFeature( type=FeatureType.VISUAL, shape=(3, 224, 224), ), } config.output_features = { "action": PolicyFeature( type=FeatureType.ACTION, shape=(7,), ), } # Create dummy dataset stats dataset_stats = { "observation.state": { "mean": torch.zeros(7), "std": torch.ones(7), }, "action": { "mean": torch.zeros(7), "std": torch.ones(7), }, "observation.images.face_view": { "mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224), }, } # Instantiate policy policy = WallXPolicy(config) preprocessor, postprocessor = make_wall_x_pre_post_processors(config=config, dataset_stats=dataset_stats) # Test forward pass with dummy data batch_size = 1 device = config.device batch = { "observation.state": torch.randn(batch_size, 7, dtype=torch.float32, device=device), "action": torch.randn(batch_size, config.chunk_size, 7, dtype=torch.float32, device=device), "observation.images.face_view": torch.rand( batch_size, 3, 224, 224, dtype=torch.float32, device=device ), # Use rand for [0,1] range "task": ["Pick up the object"] * batch_size, } batch = preprocessor(batch) try: loss, loss_dict = policy.forward(batch) print(f"Forward pass successful. Loss: {loss_dict['loss']:.4f}") except Exception as e: print(f"Forward pass failed: {e}") raise # Test inference batch = { "observation.state": torch.randn(batch_size, 7, dtype=torch.float32, device=device), "observation.images.face_view": torch.rand( batch_size, 3, 224, 224, dtype=torch.float32, device=device ), # Use rand for [0,1] range "task": ["Pick up the object"] * batch_size, } batch = preprocessor(batch) try: with torch.no_grad(): action = policy.select_action(batch) action = postprocessor(action) print(f"Action: {action}") print(f"Action prediction successful. Action shape: {action.shape}") except Exception as e: print(f"Action prediction failed: {e}") raise @require_cuda @require_hf_token def test_config_creation(): """Test policy config creation through factory.""" try: config = make_policy_config( policy_type="wall_x", ) print("Config created successfully through factory") print(f" Config type: {type(config).__name__}") except Exception as e: print(f"Config creation failed: {e}") raise
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/wall_x/test_wallx.py", "license": "Apache License 2.0", "lines": 118, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:src/lerobot/data_processing/sarm_annotations/subtask_annotation.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ SARM Subtask Annotation using local GPU (Qwen3-VL). This script implements the annotation approach from the SARM paper using local GPU inference: "SARM: Stage-Aware Reward Modeling for Long Horizon Robot Manipulation" Paper: https://arxiv.org/pdf/2509.25358 What it does: 1. Takes videos from a LeRobot dataset 2. Uses Qwen3-VL running locally on GPU to identify when subtasks occur 3. Saves subtask timestamps to the dataset metadata 4. Optionally pushes the annotated dataset to HuggingFace Hub SARM trains reward models that predict: - Stage: Which subtask is currently being executed (discrete classification) - Progress: How far along the subtask we are (continuous 0-1) Supports three annotation modes: 1. No annotations (no args): Auto-creates single sparse "task" stage covering full episode. Use with SARM config annotation_mode="single_stage" for simple tasks. 2. Dense-only (--dense-only --dense-subtasks): Dense annotations from VLM, auto-generated single sparse "task" stage. Use with annotation_mode="dense_only". 3. Dual mode (--sparse-subtasks + --dense-subtasks): Both sparse and dense annotations from VLM. Use with annotation_mode="dual". Requirements: - GPU with sufficient VRAM (16GB+ recommended for 30B model) - `pip install transformers, torch, qwen-vl-utils` Run with: ```bash python examples/dataset_annotation/subtask_annotation.py \ --repo-id your-username/your-dataset \ --sparse-subtasks "Do ..." \ --dense-subtasks "Do task 1, Do task 2, Do task 3" \ --video-key observation.images.base \ --push-to-hub ``` """ import argparse import json import multiprocessing as mp import random import re import subprocess import tempfile import textwrap import time from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path from typing import Any import cv2 import numpy as np import pandas as pd import torch from pydantic import BaseModel, Field from transformers import AutoProcessor, Qwen3VLMoeForConditionalGeneration from lerobot.datasets.lerobot_dataset import LeRobotDataset # Pydantic Models for SARM Subtask Annotation class Timestamp(BaseModel): """Timestamp in MM:SS or SS format""" start: str = Field(description="Start timestamp (MM:SS or just seconds)") end: str = Field(description="End timestamp (MM:SS or just seconds)") class Subtask(BaseModel): """Individual subtask/stage - must use EXACT names from provided list""" name: str = Field(description="Subtask name - MUST match one from the predefined list exactly") timestamps: Timestamp class SubtaskAnnotation(BaseModel): """Complete annotation for a robot manipulation episode""" subtasks: list[Subtask] = Field(description="List of all subtasks in temporal order") def compute_temporal_proportions( annotations: dict[int, Any], fps: int = 30, subtask_order: list[str] | None = None ) -> dict[str, float]: """ Compute dataset-level temporal proportions (priors) for each subtask. Implements SARM Paper Formula (1): ᾱ_k = (1/M) × Σ_i (L_{i,k} / T_i) Args: annotations: Dict mapping episode index to SubtaskAnnotation object. fps: Frames per second (unused, kept for API compatibility) subtask_order: Optional list defining the output order of subtasks. Returns: Dict mapping subtask name to its temporal proportion (ᾱ_k), ordered by subtask_order if provided. """ subtask_proportions: dict[str, list[float]] = {} for annotation in annotations.values(): total_duration = 0 durations: dict[str, int] = {} for subtask in annotation.subtasks: start_parts = subtask.timestamps.start.split(":") end_parts = subtask.timestamps.end.split(":") start_seconds = ( int(start_parts[0]) * 60 + int(start_parts[1]) if len(start_parts) == 2 else int(start_parts[0]) ) end_seconds = ( int(end_parts[0]) * 60 + int(end_parts[1]) if len(end_parts) == 2 else int(end_parts[0]) ) duration = end_seconds - start_seconds durations[subtask.name] = duration total_duration += duration if total_duration > 0: for name, duration in durations.items(): if name not in subtask_proportions: subtask_proportions[name] = [] subtask_proportions[name].append(duration / total_duration) if not subtask_proportions: return {} avg_proportions = {name: sum(props) / len(props) for name, props in subtask_proportions.items()} total = sum(avg_proportions.values()) if total > 0: avg_proportions = {name: prop / total for name, prop in avg_proportions.items()} # Reorder according to subtask_order if provided if subtask_order: avg_proportions = { name: avg_proportions.get(name, 0.0) for name in subtask_order if name in avg_proportions } return avg_proportions def create_sarm_prompt(subtask_list: list[str]) -> str: subtask_str = "\n".join([f" - {name}" for name in subtask_list]) return textwrap.dedent(f"""\ # Role You are a Robotics Vision System specializing in temporal action localization for robot manipulation. Your job is to segment a single demonstration video into distinct, non-overlapping atomic actions from a fixed subtask list. # Subtask Label Set (Closed Vocabulary) You must strictly identify the video segments using ONLY the following labels. Do not create new labels or modify existing ones: [ {subtask_str} ] The video shows one successful execution of all subtasks in a logical order. # Ground-Truth Semantics (Very Important) Use **visual state changes** to define when a subtask starts and ends. Do NOT assume equal durations for the subtasks. - A subtask **starts** at the first frame where the robot's motion clearly initiates that subtask. - A subtask **ends** at the first frame where that specific action is visually completed and the manipulated object reaches a temporary, stable configuration. If there are short pauses or micro-motions that don't clearly correspond to a new subtask, they belong to the **current** subtask. # Hard Constraints & Logic 1. **Continuous Coverage (No Gaps):** - The entire video duration from "00:00" to the final timestamp must be covered by subtasks. - There can be no gaps between subtasks. - If there is any idle or ambiguous time between clear actions, extend the *preceding* subtask to cover it. 2. **Boundary Consistency:** - The `"end"` timestamp of one subtask must be exactly equal to the `"start"` timestamp of the next subtask. - Boundaries must coincide with a real visual state transition, not just a convenient time split. 3. **Chronological Order, One Occurrence Each:** - This is a single successful demonstration. - Each subtask from the vocabulary appears **exactly once**, in the correct logical order. - **Durations may be very different** between subtasks. Never assume they are similar lengths. Base all boundaries only on the video. 4. **Reject Uniform Segmentation (Important):** - Do NOT simply divide the video into equal or nearly equal time chunks. - If your boundaries would result in subtasks with similar durations (e.g. all around 5 seconds), treat this as evidence that your segmentation is wrong and refine the boundaries. - Only use nearly equal durations if the video truly shows each subtask taking the same amount of time (this is very rare). 5. **Timestamps:** - Timestamps must be in `"MM:SS"` format. - The first subtask always starts at `"00:00"`. - The last subtask ends at the final visible frame of the video. # Step 1 — Textual Timeline (must do this first) First, write a extensive and detailed textual timeline describing what happens in the video with approximate timestamps. For each subtask, include: - its name - an approximate start and end time, - an description of the visual event at the boundary (e.g. "shirt fully folded to the left", "robot rotates folded shirt 90 degrees"). Format this as a bullet list. # Step 2 — JSON Output (final answer) After the textual timeline, output **only** valid JSON with this structure. The JSON **must** be consistent with the textual timeline above: {{ "subtasks": [ {{ "name": "EXACT_NAME_FROM_LIST", "timestamps": {{ "start": "MM:SS", "end": "MM:SS" }} }}, {{ "name": "EXACT_NAME_FROM_LIST", "timestamps": {{ "start": "MM:SS", "end": "MM:SS" }} }} ] }} Do not add any extra keys to the JSON. """) class VideoAnnotator: """Annotates robot manipulation videos using local Qwen3-VL model on GPU""" def __init__( self, subtask_list: list[str], model_name: str = "Qwen/Qwen3-VL-30B-A3B-Instruct", device: str = "cuda", torch_dtype: torch.dtype = torch.bfloat16, model: Qwen3VLMoeForConditionalGeneration | None = None, # noqa: F821 processor: AutoProcessor | None = None, # noqa: F821 ): """ Initialize the video annotator with local model. Args: subtask_list: List of allowed subtask names (for consistency) model_name: Hugging Face model name (default: Qwen/Qwen3-VL-30B-A3B-Instruct) device: Device to use (cuda, cpu) torch_dtype: Data type for model (bfloat16, float16, float32) model: Pre-loaded model instance (optional, to share between annotators) processor: Pre-loaded processor instance (optional, to share between annotators) """ self.subtask_list = subtask_list self.prompt = create_sarm_prompt(subtask_list) self.device = device # Use provided model/processor or load new ones if model is not None and processor is not None: self.model = model self.processor = processor print(f"Using shared model on {device}") else: from transformers import AutoProcessor, Qwen3VLMoeForConditionalGeneration print(f"Loading model: {model_name}...") self.model = Qwen3VLMoeForConditionalGeneration.from_pretrained( model_name, torch_dtype=torch_dtype, device_map=device, trust_remote_code=True ) self.processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True) print(f"Model loaded successfully on {device}") def extract_episode_segment( self, file_path: Path, start_timestamp: float, end_timestamp: float, target_fps: int = 1 ) -> Path: """ Extract a specific episode segment from concatenated video. Uses minimal compression to preserve quality for local inference. Args: file_path: Path to the concatenated video file start_timestamp: Starting timestamp in seconds (within this video file) end_timestamp: Ending timestamp in seconds (within this video file) target_fps: Target FPS (default: 1 for faster processing) Returns: Path to extracted video file """ # Create temporary file for extracted video with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp_file: tmp_path = Path(tmp_file.name) try: # Check if ffmpeg is available subprocess.run( # nosec B607 ["ffmpeg", "-version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True ) except (subprocess.CalledProcessError, FileNotFoundError) as err: raise RuntimeError("ffmpeg not found, cannot extract episode segment") from err try: # Calculate duration duration = end_timestamp - start_timestamp print(f"Extracting episode: {start_timestamp:.1f}s-{end_timestamp:.1f}s ({duration:.1f}s)") # Use ffmpeg to extract segment with minimal quality loss cmd = [ "ffmpeg", "-i", str(file_path), "-ss", str(start_timestamp), "-t", str(duration), "-r", str(target_fps), "-c:v", "libx264", "-preset", "ultrafast", "-crf", "23", "-an", "-y", str(tmp_path), ] subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) # Verify the output file was created and is not empty if not tmp_path.exists() or tmp_path.stat().st_size == 0: print("Video extraction failed (0 bytes) - skipping episode") if tmp_path.exists(): tmp_path.unlink() raise RuntimeError("FFmpeg produced empty video file") # Show extraction results file_size_mb = tmp_path.stat().st_size / (1024 * 1024) # Fail if file is too small (< 100KB likely means extraction failed) if file_size_mb < 0.1: print(f"Extracted video too small ({file_size_mb:.2f}MB) - skipping episode") tmp_path.unlink() raise RuntimeError(f"Video extraction produced invalid file ({file_size_mb:.2f}MB)") print(f"Extracted: {file_size_mb:.1f}MB ({target_fps} FPS)") return tmp_path except subprocess.CalledProcessError as e: raise RuntimeError(f"ffmpeg failed ({e})") from e def annotate( self, file_path: str | Path, fps: int, start_timestamp: float = 0.0, end_timestamp: float | None = None, max_retries: int = 3, ) -> SubtaskAnnotation: """Annotate a video segment using local GPU.""" from qwen_vl_utils import process_vision_info file_path = Path(file_path) if end_timestamp is None: cap = cv2.VideoCapture(str(file_path)) end_timestamp = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) / (cap.get(cv2.CAP_PROP_FPS) or 1) cap.release() duration = end_timestamp - start_timestamp duration_str = f"{int(duration // 60):02d}:{int(duration % 60):02d}" extracted_path = self.extract_episode_segment(file_path, start_timestamp, end_timestamp, 1) is_extracted = extracted_path != file_path try: messages = [ {"role": "system", "content": [{"type": "text", "text": self.prompt}]}, { "role": "user", "content": [ {"type": "video", "video": str(extracted_path), "fps": 1.0}, { "type": "text", "text": f"Video is {duration_str} (~{duration:.1f}s). Follow instructions.", }, ], }, ] for attempt in range(max_retries): try: text = self.processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) image_inputs, video_inputs = process_vision_info(messages) inputs = self.processor( text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt", ).to(self.device) with torch.no_grad(): generated_ids = self.model.generate( **inputs, max_new_tokens=1024, do_sample=True, temperature=0.7 ) response = self.processor.batch_decode( [out[len(inp) :] for inp, out in zip(inputs.input_ids, generated_ids, strict=True)], skip_special_tokens=True, )[0].strip() # Extract JSON if "```json" in response: response = response.split("```json")[1].split("```")[0] elif "```" in response: response = response.split("```")[1].split("```")[0] try: return SubtaskAnnotation.model_validate(json.loads(response)) except json.JSONDecodeError: match = re.search(r"\{.*\}", response, re.DOTALL) if match: return SubtaskAnnotation.model_validate(json.loads(match.group())) raise ValueError("No JSON found") from None except Exception as e: if attempt == max_retries - 1: raise RuntimeError(f"Failed after {max_retries} attempts") from e time.sleep(1) finally: if is_extracted and extracted_path.exists(): extracted_path.unlink() def display_annotation(annotation: SubtaskAnnotation, episode_idx: int, fps: int, prefix: str = ""): """Display annotation summary.""" subtask_summary = ", ".join( f"{s.name}({s.timestamps.start}-{s.timestamps.end})" for s in annotation.subtasks ) print(f"Episode {episode_idx} {prefix}: {len(annotation.subtasks)} subtasks - {subtask_summary}") def timestamp_to_seconds(timestamp: str) -> float: """Convert MM:SS or SS timestamp to seconds""" parts = timestamp.split(":") if len(parts) == 2: return int(parts[0]) * 60 + int(parts[1]) else: return int(parts[0]) def extract_frame(video_path: Path, timestamp: float) -> np.ndarray | None: """Extract a single frame from video at given timestamp.""" cap = cv2.VideoCapture(str(video_path)) if not cap.isOpened(): return None cap.set(cv2.CAP_PROP_POS_MSEC, timestamp * 1000) ret, frame = cap.read() cap.release() return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if ret else None def draw_timeline(ax, subtasks, total_duration, colors): """Draw a timeline with color-coded subtask segments.""" import matplotlib.patches as mpatches bar_height, bar_y = 0.6, 0.5 for i, subtask in enumerate(subtasks): start = timestamp_to_seconds(subtask.timestamps.start) end = timestamp_to_seconds(subtask.timestamps.end) color = colors[i % len(colors)] rect = mpatches.FancyBboxPatch( (start, bar_y - bar_height / 2), end - start, bar_height, boxstyle="round,pad=0.02,rounding_size=0.1", facecolor=color, edgecolor="white", linewidth=1.5, alpha=0.85, ) ax.add_patch(rect) # Add label if segment is wide enough duration = end - start if duration > total_duration * 0.06: ax.text( (start + end) / 2, bar_y, subtask.name, ha="center", va="center", fontsize=8, fontweight="bold", color="white", rotation=0 if duration > total_duration * 0.12 else 45, ) if i > 0: ax.axvline(x=start, ymin=0.1, ymax=0.9, color="white", linestyle="--", linewidth=1.5, alpha=0.7) ax.axvline(x=0, ymin=0.1, ymax=0.9, color="#00ff00", linestyle="-", linewidth=2, alpha=0.9) if subtasks: ax.axvline( x=timestamp_to_seconds(subtasks[-1].timestamps.end), ymin=0.1, ymax=0.9, color="white", linestyle="--", linewidth=1.5, alpha=0.7, ) ax.set_xlim(-total_duration * 0.02, total_duration * 1.02) ax.set_ylim(-0.1, 1.1) ax.set_xlabel("Time (seconds)", fontsize=10, color="white", labelpad=5) for spine in ["top", "right", "left"]: ax.spines[spine].set_visible(False) ax.spines["bottom"].set_color("#444444") ax.tick_params(axis="x", colors="#888888", labelsize=8) ax.tick_params(axis="y", left=False, labelleft=False) def visualize_episode( ep_idx: int, annotation: SubtaskAnnotation, video_path: Path, video_start: float, video_end: float, output_path: Path, video_key: str, ann_type: str, ): """Create visualization for a single episode with frames and timeline.""" import matplotlib.pyplot as plt if annotation is None: print(f"No {ann_type} annotation for episode {ep_idx}") return subtasks = annotation.subtasks if not subtasks: print(f"No subtasks for episode {ep_idx}") return colors = plt.cm.tab10(np.linspace(0, 1, max(len(subtasks), 10))) total_duration = timestamp_to_seconds(subtasks[-1].timestamps.end) # Extract middle frame from each subtask sample_frames, frame_times = [], [] for subtask in subtasks: start = timestamp_to_seconds(subtask.timestamps.start) end = timestamp_to_seconds(subtask.timestamps.end) mid = (start + end) / 2 frame_times.append(mid) sample_frames.append(extract_frame(video_path, video_start + mid)) # Create figure fig_width = max(16, len(subtasks) * 2.5) fig = plt.figure(figsize=(fig_width, 10)) fig.patch.set_facecolor("#1a1a2e") gs = fig.add_gridspec( 2, max(len(subtasks), 1), height_ratios=[2, 1], hspace=0.3, wspace=0.1, left=0.05, right=0.95, top=0.88, bottom=0.1, ) fig.suptitle( f"Episode {ep_idx} - {ann_type.capitalize()} Annotations", fontsize=18, fontweight="bold", color="white", y=0.96, ) fig.text( 0.5, 0.91, f"Camera: {video_key} | Duration: {video_end - video_start:.1f}s | {len(subtasks)} subtasks", ha="center", fontsize=11, color="#888888", ) # Plot frames for i, (frame, subtask) in enumerate(zip(sample_frames, subtasks, strict=True)): ax = fig.add_subplot(gs[0, i]) ax.set_facecolor("#16213e") if frame is not None: ax.imshow(frame) else: ax.text( 0.5, 0.5, "N/A", ha="center", va="center", fontsize=12, color="white", transform=ax.transAxes ) ax.set_title(subtask.name, fontsize=10, fontweight="bold", color=colors[i % len(colors)], pad=8) ax.axis("off") ax.text( 0.5, -0.08, f"t={frame_times[i]:.1f}s", ha="center", fontsize=9, color="#888888", transform=ax.transAxes, ) # Plot timeline ax_timeline = fig.add_subplot(gs[1, :]) ax_timeline.set_facecolor("#16213e") draw_timeline(ax_timeline, subtasks, total_duration, colors) output_path.parent.mkdir(parents=True, exist_ok=True) plt.savefig(output_path, dpi=150, facecolor=fig.get_facecolor(), edgecolor="none", bbox_inches="tight") plt.close() print(f"Saved: {output_path}") def visualize_annotations( dataset: LeRobotDataset, sparse_annotations: dict[int, SubtaskAnnotation], dense_annotations: dict[int, SubtaskAnnotation] | None, video_key: str, output_dir: Path, num_episodes: int = 5, annotation_type: str = "sparse", episode_indices: list[int] | None = None, ): """ Visualize subtask annotations for a set of episodes. Args: dataset: LeRobotDataset instance sparse_annotations: Dict mapping episode index to sparse annotations dense_annotations: Dict mapping episode index to dense annotations (or None) video_key: Camera/video key to use output_dir: Directory to save visualization images num_episodes: Number of episodes to visualize (ignored if episode_indices provided) annotation_type: "sparse", "dense", or "both" episode_indices: Specific episode indices to visualize (optional) """ # Determine available episodes based on annotation type if annotation_type == "sparse": available = set(sparse_annotations.keys()) elif annotation_type == "dense": available = set(dense_annotations.keys()) if dense_annotations else set() else: # both sparse_set = set(sparse_annotations.keys()) dense_set = set(dense_annotations.keys()) if dense_annotations else set() available = sparse_set | dense_set if not available: print("Error: No annotations found to visualize.") return # Select episodes to visualize if episode_indices: episodes = sorted([e for e in episode_indices if e in available]) missing = set(episode_indices) - available if missing: print(f"Episodes not found in annotations: {sorted(missing)}") else: episodes = sorted(random.sample(list(available), min(num_episodes, len(available)))) print(f"Visualizing {len(episodes)} episodes: {episodes}") output_dir.mkdir(parents=True, exist_ok=True) # Generate visualizations for i, ep_idx in enumerate(episodes, 1): print(f"Processing episode {ep_idx} ({i}/{len(episodes)})") video_path = dataset.root / dataset.meta.get_video_file_path(ep_idx, video_key) if not video_path.exists(): print(f"Video not found: {video_path}") continue video_start = float(dataset.meta.episodes[f"videos/{video_key}/from_timestamp"][ep_idx]) video_end = float(dataset.meta.episodes[f"videos/{video_key}/to_timestamp"][ep_idx]) if annotation_type == "both": # Visualize both sparse and dense for ann_type, annotations in [("sparse", sparse_annotations), ("dense", dense_annotations)]: if annotations and ep_idx in annotations: output_path = output_dir / f"episode_{ep_idx:04d}_{ann_type}.png" visualize_episode( ep_idx, annotations.get(ep_idx), video_path, video_start, video_end, output_path, video_key, ann_type, ) else: annotations = sparse_annotations if annotation_type == "sparse" else dense_annotations if annotations and ep_idx in annotations: output_path = output_dir / f"episode_{ep_idx:04d}_{annotation_type}.png" visualize_episode( ep_idx, annotations.get(ep_idx), video_path, video_start, video_end, output_path, video_key, annotation_type, ) print(f"Visualizations saved to: {output_dir.absolute()}") def save_annotations_to_dataset( dataset_path: Path, annotations: dict[int, SubtaskAnnotation], fps: int, prefix: str = "sparse" ): """Save annotations to LeRobot dataset parquet format.""" from lerobot.datasets.utils import DEFAULT_EPISODES_PATH, load_episodes episodes_dataset = load_episodes(dataset_path) if not episodes_dataset or len(episodes_dataset) == 0: return episodes_df = episodes_dataset.to_pandas() cols = [ f"{prefix}_{c}" for c in [ "subtask_names", "subtask_start_times", "subtask_end_times", "subtask_start_frames", "subtask_end_frames", ] ] for col in cols: episodes_df[col] = None for ep_idx, ann in annotations.items(): if ep_idx >= len(episodes_df): continue names, starts, ends, start_frames, end_frames = [], [], [], [], [] for s in ann.subtasks: names.append(s.name) st, et = timestamp_to_seconds(s.timestamps.start), timestamp_to_seconds(s.timestamps.end) starts.append(st) ends.append(et) start_frames.append(int(st * fps)) end_frames.append(int(et * fps)) episodes_df.at[ep_idx, cols[0]] = names episodes_df.at[ep_idx, cols[1]] = starts episodes_df.at[ep_idx, cols[2]] = ends episodes_df.at[ep_idx, cols[3]] = start_frames episodes_df.at[ep_idx, cols[4]] = end_frames # Group by file and write for ep_idx in episodes_df.index: key = ( episodes_df.loc[ep_idx, "meta/episodes/chunk_index"], episodes_df.loc[ep_idx, "meta/episodes/file_index"], ) path = dataset_path / DEFAULT_EPISODES_PATH.format(chunk_index=key[0], file_index=key[1]) if path.exists(): file_df = pd.read_parquet(path) for col in cols + ( [ "subtask_names", "subtask_start_times", "subtask_end_times", "subtask_start_frames", "subtask_end_frames", ] if prefix == "sparse" else [] ): if col not in file_df.columns: file_df[col] = None if ep_idx in annotations: for col in cols: file_df.at[ep_idx, col] = episodes_df.loc[ep_idx, col] if prefix == "sparse": # Legacy columns for i, legacy in enumerate( [ "subtask_names", "subtask_start_times", "subtask_end_times", "subtask_start_frames", "subtask_end_frames", ] ): file_df.at[ep_idx, legacy] = episodes_df.loc[ep_idx, cols[i]] file_df.to_parquet(path, engine="pyarrow", compression="snappy") def generate_auto_sparse_annotations( dataset: LeRobotDataset, episode_indices: list[int], video_key: str ) -> dict[int, SubtaskAnnotation]: """Auto-generate single 'task' stage annotations for all episodes.""" annotations = {} for ep_idx in episode_indices: start = float(dataset.meta.episodes[f"videos/{video_key}/from_timestamp"][ep_idx]) end = float(dataset.meta.episodes[f"videos/{video_key}/to_timestamp"][ep_idx]) duration = end - start end_str = f"{int(duration // 60):02d}:{int(duration % 60):02d}" annotations[ep_idx] = SubtaskAnnotation( subtasks=[Subtask(name="task", timestamps=Timestamp(start="00:00", end=end_str))] ) return annotations def load_annotations_from_dataset(dataset_path: Path, prefix: str = "sparse") -> dict[int, SubtaskAnnotation]: """Load annotations from LeRobot dataset parquet files.""" from lerobot.datasets.utils import load_episodes episodes_dataset = load_episodes(dataset_path) if not episodes_dataset or len(episodes_dataset) == 0: return {} col_names = f"{prefix}_subtask_names" col_start = f"{prefix}_subtask_start_times" col_end = f"{prefix}_subtask_end_times" # Fall back to legacy columns for sparse if col_names not in episodes_dataset.column_names: if prefix == "sparse" and "subtask_names" in episodes_dataset.column_names: col_names, col_start, col_end = "subtask_names", "subtask_start_times", "subtask_end_times" else: return {} df = episodes_dataset.to_pandas() annotations = {} for ep_idx in df.index: names = df.loc[ep_idx, col_names] if names is None or (isinstance(names, float) and pd.isna(names)): continue starts, ends = df.loc[ep_idx, col_start], df.loc[ep_idx, col_end] annotations[int(ep_idx)] = SubtaskAnnotation( subtasks=[ Subtask( name=n, timestamps=Timestamp( start=f"{int(s) // 60:02d}:{int(s) % 60:02d}", end=f"{int(e) // 60:02d}:{int(e) % 60:02d}", ), ) for n, s, e in zip(names, starts, ends, strict=True) ] ) return annotations def process_single_episode( ep_idx: int, dataset_root: Path, dataset_meta, video_key: str, fps: int, annotator: VideoAnnotator, ) -> tuple[int, SubtaskAnnotation | None, str | None]: """Process a single episode annotation.""" try: video_path = dataset_root / dataset_meta.get_video_file_path(ep_idx, video_key) if not video_path.exists(): return ep_idx, None, f"Video not found: {video_path}" start = float(dataset_meta.episodes[f"videos/{video_key}/from_timestamp"][ep_idx]) end = float(dataset_meta.episodes[f"videos/{video_key}/to_timestamp"][ep_idx]) return ep_idx, annotator.annotate(video_path, fps, start, end), None except Exception as e: return ep_idx, None, str(e) def worker_process_episodes( worker_id: int, gpu_id: int, episode_indices: list[int], repo_id: str, video_key: str, sparse_subtask_list: list[str], dense_subtask_list: list[str] | None, model_name: str, torch_dtype: torch.dtype, ) -> tuple[dict, dict | None]: """Worker for parallel processing across GPUs.""" device = f"cuda:{gpu_id}" dataset = LeRobotDataset(repo_id, download_videos=False) sparse_annotator = VideoAnnotator(sparse_subtask_list, model_name, device, torch_dtype) dense_annotator = ( VideoAnnotator( dense_subtask_list, model_name, device, torch_dtype, sparse_annotator.model, sparse_annotator.processor, ) if dense_subtask_list else None ) sparse_annotations, dense_annotations = {}, {} if dense_subtask_list else None for ep_idx in episode_indices: _, sparse_ann, err = process_single_episode( ep_idx, dataset.root, dataset.meta, video_key, dataset.fps, sparse_annotator ) if sparse_ann: sparse_annotations[ep_idx] = sparse_ann if dense_annotator: _, dense_ann, _ = process_single_episode( ep_idx, dataset.root, dataset.meta, video_key, dataset.fps, dense_annotator ) if dense_ann: dense_annotations[ep_idx] = dense_ann return sparse_annotations, dense_annotations def main(): parser = argparse.ArgumentParser(description="SARM-style subtask annotation using local GPU (Qwen3-VL)") parser.add_argument("--repo-id", type=str, required=True, help="HuggingFace dataset repository ID") parser.add_argument( "--sparse-subtasks", type=str, default=None, help="Comma-separated sparse subtask names" ) parser.add_argument( "--dense-subtasks", type=str, default=None, help="Comma-separated dense subtask names" ) parser.add_argument( "--dense-only", action="store_true", help="Dense-only mode with auto-generated sparse 'task' stage" ) parser.add_argument("--episodes", type=int, nargs="+", default=None, help="Episode indices to annotate") parser.add_argument("--model", type=str, default="Qwen/Qwen3-VL-30B-A3B-Instruct", help="VLM model") parser.add_argument("--skip-existing", action="store_true", help="Skip already annotated episodes") parser.add_argument("--video-key", type=str, default=None, help="Video key (default: first available)") parser.add_argument("--push-to-hub", action="store_true", help="Push to HuggingFace Hub") parser.add_argument("--output-repo-id", type=str, default=None, help="Output repo ID for push") parser.add_argument("--device", type=str, default="cuda", help="Device (cuda/cpu)") parser.add_argument("--dtype", type=str, default="bfloat16", choices=["bfloat16", "float16", "float32"]) parser.add_argument("--num-workers", type=int, default=1, help="Parallel workers for multi-GPU") parser.add_argument("--gpu-ids", type=int, nargs="+", default=None, help="GPU IDs to use") # Visualization options parser.add_argument( "--visualize-only", action="store_true", help="Only visualize existing annotations (no generation)", ) parser.add_argument( "--num-visualizations", type=int, default=5, help="Number of episodes to visualize (default: 5)", ) parser.add_argument( "--visualize-type", type=str, default="sparse", choices=["sparse", "dense", "both"], help="Type of annotations to visualize (default: sparse)", ) parser.add_argument( "--output-dir", type=str, default="./subtask_viz", help="Output directory for visualizations (default: ./subtask_viz)", ) args = parser.parse_args() # Load dataset first (needed for both annotation and visualization) print(f"Loading dataset: {args.repo_id}") dataset = LeRobotDataset(args.repo_id, download_videos=True) fps = dataset.fps if not dataset.meta.video_keys: raise ValueError("No video keys found") video_key = ( args.video_key if args.video_key in (dataset.meta.video_keys or []) else dataset.meta.video_keys[0] ) print(f"Using camera: {video_key}, FPS: {fps}") # Handle visualization-only mode if args.visualize_only: print("Visualization-only mode") sparse_annotations = load_annotations_from_dataset(dataset.root, prefix="sparse") dense_annotations = load_annotations_from_dataset(dataset.root, prefix="dense") if not sparse_annotations and not dense_annotations: return print("Error: No annotations found. Run annotation first.") print(f"Found {len(sparse_annotations)} sparse, {len(dense_annotations)} dense annotations") visualize_annotations( dataset=dataset, sparse_annotations=sparse_annotations, dense_annotations=dense_annotations if dense_annotations else None, video_key=video_key, output_dir=Path(args.output_dir), num_episodes=args.num_visualizations, annotation_type=args.visualize_type, episode_indices=args.episodes, ) return # Validate arguments for annotation mode if args.dense_only and not args.dense_subtasks: return print("Error: --dense-only requires --dense-subtasks") if args.dense_subtasks and not args.sparse_subtasks and not args.dense_only: return print("Error: --dense-subtasks requires --sparse-subtasks or --dense-only") sparse_subtask_list = ( [s.strip() for s in args.sparse_subtasks.split(",")] if args.sparse_subtasks else None ) dense_subtask_list = [s.strip() for s in args.dense_subtasks.split(",")] if args.dense_subtasks else None auto_sparse = sparse_subtask_list is None dense_mode = dense_subtask_list is not None torch_dtype = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}[args.dtype] # Determine episodes episode_indices = args.episodes or list(range(dataset.meta.total_episodes)) existing_annotations = load_annotations_from_dataset(dataset.root, prefix="sparse") if args.skip_existing: episode_indices = [ep for ep in episode_indices if ep not in existing_annotations] if not episode_indices: return print("All episodes already annotated!") print(f"Annotating {len(episode_indices)} episodes") # GPU setup gpu_ids = args.gpu_ids or list( range(min(args.num_workers, torch.cuda.device_count() if torch.cuda.is_available() else 1)) ) args.num_workers = len(gpu_ids) sparse_annotations = existing_annotations.copy() dense_annotations = {} if dense_mode else None # Auto-sparse mode if auto_sparse: sparse_annotations.update(generate_auto_sparse_annotations(dataset, episode_indices, video_key)) save_annotations_to_dataset(dataset.root, sparse_annotations, fps, prefix="sparse") print(f"Auto-generated {len(episode_indices)} sparse 'task' annotations") # VLM annotation (for sparse if not auto, and for dense) need_vlm = (not auto_sparse) or dense_mode if need_vlm: if args.num_workers > 1 and not auto_sparse: # Parallel processing print(f"Parallel processing with {args.num_workers} workers") episodes_per_worker = [[] for _ in range(args.num_workers)] for i, ep_idx in enumerate(episode_indices): episodes_per_worker[i % args.num_workers].append(ep_idx) with ProcessPoolExecutor( max_workers=args.num_workers, mp_context=mp.get_context("spawn") ) as executor: futures = [ executor.submit( worker_process_episodes, w, gpu_ids[w], episodes_per_worker[w], args.repo_id, video_key, sparse_subtask_list, dense_subtask_list, args.model, torch_dtype, ) for w in range(args.num_workers) if episodes_per_worker[w] ] for future in as_completed(futures): try: worker_sparse, worker_dense = future.result() sparse_annotations.update(worker_sparse) if dense_mode and worker_dense: dense_annotations.update(worker_dense) save_annotations_to_dataset(dataset.root, sparse_annotations, fps, prefix="sparse") if dense_mode: save_annotations_to_dataset(dataset.root, dense_annotations, fps, prefix="dense") except Exception as e: raise RuntimeError(f"Worker failed: {e}") from e else: # Sequential processing sparse_annotator = ( VideoAnnotator(sparse_subtask_list, args.model, args.device, torch_dtype) if not auto_sparse and sparse_subtask_list else None ) dense_annotator = ( VideoAnnotator( dense_subtask_list, args.model, args.device, torch_dtype, sparse_annotator.model if sparse_annotator else None, sparse_annotator.processor if sparse_annotator else None, ) if dense_mode else None ) for i, ep_idx in enumerate(episode_indices): print(f"Episode {ep_idx} ({i + 1}/{len(episode_indices)})") if sparse_annotator: _, sparse_ann, err = process_single_episode( ep_idx, dataset.root, dataset.meta, video_key, fps, sparse_annotator ) if sparse_ann: sparse_annotations[ep_idx] = sparse_ann save_annotations_to_dataset(dataset.root, sparse_annotations, fps, prefix="sparse") elif err: print(f"Sparse failed: {err}") if dense_annotator: _, dense_ann, err = process_single_episode( ep_idx, dataset.root, dataset.meta, video_key, fps, dense_annotator ) if dense_ann: dense_annotations[ep_idx] = dense_ann save_annotations_to_dataset(dataset.root, dense_annotations, fps, prefix="dense") elif err: print(f"Dense failed: {err}") # Save temporal proportions def save_proportions(annotations, prefix, subtask_list=None, is_auto=False): props: dict[str, float] = ( {"task": 1.0} if is_auto else compute_temporal_proportions(annotations, fps, subtask_list) ) path = dataset.root / "meta" / f"temporal_proportions_{prefix}.json" path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w") as f: json.dump(props, f, indent=2) print(f"Saved {prefix} temporal proportions") save_proportions(sparse_annotations, "sparse", sparse_subtask_list, auto_sparse) if dense_mode and dense_annotations: save_proportions(dense_annotations, "dense", dense_subtask_list) print(f"\nComplete! {len(sparse_annotations)} sparse, {len(dense_annotations or {})} dense annotations") # Visualize annotations after generation if args.num_visualizations > 0: print(f"\nGenerating {args.num_visualizations} visualizations...") visualize_type = "both" if dense_mode else "sparse" visualize_annotations( dataset=dataset, sparse_annotations=sparse_annotations, dense_annotations=dense_annotations, video_key=video_key, output_dir=Path(args.output_dir), num_episodes=args.num_visualizations, annotation_type=visualize_type, ) if args.push_to_hub: try: dataset.push_to_hub(push_videos=True) print(f"Pushed to {args.output_repo_id or args.repo_id}") except Exception as e: print(f"Push failed: {e}") if __name__ == "__main__": main()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/data_processing/sarm_annotations/subtask_annotation.py", "license": "Apache License 2.0", "lines": 1020, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/sarm/compute_rabc_weights.py
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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. """ Compute SARM progress values for RA-BC (Reward-Aware Behavior Cloning) weighting. This script processes all frames in a dataset with SARM to compute progress values [0, 1]. The results are saved as a parquet file that can be loaded during training for RA-BC weighting. Uses multi-output extraction: each SARM query returns progress for 9 frames, so we only need ~num_frames/30 queries instead of one per frame (~30x speedup). Usage: # Full RA-BC computation with visualizations python src/lerobot/policies/sarm/compute_rabc_weights.py \\ --dataset-repo-id lerobot/aloha_sim_insertion_human \\ --reward-model-path <USER>/sarm_single_uni4 # Faster computation with stride (compute every 5 frames, interpolate the rest) python src/lerobot/policies/sarm/compute_rabc_weights.py \\ --dataset-repo-id lerobot/aloha_sim_insertion_human \\ --reward-model-path <USER>/sarm_single_uni4 \\ --stride 5 # Visualize predictions only (no RA-BC computation) python src/lerobot/policies/sarm/compute_rabc_weights.py \\ --dataset-repo-id lerobot/aloha_sim_insertion_human \\ --reward-model-path <USER>/sarm_single_uni4 \\ --visualize-only \\ --num-visualizations 5 The output is saved to the dataset's local cache directory as 'sarm_progress.parquet'. """ import argparse import logging from pathlib import Path import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np import pyarrow as pa import pyarrow.parquet as pq import torch from tqdm import tqdm from lerobot.datasets.lerobot_dataset import LeRobotDataset from lerobot.policies.sarm.modeling_sarm import SARMRewardModel from lerobot.policies.sarm.processor_sarm import make_sarm_pre_post_processors from lerobot.policies.sarm.sarm_utils import normalize_stage_tau def get_reward_model_path_from_parquet(parquet_path: Path) -> str | None: """Read reward_model_path from parquet metadata if available.""" if not parquet_path.exists(): return None try: metadata = pq.read_metadata(parquet_path).schema.to_arrow_schema().metadata if metadata and b"reward_model_path" in metadata: return metadata[b"reward_model_path"].decode() except Exception: # nosec B110 return None return None def load_sarm_resources( dataset_repo_id: str, reward_model_path: str, device: str = "cuda", ) -> tuple[LeRobotDataset, SARMRewardModel, any]: """ Load SARM model, dataset, and preprocessor. Returns: Tuple of (dataset, reward_model, preprocessor) """ logging.info(f"Loading model: {reward_model_path}") reward_model = SARMRewardModel.from_pretrained(reward_model_path) reward_model.config.device = device reward_model.to(device).eval() image_key = reward_model.config.image_key state_key = reward_model.config.state_key delta_indices = reward_model.config.observation_delta_indices logging.info(f"Loading dataset: {dataset_repo_id}") temp_dataset = LeRobotDataset(dataset_repo_id, download_videos=True) fps = temp_dataset.fps delta_timestamps = { image_key: [idx / fps for idx in delta_indices], state_key: [idx / fps for idx in delta_indices], } dataset = LeRobotDataset(dataset_repo_id, delta_timestamps=delta_timestamps) logging.info(f"Dataset: {dataset.num_episodes} episodes, {dataset.num_frames} frames") preprocess, _ = make_sarm_pre_post_processors( config=reward_model.config, dataset_stats=dataset.meta.stats, dataset_meta=dataset.meta, ) return dataset, reward_model, preprocess def to_numpy_image(img) -> np.ndarray: """Convert image tensor to numpy uint8 (H, W, C).""" if isinstance(img, torch.Tensor): img = img.cpu().numpy() if img.ndim == 4: # Take center frame for bidirectional sampling img = img[img.shape[0] // 2] if img.shape[0] in [1, 3]: img = np.transpose(img, (1, 2, 0)) if img.dtype != np.uint8: # Handle normalized images (may have negative values or values > 1) img = img.astype(np.float32) img = (img - img.min()) / (img.max() - img.min() + 1e-8) # Normalize to [0, 1] img = (img * 255).astype(np.uint8) return img def visualize_episode( frames, progress_preds, stage_preds, title, output_path, stage_labels, gt_progress=None, gt_stages=None ): """Create visualization with progress plot, stage probabilities, and sample frames. Same as sarm_inference_visualization.py """ num_stages = stage_preds.shape[1] colors = plt.cm.tab10(np.linspace(0, 1, num_stages)) frame_indices = np.arange(len(progress_preds)) fig = plt.figure(figsize=(14, 12)) gs = gridspec.GridSpec(3, 1, height_ratios=[2, 1, 1], hspace=0.3) ax_progress, ax_stages, ax_frames = fig.add_subplot(gs[0]), fig.add_subplot(gs[1]), fig.add_subplot(gs[2]) # Progress plot ax_progress.plot(frame_indices, progress_preds, linewidth=2, color="#2E86AB", label="Predicted") ax_progress.fill_between(frame_indices, 0, progress_preds, alpha=0.3, color="#2E86AB") if gt_progress is not None: ax_progress.plot( frame_indices, gt_progress, linewidth=2, color="#28A745", linestyle="--", label="Ground Truth" ) ax_progress.axhline(y=1.0, color="gray", linestyle="--", alpha=0.5) ax_progress.set_ylabel("Progress") ax_progress.set_title(f'Task: "{title}"', fontweight="bold") ax_progress.set_ylim(-0.05, 1.1) ax_progress.legend(loc="upper left") ax_progress.grid(True, alpha=0.3) # Stage predictions ax_stages.stackplot( frame_indices, *[stage_preds[:, i] for i in range(num_stages)], colors=colors, alpha=0.8, labels=stage_labels, ) if gt_stages is not None: for change_idx in np.where(np.diff(gt_stages) != 0)[0] + 1: ax_stages.axvline(x=change_idx, color="black", linestyle="-", alpha=0.7, linewidth=1.5) ax_stages.set_xlabel("Frame") ax_stages.set_ylabel("Stage Probability") ax_stages.set_ylim(0, 1) ax_stages.legend(loc="upper left", ncol=min(num_stages, 5), fontsize=8) ax_stages.grid(True, alpha=0.3) # Sample frames ax_frames.axis("off") num_sample = 8 sample_indices = np.linspace(0, len(frames) - 1, num_sample, dtype=int) h, w = frames[0].shape[:2] combined = np.zeros((h, w * num_sample, 3), dtype=np.uint8) for i, idx in enumerate(sample_indices): frame = frames[idx] if frame.shape[-1] == 1: frame = np.repeat(frame, 3, axis=-1) combined[:, i * w : (i + 1) * w] = frame stage_name = stage_labels[np.argmax(stage_preds[idx])][:12] ax_frames.text( i * w + w / 2, -10, f"Frame {idx}\n{progress_preds[idx]:.2f}\n{stage_name}", ha="center", va="top", fontsize=7, ) ax_frames.imshow(combined) ax_frames.set_title("Sample Frames", pad=20) output_path.parent.mkdir(parents=True, exist_ok=True) plt.savefig(output_path, dpi=150, bbox_inches="tight") plt.close() print(f"Saved: {output_path}") def visualize_sarm_predictions( dataset: LeRobotDataset, reward_model: SARMRewardModel, preprocess, episode_indices: list[int], head_mode: str, output_dir: Path, num_display_frames: int = 5, stride: int = 1, ): """ Visualize SARM predictions for multiple episodes. Computes predictions for every frame by default. With stride > 1, computes predictions every N frames and interpolates (progress + stage probabilities) for visualization. Args: dataset: LeRobotDataset with delta_timestamps configured reward_model: Loaded SARM model preprocess: Preprocessor from make_sarm_pre_post_processors episode_indices: List of episode indices to visualize head_mode: "sparse", "dense", or "both" output_dir: Directory to save visualizations num_display_frames: Number of frames to display in thumbnail strip (default: 5) stride: Compute predictions every N frames, interpolate the rest (default: 1) """ output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) image_key = reward_model.config.image_key state_key = reward_model.config.state_key dual_mode = reward_model.config.uses_dual_heads device = reward_model.device # Center frame index for bidirectional sampling target_idx = reward_model.config.n_obs_steps // 2 # Determine which heads to visualize schemes_to_viz = [] if head_mode in ("sparse", "both") or not dual_mode: schemes_to_viz.append("sparse") if head_mode in ("dense", "both") and dual_mode: schemes_to_viz.append("dense") # Set preprocessor to eval mode to disable augmentations if hasattr(preprocess, "eval"): preprocess.eval() for step in preprocess.steps: if hasattr(step, "eval"): step.eval() for episode_idx in episode_indices: ep = dataset.meta.episodes[episode_idx] ep_start = ep["dataset_from_index"] ep_end = ep["dataset_to_index"] task = dataset[ep_start].get("task", "perform the task") num_frames = ep_end - ep_start # Select frames for display thumbnails (evenly sampled from begin to end) display_indices = set( [ ep_start + int(i * (num_frames - 1) / (num_display_frames - 1)) for i in range(num_display_frames) ] if num_frames >= num_display_frames else list(range(ep_start, ep_end)) ) viz_frames = {} # Load display frames up-front (stride mode might skip them otherwise). for frame_idx in display_indices: sample = dataset[frame_idx] viz_frames[frame_idx] = to_numpy_image(sample[image_key]) # Initialize storage for each scheme scheme_data = {} for scheme in schemes_to_viz: num_stages = getattr(reward_model.config, f"num_{scheme}_stages") scheme_data[scheme] = { "viz_progress": np.full(num_frames, np.nan), "viz_stages": np.full((num_frames, num_stages), np.nan), "viz_gt_progress": np.full(num_frames, np.nan), "viz_gt_stages": np.full(num_frames, np.nan), "target_key": f"{scheme}_targets", "num_stages": num_stages, "temporal_props": getattr(reward_model.config, f"{scheme}_temporal_proportions"), "subtask_names": getattr(reward_model.config, f"{scheme}_subtask_names"), } if stride > 1: logging.info(f"Visualization stride={stride}: inferring every {stride} frames and interpolating") # Process frames one at a time to avoid memory buildup frame_indices = list(range(ep_start, ep_end, stride)) if (ep_end - 1) not in frame_indices: frame_indices.append(ep_end - 1) frame_indices = sorted(set(frame_indices)) for frame_idx in tqdm(frame_indices, desc=f"Episode {episode_idx}", leave=False): local_idx = frame_idx - ep_start sample = dataset[frame_idx] batch = { image_key: sample[image_key], "task": task, "index": frame_idx, "episode_index": episode_idx, } if state_key in sample: batch[state_key] = sample[state_key] with torch.no_grad(): processed = preprocess(batch) video_features = processed["video_features"].to(device) text_features = processed["text_features"].to(device) state_features = processed.get("state_features") if state_features is not None: state_features = state_features.to(device) lengths = processed.get("lengths") for scheme in schemes_to_viz: sd = scheme_data[scheme] # Ground truth # In stride visualization mode, ground-truth plots can be misleading # (only sparse points are available), so we skip GT. if stride == 1 and sd["target_key"] in processed: gt_target = processed[sd["target_key"]][0, target_idx].cpu().item() sd["viz_gt_stages"][local_idx] = int(gt_target) sd["viz_gt_progress"][local_idx] = normalize_stage_tau( gt_target, num_stages=sd["num_stages"], temporal_proportions=sd["temporal_props"], subtask_names=sd["subtask_names"], ) # Predictions reward, stage_probs = reward_model.calculate_rewards( text_embeddings=text_features, video_embeddings=video_features, state_features=state_features, lengths=lengths, return_all_frames=True, return_stages=True, head_mode=scheme, ) # Handle both tensor and numpy outputs if isinstance(reward, torch.Tensor): reward = reward.cpu().numpy() stage_probs = stage_probs.cpu().numpy() if reward.ndim == 2: sd["viz_progress"][local_idx] = reward[0, target_idx] sd["viz_stages"][local_idx] = stage_probs[0, target_idx, :] else: sd["viz_progress"][local_idx] = reward[target_idx] sd["viz_stages"][local_idx] = stage_probs[target_idx, :] # Clear GPU memory after each frame del processed, video_features, text_features if state_features is not None: del state_features torch.cuda.empty_cache() # Interpolate predictions back to per-frame arrays for smooth visualization. if stride > 1: all_local = np.arange(num_frames) for scheme in schemes_to_viz: sd = scheme_data[scheme] valid = np.isfinite(sd["viz_progress"]) valid_idx = np.where(valid)[0] if valid_idx.size >= 1: sd["viz_progress"] = interpolate_progress( valid_idx, sd["viz_progress"][valid_idx], all_local ) stage_interp = np.zeros_like(sd["viz_stages"], dtype=np.float32) for s in range(sd["num_stages"]): stage_interp[:, s] = interpolate_progress( valid_idx, sd["viz_stages"][valid_idx, s], all_local ) stage_interp = np.clip(stage_interp, 0.0, 1.0) row_sums = stage_interp.sum(axis=1, keepdims=True) nz = row_sums.squeeze(-1) > 0 stage_interp[nz] = stage_interp[nz] / row_sums[nz] sd["viz_stages"] = stage_interp else: # No valid points: keep NaNs/zeros; visualization will be empty. sd["viz_stages"] = np.nan_to_num(sd["viz_stages"], nan=0.0) # Generate visualization for each head ordered_viz_frames = [viz_frames[idx] for idx in sorted(display_indices)] for scheme in schemes_to_viz: sd = scheme_data[scheme] stage_labels = sd["subtask_names"] or [f"Stage {i + 1}" for i in range(sd["num_stages"])] viz_path = output_dir / f"sarm_prediction_ep{episode_idx}_{scheme}.png" visualize_episode( frames=np.array(ordered_viz_frames), progress_preds=sd["viz_progress"], stage_preds=sd["viz_stages"], title=f"{task} (Episode {episode_idx})", output_path=viz_path, stage_labels=stage_labels, gt_progress=sd["viz_gt_progress"] if not np.all(np.isnan(sd["viz_gt_progress"])) else None, gt_stages=sd["viz_gt_stages"] if not np.all(np.isnan(sd["viz_gt_stages"])) else None, ) # Clear memory between episodes torch.cuda.empty_cache() logging.info(f"Visualizations saved to: {output_dir.absolute()}") def generate_all_frame_indices(ep_start: int, ep_end: int, frame_gap: int = 30) -> list[int]: """Generate all frame indices, ordered by offset for cache-friendly access. Orders frames as: [0, 30, 60...], [1, 31, 61...], ..., [29, 59, 89...] This groups frames that share similar temporal windows together. """ num_frames = ep_end - ep_start indices = [] for offset in range(frame_gap): for frame_rel in range(offset, num_frames, frame_gap): indices.append(ep_start + frame_rel) return indices def interpolate_progress( computed_indices: np.ndarray, computed_values: np.ndarray, all_indices: np.ndarray, ) -> np.ndarray: """Linearly interpolate values to fill in gaps (robust to NaNs / edge cases).""" computed_indices = np.asarray(computed_indices) computed_values = np.asarray(computed_values) all_indices = np.asarray(all_indices) mask = np.isfinite(computed_values) if mask.sum() == 0: return np.full(all_indices.shape, np.nan, dtype=np.float32) if mask.sum() == 1: return np.full(all_indices.shape, float(computed_values[mask][0]), dtype=np.float32) out = np.interp(all_indices, computed_indices[mask], computed_values[mask]) return out.astype(np.float32) def compute_sarm_progress( dataset_repo_id: str, reward_model_path: str, output_path: str | None = None, head_mode: str = "sparse", device: str = "cuda", num_visualizations: int = 5, output_dir: str = "./sarm_viz", stride: int = 1, ): """ Compute SARM progress predictions for all frames in a dataset. Args: dataset_repo_id: HuggingFace dataset repo ID or local path reward_model_path: Path to pretrained SARM model output_path: Path to save results. If None, saves to dataset's cache directory head_mode: SARM head to use ("sparse", "dense", or "both") device: Device to use for inference num_visualizations: Number of episodes to visualize (0 to skip) output_dir: Directory to save visualizations stride: Compute progress every N frames, interpolate the rest (default: 1 = every frame) """ dataset, reward_model, preprocess = load_sarm_resources(dataset_repo_id, reward_model_path, device) # Set preprocessor to eval mode to disable augmentations if hasattr(preprocess, "eval"): preprocess.eval() for step in preprocess.steps: if hasattr(step, "eval"): step.eval() image_key = reward_model.config.image_key state_key = reward_model.config.state_key frame_gap = reward_model.config.frame_gap num_episodes = dataset.num_episodes total_frames = dataset.num_frames logging.info(f"Processing {total_frames} frames across {num_episodes} episodes") # Determine which heads to compute dual_mode = reward_model.config.uses_dual_heads compute_sparse = head_mode in ("sparse", "both") or not dual_mode compute_dense = head_mode in ("dense", "both") and dual_mode # Storage arrays all_indices = [] all_episode_indices = [] all_frame_indices = [] all_progress_sparse = [] if compute_sparse else None all_progress_dense = [] if compute_dense else None if stride > 1: logging.info(f"Using stride={stride}: computing every {stride} frames, interpolating the rest") # Process all episodes for episode_idx in tqdm(range(num_episodes), desc="Episodes"): ep = dataset.meta.episodes[episode_idx] ep_start = ep["dataset_from_index"] ep_end = ep["dataset_to_index"] # Get task description task = dataset[ep_start].get("task", "perform the task") # Generate frames to compute (with stride applied) all_ep_indices = generate_all_frame_indices(ep_start, ep_end, frame_gap) if stride > 1: # Only compute every stride-th frame (relative to episode start) compute_indices = [idx for idx in all_ep_indices if (idx - ep_start) % stride == 0] # Always include last frame for better interpolation at episode end last_frame = ep_end - 1 if last_frame not in compute_indices: compute_indices.append(last_frame) compute_indices = sorted(set(compute_indices)) else: compute_indices = all_ep_indices center_idx = reward_model.config.n_obs_steps // 2 # Center of bidirectional window # Dictionary to collect results frame_results = {} for query_idx in tqdm(compute_indices, desc=f" Ep {episode_idx}", leave=False): try: sample = dataset[query_idx] batch = { image_key: sample[image_key], "task": task, "index": query_idx, "episode_index": episode_idx, } if state_key in sample: batch[state_key] = sample[state_key] with torch.no_grad(): processed = preprocess(batch) video_features = processed["video_features"].to(device) text_features = processed["text_features"].to(device) state_features = processed.get("state_features") if state_features is not None: state_features = state_features.to(device) lengths = processed.get("lengths") sparse_val = np.nan dense_val = np.nan # Compute sparse prediction for center frame if compute_sparse: sparse_progress = reward_model.calculate_rewards( text_embeddings=text_features, video_embeddings=video_features, state_features=state_features, lengths=lengths, return_all_frames=True, head_mode="sparse", ) sparse_val = float( sparse_progress[0, center_idx] if sparse_progress.ndim == 2 else sparse_progress[center_idx] ) # Compute dense prediction for center frame if compute_dense: dense_progress = reward_model.calculate_rewards( text_embeddings=text_features, video_embeddings=video_features, state_features=state_features, lengths=lengths, return_all_frames=True, head_mode="dense", ) dense_val = float( dense_progress[0, center_idx] if dense_progress.ndim == 2 else dense_progress[center_idx] ) frame_results[query_idx] = (sparse_val, dense_val) except Exception as e: logging.warning(f"Failed to process frame {query_idx}: {e}") # Interpolate to get values for all frames computed_indices = np.array(sorted(frame_results.keys())) computed_sparse = ( np.array([frame_results[i][0] for i in computed_indices]) if compute_sparse else None ) computed_dense = np.array([frame_results[i][1] for i in computed_indices]) if compute_dense else None # All frame indices for this episode all_frame_idx_array = np.arange(ep_start, ep_end) if stride > 1 and len(computed_indices) > 1: # Interpolate progress values if compute_sparse: interp_sparse = interpolate_progress(computed_indices, computed_sparse, all_frame_idx_array) if compute_dense: interp_dense = interpolate_progress(computed_indices, computed_dense, all_frame_idx_array) else: # No interpolation needed interp_sparse = computed_sparse if compute_sparse else None interp_dense = computed_dense if compute_dense else None # Store results for all frames for i, frame_idx in enumerate(all_frame_idx_array): local_idx = frame_idx - ep_start all_indices.append(frame_idx) all_episode_indices.append(episode_idx) all_frame_indices.append(local_idx) if compute_sparse: if stride > 1 and len(computed_indices) > 1: all_progress_sparse.append(float(interp_sparse[i])) elif frame_idx in frame_results: all_progress_sparse.append(frame_results[frame_idx][0]) else: all_progress_sparse.append(np.nan) if compute_dense: if stride > 1 and len(computed_indices) > 1: all_progress_dense.append(float(interp_dense[i])) elif frame_idx in frame_results: all_progress_dense.append(frame_results[frame_idx][1]) else: all_progress_dense.append(np.nan) # Create output table table_data = { "index": np.array(all_indices, dtype=np.int64), "episode_index": np.array(all_episode_indices, dtype=np.int64), "frame_index": np.array(all_frame_indices, dtype=np.int64), } if compute_sparse: table_data["progress_sparse"] = np.array(all_progress_sparse, dtype=np.float32) if compute_dense: table_data["progress_dense"] = np.array(all_progress_dense, dtype=np.float32) # Sort by index df = pa.table(table_data).to_pandas() df = df.sort_values("index").reset_index(drop=True) final_table = pa.Table.from_pandas(df, preserve_index=False) # Add metadata with reward model path metadata = {b"reward_model_path": reward_model_path.encode()} final_table = final_table.replace_schema_metadata(metadata) # Determine output path output_path = Path(dataset.root) / "sarm_progress.parquet" if output_path is None else Path(output_path) # Save output_path.parent.mkdir(parents=True, exist_ok=True) pq.write_table(final_table, output_path) logging.info(f"Saved {len(final_table)} frame progress values to {output_path}") # Print statistics if "progress_sparse" in df.columns: valid = df["progress_sparse"].dropna() logging.info( f"Sparse progress: mean={valid.mean():.4f}, std={valid.std():.4f}, " f"min={valid.min():.4f}, max={valid.max():.4f}" ) if "progress_dense" in df.columns: valid = df["progress_dense"].dropna() logging.info( f"Dense progress: mean={valid.mean():.4f}, std={valid.std():.4f}, " f"min={valid.min():.4f}, max={valid.max():.4f}" ) # Visualize episodes after processing if num_visualizations > 0: viz_episodes = list(range(min(num_visualizations, num_episodes))) logging.info(f"Generating {len(viz_episodes)} visualizations...") visualize_sarm_predictions( dataset=dataset, reward_model=reward_model, preprocess=preprocess, episode_indices=viz_episodes, head_mode=head_mode, output_dir=Path(output_dir), stride=stride, ) return output_path def main(): parser = argparse.ArgumentParser( description="Compute SARM progress values for RA-BC weighting or visualize SARM predictions", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Full RA-BC computation with visualizations python src/lerobot/policies/sarm/compute_rabc_weights.py \\ --dataset-repo-id lerobot/aloha_sim_insertion_human \\ --reward-model-path <USER>/sarm_single_uni4 # Visualize predictions only (no RA-BC computation) python src/lerobot/policies/sarm/compute_rabc_weights.py \\ --dataset-repo-id lerobot/aloha_sim_insertion_human \\ --reward-model-path <USER>/sarm_single_uni4 \\ --visualize-only \\ --num-visualizations 10 """, ) parser.add_argument( "--dataset-repo-id", type=str, required=True, help="HuggingFace dataset repo ID or local path", ) parser.add_argument( "--reward-model-path", type=str, default=None, help="Path to pretrained SARM model (reads from existing parquet metadata if not provided)", ) parser.add_argument( "--output-path", type=str, default=None, help="Output path for parquet. If not set, saves to dataset's cache directory", ) parser.add_argument( "--head-mode", type=str, default="sparse", choices=["sparse", "dense", "both"], help="SARM head to use (default: sparse)", ) parser.add_argument( "--device", type=str, default="cuda", help="Device to use (default: cuda)", ) # Visualization options parser.add_argument( "--visualize-only", action="store_true", help="Only visualize SARM predictions (no RA-BC computation)", ) parser.add_argument( "--num-visualizations", type=int, default=5, help="Number of episodes to visualize (default: 5, set to 0 to skip)", ) parser.add_argument( "--output-dir", type=str, default="./sarm_viz", help="Output directory for visualizations (default: ./sarm_viz)", ) parser.add_argument( "--push-to-hub", action="store_true", help="Upload progress file to the dataset repo on HuggingFace Hub", default=True, ) parser.add_argument( "--stride", type=int, default=1, help="Compute progress every N frames, interpolate the rest (default: 1 = every frame)", ) args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") # Try to get reward_model_path from parquet metadata if not provided reward_model_path = args.reward_model_path if reward_model_path is None: # Load dataset to find parquet path temp_dataset = LeRobotDataset(args.dataset_repo_id, download_videos=False) parquet_path = Path(temp_dataset.root) / "sarm_progress.parquet" reward_model_path = get_reward_model_path_from_parquet(parquet_path) if reward_model_path: logging.info(f"Using reward model from parquet metadata: {reward_model_path}") else: raise ValueError( "--reward-model-path is required (no existing parquet with model metadata found)" ) # Handle visualize-only mode if args.visualize_only: dataset, reward_model, preprocess = load_sarm_resources( args.dataset_repo_id, reward_model_path, args.device ) logging.info(f"Visualization-only mode: visualizing {args.num_visualizations} episodes") viz_episodes = list(range(min(args.num_visualizations, dataset.num_episodes))) visualize_sarm_predictions( dataset=dataset, reward_model=reward_model, preprocess=preprocess, episode_indices=viz_episodes, head_mode=args.head_mode, output_dir=Path(args.output_dir), stride=args.stride, ) print(f"\nVisualizations saved to: {Path(args.output_dir).absolute()}") return # Full RABC computation (compute_sarm_progress loads model/dataset itself) output_path = compute_sarm_progress( dataset_repo_id=args.dataset_repo_id, reward_model_path=reward_model_path, output_path=args.output_path, head_mode=args.head_mode, device=args.device, num_visualizations=args.num_visualizations, output_dir=args.output_dir, stride=args.stride, ) print(f"\nSARM progress values saved to: {output_path}") # Upload to Hub if requested if args.push_to_hub: from huggingface_hub import HfApi api = HfApi() hub_path = "sarm_progress.parquet" print(f"\nUploading to Hub: {args.dataset_repo_id}/{hub_path}") api.upload_file( path_or_fileobj=str(output_path), path_in_repo=hub_path, repo_id=args.dataset_repo_id, repo_type="dataset", ) print( f"Successfully uploaded to: https://huggingface.co/datasets/{args.dataset_repo_id}/blob/main/{hub_path}" ) print("\nTo use in training, add to your config:") print(" use_rabc: true") print(f" rabc_progress_path: hf://datasets/{args.dataset_repo_id}/{hub_path}") print(" rabc_head_mode: sparse # or dense") else: print("\nTo use in training, add to your config:") print(" use_rabc: true") print(f" rabc_progress_path: {output_path}") print(" rabc_head_mode: sparse # or dense") if __name__ == "__main__": main()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/sarm/compute_rabc_weights.py", "license": "Apache License 2.0", "lines": 751, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/sarm/configuration_sarm.py
#!/usr/bin/env python # Copyright 2025 Qianzhong Chen, Justin Yu, Mac Schwager, Pieter Abbeel, Yide Shentu, Philipp Wu # and The HuggingFace Inc. team. All rights reserved. # # 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. """ SARM: Stage-Aware Reward Modeling for Long Horizon Robot Manipulation. Paper: https://arxiv.org/abs/2509.25358 """ from dataclasses import dataclass, field from lerobot.configs.policies import PreTrainedConfig from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature from lerobot.optim.optimizers import AdamWConfig from lerobot.optim.schedulers import CosineDecayWithWarmupSchedulerConfig from lerobot.utils.constants import OBS_IMAGES, OBS_STATE @PreTrainedConfig.register_subclass("sarm") @dataclass class SARMConfig(PreTrainedConfig): """Configuration class for SARM (Stage-Aware Reward Modeling). Supports three annotation modes: 1. single_stage (default): No annotations needed. Uses the episode's task description as a single stage covering the entire episode. 2. dense_only: Uses dense (fine-grained) annotations from VLM, with an auto-generated single sparse "task" stage covering the full episode. The dense head learns detailed subtask progression while sparse provides overall task completion. 3. dual: Full dual-head mode with both sparse (high-level) and dense (fine-grained) annotations from VLM. Both heads are trained on their respective annotations. The annotation_mode determines how sparse_temporal_proportions and dense_temporal_proportions are loaded/generated during model initialization. """ annotation_mode: str = "single_stage" # "single_stage", "dense_only", or "dual" n_obs_steps: int = 8 # Number of observation history steps frame_gap: int = 30 # Frame gap between frames (at 30 fps = 1 second) max_rewind_steps: int = 4 # Maximum rewind steps for temporal augmentation # Total frames = 1 + n_obs_steps + max_rewind_steps (computed in property) # During training with rewind: [obs_frames] + [rewind_frames] # During inference: [obs_frames] only # Architecture params image_dim: int = 512 text_dim: int = 512 hidden_dim: int = 768 num_heads: int = 12 num_layers: int = 8 max_state_dim: int = 32 drop_n_last_frames: int = 1 batch_size: int = 64 clip_batch_size: int = 64 dropout: float = 0.1 stage_loss_weight: float = 1.0 # Weight for stage classification loss when using subtask annotations rewind_probability: float = 0.8 language_perturbation_probability: float = 0.2 # Sparse annotations (high-level stages) num_sparse_stages: int = 1 sparse_subtask_names: list | None = None sparse_temporal_proportions: list | None = None # Dense annotations (fine-grained stages) num_dense_stages: int | None = None dense_subtask_names: list | None = None dense_temporal_proportions: list | None = None pretrained_model_path: str | None = None device: str | None = None image_key: str = OBS_IMAGES + ".top" # Key for image used from the dataset state_key: str = OBS_STATE # Populated by the processor (video_features, state_features, text_features) input_features: dict = field(default_factory=lambda: {}) # Output features (updated in __post_init__) output_features: dict = field( default_factory=lambda: { "stage": PolicyFeature(shape=(9, 5), type=FeatureType.REWARD), "progress": PolicyFeature(shape=(9, 1), type=FeatureType.REWARD), } ) normalization_mapping: dict[str, NormalizationMode] = field( default_factory=lambda: { "VISUAL": NormalizationMode.IDENTITY, "STATE": NormalizationMode.MEAN_STD, "LANGUAGE": NormalizationMode.IDENTITY, "REWARD": NormalizationMode.IDENTITY, } ) def __post_init__(self): super().__post_init__() if self.annotation_mode not in ["single_stage", "dense_only", "dual"]: raise ValueError( f"annotation_mode must be 'single_stage', 'dense_only', or 'dual', got {self.annotation_mode}" ) if self.annotation_mode == "single_stage": # Use task description as stage name, full episode as one stage self.num_sparse_stages = 1 self.sparse_subtask_names = ["task"] self.sparse_temporal_proportions = [1.0] self.num_dense_stages = None self.dense_subtask_names = None self.dense_temporal_proportions = None elif self.annotation_mode == "dense_only": self.num_sparse_stages = 1 self.sparse_subtask_names = ["task"] self.sparse_temporal_proportions = [1.0] self.input_features = {} self.output_features = {} if self.image_key: self.input_features[self.image_key] = PolicyFeature(shape=(480, 640, 3), type=FeatureType.VISUAL) self.input_features[self.state_key] = PolicyFeature( shape=(self.max_state_dim,), type=FeatureType.STATE, ) # Update output features based on annotation_mode if self.annotation_mode in ["dense_only", "dual"]: self.output_features["sparse_stage"] = PolicyFeature( shape=(self.num_frames, self.num_sparse_stages), type=FeatureType.REWARD ) self.output_features["sparse_progress"] = PolicyFeature( shape=(self.num_frames, 1), type=FeatureType.REWARD ) dense_stages = self.num_dense_stages or self.num_sparse_stages self.output_features["dense_stage"] = PolicyFeature( shape=(self.num_frames, dense_stages), type=FeatureType.REWARD ) self.output_features["dense_progress"] = PolicyFeature( shape=(self.num_frames, 1), type=FeatureType.REWARD ) else: self.output_features["sparse_stage"] = PolicyFeature( shape=(self.num_frames, self.num_sparse_stages), type=FeatureType.REWARD ) self.output_features["sparse_progress"] = PolicyFeature( shape=(self.num_frames, 1), type=FeatureType.REWARD ) if self.max_rewind_steps >= self.n_obs_steps: raise ValueError( f"max_rewind_steps ({self.max_rewind_steps}) must be less than n_obs_steps ({self.n_obs_steps})" ) if self.num_sparse_stages < 1: raise ValueError(f"num_sparse_stages must be at least 1, got {self.num_sparse_stages}") if ( self.annotation_mode in ["dense_only", "dual"] and self.num_dense_stages is not None and self.num_dense_stages < 2 ): raise ValueError(f"num_dense_stages must be at least 2, got {self.num_dense_stages}") def get_optimizer_preset(self) -> AdamWConfig: """Get default optimizer configuration for SARM training.""" return AdamWConfig( lr=5e-5, weight_decay=1e-3, betas=(0.9, 0.999), eps=1e-8, ) def get_scheduler_preset(self) -> CosineDecayWithWarmupSchedulerConfig: """Get default learning rate scheduler configuration.""" return CosineDecayWithWarmupSchedulerConfig( peak_lr=5e-5, decay_lr=5e-6, num_warmup_steps=500, num_decay_steps=50000, ) def validate_features(self) -> None: pass @property def uses_dual_heads(self) -> bool: """Whether the model uses dual heads (dense_only or dual annotation modes).""" return self.annotation_mode in ["dense_only", "dual"] @property def num_frames(self) -> int: """Total number of frames in sequence. For training: 1 + n_obs_steps + max_rewind_steps The sequence is: [obs_frames (n_obs_steps + 1)] + [rewind_frames (max_rewind_steps)] """ return 1 + self.n_obs_steps + self.max_rewind_steps @property def max_length(self) -> int: return self.num_frames @property def observation_delta_indices(self) -> list[int]: """Bidirectional frame sampling centered on target frame. Example with n_obs_steps=8, gap=30: Before: [-120, -90, -60, -30] (4 frames) Current: [0] (1 frame) After: [30, 60, 90, 120] (4 frames) Total: 9 frames """ half_steps = self.n_obs_steps // 2 past_deltas = [-self.frame_gap * i for i in range(half_steps, 0, -1)] future_deltas = [self.frame_gap * i for i in range(1, half_steps + 1)] obs_deltas = past_deltas + [0] + future_deltas # Rewind placeholders rewind_deltas = [-self.frame_gap * (i + 1) for i in range(self.max_rewind_steps)] return obs_deltas + rewind_deltas @property def action_delta_indices(self) -> None: """SARM is a reward model, not an action policy.""" return None @property def reward_delta_indices(self) -> None: return None
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/sarm/configuration_sarm.py", "license": "Apache License 2.0", "lines": 205, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/sarm/modeling_sarm.py
#!/usr/bin/env python # Copyright 2025 Qianzhong Chen, Justin Yu, Mac Schwager, Pieter Abbeel, Yide Shentu, Philipp Wu # and The HuggingFace Inc. team. All rights reserved. # # 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. """ SARM: Stage-Aware Reward Modeling for Long Horizon Robot Manipulation. Paper: https://arxiv.org/abs/2509.25358 - StageTransformer: Predicts stage classification (sparse/dense) - SubtaskTransformer: Predicts within-stage progress (tau) conditioned on stage """ import json import logging import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # noqa: N812 from torch import Tensor from lerobot.policies.pretrained import PreTrainedPolicy from lerobot.policies.sarm.configuration_sarm import SARMConfig from lerobot.policies.sarm.sarm_utils import ( normalize_stage_tau, pad_state_to_max_dim, ) from lerobot.utils.constants import OBS_STR class StageTransformer(nn.Module): """ Stage classification transformer for SARM. Predicts which stage/subtask the current frame belongs to. Supports both sparse (high-level) and dense (fine-grained) annotation schemes. Input streams: [vis_proj, lang_proj, state_proj] concatenated -> (B, N+2, T, D) Output: stage logits (B, T, num_classes) """ def __init__( self, d_model: int = 512, vis_emb_dim: int = 512, text_emb_dim: int = 512, state_dim: int = 32, n_layers: int = 6, n_heads: int = 8, dropout: float = 0.1, num_cameras: int = 1, num_classes_sparse: int = 4, num_classes_dense: int = 8, ): super().__init__() self.d_model = d_model self.num_cameras = num_cameras # Projections self.lang_proj = nn.Linear(text_emb_dim, d_model) self.visual_proj = nn.Linear(vis_emb_dim, d_model) self.state_proj = nn.Linear(state_dim, d_model) # Encoder enc_layer = nn.TransformerEncoderLayer(d_model, n_heads, 4 * d_model, dropout, batch_first=True) self.transformer = nn.TransformerEncoder(enc_layer, n_layers) # Positional bias on first visual frame self.first_pos = nn.Parameter(torch.zeros(1, d_model)) # Shared fusion MLP # Fuses (num_cameras + 2) streams: cameras + lang + state fused_in = d_model * (num_cameras + 2) self.fusion_backbone = nn.Sequential( nn.LayerNorm(fused_in), nn.Linear(fused_in, d_model), nn.ReLU(), ) # Scheme-specific heads self.heads = nn.ModuleDict( { "sparse": nn.Linear(d_model, num_classes_sparse), "dense": nn.Linear(d_model, num_classes_dense), } ) def _prep_lang(self, lang_emb: torch.Tensor, B: int, T: int, D: int) -> torch.Tensor: # noqa: N803 """ Prepare language embeddings for fusion. Accepts lang_emb of shape: - (B, text_emb_dim) -> broadcast across time - (B, T, text_emb_dim) -> per-timestep (dense annotation mode) Returns: (B, 1, T, D) """ if lang_emb.dim() == 3: # (B, T, E) -> (B, T, D) -> (B, 1, T, D) lang_proj = self.lang_proj(lang_emb).unsqueeze(1) else: # (B, E) -> (B, 1, 1, D) -> expand to (B, 1, T, D) lang_proj = self.lang_proj(lang_emb).unsqueeze(1).unsqueeze(2).expand(B, 1, T, D) return lang_proj def forward( self, img_seq: torch.Tensor, # (B, N, T, vis_emb_dim) lang_emb: torch.Tensor, # (B, E) or (B, T, E) state: torch.Tensor, # (B, T, state_dim) lengths: torch.Tensor, # (B,) - valid sequence lengths scheme: str = "sparse", # "sparse" or "dense" ) -> torch.Tensor: """ Forward pass for stage classification. Args: img_seq: Image embeddings (B, N, T, vis_emb_dim) where N=num_cameras lang_emb: Language embeddings (B, E) or (B, T, E) for dense state: State features (B, T, state_dim) lengths: Valid sequence lengths (B,) for masking scheme: "sparse" or "dense" for head selection Returns: Stage logits (B, T, num_classes) """ assert scheme in self.heads, f"Unknown scheme '{scheme}'. Use one of {list(self.heads.keys())}." B, N, T, _ = img_seq.shape # noqa: N806 D = self.d_model # noqa: N806 device = img_seq.device # Project inputs vis_proj = self.visual_proj(img_seq) # (B, N, T, D) state_proj = self.state_proj(state).unsqueeze(1) # (B, 1, T, D) lang_proj = self._prep_lang(lang_emb, B, T, D) # (B, 1, T, D) # Concatenate streams # cameras + lang + state -> (B, N+2, T, D) x = torch.cat([vis_proj, lang_proj, state_proj], dim=1) # Add positional bias to first visual frame x[:, :N, 0, :] = x[:, :N, 0, :] + self.first_pos # Flatten to tokens for Transformer x_tokens = x.view(B, (N + 2) * T, D) L = x_tokens.size(1) # noqa: N806 # Create padding mask base_mask = torch.arange(T, device=device).expand(B, T) >= lengths.unsqueeze(1) # (B, T) mask = base_mask.unsqueeze(1).expand(B, N + 2, T).reshape(B, (N + 2) * T) # Create causal mask causal_mask = torch.triu(torch.ones(L, L, device=device, dtype=torch.bool), diagonal=1) # Encode h = self.transformer(x_tokens, mask=causal_mask, src_key_padding_mask=mask, is_causal=True) # Reshape and fuse h = h.view(B, N + 2, T, D).permute(0, 2, 1, 3).reshape(B, T, (N + 2) * D) fused = self.fusion_backbone(h) # (B, T, D) # Scheme-specific logits logits = self.heads[scheme](fused) # (B, T, num_classes) return logits class SubtaskTransformer(nn.Module): """ Subtask progress regression transformer for SARM. Predicts within-stage normalized progress (tau) conditioned on stage prior. The stage prior is a one-hot encoding passed from StageTransformer predictions. Input streams: [vis_proj, lang_proj, state_proj, stage_emb] -> (B, N+3, T, D) Output: tau predictions (B, T) in [0, 1] """ def __init__( self, d_model: int = 512, vis_emb_dim: int = 512, text_emb_dim: int = 512, state_dim: int = 32, n_layers: int = 6, n_heads: int = 8, dropout: float = 0.1, num_cameras: int = 1, ): super().__init__() self.d_model = d_model self.num_cameras = num_cameras # Projections self.lang_proj = nn.Linear(text_emb_dim, d_model) self.visual_proj = nn.Linear(vis_emb_dim, d_model) self.state_proj = nn.Linear(state_dim, d_model) # Encoder enc = nn.TransformerEncoderLayer(d_model, n_heads, 4 * d_model, dropout, batch_first=True) self.transformer = nn.TransformerEncoder(enc, n_layers) # Learned bias on first visual frame self.first_pos = nn.Parameter(torch.zeros(1, d_model)) # Shared fusion backbone # Fuses (num_cameras + 3) streams: cameras + lang + state + stage_emb fused_in = d_model * (num_cameras + 3) self.fusion_backbone = nn.Sequential( nn.LayerNorm(fused_in), nn.Linear(fused_in, d_model), nn.ReLU(), ) # Scheme-specific regression heads self.heads = nn.ModuleDict( { "sparse": nn.Linear(d_model, 1), "dense": nn.Linear(d_model, 1), } ) def _prep_lang(self, lang_emb: torch.Tensor, B: int, T: int, D: int) -> torch.Tensor: # noqa: N803 """ Prepare language embeddings for fusion. """ if lang_emb.dim() == 3: # (B, T, E) -> (B, T, D) -> (B, 1, T, D) return self.lang_proj(lang_emb).unsqueeze(1) else: # (B, E) -> (B, 1, 1, D) -> (B, 1, T, D) return self.lang_proj(lang_emb).unsqueeze(1).unsqueeze(2).expand(B, 1, T, D) def _stage_to_dmodel(self, stage_prior: torch.Tensor) -> torch.Tensor: """ Deterministic projection of one-hot stage to d_model by pad/truncate. Args: stage_prior: One-hot stage embedding (B, 1, T, C) Returns: Projected stage embedding (B, 1, T, d_model) """ B, one, T, C = stage_prior.shape # noqa: N806 D = self.d_model # noqa: N806 if D == C: return stage_prior elif D > C: pad = torch.zeros(B, one, T, D - C, device=stage_prior.device, dtype=stage_prior.dtype) return torch.cat([stage_prior, pad], dim=-1) else: return stage_prior[..., :D] def forward( self, img_seq: torch.Tensor, # (B, N, T, vis_emb_dim) lang_emb: torch.Tensor, # (B, E) or (B, T, E) state: torch.Tensor, # (B, T, state_dim) lengths: torch.Tensor, # (B,) - valid sequence lengths stage_prior: torch.Tensor, # (B, 1, T, C) one-hot from gen_stage_emb scheme: str = "sparse", # "sparse" or "dense" ) -> torch.Tensor: """ Forward pass for subtask progress regression. Args: img_seq: Image embeddings (B, N, T, vis_emb_dim) lang_emb: Language embeddings (B, E) or (B, T, E) state: State features (B, T, state_dim) lengths: Valid sequence lengths (B,) for masking stage_prior: One-hot stage prior (B, 1, T, num_classes) scheme: "sparse" or "dense" for head selection Returns: Tau predictions (B, T) in [0, 1] via sigmoid """ assert scheme in self.heads, f"Unknown scheme '{scheme}'. Use one of {list(self.heads.keys())}." B, N, T, _ = img_seq.shape # noqa: N806 D = self.d_model # noqa: N806 device = img_seq.device # Project inputs vis_proj = self.visual_proj(img_seq) # (B, N, T, D) state_proj = self.state_proj(state).unsqueeze(1) # (B, 1, T, D) lang_proj = self._prep_lang(lang_emb, B, T, D) # (B, 1, T, D) stage_emb = self._stage_to_dmodel(stage_prior) # (B, 1, T, D) # Concatenate all streams # cameras + lang + state + stage_emb -> (B, N+3, T, D) x = torch.cat([vis_proj, lang_proj, state_proj, stage_emb], dim=1) # Add positional bias to first visual frame x[:, :N, 0, :] = x[:, :N, 0, :] + self.first_pos # Flatten to tokens x_tokens = x.view(B, (N + 3) * T, D) L = x_tokens.size(1) # noqa: N806 # Create padding mask base_mask = torch.arange(T, device=device).expand(B, T) >= lengths.unsqueeze(1) mask = base_mask.unsqueeze(1).expand(B, N + 3, T).reshape(B, (N + 3) * T) # Create causal mask causal_mask = torch.triu(torch.ones(L, L, device=device, dtype=torch.bool), diagonal=1) # Encode h = self.transformer(x_tokens, mask=causal_mask, src_key_padding_mask=mask, is_causal=True) # Reshape and fuse h = h.view(B, N + 3, T, D) h_flat = h.permute(0, 2, 1, 3).reshape(B, T, (N + 3) * D) fused = self.fusion_backbone(h_flat) # (B, T, D) # Scheme-specific regression head -> sigmoid r = torch.sigmoid(self.heads[scheme](fused)).squeeze(-1) # (B, T) return r def gen_stage_emb(num_classes: int, targets: torch.Tensor) -> torch.Tensor: """ Generate one-hot stage embeddings from targets. Args: num_classes: Number of stage classes targets: Target values (B, T) where integer part is stage index Returns: One-hot stage embedding (B, 1, T, num_classes) """ # Integer part of float targets -> [0, C-1] idx = targets.long().clamp(min=0, max=num_classes - 1) # (B, T) C = num_classes # noqa: N806 # Identity-lookup one-hot stage_onehot = torch.eye(C, device=targets.device)[idx] # (B, T, C) stage_onehot = stage_onehot.unsqueeze(1) # (B, 1, T, C) return stage_onehot class SARMRewardModel(PreTrainedPolicy): """ SARM Reward Model for stage-aware task completion rewards. Uses two separate transformer models: - StageTransformer: Classifies which stage/subtask - SubtaskTransformer: Predicts within-stage progress (tau) Training uses 75%/25% GT/predicted stage conditioning (teacher forcing). """ name = "sarm" config_class = SARMConfig def __init__(self, config: SARMConfig, dataset_stats: dict | None = None, dataset_meta=None): super().__init__(config, dataset_stats) config.validate_features() self.config = config self.dataset_stats = dataset_stats self.device = torch.device( config.device if config.device else "cuda" if torch.cuda.is_available() else "cpu" ) # Load temporal proportions based on annotation_mode if config.annotation_mode == "single_stage": logging.info(f"Using single_stage mode: sparse_subtask_names={config.sparse_subtask_names}") elif dataset_meta is not None: self._load_temporal_proportions(dataset_meta) # Create two separate models self.stage_model = StageTransformer( d_model=config.hidden_dim, vis_emb_dim=config.image_dim, text_emb_dim=config.text_dim, state_dim=config.max_state_dim, n_layers=config.num_layers, n_heads=config.num_heads, dropout=config.dropout, num_cameras=1, # Single camera for now num_classes_sparse=config.num_sparse_stages, num_classes_dense=config.num_dense_stages or config.num_sparse_stages, ) self.subtask_model = SubtaskTransformer( d_model=config.hidden_dim, vis_emb_dim=config.image_dim, text_emb_dim=config.text_dim, state_dim=config.max_state_dim, n_layers=config.num_layers, n_heads=config.num_heads, dropout=config.dropout, num_cameras=1, ) self.stage_model.to(self.device) self.subtask_model.to(self.device) # GT/predicted stage ratio for teacher forcing self.gt_stage_ratio = 0.75 if config.uses_dual_heads: logging.info( f"SARM initialized with dual heads: {config.num_sparse_stages} sparse stages, " f"{config.num_dense_stages} dense stages" ) else: logging.info(f"SARM initialized with sparse head only: {config.num_sparse_stages} stages") logging.info(f"SARM initialized on {self.device}") def _load_proportions_from_json(self, path, annotation_type: str) -> tuple[list[str], list[float]]: """Load temporal proportions from a JSON file (preserving order).""" if not path.exists(): raise ValueError( f"{annotation_type.capitalize()} temporal proportions not found at {path}. " f"Run the subtask annotation tool with --{annotation_type}-subtasks to generate annotations." ) with open(path) as f: proportions_dict = json.load(f) names = list(proportions_dict.keys()) logging.info(f"Loaded {len(names)} {annotation_type} subtasks: {names}") logging.info(f"{annotation_type.capitalize()} temporal proportions: {proportions_dict}") return names, [proportions_dict[name] for name in names] def _load_temporal_proportions(self, dataset_meta) -> None: """Load temporal proportions based on annotation_mode.""" meta_path = dataset_meta.root / "meta" if self.config.annotation_mode == "dual": names, props = self._load_proportions_from_json( meta_path / "temporal_proportions_sparse.json", "sparse" ) ( self.config.num_sparse_stages, self.config.sparse_subtask_names, self.config.sparse_temporal_proportions, ) = len(names), names, props if self.config.annotation_mode in ["dense_only", "dual"]: names, props = self._load_proportions_from_json( meta_path / "temporal_proportions_dense.json", "dense" ) ( self.config.num_dense_stages, self.config.dense_subtask_names, self.config.dense_temporal_proportions, ) = len(names), names, props if self.config.annotation_mode == "dense_only": logging.info(f"Using auto-generated sparse 'task' stage: {self.config.sparse_subtask_names}") def to(self, device): """Override to method to ensure all components move together.""" super().to(device) self.device = device if isinstance(device, torch.device) else torch.device(device) self.stage_model.to(device) self.subtask_model.to(device) return self @torch.no_grad() def calculate_rewards( self, text_embeddings: np.ndarray | torch.Tensor, video_embeddings: np.ndarray | torch.Tensor, state_features: np.ndarray | torch.Tensor | None = None, lengths: np.ndarray | torch.Tensor | None = None, return_all_frames: bool = False, return_stages: bool = False, return_confidence: bool = False, head_mode: str | None = "sparse", frame_index: int | None = None, ) -> np.ndarray | tuple: """ Calculate rewards for given text, video, and state representations. This is the canonical method for SARM reward computation, used for: - Inference/visualization - RA-BC weight computation Args: text_embeddings: Encoded text representations (batch_size, 512) video_embeddings: Encoded video representations (batch_size, num_frames, 512) state_features: Joint state features (batch_size, num_frames, state_dim) lengths: Valid sequence lengths (batch_size,) return_all_frames: If True, return rewards for all frames return_stages: If True, also return stage predictions return_confidence: If True, also return stage confidence head_mode: Which head to use ("sparse" or "dense") frame_index: Index of the target frame to extract (default: n_obs_steps). Returns: Rewards and optionally stage probs/confidence. """ if isinstance(text_embeddings, np.ndarray): text_embeddings = torch.tensor(text_embeddings, dtype=torch.float32) if isinstance(video_embeddings, np.ndarray): video_embeddings = torch.tensor(video_embeddings, dtype=torch.float32) if state_features is not None and isinstance(state_features, np.ndarray): state_features = torch.tensor(state_features, dtype=torch.float32) # Handle single sample case if text_embeddings.dim() == 1: text_embeddings = text_embeddings.unsqueeze(0) video_embeddings = video_embeddings.unsqueeze(0) if state_features is not None: state_features = state_features.unsqueeze(0) single_sample = True else: single_sample = False batch_size = video_embeddings.shape[0] seq_len = video_embeddings.shape[1] scheme = head_mode # Default lengths if not provided if lengths is None: lengths = torch.full((batch_size,), seq_len, dtype=torch.int32) elif isinstance(lengths, np.ndarray): lengths = torch.tensor(lengths, dtype=torch.int32) # Reshape video to (B, N, T, D) for multi-camera format # Currently single camera: (B, T, D) -> (B, 1, T, D) img_seq = video_embeddings.unsqueeze(1).to(self.device) lang_emb = text_embeddings.to(self.device) state = ( state_features.to(self.device) if state_features is not None else torch.zeros(batch_size, seq_len, self.config.max_state_dim, device=self.device) ) lens = lengths.to(self.device) # Pad state to max_state_dim state = pad_state_to_max_dim(state, self.config.max_state_dim) # Get num_classes for this scheme num_classes = self.config.num_sparse_stages if scheme == "sparse" else self.config.num_dense_stages # Run stage model stage_logits = self.stage_model(img_seq, lang_emb, state, lens, scheme=scheme) stage_probs = F.softmax(stage_logits, dim=-1) # (B, T, num_classes) stage_idx = stage_probs.argmax(dim=-1) # (B, T) stage_conf = stage_probs.gather(-1, stage_idx.unsqueeze(-1)).squeeze(-1) # (B, T) # Create one-hot stage prior stage_onehot = F.one_hot(stage_idx, num_classes=num_classes).float() # (B, T, C) stage_emb = stage_onehot.unsqueeze(1) # (B, 1, T, C) # Run subtask model tau_pred = self.subtask_model(img_seq, lang_emb, state, lens, stage_emb, scheme=scheme) # Compute final reward: stage + tau raw_reward = stage_idx.float() + tau_pred # (B, T) # Normalize to [0, 1] using temporal proportions for proper weighting if scheme == "sparse": normalized_reward = normalize_stage_tau( raw_reward, num_stages=num_classes, temporal_proportions=self.config.sparse_temporal_proportions, subtask_names=self.config.sparse_subtask_names, ) else: normalized_reward = normalize_stage_tau( raw_reward, num_stages=num_classes, temporal_proportions=self.config.dense_temporal_proportions, subtask_names=self.config.dense_subtask_names, ) # Default frame index is n_obs_steps (last observation frame) if frame_index is None: frame_index = self.config.n_obs_steps # Prepare outputs (batch mode or no smoothing) if return_all_frames: rewards = normalized_reward.cpu().numpy() else: rewards = normalized_reward[:, frame_index].cpu().numpy() if single_sample: rewards = rewards[0] if not return_all_frames else rewards[0] outputs = [rewards] if return_stages: probs = stage_probs.cpu().numpy() if single_sample: probs = probs[0] outputs.append(probs) if return_confidence: conf = stage_conf.cpu().numpy() if single_sample: conf = conf[0] outputs.append(conf) return outputs[0] if len(outputs) == 1 else tuple(outputs) def train(self, mode: bool = True): """Set training mode for both models.""" super().train(mode) self.stage_model.train(mode) self.subtask_model.train(mode) return self def eval(self): """Set evaluation mode for both models.""" return self.train(False) def parameters(self): """Override to return trainable parameters from both models.""" from itertools import chain return chain(self.stage_model.parameters(), self.subtask_model.parameters()) def get_optim_params(self): """Override to return optimizer parameters from both models.""" return self.parameters() def reset(self): """Required by PreTrainedPolicy but not used for reward models.""" pass def predict_action_chunk(self, batch: dict[str, Tensor]) -> Tensor: """Required by PreTrainedPolicy but not used for reward models.""" raise NotImplementedError("SARM model does not predict action chunks") def select_action(self, batch: dict[str, Tensor]) -> Tensor: """Required by PreTrainedPolicy but not used for SARM.""" raise NotImplementedError("SARM model does not select actions") def _train_step( self, img_emb: torch.Tensor, # (B, N, T, D) lang_emb: torch.Tensor, # (B, E) or (B, T, E) state: torch.Tensor, # (B, T, state_dim) lengths: torch.Tensor, # (B,) targets: torch.Tensor, # (B, T) - format: stage.tau scheme: str, ) -> dict[str, torch.Tensor]: """ Single training step for one annotation scheme. Implements 75%/25% GT/predicted stage conditioning. Args: img_emb: Image embeddings (B, N, T, D) lang_emb: Language embeddings state: State features lengths: Valid sequence lengths targets: Target values where floor=stage, remainder=tau scheme: "sparse" or "dense" Returns: Dict with stage_loss, subtask_loss, total_loss """ num_classes = self.config.num_sparse_stages if scheme == "sparse" else self.config.num_dense_stages # Ground truth: stage (integer) and tau (fractional) # Clamp stage indices to valid range [0, num_classes-1] to handle edge cases # where targets may exceed expected range (e.g., frames between subtasks) gt_stage = torch.floor(targets).long().clamp(0, num_classes - 1) # (B, T) gt_tau = torch.remainder(targets, 1.0) # (B, T) # Run stage model stage_pred = self.stage_model(img_emb, lang_emb, state, lengths, scheme=scheme) # 75%/25% GT/predicted stage conditioning if random.random() < self.gt_stage_ratio: # Mode 1: Use ground truth stage -> one-hot stage_emb = gen_stage_emb(num_classes, targets) # (B, 1, T, C) else: # Mode 2: Use predicted stage argmax -> one-hot stage_idx = stage_pred.argmax(dim=-1) # (B, T) stage_onehot = F.one_hot(stage_idx, num_classes=num_classes).float() # (B, T, C) stage_emb = stage_onehot.unsqueeze(1) # (B, 1, T, C) # Run subtask model with stage prior tau_pred = self.subtask_model(img_emb, lang_emb, state, lengths, stage_emb, scheme=scheme) # Compute losses stage_loss = F.cross_entropy(stage_pred.view(-1, num_classes), gt_stage.view(-1), reduction="mean") subtask_loss = F.mse_loss(tau_pred, gt_tau, reduction="mean") return { "stage_loss": stage_loss, "subtask_loss": subtask_loss, "total_loss": stage_loss + subtask_loss, } def forward(self, batch): """ Forward pass for SARM reward model training. Uses stage+tau target format where: - Integer part = stage index - Fractional part = within-stage progress (tau) Training uses 75%/25% GT/predicted stage conditioning. Args: batch: Dictionary with 'observation' containing: - 'video_features': (B, T, 512) pre-encoded video features - 'text_features': (B, 512) or (B, T, 512) text features - 'state_features': (B, T, state_dim) joint state features - 'lengths': (B,) valid sequence lengths - 'sparse_targets': (B, T) sparse targets (stage.tau format) - 'dense_targets': (B, T) dense targets (optional, for dual mode) Returns: Tuple of (total_loss, output_dict with loss components) """ observation = batch.get(OBS_STR, batch) # Extract features video_features = observation["video_features"].to(self.device) text_features = observation["text_features"].to(self.device) state_features = observation.get("state_features") if state_features is not None: state_features = state_features.to(self.device) batch_size = video_features.shape[0] seq_len = video_features.shape[1] # Get lengths (default to full sequence) lengths = observation.get("lengths") if lengths is None: lengths = torch.full((batch_size,), seq_len, dtype=torch.int32, device=self.device) else: lengths = lengths.to(self.device) # Reshape video to (B, N, T, D) - single camera img_emb = video_features.unsqueeze(1) # Pad state to max_state_dim if state_features is None: state_features = torch.zeros(batch_size, seq_len, self.config.max_state_dim, device=self.device) else: state_features = pad_state_to_max_dim(state_features, self.config.max_state_dim) output_dict = {} total_loss = torch.tensor(0.0, device=self.device) # Sparse training (always) sparse_targets = observation.get("sparse_targets") if sparse_targets is None: # Try legacy format sparse_targets = observation.get("targets") if sparse_targets is None: raise ValueError("sparse_targets (or targets) is required for SARM training") sparse_targets = sparse_targets.to(self.device) sparse_result = self._train_step( img_emb, text_features, state_features, lengths, sparse_targets, scheme="sparse" ) output_dict["sparse_stage_loss"] = sparse_result["stage_loss"].item() output_dict["sparse_subtask_loss"] = sparse_result["subtask_loss"].item() total_loss = total_loss + sparse_result["total_loss"] # Dense training (if dual mode) if self.config.uses_dual_heads: dense_targets = observation.get("dense_targets") if dense_targets is not None: dense_targets = dense_targets.to(self.device) dense_result = self._train_step( img_emb, text_features, state_features, lengths, dense_targets, scheme="dense" ) output_dict["dense_stage_loss"] = dense_result["stage_loss"].item() output_dict["dense_subtask_loss"] = dense_result["subtask_loss"].item() total_loss = total_loss + dense_result["total_loss"] output_dict["total_loss"] = total_loss.item() return total_loss, output_dict def compute_stage_loss(stage_logits: torch.Tensor, target_stages: torch.Tensor) -> torch.Tensor: """Compute cross-entropy loss for stage classification.""" _, _, num_stages = stage_logits.shape stage_logits_flat = stage_logits.reshape(-1, num_stages) # Clamp target stage indices to valid range [0, num_stages-1] target_stages_flat = target_stages.reshape(-1).clamp(0, num_stages - 1) return F.cross_entropy(stage_logits_flat, target_stages_flat)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/sarm/modeling_sarm.py", "license": "Apache License 2.0", "lines": 656, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/sarm/processor_sarm.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """SARM Processor for encoding images/text and generating stage+tau targets.""" import random from typing import Any import numpy as np import pandas as pd import torch from faker import Faker from PIL import Image from transformers import CLIPModel, CLIPProcessor from lerobot.configs.types import FeatureType, PolicyFeature from lerobot.policies.sarm.configuration_sarm import SARMConfig from lerobot.policies.sarm.sarm_utils import ( apply_rewind_augmentation, compute_absolute_indices, find_stage_and_tau, pad_state_to_max_dim, ) from lerobot.processor import ( AddBatchDimensionProcessorStep, DeviceProcessorStep, NormalizerProcessorStep, PolicyAction, PolicyProcessorPipeline, ProcessorStep, RenameObservationsProcessorStep, ) from lerobot.processor.converters import ( from_tensor_to_numpy, policy_action_to_transition, transition_to_policy_action, ) from lerobot.processor.core import EnvTransition, TransitionKey from lerobot.processor.pipeline import PipelineFeatureType from lerobot.utils.constants import POLICY_POSTPROCESSOR_DEFAULT_NAME, POLICY_PREPROCESSOR_DEFAULT_NAME class SARMEncodingProcessorStep(ProcessorStep): """ProcessorStep that encodes images and text with CLIP and generates stage and progress labels for SARM.""" def __init__( self, config: SARMConfig, image_key: str | None = None, dataset_meta=None, dataset_stats: dict | None = None, ): super().__init__() self.config = config self.image_key = image_key or config.image_key self.dataset_meta = dataset_meta self.dataset_stats = dataset_stats self.annotation_mode = config.annotation_mode # Helper to create temporal proportions dict def make_props_dict(names, props): return dict(zip(names, props, strict=True)) if names and props else None # Sparse annotations (always needed) self.sparse_temporal_proportions = make_props_dict( config.sparse_subtask_names, config.sparse_temporal_proportions ) self.sparse_subtask_names = config.sparse_subtask_names # Dense annotations (only for dual mode) self.dense_subtask_names = config.dense_subtask_names if config.uses_dual_heads else None self.dense_temporal_proportions = ( make_props_dict(config.dense_subtask_names, config.dense_temporal_proportions) if config.uses_dual_heads else None ) self.device = torch.device( self.config.device if self.config.device else "cuda" if torch.cuda.is_available() else "cpu" ) self.clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32") self.clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32", use_fast=True) self.clip_model.to(self.device) self.clip_model.eval() self.verbs = ["move", "grasp", "rotate", "push", "pull", "slide", "lift", "place"] self.fake = Faker() def _find_episode_for_frame(self, frame_idx: int) -> int: """Find the episode index for a given frame index.""" for ep_idx in range(len(self.dataset_meta.episodes)): ep_start = self.dataset_meta.episodes[ep_idx]["dataset_from_index"] ep_end = self.dataset_meta.episodes[ep_idx]["dataset_to_index"] if ep_start <= frame_idx < ep_end: return ep_idx return 0 def _get_episode_indices(self, frame_indices: np.ndarray, episode_index) -> np.ndarray: """Get episode indices for each frame index.""" if episode_index is None: return np.array([self._find_episode_for_frame(int(f)) for f in frame_indices]) episode_indices = np.atleast_1d(np.asarray(from_tensor_to_numpy(episode_index))) # If single episode but multiple frames, compute episode for each frame if len(episode_indices) == 1 and len(frame_indices) > 1: return np.array([self._find_episode_for_frame(int(f)) for f in frame_indices]) return episode_indices def _generate_perturbed_task(self) -> str: """Generate a random perturbed task string for language perturbation.""" num_words = random.randint(1, 5) verb = random.choice(self.verbs) phrase = " ".join([verb] + self.fake.words(nb=num_words)) return phrase def _get_annotation_config(self, annotation_type: str) -> tuple[list[str], dict[str, float] | None]: """Get global subtask names and temporal proportions for an annotation type.""" if annotation_type == "dense": return self.dense_subtask_names, self.dense_temporal_proportions return self.sparse_subtask_names, self.sparse_temporal_proportions def _load_episode_annotations( self, ep_idx: int, episodes_df: pd.DataFrame | None, annotation_type: str, global_names: list[str], ) -> tuple[list | None, list | None, list | None]: """Load subtask annotations for an episode from DataFrame.""" # Single-stage mode: (linear progress 0→1) if episodes_df is None or len(global_names) == 1: return None, None, None # Resolve column name with fallback def col(suffix): prefixed = f"{annotation_type}_{suffix}" return prefixed if prefixed in episodes_df.columns else suffix col_names = col("subtask_names") if col_names not in episodes_df.columns or ep_idx >= len(episodes_df): return None, None, None subtask_names = episodes_df.loc[ep_idx, col_names] if subtask_names is None or (isinstance(subtask_names, float) and pd.isna(subtask_names)): return None, None, None return ( subtask_names, episodes_df.loc[ep_idx, col("subtask_start_frames")], episodes_df.loc[ep_idx, col("subtask_end_frames")], ) def __call__(self, transition: EnvTransition) -> EnvTransition: """ Encode images, text, and normalize states in the transition. Implements SARM training data preparation: - Applies language perturbation (20% probability) - Applies rewind augmentation (80% probability) - Generates stage+tau targets for all frames - Outputs lengths tensor for valid sequence masking """ new_transition = transition.copy() if hasattr(transition, "copy") else dict(transition) observation = new_transition.get(TransitionKey.OBSERVATION) comp_data = new_transition.get(TransitionKey.COMPLEMENTARY_DATA, {}) frame_index = comp_data.get("index") episode_index = comp_data.get("episode_index") if frame_index is None: raise ValueError("Frame index ('index') not found in COMPLEMENTARY_DATA") if episode_index is None: raise ValueError("Episode index ('episode_index') not found in COMPLEMENTARY_DATA") frame_indices = np.atleast_1d(np.asarray(from_tensor_to_numpy(frame_index))) episode_indices = self._get_episode_indices(frame_indices, episode_index) image = observation.get(self.image_key) if isinstance(image, torch.Tensor): image = image.cpu().numpy() # If 4D (T, C, H, W) from delta_timestamps, add batch dim # If 3D (C, H, W) single frame, add batch and time dims if image.ndim == 4: image = image[np.newaxis, ...] # (T, C, H, W) -> (1, T, C, H, W) elif image.ndim == 3: image = image[np.newaxis, np.newaxis, ...] # (C, H, W) -> (1, 1, C, H, W) batch_size = image.shape[0] total_frames = image.shape[1] # Should be 13: 9 obs + 4 rewind placeholders n_obs_steps = self.config.n_obs_steps max_rewind_steps = self.config.max_rewind_steps n_obs_frames = 1 + n_obs_steps # 9 observation frames (including current) # Rewind augmentation rewind_steps = torch.zeros(batch_size, dtype=torch.int32) apply_rewind = self.training and random.random() < self.config.rewind_probability if apply_rewind and self.dataset_meta is not None: for b_idx, (ep_idx, frame_idx) in enumerate( zip(episode_indices.tolist(), frame_indices.tolist(), strict=True) ): ep_idx, frame_idx = int(ep_idx), int(frame_idx) ep_start = self.dataset_meta.episodes[ep_idx]["dataset_from_index"] rewind_step, _ = apply_rewind_augmentation( frame_idx, ep_start, n_obs_steps, max_rewind_steps, frame_gap=self.config.frame_gap ) rewind_steps[b_idx] = rewind_step # Compute valid lengths: n_obs_frames + rewind_steps lengths = n_obs_frames + rewind_steps # (B,) # Apply rewind masking to images # For frames beyond valid length, we mask with zeros (or copy last valid frame) for b_idx in range(batch_size): valid_len = lengths[b_idx].item() if valid_len < total_frames: image[b_idx, valid_len:] = 0 # Zero out frames beyond valid length # Encode images with CLIP video_features = self._encode_images_batch(image) observation["video_features"] = video_features state_key = self.config.state_key state_data = observation.get(state_key) if isinstance(state_data, torch.Tensor): state_tensor = state_data.float() else: state_tensor = torch.tensor(state_data, dtype=torch.float32) if state_tensor.ndim == 2: state_tensor = state_tensor.unsqueeze(0) # (T, D) -> (1, T, D) elif state_tensor.ndim == 1: state_tensor = state_tensor.unsqueeze(0).unsqueeze(0) # (D,) -> (1, 1, D) # Apply same rewind masking to state for b_idx in range(batch_size): valid_len = lengths[b_idx].item() if valid_len < state_tensor.shape[1]: state_tensor[b_idx, valid_len:] = 0 # Zero out frames beyond valid length observation["state_features"] = pad_state_to_max_dim(state_tensor, self.config.max_state_dim) task = comp_data.get("task") if isinstance(task, list): task = task[0] if task else "" # Apply language perturbation during training (20% probability) # When perturbed, targets will be zeroed to train model to output low values for irrelevant text apply_perturbation = self.training and random.random() < self.config.language_perturbation_probability if apply_perturbation: task = self._generate_perturbed_task() # Encode text with CLIP observation["text_features"] = self._encode_text_clip(task, batch_size) # Store lengths for model observation["lengths"] = lengths # When language is perturbed, targets are zero so perturbed samples don't contribute to progress loss if self.dataset_meta is not None: episodes_df = self.dataset_meta.episodes.to_pandas() # Generate sparse targets if self.sparse_temporal_proportions is not None: if apply_perturbation: # Zero targets when language is perturbed sparse_targets = torch.zeros(batch_size, total_frames, dtype=torch.float32) else: sparse_targets = self._compute_batch_targets( frame_indices, episode_indices, lengths, rewind_steps, episodes_df, "sparse" ) observation["sparse_targets"] = sparse_targets # Generate dense targets (for dual mode) if self.config.uses_dual_heads and self.dense_temporal_proportions is not None: if apply_perturbation: # Zero targets when language is perturbed dense_targets = torch.zeros(batch_size, total_frames, dtype=torch.float32) else: dense_targets = self._compute_batch_targets( frame_indices, episode_indices, lengths, rewind_steps, episodes_df, "dense" ) observation["dense_targets"] = dense_targets new_transition[TransitionKey.OBSERVATION] = observation return new_transition def _compute_batch_targets( self, frame_indices: np.ndarray, episode_indices: np.ndarray, lengths: torch.Tensor, rewind_steps: torch.Tensor, episodes_df: pd.DataFrame | None, annotation_type: str, ) -> torch.Tensor: """Compute stage+tau targets for a batch of samples.""" batch_size = len(frame_indices) n_obs_steps = self.config.n_obs_steps max_rewind_steps = self.config.max_rewind_steps total_frames = 1 + n_obs_steps + max_rewind_steps frame_gap = self.config.frame_gap global_names, temporal_props = self._get_annotation_config(annotation_type) targets = torch.zeros(batch_size, total_frames, dtype=torch.float32) for b_idx in range(batch_size): ep_idx = int(episode_indices[b_idx]) frame_idx = int(frame_indices[b_idx]) ep_start = self.dataset_meta.episodes[ep_idx]["dataset_from_index"] ep_end = self.dataset_meta.episodes[ep_idx]["dataset_to_index"] ep_length = ep_end - ep_start subtask_names, subtask_start_frames, subtask_end_frames = self._load_episode_annotations( ep_idx, episodes_df, annotation_type, global_names ) # Compute observation frame indices obs_indices, _ = compute_absolute_indices( frame_idx, ep_start, ep_end, n_obs_steps, frame_gap=frame_gap ) obs_indices = obs_indices.tolist() # Compute targets for observation frames for t_idx, abs_idx in enumerate(obs_indices): rel_frame = abs_idx - ep_start targets[b_idx, t_idx] = find_stage_and_tau( rel_frame, ep_length, subtask_names, subtask_start_frames, subtask_end_frames, global_names, temporal_props, return_combined=True, ) # Compute targets for rewind frames (if any) rewind_step = rewind_steps[b_idx].item() if rewind_step > 0: _, rewind_indices = apply_rewind_augmentation( frame_idx, ep_start, n_obs_steps, max_rewind_steps, frame_gap=frame_gap, rewind_step=rewind_step, ) for r_idx, abs_idx in enumerate(rewind_indices[:rewind_step]): rel_frame = max(0, abs_idx - ep_start) targets[b_idx, n_obs_steps + 1 + r_idx] = find_stage_and_tau( rel_frame, ep_length, subtask_names, subtask_start_frames, subtask_end_frames, global_names, temporal_props, return_combined=True, ) return targets @property def training(self) -> bool: return getattr(self, "_training_mode", True) def train(self, mode: bool = True): """Set training mode for augmentation decisions.""" self._training_mode = mode return self def eval(self): """Set evaluation mode (disable augmentations).""" return self.train(False) @torch.no_grad() def _encode_images_batch(self, images: np.ndarray) -> torch.Tensor: """Encode a batch of images using CLIP. Args: images: Batched images with shape: (B, T, C, H, W) Returns: Encoded feature vectors with shape (B, T, 512) """ batch_size, seq_length = images.shape[0], images.shape[1] images = images.reshape(batch_size * seq_length, *images.shape[2:]) num_frames = images.shape[0] images_list = [] for i in range(num_frames): img = images[i] if img.shape[0] in [1, 3]: # Channel first (C, H, W) img = img.transpose(1, 2, 0) # Handle single channel if img.shape[-1] == 1: img = np.repeat(img, 3, axis=-1) if img.dtype != np.uint8: img = (img * 255).astype(np.uint8) if img.max() <= 1.0 else img.astype(np.uint8) images_list.append(Image.fromarray(img)) all_embeddings = [] for i in range(0, num_frames, self.config.clip_batch_size): batch_imgs = images_list[i : i + self.config.clip_batch_size] inputs = self.clip_processor(images=batch_imgs, return_tensors="pt") inputs = {k: v.to(self.device) for k, v in inputs.items()} # Get image embeddings embeddings = self.clip_model.get_image_features(**inputs).detach().cpu() # Handle single frame case if embeddings.dim() == 1: embeddings = embeddings.unsqueeze(0) all_embeddings.append(embeddings) all_embeddings = torch.cat(all_embeddings) # (B*T, 512) all_embeddings = all_embeddings.reshape(batch_size, seq_length, -1) # (B, T, 512) return all_embeddings @torch.no_grad() def _encode_text_clip(self, text: str, batch_size: int) -> torch.Tensor: """Encode text using CLIP text encoder (per SARM paper A.4). Args: text: Task description text to encode batch_size: Batch size to replicate for Returns: Encoded text features with shape (B, 512) """ inputs = self.clip_processor.tokenizer([text], return_tensors="pt", padding=True, truncation=True) inputs = {k: v.to(self.device) for k, v in inputs.items()} text_embedding = self.clip_model.get_text_features(**inputs).detach().cpu() text_embedding = text_embedding.expand(batch_size, -1) return text_embedding def transform_features( self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]] ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]: """Add encoded features to the observation features.""" features[PipelineFeatureType.OBSERVATION]["video_features"] = PolicyFeature( type=FeatureType.VISUAL, shape=(self.config.num_frames, self.config.image_dim) ) features[PipelineFeatureType.OBSERVATION]["text_features"] = PolicyFeature( type=FeatureType.LANGUAGE, shape=(self.config.text_dim,) ) features[PipelineFeatureType.OBSERVATION]["state_features"] = PolicyFeature( type=FeatureType.STATE, shape=(self.config.num_frames, self.config.max_state_dim) ) return features def make_sarm_pre_post_processors( config: SARMConfig, dataset_stats: dict[str, dict[str, torch.Tensor]] | None = None, dataset_meta=None, ) -> tuple[ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """Create pre-processor and post-processor pipelines for SARM.""" return ( PolicyProcessorPipeline[dict[str, Any], dict[str, Any]]( steps=[ AddBatchDimensionProcessorStep(), RenameObservationsProcessorStep(rename_map={}), NormalizerProcessorStep( features={**config.input_features, **config.output_features}, norm_map=config.normalization_mapping, stats=dataset_stats, ), SARMEncodingProcessorStep( config=config, dataset_meta=dataset_meta, dataset_stats=dataset_stats ), DeviceProcessorStep(device=config.device), ], name=POLICY_PREPROCESSOR_DEFAULT_NAME, ), PolicyProcessorPipeline[PolicyAction, PolicyAction]( steps=[DeviceProcessorStep(device="cpu")], name=POLICY_POSTPROCESSOR_DEFAULT_NAME, to_transition=policy_action_to_transition, to_output=transition_to_policy_action, ), )
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/sarm/processor_sarm.py", "license": "Apache License 2.0", "lines": 427, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/sarm/sarm_utils.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 random import numpy as np import torch import torch.nn.functional as F # noqa: N812 def find_stage_and_tau( current_frame: int, episode_length: int, subtask_names: list | None, subtask_start_frames: list | None, subtask_end_frames: list | None, global_subtask_names: list, temporal_proportions: dict, return_combined: bool = False, ) -> tuple[int, float] | float: """Find stage and within-stage progress (tau) for a frame. Args: current_frame: Frame index relative to episode start episode_length: Total frames in episode subtask_names: Subtask names for this episode (None for single_stage) subtask_start_frames: Subtask start frames subtask_end_frames: Subtask end frames global_subtask_names: Global list of all subtask names temporal_proportions: Dict of temporal proportions return_combined: If True, return stage+tau as float; else (stage_idx, tau) tuple Returns: Float (stage.tau) if return_combined, else (stage_idx, tau) tuple """ stage_idx, tau = 0, 0.0 num_stages = len(global_subtask_names) # Single-stage mode: linear progress from 0 to 1 if num_stages == 1: tau = min(1.0, max(0.0, current_frame / max(episode_length - 1, 1))) elif subtask_names is None: pass # stage_idx=0, tau=0.0 elif current_frame < subtask_start_frames[0]: pass # Before first subtask: stage_idx=0, tau=0.0 elif current_frame > subtask_end_frames[-1]: stage_idx, tau = num_stages - 1, 0.999 # After last subtask else: # Find which subtask this frame belongs to found = False for name, start, end in zip(subtask_names, subtask_start_frames, subtask_end_frames, strict=True): if start <= current_frame <= end: stage_idx = global_subtask_names.index(name) if name in global_subtask_names else 0 tau = compute_tau(current_frame, start, end) found = True break # Frame between subtasks - use previous subtask's end state if not found: for j in range(len(subtask_names) - 1): if subtask_end_frames[j] < current_frame < subtask_start_frames[j + 1]: name = subtask_names[j] stage_idx = global_subtask_names.index(name) if name in global_subtask_names else j tau = 1.0 break if return_combined: # Clamp to avoid overflow at end if stage_idx >= num_stages - 1 and tau >= 1.0: return num_stages - 1 + 0.999 return stage_idx + tau return stage_idx, tau def compute_absolute_indices( frame_idx: int, ep_start: int, ep_end: int, n_obs_steps: int, frame_gap: int = 30, ) -> tuple[torch.Tensor, torch.Tensor]: """Compute absolute frame indices with clamping for bidirectional observation sequence. Bidirectional sampling centered on target frame: - Before: [-frame_gap * half_steps, ..., -frame_gap] (half_steps frames) - Current: [0] (1 frame) - After: [frame_gap, ..., frame_gap * half_steps] (half_steps frames) - Total: n_obs_steps + 1 frames Out-of-bounds frames are clamped (duplicated from boundary). Args: frame_idx: Target frame index (center frame of sequence) ep_start: Episode start index ep_end: Episode end index (exclusive) n_obs_steps: Number of observation steps (must be even for symmetric sampling) frame_gap: Gap between observation frames Returns: Tuple of (indices, out_of_bounds_flags) """ half_steps = n_obs_steps // 2 # Bidirectional deltas: past + current + future past_deltas = [-frame_gap * i for i in range(half_steps, 0, -1)] future_deltas = [frame_gap * i for i in range(1, half_steps + 1)] delta_indices = past_deltas + [0] + future_deltas frames = [] out_of_bounds = [] for delta in delta_indices: target_idx = frame_idx + delta # Clamp to episode bounds (duplicate boundary frames for out-of-bounds) clamped_idx = max(ep_start, min(ep_end - 1, target_idx)) frames.append(clamped_idx) # Flag as out-of-bounds if clamping occurred out_of_bounds.append(1 if target_idx != clamped_idx else 0) return torch.tensor(frames), torch.tensor(out_of_bounds) def apply_rewind_augmentation( frame_idx: int, ep_start: int, n_obs_steps: int, max_rewind_steps: int, frame_gap: int = 30, rewind_step: int | None = None, ) -> tuple[int, list[int]]: """ Generate rewind frame indices for temporal augmentation. Rewind simulates going backwards through previously seen frames, starting from before the earliest observation frame (for bidirectional sampling). Appends reversed frames after the observation sequence. Args: frame_idx: Target frame index (center of bidirectional observation window) ep_start: Episode start index n_obs_steps: Number of observation steps max_rewind_steps: Maximum rewind steps frame_gap: Gap between frames rewind_step: If provided, use this exact rewind step (for deterministic behavior). If None, sample randomly. Returns: Tuple of (rewind_step, rewind_indices) """ # For bidirectional sampling, earliest obs frame is at frame_idx - half_steps * frame_gap half_steps = n_obs_steps // 2 earliest_obs_frame = frame_idx - half_steps * frame_gap # Required history: frames before earliest observation frame if earliest_obs_frame <= ep_start: return 0, [] # No history before observation window # Max valid rewind steps based on available history before earliest obs frame available_history = earliest_obs_frame - ep_start max_valid_step = available_history // frame_gap max_rewind = min(max_rewind_steps, max(0, max_valid_step)) if max_rewind <= 0: return 0, [] # Sample rewind steps if not provided rewind_step = random.randint(1, max_rewind) if rewind_step is None else min(rewind_step, max_rewind) if rewind_step == 0: return 0, [] # Generate rewind indices going backwards from earliest obs frame # rewind_indices[0] is closest to obs window, rewind_indices[-1] is furthest back rewind_indices = [] for i in range(1, rewind_step + 1): idx = earliest_obs_frame - i * frame_gap idx = max(ep_start, idx) # Clamp to episode start rewind_indices.append(idx) return rewind_step, rewind_indices def compute_tau(current_frame: int | float, subtask_start: int | float, subtask_end: int | float) -> float: """Compute τ_t = (t - s_k) / (e_k - s_k) ∈ [0, 1]. Returns 1.0 for zero-duration subtasks.""" duration = subtask_end - subtask_start if duration <= 0: return 1.0 return float(np.clip((current_frame - subtask_start) / duration, 0.0, 1.0)) def pad_state_to_max_dim(state: torch.Tensor, max_state_dim: int) -> torch.Tensor: """Pad the state tensor's last dimension to max_state_dim with zeros.""" current_dim = state.shape[-1] if current_dim >= max_state_dim: return state[..., :max_state_dim] # Truncate if larger # Pad with zeros on the right padding = (0, max_state_dim - current_dim) # (left, right) for last dim return F.pad(state, padding, mode="constant", value=0) def temporal_proportions_to_breakpoints( temporal_proportions: dict[str, float] | list[float] | None, subtask_names: list[str] | None = None, ) -> list[float] | None: """Convert temporal proportions to cumulative breakpoints for normalization.""" if temporal_proportions is None: return None if isinstance(temporal_proportions, dict): if subtask_names is not None: proportions = [temporal_proportions.get(name, 0.0) for name in subtask_names] else: proportions = list(temporal_proportions.values()) else: proportions = list(temporal_proportions) total = sum(proportions) if total > 0 and abs(total - 1.0) > 1e-6: proportions = [p / total for p in proportions] breakpoints = [0.0] cumsum = 0.0 for prop in proportions: cumsum += prop breakpoints.append(cumsum) breakpoints[-1] = 1.0 return breakpoints def normalize_stage_tau( x: float | torch.Tensor, num_stages: int | None = None, breakpoints: list[float] | None = None, temporal_proportions: dict[str, float] | list[float] | None = None, subtask_names: list[str] | None = None, ) -> float | torch.Tensor: """ Normalize stage+tau reward to [0, 1] with custom breakpoints. Maps stage index + within-stage tau to normalized progress [0, 1]. The breakpoints are designed to give appropriate weight to each stage based on their importance in the task (using temporal proportions). Priority: breakpoints > temporal_proportions > linear fallback Args: x: Raw reward value (stage index + tau) where stage ∈ [0, num_stages-1] and tau ∈ [0, 1) num_stages: Number of stages (required if breakpoints/proportions not provided) breakpoints: Optional custom breakpoints list of length num_stages + 1. temporal_proportions: Optional temporal proportions dict/list to compute breakpoints. subtask_names: Optional ordered list of subtask names (for dict proportions) Returns: Normalized progress value ∈ [0, 1] """ if breakpoints is not None: num_stages = len(breakpoints) - 1 elif temporal_proportions is not None: breakpoints = temporal_proportions_to_breakpoints(temporal_proportions, subtask_names) num_stages = len(breakpoints) - 1 elif num_stages is not None: breakpoints = [i / num_stages for i in range(num_stages + 1)] else: raise ValueError("Either num_stages, breakpoints, or temporal_proportions must be provided") if isinstance(x, torch.Tensor): result = torch.zeros_like(x) for i in range(num_stages): mask = (x >= i) & (x < i + 1) tau_in_stage = x - i result[mask] = breakpoints[i] + tau_in_stage[mask] * (breakpoints[i + 1] - breakpoints[i]) result[x >= num_stages] = 1.0 return result.clamp(0.0, 1.0) else: if x < 0: return 0.0 if x >= num_stages: return 1.0 stage = int(x) tau = x - stage return breakpoints[stage] + tau * (breakpoints[stage + 1] - breakpoints[stage])
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/sarm/sarm_utils.py", "license": "Apache License 2.0", "lines": 246, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/utils/rabc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 logging from pathlib import Path import numpy as np import pandas as pd import torch from huggingface_hub import hf_hub_download def resolve_hf_path(path: str | Path) -> Path: """Resolve a path that may be a HuggingFace URL (hf://datasets/...) to a local path.""" path_str = str(path) if path_str.startswith("hf://datasets/"): parts = path_str.replace("hf://datasets/", "").split("/") repo_id = "/".join(parts[:2]) filename = "/".join(parts[2:]) return Path(hf_hub_download(repo_id=repo_id, filename=filename, repo_type="dataset")) return Path(path) class RABCWeights: """ Load precomputed SARM progress values and compute RA-BC weights during training. Progress values are loaded from a parquet file (generated by compute_rabc_weights.py). During training, computes: - progress_delta = progress[t + chunk_size] - progress[t] - rabc_weight based on the delta (paper Eq. 8-9) Args: progress_path: Path to parquet file with precomputed progress values chunk_size: Number of frames ahead for computing progress delta head_mode: Which SARM head to use ("sparse" or "dense") kappa: Hard threshold for high-quality samples (default: 0.01) epsilon: Small constant for numerical stability (default: 1e-6) fallback_weight: Weight to use for frames without valid delta (default: 1.0) device: Device to return tensors on """ def __init__( self, progress_path: str | Path, chunk_size: int = 50, head_mode: str = "sparse", kappa: float = 0.01, epsilon: float = 1e-6, fallback_weight: float = 1.0, device: torch.device = None, ): self.progress_path = resolve_hf_path(progress_path) self.chunk_size = chunk_size self.head_mode = head_mode self.kappa = kappa self.epsilon = epsilon self.fallback_weight = fallback_weight self.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu") # Determine progress column name self.progress_column = f"progress_{head_mode}" # Load progress values logging.info(f"Loading SARM progress values from {self.progress_path}") self.df = pd.read_parquet(self.progress_path) # Check if the requested head mode column exists if self.progress_column not in self.df.columns: available = [c for c in self.df.columns if c.startswith("progress")] raise ValueError( f"Column '{self.progress_column}' not found. Available progress columns: {available}" ) logging.info(f"Using progress column: {self.progress_column}") self.progress_lookup = {} self.episode_lookup = {} for _, row in self.df.iterrows(): global_idx = int(row["index"]) progress = row[self.progress_column] episode_idx = int(row["episode_index"]) if not np.isnan(progress): self.progress_lookup[global_idx] = float(progress) self.episode_lookup[global_idx] = episode_idx # Build episode boundaries for delta computation self.episode_boundaries = {} for episode_idx in self.df["episode_index"].unique(): ep_df = self.df[self.df["episode_index"] == episode_idx] self.episode_boundaries[int(episode_idx)] = { "start": int(ep_df["index"].min()), "end": int(ep_df["index"].max()) + 1, } logging.info(f"Loaded {len(self.progress_lookup)} frame progress values") logging.info(f"Chunk size for delta computation: {chunk_size}") # Compute global statistics for weight computation self._compute_global_stats() def _compute_global_stats(self): """Compute global mean and std of progress deltas for weight calculation.""" all_deltas = [] for global_idx, progress in self.progress_lookup.items(): episode_idx = self.episode_lookup.get(global_idx) if episode_idx is None: continue bounds = self.episode_boundaries.get(episode_idx) if bounds is None: continue future_idx = global_idx + self.chunk_size if future_idx >= bounds["end"]: # Near end of episode: use last frame's progress future_idx = bounds["end"] - 1 future_progress = self.progress_lookup.get(future_idx) if future_progress is not None: delta = future_progress - progress all_deltas.append(delta) if all_deltas: self.delta_mean = max(np.mean(all_deltas), 0.0) self.delta_std = max(np.std(all_deltas), self.epsilon) logging.info(f"Progress delta stats: mean={self.delta_mean:.4f}, std={self.delta_std:.4f}") else: self.delta_mean = 0.0 self.delta_std = self.epsilon logging.warning("No valid progress deltas found, using default stats") def compute_batch_weights(self, batch: dict) -> tuple[torch.Tensor, dict]: """ Compute RA-BC weights for a batch. For each sample: 1. Get progress at current frame 2. Get progress at frame + chunk_size (within same episode) 3. Compute delta = future_progress - current_progress 4. Compute weight using paper Eq. 8-9 Args: batch: Training batch containing "index" key with global frame indices Returns: Tuple of: - Weights tensor (batch_size,) normalized to sum to batch_size - Stats dict with raw_mean_weight, num_zero_weight, num_full_weight """ indices = batch.get("index") if indices is None: logging.warning("RA-BC: Batch missing 'index' key, using uniform weights") batch_size = self._get_batch_size(batch) return torch.ones(batch_size, device=self.device), {"raw_mean_weight": 1.0} # Convert to list of ints if isinstance(indices, torch.Tensor): indices = indices.cpu().numpy().tolist() elif isinstance(indices, np.ndarray): indices = indices.tolist() # Compute deltas and weights for each sample deltas = [] for idx in indices: idx = int(idx) delta = self._compute_delta(idx) deltas.append(delta) deltas = np.array(deltas, dtype=np.float32) # Compute weights from deltas weights = self._compute_weights(deltas) # Compute stats before normalization for logging raw_mean_weight = float(np.nanmean(weights)) num_zero_weight = int(np.sum(weights == 0)) num_full_weight = int(np.sum(weights == 1.0)) batch_stats = { "raw_mean_weight": raw_mean_weight, "num_zero_weight": num_zero_weight, "num_full_weight": num_full_weight, } weights = torch.tensor(weights, device=self.device, dtype=torch.float32) # Normalize to sum to batch_size batch_size = len(weights) weight_sum = weights.sum() + self.epsilon weights = weights * batch_size / weight_sum return weights, batch_stats def _compute_delta(self, global_idx: int) -> float: """Compute progress delta for a single frame.""" current_progress = self.progress_lookup.get(global_idx) if current_progress is None: return np.nan episode_idx = self.episode_lookup.get(global_idx) if episode_idx is None: return np.nan bounds = self.episode_boundaries.get(episode_idx) if bounds is None: return np.nan future_idx = global_idx + self.chunk_size # Δ = chunk_size if future_idx >= bounds["end"]: # Near end of episode: use last frame's progress instead future_idx = bounds["end"] - 1 future_progress = self.progress_lookup.get(future_idx) if future_progress is None: return np.nan return future_progress - current_progress def _compute_weights(self, deltas: np.ndarray) -> np.ndarray: """ Compute RA-BC weights from progress deltas. Following paper Eq. 8-9: - Soft weight: ˜wi = clip((ri − (µ − 2σ)) / (4σ + ε), 0, 1) - Final weight: wi = 1{ri > κ} + 1{0 ≤ ri ≤ κ}˜wi Returns: Array of weights """ valid_mask = ~np.isnan(deltas) # Compute soft weights using global statistics lower_bound = self.delta_mean - 2 * self.delta_std soft_weights = (deltas - lower_bound) / (4 * self.delta_std + self.epsilon) soft_weights = np.clip(soft_weights, 0.0, 1.0) # Apply paper's Eq. 9 weights = np.zeros_like(deltas, dtype=np.float32) # High quality: ri > kappa → weight = 1 high_quality_mask = deltas > self.kappa weights[high_quality_mask] = 1.0 # Moderate quality: 0 <= ri <= kappa → weight = soft_weight moderate_mask = (deltas >= 0) & (deltas <= self.kappa) weights[moderate_mask] = soft_weights[moderate_mask] # Negative progress: ri < 0 → weight = 0 (already 0) # Invalid (NaN): use fallback weight weights[~valid_mask] = self.fallback_weight return weights def _get_batch_size(self, batch: dict) -> int: """Determine batch size from batch.""" for key in ["action", "index"]: if key in batch: val = batch[key] if isinstance(val, (torch.Tensor, np.ndarray)): return val.shape[0] return 1 def get_stats(self) -> dict: """Get statistics.""" return { "num_frames": len(self.progress_lookup), "chunk_size": self.chunk_size, "head_mode": self.head_mode, "delta_mean": self.delta_mean, "delta_std": self.delta_std, "kappa": self.kappa, }
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/utils/rabc.py", "license": "Apache License 2.0", "lines": 233, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/policies/test_sarm_processor.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 pytest pytest.importorskip("faker") from unittest.mock import MagicMock, patch import numpy as np import pandas as pd import pytest import torch from lerobot.processor.core import TransitionKey class MockDatasetMeta: """Mock dataset metadata for testing processor.""" def __init__(self, episodes: list[dict]): self._episodes = episodes @property def episodes(self): """Return episodes as a mock object with to_pandas() method.""" mock = MagicMock() mock.__len__ = lambda s: len(self._episodes) mock.__getitem__ = lambda s, idx: self._episodes[idx] mock.to_pandas = lambda: pd.DataFrame(self._episodes) return mock class MockConfig: """Mock SARMConfig for testing processor methods.""" def __init__( self, n_obs_steps: int = 8, max_rewind_steps: int = 4, frame_gap: int = 30, sparse_subtask_names: list = None, sparse_temporal_proportions: list = None, dense_subtask_names: list = None, dense_temporal_proportions: list = None, image_key: str = "observation.images.top", state_key: str = "observation.state", max_state_dim: int = 32, device: str = None, rewind_probability: float = 0.8, language_perturbation_probability: float = 0.2, annotation_mode: str = "dual", clip_batch_size: int = 64, text_dim: int = 512, ): self.n_obs_steps = n_obs_steps self.max_rewind_steps = max_rewind_steps self.frame_gap = frame_gap self.sparse_subtask_names = sparse_subtask_names or ["task"] self.sparse_temporal_proportions = sparse_temporal_proportions or [1.0] self.dense_subtask_names = dense_subtask_names self.dense_temporal_proportions = dense_temporal_proportions self.uses_dual_heads = annotation_mode in ["dense_only", "dual"] self.image_key = image_key self.state_key = state_key self.max_state_dim = max_state_dim self.device = device self.rewind_probability = rewind_probability self.language_perturbation_probability = language_perturbation_probability self.annotation_mode = annotation_mode self.clip_batch_size = clip_batch_size self.text_dim = text_dim # Compute observation delta indices (same as config: bidirectional) half_steps = self.n_obs_steps // 2 past_deltas = [-self.frame_gap * i for i in range(half_steps, 0, -1)] future_deltas = [self.frame_gap * i for i in range(1, half_steps + 1)] obs_deltas = past_deltas + [0] + future_deltas rewind_deltas = [-self.frame_gap * (i + 1) for i in range(self.max_rewind_steps)] self.observation_delta_indices = obs_deltas + rewind_deltas @property def num_frames(self) -> int: return 1 + self.n_obs_steps + self.max_rewind_steps class TestSARMEncodingProcessorStepEndToEnd: """End-to-end test for SARMEncodingProcessorStep with dummy batch data.""" @pytest.fixture def mock_clip_model(self): """Mock CLIP model to avoid loading real weights.""" with ( patch("lerobot.policies.sarm.processor_sarm.CLIPModel") as mock_model_cls, patch("lerobot.policies.sarm.processor_sarm.CLIPProcessor") as mock_processor_cls, ): # Mock the CLIP model - return embeddings based on input batch size mock_model = MagicMock() def get_image_features_side_effect(**kwargs): pixel_values = kwargs.get("pixel_values") batch_size = pixel_values.shape[0] if pixel_values is not None else 1 return torch.randn(batch_size, 512) mock_model.get_image_features.side_effect = get_image_features_side_effect mock_model.get_text_features.return_value = torch.randn(1, 512) mock_model.to.return_value = mock_model mock_model_cls.from_pretrained.return_value = mock_model # Mock the CLIP processor - return tensors based on input images mock_processor = MagicMock() def processor_side_effect(images=None, **kwargs): num_images = len(images) if images is not None else 1 return { "pixel_values": torch.randn(num_images, 3, 224, 224), } mock_processor.side_effect = processor_side_effect # Mock tokenizer for text encoding mock_processor.tokenizer.return_value = { "input_ids": torch.ones(1, 77, dtype=torch.long), "attention_mask": torch.ones(1, 77, dtype=torch.long), } mock_processor_cls.from_pretrained.return_value = mock_processor yield mock_model, mock_processor @pytest.fixture def processor_with_mocks(self, mock_clip_model): """Create a processor with mocked CLIP and dataset metadata for dual mode.""" from lerobot.policies.sarm.processor_sarm import SARMEncodingProcessorStep # Dual mode config with both sparse and dense annotations config = MockConfig( n_obs_steps=8, max_rewind_steps=4, frame_gap=30, rewind_probability=0.0, # Disable for deterministic test language_perturbation_probability=0.0, # Disable for deterministic test annotation_mode="dual", sparse_subtask_names=["reach", "grasp", "lift"], sparse_temporal_proportions=[0.3, 0.4, 0.3], dense_subtask_names=["approach", "contact", "close_gripper", "lift_up"], dense_temporal_proportions=[0.25, 0.25, 0.25, 0.25], ) # Create mock dataset metadata with one episode of 300 frames # Include annotation columns for dual mode episodes = [ { "dataset_from_index": 0, "dataset_to_index": 300, "task": "pick up the cube", "sparse_subtask_names": ["reach", "grasp", "lift"], "sparse_subtask_start_frames": [0, 90, 210], "sparse_subtask_end_frames": [90, 210, 300], "dense_subtask_names": ["approach", "contact", "close_gripper", "lift_up"], "dense_subtask_start_frames": [0, 75, 150, 225], "dense_subtask_end_frames": [75, 150, 225, 300], } ] dataset_meta = MockDatasetMeta(episodes) processor = SARMEncodingProcessorStep( config=config, dataset_meta=dataset_meta, ) processor.train(True) # Use train() method, not direct assignment return processor, config def test_call_with_single_frame_batch(self, processor_with_mocks): """Test processor __call__ with a single-frame batch.""" processor, config = processor_with_mocks # Create dummy input transition batch_size = 1 num_frames = config.num_frames # 13 frames (9 obs + 4 rewind) # Image: (T, C, H, W) format as expected by processor dummy_image = np.random.rand(num_frames, 3, 224, 224).astype(np.float32) # State: (T, D) format dummy_state = np.random.rand(num_frames, 6).astype(np.float32) transition = { TransitionKey.OBSERVATION: { config.image_key: dummy_image, config.state_key: dummy_state, }, TransitionKey.COMPLEMENTARY_DATA: { "index": 150, # Middle of episode "episode_index": 0, "task": "pick up the cube", }, } # Run processor result = processor(transition) # Verify output structure obs = result[TransitionKey.OBSERVATION] # Check video features exist and have correct shape assert "video_features" in obs video_features = obs["video_features"] assert video_features.shape[0] == batch_size assert video_features.shape[1] == num_frames assert video_features.shape[2] == 512 # CLIP embedding dim # Check state features exist and have correct shape assert "state_features" in obs state_features = obs["state_features"] assert state_features.shape[0] == batch_size assert state_features.shape[1] == num_frames assert state_features.shape[2] == config.max_state_dim # Padded to max_state_dim # Check text features exist and have correct shape assert "text_features" in obs text_features = obs["text_features"] assert text_features.shape[0] == batch_size assert text_features.shape[1] == 512 # CLIP embedding dim # Check lengths tensor assert "lengths" in obs lengths = obs["lengths"] assert lengths.shape[0] == batch_size assert lengths.dtype == torch.int32 # Check sparse_targets exist assert "sparse_targets" in obs sparse_targets = obs["sparse_targets"] assert sparse_targets.shape == (batch_size, num_frames) # All targets should be in [0, max_stages] range (stage.tau format) assert (sparse_targets >= 0).all() # Check dense_targets exist (for dual mode) assert "dense_targets" in obs dense_targets = obs["dense_targets"] assert dense_targets.shape == (batch_size, num_frames) assert (dense_targets >= 0).all() def test_call_with_batched_input(self, mock_clip_model): """Test processor __call__ with a batched input (multiple frames) in dual mode.""" from lerobot.policies.sarm.processor_sarm import SARMEncodingProcessorStep config = MockConfig( n_obs_steps=8, max_rewind_steps=4, frame_gap=30, rewind_probability=0.0, language_perturbation_probability=0.0, annotation_mode="dual", sparse_subtask_names=["reach", "grasp"], sparse_temporal_proportions=[0.5, 0.5], dense_subtask_names=["step1", "step2", "step3"], dense_temporal_proportions=[0.33, 0.34, 0.33], ) # Two episodes with different lengths, each with sparse+dense annotations episodes = [ { "dataset_from_index": 0, "dataset_to_index": 200, "task": "task A", "sparse_subtask_names": ["reach", "grasp"], "sparse_subtask_start_frames": [0, 100], "sparse_subtask_end_frames": [100, 200], "dense_subtask_names": ["step1", "step2", "step3"], "dense_subtask_start_frames": [0, 66, 133], "dense_subtask_end_frames": [66, 133, 200], }, { "dataset_from_index": 200, "dataset_to_index": 500, "task": "task B", "sparse_subtask_names": ["reach", "grasp"], "sparse_subtask_start_frames": [200, 350], "sparse_subtask_end_frames": [350, 500], "dense_subtask_names": ["step1", "step2", "step3"], "dense_subtask_start_frames": [200, 300, 400], "dense_subtask_end_frames": [300, 400, 500], }, ] dataset_meta = MockDatasetMeta(episodes) processor = SARMEncodingProcessorStep(config=config, dataset_meta=dataset_meta) processor.train(True) batch_size = 2 num_frames = config.num_frames # Image: (B, T, C, H, W) format dummy_image = np.random.rand(batch_size, num_frames, 3, 224, 224).astype(np.float32) dummy_state = np.random.rand(batch_size, num_frames, 6).astype(np.float32) transition = { TransitionKey.OBSERVATION: { config.image_key: dummy_image, config.state_key: dummy_state, }, TransitionKey.COMPLEMENTARY_DATA: { "index": np.array([100, 350]), # One frame from each episode "episode_index": np.array([0, 1]), "task": ["task A", "task B"], }, } result = processor(transition) obs = result[TransitionKey.OBSERVATION] # Verify batch dimension is preserved for all outputs assert obs["video_features"].shape[0] == batch_size assert obs["state_features"].shape[0] == batch_size assert obs["lengths"].shape[0] == batch_size assert obs["sparse_targets"].shape[0] == batch_size assert obs["dense_targets"].shape[0] == batch_size # Dual mode has dense targets def test_targets_increase_with_progress(self, mock_clip_model): """Test that both sparse and dense targets increase as frame index progresses.""" from lerobot.policies.sarm.processor_sarm import SARMEncodingProcessorStep config = MockConfig( n_obs_steps=8, max_rewind_steps=4, frame_gap=30, rewind_probability=0.0, language_perturbation_probability=0.0, annotation_mode="dual", sparse_subtask_names=["phase1", "phase2"], sparse_temporal_proportions=[0.5, 0.5], dense_subtask_names=["a", "b", "c", "d"], dense_temporal_proportions=[0.25, 0.25, 0.25, 0.25], ) episodes = [ { "dataset_from_index": 0, "dataset_to_index": 300, "task": "test task", "sparse_subtask_names": ["phase1", "phase2"], "sparse_subtask_start_frames": [0, 150], "sparse_subtask_end_frames": [150, 300], "dense_subtask_names": ["a", "b", "c", "d"], "dense_subtask_start_frames": [0, 75, 150, 225], "dense_subtask_end_frames": [75, 150, 225, 300], } ] dataset_meta = MockDatasetMeta(episodes) processor = SARMEncodingProcessorStep(config=config, dataset_meta=dataset_meta) processor.train(True) num_frames = config.num_frames # Test at early, middle, and late points in episode frame_indices = [30, 150, 270] sparse_center_targets = [] dense_center_targets = [] for frame_idx in frame_indices: dummy_image = np.random.rand(num_frames, 3, 224, 224).astype(np.float32) dummy_state = np.random.rand(num_frames, 6).astype(np.float32) transition = { TransitionKey.OBSERVATION: { config.image_key: dummy_image, config.state_key: dummy_state, }, TransitionKey.COMPLEMENTARY_DATA: { "index": frame_idx, "episode_index": 0, "task": "test task", }, } result = processor(transition) obs = result[TransitionKey.OBSERVATION] # Get target at center frame (index 4 in 9-frame observation window) sparse_center_targets.append(obs["sparse_targets"][0, 4].item()) dense_center_targets.append(obs["dense_targets"][0, 4].item()) # Both sparse and dense targets should increase with frame index assert sparse_center_targets[0] < sparse_center_targets[2], ( f"Early sparse target ({sparse_center_targets[0]}) should be < late ({sparse_center_targets[2]})" ) assert dense_center_targets[0] < dense_center_targets[2], ( f"Early dense target ({dense_center_targets[0]}) should be < late ({dense_center_targets[2]})" ) def test_progress_labels_exact_values(self, mock_clip_model): """Test that progress labels (stage.tau) are computed correctly for known positions.""" from lerobot.policies.sarm.processor_sarm import SARMEncodingProcessorStep # Simple setup: 2 sparse stages, 4 dense stages, 100 frame episode config = MockConfig( n_obs_steps=8, max_rewind_steps=4, frame_gap=10, # Smaller gap for easier calculation rewind_probability=0.0, language_perturbation_probability=0.0, annotation_mode="dual", sparse_subtask_names=["A", "B"], sparse_temporal_proportions=[0.5, 0.5], dense_subtask_names=["d1", "d2", "d3", "d4"], dense_temporal_proportions=[0.25, 0.25, 0.25, 0.25], ) # Episode: frames 0-99, sparse stages at [0-49], [50-99] # Dense stages at [0-24], [25-49], [50-74], [75-99] episodes = [ { "dataset_from_index": 0, "dataset_to_index": 100, "task": "test", "sparse_subtask_names": ["A", "B"], "sparse_subtask_start_frames": [0, 50], "sparse_subtask_end_frames": [50, 100], "dense_subtask_names": ["d1", "d2", "d3", "d4"], "dense_subtask_start_frames": [0, 25, 50, 75], "dense_subtask_end_frames": [25, 50, 75, 100], } ] dataset_meta = MockDatasetMeta(episodes) processor = SARMEncodingProcessorStep(config=config, dataset_meta=dataset_meta) processor.train(True) num_frames = config.num_frames # Test at frame 50 (center of episode) # With frame_gap=10, n_obs_steps=8: # obs indices around frame 50: [10, 20, 30, 40, 50, 60, 70, 80, 90] (9 frames) dummy_image = np.random.rand(num_frames, 3, 224, 224).astype(np.float32) dummy_state = np.random.rand(num_frames, 6).astype(np.float32) transition = { TransitionKey.OBSERVATION: { config.image_key: dummy_image, config.state_key: dummy_state, }, TransitionKey.COMPLEMENTARY_DATA: { "index": 50, "episode_index": 0, "task": "test", }, } result = processor(transition) obs = result[TransitionKey.OBSERVATION] sparse_targets = obs["sparse_targets"][0] # (13,) dense_targets = obs["dense_targets"][0] # (13,) # First 9 frames are observation frames, last 4 are rewind placeholders (zeros when no rewind) # Check that obs frames have non-zero targets obs_sparse = sparse_targets[:9] obs_dense = dense_targets[:9] # Verify targets are monotonically increasing for observation frames for i in range(1, 9): assert obs_sparse[i] >= obs_sparse[i - 1], ( f"Sparse targets should be monotonic: {obs_sparse[i - 1].item():.3f} -> {obs_sparse[i].item():.3f}" ) assert obs_dense[i] >= obs_dense[i - 1], ( f"Dense targets should be monotonic: {obs_dense[i - 1].item():.3f} -> {obs_dense[i].item():.3f}" ) # Rewind slots should be zero when rewind is disabled rewind_targets = sparse_targets[9:] assert (rewind_targets == 0).all(), "Rewind slots should be zero when rewind is disabled" # Check stage transitions: frame 50 is at boundary of sparse stage A->B # Center frame (index 4) corresponds to actual frame 50 center_sparse = obs_sparse[4].item() # At frame 50, sparse stage B starts, so target should be ~1.0 (stage 1 + tau 0) assert 0.9 <= center_sparse <= 1.1, ( f"At sparse boundary, target should be ~1.0, got {center_sparse:.3f}" ) def test_rewind_augmentation_applied(self, mock_clip_model): """Test that rewind augmentation correctly extends sequence and generates targets.""" import random from lerobot.policies.sarm.processor_sarm import SARMEncodingProcessorStep config = MockConfig( n_obs_steps=8, max_rewind_steps=4, frame_gap=10, rewind_probability=1.0, # Always apply rewind language_perturbation_probability=0.0, annotation_mode="dual", sparse_subtask_names=["A", "B"], sparse_temporal_proportions=[0.5, 0.5], dense_subtask_names=["d1", "d2"], dense_temporal_proportions=[0.5, 0.5], ) episodes = [ { "dataset_from_index": 0, "dataset_to_index": 200, "task": "test", "sparse_subtask_names": ["A", "B"], "sparse_subtask_start_frames": [0, 100], "sparse_subtask_end_frames": [100, 200], "dense_subtask_names": ["d1", "d2"], "dense_subtask_start_frames": [0, 100], "dense_subtask_end_frames": [100, 200], } ] dataset_meta = MockDatasetMeta(episodes) processor = SARMEncodingProcessorStep(config=config, dataset_meta=dataset_meta) processor.train(True) num_frames = config.num_frames # 13 # Test at frame 150 (center of bidirectional window) # With n_obs_steps=8, half_steps=4, frame_gap=10: # - Earliest obs frame = 150 - 4*10 = 110 # - Rewind can go back from 110 to frames like 100, 90, 80, 70 # - History available = 110 - 0 = 110, so max rewind = 110/10 = 11 (capped at 4) dummy_image = np.random.rand(num_frames, 3, 224, 224).astype(np.float32) dummy_state = np.random.rand(num_frames, 6).astype(np.float32) transition = { TransitionKey.OBSERVATION: { config.image_key: dummy_image, config.state_key: dummy_state, }, TransitionKey.COMPLEMENTARY_DATA: { "index": 150, "episode_index": 0, "task": "test", }, } # Seed random for reproducibility random.seed(42) result = processor(transition) obs = result[TransitionKey.OBSERVATION] lengths = obs["lengths"][0].item() sparse_targets = obs["sparse_targets"][0] # With rewind_probability=1.0 and enough history, lengths should be > 9 (9 obs + some rewind) assert lengths > 9, f"With rewind enabled, lengths should be > 9, got {lengths}" assert lengths <= num_frames, f"Lengths should not exceed total frames {num_frames}, got {lengths}" # Rewind targets should be non-zero for frames within valid length n_obs_frames = 9 rewind_count = lengths - n_obs_frames if rewind_count > 0: # Check that rewind frames have targets rewind_targets = sparse_targets[n_obs_frames : n_obs_frames + rewind_count] # Rewind frames are from BEFORE the earliest obs frame (110) # These frames (100, 90, 80, 70) are earlier in the episode earliest_obs_target = sparse_targets[0].item() # Frame 110 # Rewind targets should be less than earliest obs (they're from earlier frames) for i, rt in enumerate(rewind_targets): assert rt.item() < earliest_obs_target, ( f"Rewind target {i} ({rt.item():.3f}) should be < earliest obs ({earliest_obs_target:.3f})" ) # Rewind targets should be decreasing (going further back in time) for i in range(1, len(rewind_targets)): assert rewind_targets[i] <= rewind_targets[i - 1], ( f"Rewind targets should decrease: {rewind_targets[i - 1].item():.3f} -> {rewind_targets[i].item():.3f}" ) def test_full_sequence_target_consistency(self, mock_clip_model): """Test that the full sequence of targets is consistent with frame positions.""" from lerobot.policies.sarm.processor_sarm import SARMEncodingProcessorStep from lerobot.policies.sarm.sarm_utils import find_stage_and_tau config = MockConfig( n_obs_steps=8, max_rewind_steps=4, frame_gap=10, rewind_probability=0.0, language_perturbation_probability=0.0, annotation_mode="dual", sparse_subtask_names=["s1", "s2", "s3"], sparse_temporal_proportions=[0.33, 0.34, 0.33], dense_subtask_names=["d1", "d2"], dense_temporal_proportions=[0.5, 0.5], ) # 3 sparse stages: [0-33), [33-66), [66-99] # 2 dense stages: [0-50), [50-100) episodes = [ { "dataset_from_index": 0, "dataset_to_index": 100, "task": "test", "sparse_subtask_names": ["s1", "s2", "s3"], "sparse_subtask_start_frames": [0, 33, 66], "sparse_subtask_end_frames": [33, 66, 100], "dense_subtask_names": ["d1", "d2"], "dense_subtask_start_frames": [0, 50], "dense_subtask_end_frames": [50, 100], } ] dataset_meta = MockDatasetMeta(episodes) processor = SARMEncodingProcessorStep(config=config, dataset_meta=dataset_meta) processor.train(True) num_frames = config.num_frames # Test at frame 50 (middle of episode) dummy_image = np.random.rand(num_frames, 3, 224, 224).astype(np.float32) dummy_state = np.random.rand(num_frames, 6).astype(np.float32) transition = { TransitionKey.OBSERVATION: { config.image_key: dummy_image, config.state_key: dummy_state, }, TransitionKey.COMPLEMENTARY_DATA: { "index": 50, "episode_index": 0, "task": "test", }, } result = processor(transition) obs = result[TransitionKey.OBSERVATION] sparse_targets = obs["sparse_targets"][0] dense_targets = obs["dense_targets"][0] # Manually compute expected targets for observation frames # With frame_gap=10, n_obs_steps=8, center at 50: # obs frames: [10, 20, 30, 40, 50, 60, 70, 80, 90] expected_obs_frames = [10, 20, 30, 40, 50, 60, 70, 80, 90] sparse_names = ["s1", "s2", "s3"] sparse_starts = [0, 33, 66] sparse_ends = [33, 66, 100] sparse_props = {"s1": 0.33, "s2": 0.34, "s3": 0.33} dense_names = ["d1", "d2"] dense_starts = [0, 50] dense_ends = [50, 100] dense_props = {"d1": 0.5, "d2": 0.5} for i, frame in enumerate(expected_obs_frames): expected_sparse = find_stage_and_tau( frame, 100, sparse_names, sparse_starts, sparse_ends, sparse_names, sparse_props, return_combined=True, ) expected_dense = find_stage_and_tau( frame, 100, dense_names, dense_starts, dense_ends, dense_names, dense_props, return_combined=True, ) actual_sparse = sparse_targets[i].item() actual_dense = dense_targets[i].item() assert abs(actual_sparse - expected_sparse) < 0.01, ( f"Frame {frame}: sparse mismatch {actual_sparse:.3f} vs expected {expected_sparse:.3f}" ) assert abs(actual_dense - expected_dense) < 0.01, ( f"Frame {frame}: dense mismatch {actual_dense:.3f} vs expected {expected_dense:.3f}" )
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/test_sarm_processor.py", "license": "Apache License 2.0", "lines": 592, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/test_sarm_subtask_annotations.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 pytest pytest.importorskip("transformers") from lerobot.data_processing.sarm_annotations.subtask_annotation import ( Subtask, SubtaskAnnotation, Timestamp, compute_temporal_proportions, ) def make_annotation(subtasks: list[tuple[str, int, int]]) -> SubtaskAnnotation: """Helper to create SubtaskAnnotation from list of (name, start_sec, end_sec).""" return SubtaskAnnotation( subtasks=[ Subtask( name=name, timestamps=Timestamp( start=f"{start // 60:02d}:{start % 60:02d}", end=f"{end // 60:02d}:{end % 60:02d}" ), ) for name, start, end in subtasks ] ) class TestComputeTemporalProportions: """Tests for compute_temporal_proportions (SARM Paper Formula 1). Formula: ᾱ_k = (1/M) × Σ_i (L_{i,k} / T_i) Key insight: This averages the PROPORTION of each subtask within each trajectory, giving equal weight to all trajectories regardless of absolute length. """ def test_basic_two_trajectories_equal_proportions(self): """Test with two trajectories that have equal proportions.""" # Both trajectories: subtask1 = 50%, subtask2 = 50% # Traj 1: T=100s, subtask1=50s, subtask2=50s # Traj 2: T=200s, subtask1=100s, subtask2=100s annotations = { 0: make_annotation([("subtask1", 0, 50), ("subtask2", 50, 100)]), 1: make_annotation([("subtask1", 0, 100), ("subtask2", 100, 200)]), } result = compute_temporal_proportions(annotations) # Both should be 0.5 assert abs(result["subtask1"] - 0.5) < 1e-6 assert abs(result["subtask2"] - 0.5) < 1e-6 def test_paper_example_different_from_avg_durations(self): """Test that compute_temporal_proportions differs from naive average duration approach. This is the key test showing the difference between: - Paper formula: average of (L_i,k / T_i) - Naive approach: mean(L_i,k) / sum(mean(L_i,j)) """ # Episode 1: T=100s, subtask1=80s, subtask2=20s (proportions: 0.8, 0.2) # Episode 2: T=200s, subtask1=40s, subtask2=160s (proportions: 0.2, 0.8) annotations = { 0: make_annotation([("subtask1", 0, 80), ("subtask2", 80, 100)]), 1: make_annotation([("subtask1", 0, 40), ("subtask2", 40, 200)]), } result = compute_temporal_proportions(annotations) # Paper formula: # ᾱ_1 = (1/2) × (80/100 + 40/200) = (1/2) × (0.8 + 0.2) = 0.5 # ᾱ_2 = (1/2) × (20/100 + 160/200) = (1/2) × (0.2 + 0.8) = 0.5 assert abs(result["subtask1"] - 0.5) < 1e-6 assert abs(result["subtask2"] - 0.5) < 1e-6 def test_single_trajectory(self): """Test with a single trajectory.""" # T=100s, reach=30s, grasp=20s, lift=50s annotations = { 0: make_annotation([("reach", 0, 30), ("grasp", 30, 50), ("lift", 50, 100)]), } result = compute_temporal_proportions(annotations) assert abs(result["reach"] - 0.3) < 1e-6 assert abs(result["grasp"] - 0.2) < 1e-6 assert abs(result["lift"] - 0.5) < 1e-6 def test_sum_to_one(self): """Test that proportions always sum to 1.""" # Three episodes with varying proportions annotations = { 0: make_annotation([("a", 0, 10), ("b", 10, 50), ("c", 50, 100)]), # 0.1, 0.4, 0.5 1: make_annotation([("a", 0, 20), ("b", 20, 70), ("c", 70, 100)]), # 0.2, 0.5, 0.3 2: make_annotation([("a", 0, 30), ("b", 30, 90), ("c", 90, 100)]), # 0.3, 0.6, 0.1 } result = compute_temporal_proportions(annotations) total = sum(result.values()) assert abs(total - 1.0) < 1e-6 def test_empty_annotations_returns_empty(self): """Test that empty annotations returns empty dict.""" result = compute_temporal_proportions({}) assert result == {} def test_uniform_proportions(self): """Test with uniform proportions across subtasks.""" # Each subtask takes 25% of each episode annotations = { 0: make_annotation([("a", 0, 25), ("b", 25, 50), ("c", 50, 75), ("d", 75, 100)]), 1: make_annotation([("a", 0, 50), ("b", 50, 100), ("c", 100, 150), ("d", 150, 200)]), } result = compute_temporal_proportions(annotations) for name in ["a", "b", "c", "d"]: assert abs(result[name] - 0.25) < 1e-6
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/test_sarm_subtask_annotations.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:src/lerobot/robots/omx_follower/config_omx_follower.py
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from lerobot.cameras import CameraConfig from ..config import RobotConfig @RobotConfig.register_subclass("omx_follower") @dataclass class OmxFollowerConfig(RobotConfig): # Port to connect to the arm port: str disable_torque_on_disconnect: bool = True # `max_relative_target` limits the magnitude of the relative positional target vector for safety purposes. # Set this to a positive scalar to have the same value for all motors, or a dictionary that maps motor # names to the max_relative_target value for that motor. max_relative_target: float | dict[str, float] | None = None # cameras cameras: dict[str, CameraConfig] = field(default_factory=dict) # Set to `True` for backward compatibility with previous policies/dataset use_degrees: bool = False
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/omx_follower/config_omx_follower.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/omx_follower/omx_follower.py
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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 logging import time from functools import cached_property from lerobot.cameras.utils import make_cameras_from_configs from lerobot.motors import Motor, MotorCalibration, MotorNormMode from lerobot.motors.dynamixel import ( DriveMode, DynamixelMotorsBus, OperatingMode, ) from lerobot.processor import RobotAction, RobotObservation from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..robot import Robot from ..utils import ensure_safe_goal_position from .config_omx_follower import OmxFollowerConfig logger = logging.getLogger(__name__) class OmxFollower(Robot): """ - [OMX](https://github.com/ROBOTIS-GIT/open_manipulator), expansion, developed by Woojin Wie and Junha Cha from [ROBOTIS](https://ai.robotis.com/) """ config_class = OmxFollowerConfig name = "omx_follower" def __init__(self, config: OmxFollowerConfig): super().__init__(config) self.config = config norm_mode_body = MotorNormMode.DEGREES if config.use_degrees else MotorNormMode.RANGE_M100_100 self.bus = DynamixelMotorsBus( port=self.config.port, motors={ "shoulder_pan": Motor(11, "xl430-w250", norm_mode_body), "shoulder_lift": Motor(12, "xl430-w250", norm_mode_body), "elbow_flex": Motor(13, "xl430-w250", norm_mode_body), "wrist_flex": Motor(14, "xl330-m288", norm_mode_body), "wrist_roll": Motor(15, "xl330-m288", norm_mode_body), "gripper": Motor(16, "xl330-m288", MotorNormMode.RANGE_0_100), }, calibration=self.calibration, ) self.cameras = make_cameras_from_configs(config.cameras) @property def _motors_ft(self) -> dict[str, type]: return {f"{motor}.pos": float for motor in self.bus.motors} @property def _cameras_ft(self) -> dict[str, tuple]: return { cam: (self.config.cameras[cam].height, self.config.cameras[cam].width, 3) for cam in self.cameras } @cached_property def observation_features(self) -> dict[str, type | tuple]: return {**self._motors_ft, **self._cameras_ft} @cached_property def action_features(self) -> dict[str, type]: return self._motors_ft @property def is_connected(self) -> bool: return self.bus.is_connected and all(cam.is_connected for cam in self.cameras.values()) @check_if_already_connected def connect(self, calibrate: bool = True) -> None: """ For OMX robots that come pre-calibrated: - If default calibration from package doesn't match motors, read from motors and save - This allows using pre-calibrated robots without manual calibration - If no calibration file exists, use factory default values (homing_offset=0, range_min=0, range_max=4095) """ self.bus.connect() if not self.is_calibrated and calibrate: logger.info( "Mismatch between calibration values in the motor and the calibration file or no calibration file found" ) self.calibrate() for cam in self.cameras.values(): cam.connect() self.configure() logger.info(f"{self} connected.") @property def is_calibrated(self) -> bool: return self.bus.is_calibrated def calibrate(self) -> None: self.bus.disable_torque() logger.info(f"\nUsing factory default calibration values for {self}") logger.info(f"\nWriting default configuration of {self} to the motors") for motor in self.bus.motors: self.bus.write("Operating_Mode", motor, OperatingMode.EXTENDED_POSITION.value) for motor in self.bus.motors: self.bus.write("Drive_Mode", motor, DriveMode.NON_INVERTED.value) self.calibration = {} for motor, m in self.bus.motors.items(): self.calibration[motor] = MotorCalibration( id=m.id, drive_mode=0, homing_offset=0, range_min=0, range_max=4095, ) self.bus.write_calibration(self.calibration) self._save_calibration() logger.info(f"Calibration saved to {self.calibration_fpath}") def configure(self) -> None: with self.bus.torque_disabled(): self.bus.configure_motors() # Use 'extended position mode' for all motors except gripper, because in joint mode the servos # can't rotate more than 360 degrees (from 0 to 4095) And some mistake can happen while assembling # the arm, you could end up with a servo with a position 0 or 4095 at a crucial point for motor in self.bus.motors: if motor != "gripper": self.bus.write("Operating_Mode", motor, OperatingMode.EXTENDED_POSITION.value) # Use 'position control current based' for gripper to be limited by the limit of the current. For # the follower gripper, it means it can grasp an object without forcing too much even tho, its # goal position is a complete grasp (both gripper fingers are ordered to join and reach a touch). # For the leader gripper, it means we can use it as a physical trigger, since we can force with # our finger to make it move, and it will move back to its original target position when we # release the force. self.bus.write("Operating_Mode", "gripper", OperatingMode.CURRENT_POSITION.value) # Set better PID values to close the gap between recorded states and actions # TODO(rcadene): Implement an automatic procedure to set optimal PID values for each motor self.bus.write("Position_P_Gain", "elbow_flex", 1500) self.bus.write("Position_I_Gain", "elbow_flex", 0) self.bus.write("Position_D_Gain", "elbow_flex", 600) def setup_motors(self) -> None: for motor in reversed(self.bus.motors): input(f"Connect the controller board to the '{motor}' motor only and press enter.") self.bus.setup_motor(motor) print(f"'{motor}' motor id set to {self.bus.motors[motor].id}") @check_if_not_connected def get_observation(self) -> RobotObservation: # Read arm position start = time.perf_counter() obs_dict = self.bus.sync_read("Present_Position") obs_dict = {f"{motor}.pos": val for motor, val in obs_dict.items()} dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} read state: {dt_ms:.1f}ms") # Capture images from cameras for cam_key, cam in self.cameras.items(): start = time.perf_counter() obs_dict[cam_key] = cam.read_latest() dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} read {cam_key}: {dt_ms:.1f}ms") return obs_dict @check_if_not_connected def send_action(self, action: RobotAction) -> RobotAction: """Command arm to move to a target joint configuration. The relative action magnitude may be clipped depending on the configuration parameter `max_relative_target`. In this case, the action sent differs from original action. Thus, this function always returns the action actually sent. Args: action (RobotAction): The goal positions for the motors. Returns: RobotAction: The action sent to the motors, potentially clipped. """ goal_pos = {key.removesuffix(".pos"): val for key, val in action.items() if key.endswith(".pos")} # Cap goal position when too far away from present position. # /!\ Slower fps expected due to reading from the follower. if self.config.max_relative_target is not None: present_pos = self.bus.sync_read("Present_Position") goal_present_pos = {key: (g_pos, present_pos[key]) for key, g_pos in goal_pos.items()} goal_pos = ensure_safe_goal_position(goal_present_pos, self.config.max_relative_target) # Send goal position to the arm self.bus.sync_write("Goal_Position", goal_pos) return {f"{motor}.pos": val for motor, val in goal_pos.items()} @check_if_not_connected def disconnect(self): self.bus.disconnect(self.config.disable_torque_on_disconnect) for cam in self.cameras.values(): cam.disconnect() logger.info(f"{self} disconnected.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/omx_follower/omx_follower.py", "license": "Apache License 2.0", "lines": 180, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/omx_leader/config_omx_leader.py
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass from ..config import TeleoperatorConfig @TeleoperatorConfig.register_subclass("omx_leader") @dataclass class OmxLeaderConfig(TeleoperatorConfig): # Port to connect to the arm port: str # Sets the arm in torque mode with the gripper motor set to this value. This makes it possible to squeeze # the gripper and have it spring back to an open position on its own. gripper_open_pos: float = 60.0
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/omx_leader/config_omx_leader.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/teleoperators/omx_leader/omx_leader.py
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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 logging import time from lerobot.motors import Motor, MotorCalibration, MotorNormMode from lerobot.motors.dynamixel import ( DriveMode, DynamixelMotorsBus, OperatingMode, ) from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from ..teleoperator import Teleoperator from .config_omx_leader import OmxLeaderConfig logger = logging.getLogger(__name__) class OmxLeader(Teleoperator): """ - [OMX](https://github.com/ROBOTIS-GIT/open_manipulator), expansion, developed by Woojin Wie and Junha Cha from [ROBOTIS](https://ai.robotis.com/) """ config_class = OmxLeaderConfig name = "omx_leader" def __init__(self, config: OmxLeaderConfig): super().__init__(config) self.config = config self.bus = DynamixelMotorsBus( port=self.config.port, motors={ "shoulder_pan": Motor(1, "xl330-m288", MotorNormMode.RANGE_M100_100), "shoulder_lift": Motor(2, "xl330-m288", MotorNormMode.RANGE_M100_100), "elbow_flex": Motor(3, "xl330-m288", MotorNormMode.RANGE_M100_100), "wrist_flex": Motor(4, "xl330-m288", MotorNormMode.RANGE_M100_100), "wrist_roll": Motor(5, "xl330-m288", MotorNormMode.RANGE_M100_100), "gripper": Motor(6, "xl330-m077", MotorNormMode.RANGE_0_100), }, calibration=self.calibration, ) @property def action_features(self) -> dict[str, type]: return {f"{motor}.pos": float for motor in self.bus.motors} @property def feedback_features(self) -> dict[str, type]: return {} @property def is_connected(self) -> bool: return self.bus.is_connected @check_if_already_connected def connect(self, calibrate: bool = True) -> None: self.bus.connect() if not self.is_calibrated and calibrate: logger.info( "Mismatch between calibration values in the motor and the calibration file or no calibration file found" ) self.calibrate() self.configure() logger.info(f"{self} connected.") @property def is_calibrated(self) -> bool: return self.bus.is_calibrated def calibrate(self) -> None: self.bus.disable_torque() logger.info(f"\nUsing factory default calibration values for {self}") logger.info(f"\nWriting default configuration of {self} to the motors") for motor in self.bus.motors: self.bus.write("Operating_Mode", motor, OperatingMode.EXTENDED_POSITION.value) for motor in self.bus.motors: if motor == "gripper": self.bus.write("Drive_Mode", motor, DriveMode.INVERTED.value) else: self.bus.write("Drive_Mode", motor, DriveMode.NON_INVERTED.value) drive_modes = {motor: 1 if motor == "gripper" else 0 for motor in self.bus.motors} self.calibration = {} for motor, m in self.bus.motors.items(): self.calibration[motor] = MotorCalibration( id=m.id, drive_mode=drive_modes[motor], homing_offset=0 if motor != "gripper" else 100, range_min=0, range_max=4095, ) self.bus.write_calibration(self.calibration) self._save_calibration() logger.info(f"Calibration saved to {self.calibration_fpath}") def configure(self) -> None: self.bus.disable_torque() self.bus.configure_motors() for motor in self.bus.motors: if motor != "gripper": # Use 'extended position mode' for all motors except gripper, because in joint mode the servos # can't rotate more than 360 degrees (from 0 to 4095) And some mistake can happen while # assembling the arm, you could end up with a servo with a position 0 or 4095 at a crucial # point self.bus.write("Operating_Mode", motor, OperatingMode.EXTENDED_POSITION.value) if motor == "gripper": self.bus.write("Drive_Mode", motor, DriveMode.INVERTED.value) else: self.bus.write("Drive_Mode", motor, DriveMode.NON_INVERTED.value) # Use 'position control current based' for gripper to be limited by the limit of the current. # For the follower gripper, it means it can grasp an object without forcing too much even tho, # its goal position is a complete grasp (both gripper fingers are ordered to join and reach a touch). # For the leader gripper, it means we can use it as a physical trigger, since we can force with our finger # to make it move, and it will move back to its original target position when we release the force. self.bus.write("Operating_Mode", "gripper", OperatingMode.CURRENT_POSITION.value) self.bus.write("Current_Limit", "gripper", 100) self.bus.write("Goal_Current", "gripper", 100) self.bus.write("Homing_Offset", "gripper", 100) # Set gripper's goal pos in current position mode so that we can use it as a trigger. self.bus.enable_torque("gripper") if self.is_calibrated: self.bus.write("Goal_Position", "gripper", self.config.gripper_open_pos) def setup_motors(self) -> None: for motor in reversed(self.bus.motors): input(f"Connect the controller board to the '{motor}' motor only and press enter.") self.bus.setup_motor(motor) print(f"'{motor}' motor id set to {self.bus.motors[motor].id}") @check_if_not_connected def get_action(self) -> dict[str, float]: start = time.perf_counter() action = self.bus.sync_read("Present_Position") action = {f"{motor}.pos": val for motor, val in action.items()} dt_ms = (time.perf_counter() - start) * 1e3 logger.debug(f"{self} read action: {dt_ms:.1f}ms") return action def send_feedback(self, feedback: dict[str, float]) -> None: # TODO(rcadene, aliberts): Implement force feedback raise NotImplementedError @check_if_not_connected def disconnect(self) -> None: self.bus.disconnect() logger.info(f"{self} disconnected.")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/teleoperators/omx_leader/omx_leader.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/earthrover_mini_plus/config_earthrover_mini_plus.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Configuration for EarthRover Mini Plus robot.""" from dataclasses import dataclass from ..config import RobotConfig @RobotConfig.register_subclass("earthrover_mini_plus") @dataclass class EarthRoverMiniPlusConfig(RobotConfig): """Configuration for EarthRover Mini Plus robot using Frodobots SDK. This robot uses cloud-based control via the Frodobots SDK HTTP API. Camera frames are accessed directly through SDK HTTP endpoints. Attributes: sdk_url: URL of the Frodobots SDK server (default: http://localhost:8000) """ sdk_url: str = "http://localhost:8000"
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/earthrover_mini_plus/config_earthrover_mini_plus.py", "license": "Apache License 2.0", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/earthrover_mini_plus/robot_earthrover_mini_plus.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """EarthRover Mini Plus robot using Frodobots SDK.""" import base64 import logging from functools import cached_property import cv2 import numpy as np import requests from lerobot.processor import RobotAction, RobotObservation from lerobot.utils.decorators import check_if_already_connected, check_if_not_connected from lerobot.utils.errors import DeviceNotConnectedError from ..robot import Robot from .config_earthrover_mini_plus import EarthRoverMiniPlusConfig logger = logging.getLogger(__name__) # Action feature keys ACTION_LINEAR_VEL = "linear.vel" ACTION_ANGULAR_VEL = "angular.vel" # Observation feature keys OBS_FRONT = "front" OBS_REAR = "rear" OBS_LINEAR_VEL = "linear.vel" OBS_BATTERY_LEVEL = "battery.level" OBS_ORIENTATION_DEG = "orientation.deg" OBS_GPS_LATITUDE = "gps.latitude" OBS_GPS_LONGITUDE = "gps.longitude" OBS_GPS_SIGNAL = "gps.signal" OBS_SIGNAL_LEVEL = "signal.level" OBS_VIBRATION = "vibration" OBS_LAMP_STATE = "lamp.state" class EarthRoverMiniPlus(Robot): """ EarthRover Mini Plus robot controlled via Frodobots SDK HTTP API. This robot uses cloud-based control through the Frodobots SDK instead of direct hardware connection. Cameras stream via WebRTC through Agora cloud, and control commands are sent via HTTP POST requests. The robot supports: - Dual cameras (front and rear) accessed via SDK HTTP endpoints - Linear and angular velocity control - Battery and orientation telemetry Attributes: config: Robot configuration sdk_base_url: URL of the Frodobots SDK server (default: http://localhost:8000) """ config_class = EarthRoverMiniPlusConfig name = "earthrover_mini_plus" def __init__(self, config: EarthRoverMiniPlusConfig): """Initialize EarthRover Mini Plus robot. Args: config: Robot configuration including SDK URL """ super().__init__(config) self.config = config self.sdk_base_url = "http://localhost:8000" # Empty cameras dict for compatibility with recording script # Cameras are accessed directly via SDK, not through Camera objects self.cameras = {} self._is_connected = False # Cache for camera frames (fallback when requests fail) self._last_front_frame = None self._last_rear_frame = None # Cache for robot telemetry data (fallback when requests fail) self._last_robot_data = None logger.info(f"Initialized {self.name} with SDK at {self.sdk_base_url}") @property def is_connected(self) -> bool: """Check if robot is connected to SDK.""" return self._is_connected @check_if_already_connected def connect(self, calibrate: bool = True) -> None: """Connect to robot via Frodobots SDK. Args: calibrate: Not used for SDK-based robot (kept for API compatibility) Raises: DeviceAlreadyConnectedError: If robot is already connected DeviceNotConnectedError: If cannot connect to SDK server """ # Verify SDK is running and accessible try: response = requests.get(f"{self.sdk_base_url}/data", timeout=10.0) if response.status_code != 200: raise DeviceNotConnectedError( f"Cannot connect to SDK at {self.sdk_base_url}. " "Make sure it's running: hypercorn main:app --reload" ) except requests.RequestException as e: raise DeviceNotConnectedError(f"Cannot connect to SDK at {self.sdk_base_url}: {e}") from e self._is_connected = True logger.info(f"{self.name} connected to SDK") if calibrate: self.calibrate() def calibrate(self) -> None: """Calibration not needed for SDK-based robot.""" logger.info("Calibration not required for SDK-based robot") @property def is_calibrated(self) -> bool: """SDK robot doesn't require calibration. Returns: bool: Always True for SDK-based robots """ return True def configure(self) -> None: """Configure robot (no-op for SDK-based robot).""" pass @cached_property def observation_features(self) -> dict[str, type | tuple]: """Define the observation space for dataset recording. Returns: dict: Observation features with types/shapes: - front: (480, 640, 3) - Front camera RGB image - rear: (480, 640, 3) - Rear camera RGB image - linear.vel: float - Current speed (0-1, SDK reports only positive speeds) - battery.level: float - Battery level (0-1, normalized from 0-100) - orientation.deg: float - Robot orientation (0-1, normalized from raw value) - gps.latitude: float - GPS latitude coordinate - gps.longitude: float - GPS longitude coordinate - gps.signal: float - GPS signal strength (0-1, normalized from percentage) - signal.level: float - Network signal level (0-1, normalized from 0-5) - vibration: float - Vibration sensor reading - lamp.state: float - Lamp state (0=off, 1=on) """ return { # Cameras (height, width, channels) OBS_FRONT: (480, 640, 3), OBS_REAR: (480, 640, 3), # Motion state OBS_LINEAR_VEL: float, # Robot state OBS_BATTERY_LEVEL: float, OBS_ORIENTATION_DEG: float, # GPS OBS_GPS_LATITUDE: float, OBS_GPS_LONGITUDE: float, OBS_GPS_SIGNAL: float, # Sensors OBS_SIGNAL_LEVEL: float, OBS_VIBRATION: float, OBS_LAMP_STATE: float, } @cached_property def action_features(self) -> dict[str, type]: """Define the action space. Returns: dict: Action features with types: - linear.vel: float - Target linear velocity - angular.vel: float - Target angular velocity """ return { ACTION_LINEAR_VEL: float, ACTION_ANGULAR_VEL: float, } @check_if_not_connected def get_observation(self) -> RobotObservation: """Get current robot observation from SDK. Returns: RobotObservation: Observation containing: - front: Front camera image (480, 640, 3) in RGB format - rear: Rear camera image (480, 640, 3) in RGB format - linear.vel: Current speed (0-1, SDK reports only positive speeds) - battery.level: Battery level (0-1, normalized from 0-100) - orientation.deg: Robot orientation (0-1, normalized from raw value) - gps.latitude: GPS latitude coordinate - gps.longitude: GPS longitude coordinate - gps.signal: GPS signal strength (0-1, normalized from percentage) - signal.level: Network signal level (0-1, normalized from 0-5) - vibration: Vibration sensor reading - lamp.state: Lamp state (0=off, 1=on) Raises: DeviceNotConnectedError: If robot is not connected Note: Camera frames are retrieved from SDK endpoints /v2/front and /v2/rear. Frames are decoded from base64 and converted from BGR to RGB format. Robot telemetry is retrieved from /data endpoint. All SDK values are normalized to appropriate ranges for dataset recording. """ observation = {} # Get camera images from SDK frames = self._get_camera_frames() observation[OBS_FRONT] = frames["front"] observation[OBS_REAR] = frames["rear"] # Get robot state from SDK robot_data = self._get_robot_data() # Motion state observation[OBS_LINEAR_VEL] = robot_data["speed"] / 100.0 # Normalize 0-100 to 0-1 # Robot state observation[OBS_BATTERY_LEVEL] = robot_data["battery"] / 100.0 # Normalize 0-100 to 0-1 observation[OBS_ORIENTATION_DEG] = robot_data["orientation"] / 360.0 # Normalize to 0-1 # GPS data observation[OBS_GPS_LATITUDE] = robot_data["latitude"] observation[OBS_GPS_LONGITUDE] = robot_data["longitude"] observation[OBS_GPS_SIGNAL] = robot_data["gps_signal"] / 100.0 # Normalize percentage to 0-1 # Sensors observation[OBS_SIGNAL_LEVEL] = robot_data["signal_level"] / 5.0 # Normalize 0-5 to 0-1 observation[OBS_VIBRATION] = robot_data["vibration"] observation[OBS_LAMP_STATE] = float(robot_data["lamp"]) # 0 or 1 return observation @check_if_not_connected def send_action(self, action: RobotAction) -> RobotAction: """Send action to robot via SDK. Args: action: Action dict with keys: - linear.vel: Target linear velocity (-1 to 1) - angular.vel: Target angular velocity (-1 to 1) Returns: RobotAction: The action that was sent (matches action_features keys) Raises: DeviceNotConnectedError: If robot is not connected Note: Actions are sent to SDK via POST /control endpoint. SDK expects commands in range [-1, 1]. """ # Extract action values and convert to float linear = float(action.get(ACTION_LINEAR_VEL, 0.0)) angular = float(action.get(ACTION_ANGULAR_VEL, 0.0)) # Send command to SDK try: self._send_command_to_sdk(linear, angular) except Exception as e: logger.error(f"Error sending action: {e}") # Return action in format matching action_features return { ACTION_LINEAR_VEL: linear, ACTION_ANGULAR_VEL: angular, } @check_if_not_connected def disconnect(self) -> None: """Disconnect from robot. Stops the robot and closes connection to SDK. Raises: DeviceNotConnectedError: If robot is not connected """ # Stop the robot before disconnecting try: self._send_command_to_sdk(0.0, 0.0) except Exception as e: logger.warning(f"Failed to stop robot during disconnect: {e}") self._is_connected = False logger.info(f"{self.name} disconnected") # Private helper methods for SDK communication def _get_camera_frames(self) -> dict[str, np.ndarray]: """Get camera frames from SDK using v2 endpoints with caching fallback. Returns: dict: Dictionary with 'front' and 'rear' keys containing: - Current frame (if request succeeds) - Cached frame (if request fails but cache exists) - Zero array (if request fails and no cache exists yet) Note: Uses /v2/front and /v2/rear endpoints which are 15x faster than /screenshot. Images are base64 encoded, resized to 640x480, and converted from BGR to RGB. If request fails, returns the last successfully retrieved frame (cached). """ frames = {} # Get front camera try: response = requests.get(f"{self.sdk_base_url}/v2/front", timeout=2.0) if response.status_code == 200: data = response.json() if "front_frame" in data and data["front_frame"]: front_img = self._decode_base64_image(data["front_frame"]) if front_img is not None: # Resize and convert BGR to RGB front_img = cv2.resize(front_img, (640, 480)) front_rgb = cv2.cvtColor(front_img, cv2.COLOR_BGR2RGB) frames["front"] = front_rgb # Cache the successful frame self._last_front_frame = front_rgb except Exception as e: logger.warning(f"Error fetching front camera: {e}") # Fallback: use cache or zero array if "front" not in frames: if self._last_front_frame is not None: frames["front"] = self._last_front_frame else: frames["front"] = np.zeros((480, 640, 3), dtype=np.uint8) # Get rear camera try: response = requests.get(f"{self.sdk_base_url}/v2/rear", timeout=2.0) if response.status_code == 200: data = response.json() if "rear_frame" in data and data["rear_frame"]: rear_img = self._decode_base64_image(data["rear_frame"]) if rear_img is not None: # Resize and convert BGR to RGB rear_img = cv2.resize(rear_img, (640, 480)) rear_rgb = cv2.cvtColor(rear_img, cv2.COLOR_BGR2RGB) frames["rear"] = rear_rgb # Cache the successful frame self._last_rear_frame = rear_rgb except Exception as e: logger.warning(f"Error fetching rear camera: {e}") # Fallback: use cache or zero array if "rear" not in frames: if self._last_rear_frame is not None: frames["rear"] = self._last_rear_frame else: frames["rear"] = np.zeros((480, 640, 3), dtype=np.uint8) return frames def _decode_base64_image(self, base64_string: str) -> np.ndarray | None: """Decode base64 string to image. Args: base64_string: Base64 encoded image string Returns: np.ndarray: Decoded image in BGR format (OpenCV default), or None if decoding fails """ try: img_bytes = base64.b64decode(base64_string) nparr = np.frombuffer(img_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) return img # Return in BGR format (OpenCV default) except Exception as e: logger.error(f"Error decoding image: {e}") return None def _get_robot_data(self) -> dict: """Get robot telemetry data from SDK. Returns: dict: Robot telemetry data including battery, speed, orientation, GPS, etc: - Current data (if request succeeds) - Cached data (if request fails but cache exists) - Default values (if request fails and no cache exists yet) Note: Uses /data endpoint which provides comprehensive robot state. If request fails, returns the last successfully retrieved data (cached). """ try: response = requests.get(f"{self.sdk_base_url}/data", timeout=2.0) if response.status_code == 200: data = response.json() # Cache the successful data self._last_robot_data = data return data except Exception as e: logger.warning(f"Error fetching robot data: {e}") # Fallback: use cache or default values if self._last_robot_data is not None: return self._last_robot_data else: # Return dict with default values (used only on first failure before any cache exists) return { "speed": 0, "battery": 0, "orientation": 0, "latitude": 0.0, "longitude": 0.0, "gps_signal": 0, "signal_level": 0, "vibration": 0.0, "lamp": 0, } def _send_command_to_sdk(self, linear: float, angular: float, lamp: int = 0) -> bool: """Send control command to SDK. Args: linear: Linear velocity command (-1 to 1) angular: Angular velocity command (-1 to 1) lamp: Lamp control (0=off, 1=on) Returns: bool: True if command sent successfully, False otherwise Note: Uses POST /control endpoint. Commands are sent as JSON payload. """ try: payload = { "command": { "linear": linear, "angular": angular, "lamp": lamp, } } response = requests.post( f"{self.sdk_base_url}/control", json=payload, timeout=1.0, ) return response.status_code == 200 except Exception as e: logger.error(f"Error sending command: {e}") return False
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/earthrover_mini_plus/robot_earthrover_mini_plus.py", "license": "Apache License 2.0", "lines": 388, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/action_hub.py
# ------------------------------------------------------------------------------ # Copyright 2025 2toINF and HuggingFace Inc. (https://github.com/2toINF) # # 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 __future__ import annotations from collections.abc import Iterable import torch import torch.nn as nn # ============================================================================= # Registry # ============================================================================= ACTION_REGISTRY: dict[str, type[BaseActionSpace]] = {} def register_action(name: str): """Decorator for registering a new action space.""" def _wrap(cls): key = name.lower() if key in ACTION_REGISTRY: raise KeyError(f"ActionSpace '{key}' already registered -> {ACTION_REGISTRY[key]}") ACTION_REGISTRY[key] = cls cls.name = key return cls return _wrap def build_action_space(name: str, **kwargs) -> BaseActionSpace: """Instantiate a registered action space by name.""" key = name.lower() if key not in ACTION_REGISTRY: raise KeyError(f"Unknown action space '{name}'. Available: {list(ACTION_REGISTRY.keys())}") return ACTION_REGISTRY[key](**kwargs) # ============================================================================= # Base class # ============================================================================= class BaseActionSpace(nn.Module): """ Abstract base class for all action-space definitions. Each subclass defines: - `dim_action`: dimension of the action vector. - `gripper_idx`: indices of gripper channels. - `compute_loss(pred, target)`: supervised loss for this space. - `preprocess(proprio, action, mode)`: pre-step modifications. - `postprocess(action)`: post-step corrections (e.g. apply sigmoid). """ name: str = "base" dim_action: int = 0 gripper_idx: tuple[int, ...] = () def __init__(self): super().__init__() # --------------------------------------------------------------------- # Core supervised loss # --------------------------------------------------------------------- def compute_loss(self, pred: torch.Tensor, target: torch.Tensor) -> dict[str, torch.Tensor]: raise NotImplementedError def forward(self, pred: torch.Tensor, target: torch.Tensor) -> dict[str, torch.Tensor]: """Alias for compute_loss.""" return self.compute_loss(pred, target) # --------------------------------------------------------------------- # Space-level hooks # --------------------------------------------------------------------- def preprocess( self, proprio: torch.Tensor, action: torch.Tensor, mode: str = "train", ) -> tuple[torch.Tensor, torch.Tensor]: """Default: return unchanged.""" return proprio, action def postprocess(self, action: torch.Tensor) -> torch.Tensor: """Default: return unchanged.""" return action # ============================================================================= # Utilities # ============================================================================= def _ensure_indices_valid(dim_action: int, idx: Iterable[int], name: str) -> None: bad = [i for i in idx if i < 0 or i >= dim_action] if bad: raise IndexError(f"{name} contains out-of-range indices {bad} for action dim dim_action={dim_action}") # ============================================================================= # Implementations # ============================================================================= @register_action("ee6d") class EE6DActionSpace(BaseActionSpace): """End-effector layout with xyz, 6D rotation, and gripper channels.""" dim_action = 20 gripper_idx = (9, 19) GRIPPER_SCALE = 1.0 XYZ_SCALE = 500.0 ROT_SCALE = 10.0 POS_IDX_1 = (0, 1, 2) POS_IDX_2 = (10, 11, 12) ROT_IDX_1 = (3, 4, 5, 6, 7, 8) ROT_IDX_2 = (13, 14, 15, 16, 17, 18) def __init__(self): super().__init__() self.mse = nn.MSELoss() self.bce = nn.BCEWithLogitsLoss() def compute_loss(self, pred, target): assert pred.shape == target.shape, "pred/target shapes must match" batch_size, seq_len, action_dim = pred.shape _ensure_indices_valid(action_dim, self.gripper_idx, "gripper_idx") # Gripper BCE g_losses = [self.bce(pred[:, :, gi], target[:, :, gi]) for gi in self.gripper_idx] gripper_loss = sum(g_losses) / len(self.gripper_idx) * self.GRIPPER_SCALE # XYZ position pos_loss = ( self.mse(pred[:, :, self.POS_IDX_1], target[:, :, self.POS_IDX_1]) + self.mse(pred[:, :, self.POS_IDX_2], target[:, :, self.POS_IDX_2]) ) * self.XYZ_SCALE # Rotation 6D rot_loss = ( self.mse(pred[:, :, self.ROT_IDX_1], target[:, :, self.ROT_IDX_1]) + self.mse(pred[:, :, self.ROT_IDX_2], target[:, :, self.ROT_IDX_2]) ) * self.ROT_SCALE return { "position_loss": pos_loss, "rotate6D_loss": rot_loss, "gripper_loss": gripper_loss, } def preprocess(self, proprio, action, mode="train"): """Zero-out gripper channels in proprio/action.""" proprio_m = proprio.clone() action_m = action.clone() proprio_m[..., self.gripper_idx] = 0.0 action_m[..., self.gripper_idx] = 0.0 return proprio_m, action_m def postprocess(self, action: torch.Tensor) -> torch.Tensor: """Apply sigmoid to gripper logits.""" if action.size(-1) > max(self.gripper_idx): action[..., self.gripper_idx] = torch.sigmoid(action[..., self.gripper_idx]) return action @register_action("joint") class JointActionSpace(BaseActionSpace): """Joint-space layout with joints + gripper only.""" dim_action = 14 gripper_idx = (6, 13) GRIPPER_SCALE = 0.1 JOINTS_SCALE = 1.0 def __init__(self): super().__init__() self.mse = nn.MSELoss() self.bce = nn.BCEWithLogitsLoss() def compute_loss(self, pred, target): assert pred.shape == target.shape batch_size, seq_len, action_dim = pred.shape _ensure_indices_valid(action_dim, self.gripper_idx, "gripper_idx") g_losses = [self.bce(pred[:, :, gi], target[:, :, gi]) for gi in self.gripper_idx] gripper_loss = sum(g_losses) / len(self.gripper_idx) * self.GRIPPER_SCALE joints_idx = tuple(i for i in range(action_dim) if i not in set(self.gripper_idx)) joints_loss = self.mse(pred[:, :, joints_idx], target[:, :, joints_idx]) * self.JOINTS_SCALE return { "joints_loss": joints_loss, "gripper_loss": gripper_loss, } def preprocess(self, proprio, action, mode="train"): """Zero-out gripper channels in proprio/action.""" proprio_m = proprio.clone() action_m = action.clone() proprio_m[..., self.gripper_idx] = 0.0 action_m[..., self.gripper_idx] = 0.0 return proprio_m, action_m def postprocess(self, action: torch.Tensor) -> torch.Tensor: """Apply sigmoid to gripper logits.""" if action.size(-1) > max(self.gripper_idx): action[..., self.gripper_idx] = torch.sigmoid(action[..., self.gripper_idx]) return action @register_action("agibot_ee6d") class AGIBOTEE6DActionSpace(BaseActionSpace): """AGI-bot variant of EE6DActionSpace using MSE for all components.""" dim_action = 20 gripper_idx = (9, 19) GRIPPER_SCALE = 10.0 XYZ_SCALE = 500.0 ROT_SCALE = 10.0 POS_IDX_1 = (0, 1, 2) POS_IDX_2 = (10, 11, 12) ROT_IDX_1 = (3, 4, 5, 6, 7, 8) ROT_IDX_2 = (13, 14, 15, 16, 17, 18) def __init__(self): super().__init__() self.mse = nn.MSELoss() def compute_loss(self, pred, target): assert pred.shape == target.shape batch_size, seq_len, action_dim = pred.shape _ensure_indices_valid(action_dim, self.gripper_idx, "gripper_idx") gripper_loss = ( self.mse(pred[:, :, self.gripper_idx], target[:, :, self.gripper_idx]) * self.GRIPPER_SCALE ) pos_loss = ( self.mse(pred[:, :, self.POS_IDX_1], target[:, :, self.POS_IDX_1]) + self.mse(pred[:, :, self.POS_IDX_2], target[:, :, self.POS_IDX_2]) ) * self.XYZ_SCALE rot_loss = ( self.mse(pred[:, :, self.ROT_IDX_1], target[:, :, self.ROT_IDX_1]) + self.mse(pred[:, :, self.ROT_IDX_2], target[:, :, self.ROT_IDX_2]) ) * self.ROT_SCALE return { "position_loss": pos_loss, "rotate6D_loss": rot_loss, "gripper_loss": gripper_loss, } def preprocess(self, proprio, action, mode="train"): """No preprocessing applied in AGIBOT variant.""" return proprio, action def postprocess(self, action: torch.Tensor) -> torch.Tensor: """AGIBOT does not postprocess.""" return action @register_action("franka_joint7") class FrankaJoint7ActionSpace(BaseActionSpace): """ Franka Panda joint-space: 7 joints, with gripper. - Real robot action dim: 7 - Model-facing dim: 20 (padded with zeros) compatible with pretrained VLA models expecting 20D. """ dim_action = 20 # model dimension REAL_DIM = 7 # actual Franka joints JOINTS_SCALE = 1.0 def __init__(self): super().__init__() self.mse = nn.MSELoss() def _pad_to_model_dim(self, x: torch.Tensor) -> torch.Tensor: """Pad 7 → 20 dims (zeros for the dummy channels).""" if x is None: return None if x.size(-1) == self.dim_action: return x if x.size(-1) != self.REAL_DIM: raise ValueError( f"Expected last dim to be {self.REAL_DIM} or {self.dim_action}, got {x.size(-1)}" ) pad_shape = list(x.shape[:-1]) + [self.dim_action - self.REAL_DIM] # 13 zeros pad = x.new_zeros(pad_shape) return torch.cat([x, pad], dim=-1) def _trim_to_real_dim(self, x: torch.Tensor) -> torch.Tensor: """Trim model output 20 → 7 dims.""" return x[..., : self.REAL_DIM] def compute_loss(self, pred, target): """ pred : [B, T, 20] target : [B, T, 7] or [B, T, 20] Only compute MSE on the first 7 dims. """ pred = self._pad_to_model_dim(pred) target = self._pad_to_model_dim(target) assert pred.shape == target.shape joints_loss = ( self.mse( pred[:, :, : self.REAL_DIM], # use only the first 7 joints target[:, :, : self.REAL_DIM], ) * self.JOINTS_SCALE ) return {"joints_loss": joints_loss} def preprocess(self, proprio, action, mode="train"): """ During training: - Pad [7] → [20] """ return proprio, self._pad_to_model_dim(action) def postprocess(self, action: torch.Tensor) -> torch.Tensor: """ After model prediction: - Trim [20] → [7] for real robot control. """ return self._trim_to_real_dim(action) @register_action("auto") class AutoActionSpace(BaseActionSpace): """ Auto-detecting action space that adapts to any action dimension. - Auto-detects the real action dimension from the policy feature - Model outputs max_dim for compatibility with pretrained models - Loss is computed only on the first real_dim dimensions - Postprocess trims output back to real_dim Args: real_dim: The actual action dimension from the dataset/policy feature max_dim: The model's output dimension for pretrained VLA compatibility """ JOINTS_SCALE = 1.0 def __init__(self, real_dim: int, max_dim: int): super().__init__() self.real_dim = real_dim self.dim_action = max_dim # Model-facing dimension self.mse = nn.MSELoss() def _pad_to_model_dim(self, x: torch.Tensor) -> torch.Tensor: """Pad real_dim → max_dim (zeros for the dummy channels).""" if x is None: return None if x.size(-1) == self.dim_action: return x if x.size(-1) != self.real_dim: # If dimension doesn't match either, pad/trim to real_dim first if x.size(-1) < self.real_dim: pad_shape = list(x.shape[:-1]) + [self.real_dim - x.size(-1)] pad = x.new_zeros(pad_shape) x = torch.cat([x, pad], dim=-1) else: x = x[..., : self.real_dim] pad_shape = list(x.shape[:-1]) + [self.dim_action - self.real_dim] pad = x.new_zeros(pad_shape) return torch.cat([x, pad], dim=-1) def _trim_to_real_dim(self, x: torch.Tensor) -> torch.Tensor: """Trim model output max_dim → real_dim.""" return x[..., : self.real_dim] def compute_loss(self, pred: torch.Tensor, target: torch.Tensor) -> dict[str, torch.Tensor]: """ Compute loss only on the first real_dim dimensions. pred: [B, T, max_dim] from the model target: [B, T, real_dim] or [B, T, max_dim] Loss = MSE(pred[:,:,:real_dim], target[:,:,:real_dim]) """ pred = self._pad_to_model_dim(pred) target = self._pad_to_model_dim(target) assert pred.shape == target.shape, f"Shape mismatch: pred {pred.shape} vs target {target.shape}" # only compute loss on the real dimensions joints_loss = ( self.mse( pred[:, :, : self.real_dim], target[:, :, : self.real_dim], ) * self.JOINTS_SCALE ) return {"joints_loss": joints_loss} def preprocess(self, proprio: torch.Tensor, action: torch.Tensor, mode: str = "train"): """ Pad action from real_dim to max_dim for the model. """ return proprio, self._pad_to_model_dim(action) def postprocess(self, action: torch.Tensor) -> torch.Tensor: """ Trim model output from max_dim to real_dim for real robot control. """ return self._trim_to_real_dim(action) @register_action("so101_bimanual") class BimanualSO101ActionSpace(BaseActionSpace): """ Bimanual SO101 robot: 2 arms with 5 joints each + gripper. Layout (real robot): [left_arm (5 joints + gripper), right_arm (5 joints + gripper)] - Left arm: shoulder_pan, shoulder_lift, elbow_flex, wrist_flex, wrist_roll, gripper - Right arm: shoulder_pan, shoulder_lift, elbow_flex, wrist_flex, wrist_roll, gripper Real action dim: 12 Model-facing dim: 20 (extra 8 dummy dims at the end) """ # Model output / training dimension (to match pretrained policy) dim_action = 20 # Real robot action dimension REAL_DIM = 12 # Indices of real vs dummy channels REAL_IDXS = tuple(range(REAL_DIM)) # 0..11 DUMMY_IDXS = tuple(range(REAL_DIM, dim_action)) # 12..19 # Grippers live in the real part gripper_idx = (5, 11) # left_gripper at idx 5, right_gripper at idx 11 GRIPPER_SCALE = 1.0 JOINTS_SCALE = 1.0 # Indices for left and right arm joints (excluding grippers) LEFT_ARM_JOINTS = (0, 1, 2, 3, 4) RIGHT_ARM_JOINTS = (6, 7, 8, 9, 10) def __init__(self): super().__init__() self.mse = nn.MSELoss() self.bce = nn.BCEWithLogitsLoss() # ---------- helpers ---------- def _pad_to_model_dim(self, x: torch.Tensor) -> torch.Tensor: """If last dim is REAL_DIM (12), pad zeros to reach dim_action (20).""" if x is None: return None if x.size(-1) == self.dim_action: return x if x.size(-1) != self.REAL_DIM: raise ValueError( f"Expected last dim to be {self.REAL_DIM} or {self.dim_action}, got {x.size(-1)}" ) pad_shape = list(x.shape[:-1]) + [self.dim_action - self.REAL_DIM] pad = x.new_zeros(pad_shape) return torch.cat([x, pad], dim=-1) def _trim_to_real_dim(self, x: torch.Tensor) -> torch.Tensor: """Keep only the first REAL_DIM (12) dims for the real robot.""" return x[..., : self.REAL_DIM] # ---------- loss ---------- def compute_loss(self, pred, target): """ pred: [B, T, 20] from the model target: [B, T, 12] or [B, T, 20] We pad target → 20 and compute loss only on the real dims. """ # Ensure both are [B, T, 20] pred = self._pad_to_model_dim(pred) target = self._pad_to_model_dim(target) assert pred.shape == target.shape # ---- MSE for all real dims (0–11) ---- real_dims = 12 joints_loss = ( self.mse( pred[:, :, :real_dims], target[:, :, :real_dims], ) * self.JOINTS_SCALE ) left_arm_loss = self.mse(pred[:, :, :6], target[:, :, :6]) right_arm_loss = self.mse(pred[:, :, 6:12], target[:, :, 6:12]) gripper_loss = ( self.mse( pred[:, :, [5, 11]], target[:, :, [5, 11]], ) * self.GRIPPER_SCALE ) return { "joints_loss": joints_loss, "gripper_loss": gripper_loss, "left_arm_loss": left_arm_loss, "right_arm_loss": right_arm_loss, } # ---------- preprocess / postprocess ---------- def preprocess(self, proprio, action, mode="train"): """ - If proprio/action are 12-dim, pad them to 20 for the model. - Zero-out gripper channels in proprio/action to focus learning on joints. """ proprio_m = self._pad_to_model_dim(proprio.clone()) action_m = self._pad_to_model_dim(action.clone()) if action is not None else None proprio_m[..., self.gripper_idx] = 0.0 if action_m is not None: action_m[..., self.gripper_idx] = 0.0 return proprio_m, action_m def postprocess(self, action: torch.Tensor) -> torch.Tensor: """ - Model outputs [*, 20] - Apply sigmoid to gripper logits - Return only the first 12 dims for the real robot: ["left_shoulder_pan.pos", "left_shoulder_lift.pos", "left_elbow_flex.pos", "left_wrist_flex.pos", "left_wrist_roll.pos", "left_gripper.pos", "right_shoulder_pan.pos", "right_shoulder_lift.pos", "right_elbow_flex.pos", "right_wrist_flex.pos", "right_wrist_roll.pos", "right_gripper.pos"] """ # Ensure we at least have the real dims + grippers if action.size(-1) < self.REAL_DIM: raise ValueError(f"Expected at least {self.REAL_DIM} dims in action, got {action.size(-1)}") # Apply sigmoid on gripper channels in model space (indices 5 and 11) if action.size(-1) > max(self.gripper_idx): action[..., self.gripper_idx] = torch.sigmoid(action[..., self.gripper_idx]) # Return only the real 12-dim control vector for the env return self._trim_to_real_dim(action) # ============================================================================= # Exports # ============================================================================= __all__ = [ "BaseActionSpace", "build_action_space", "register_action", "EE6DActionSpace", "JointActionSpace", "AGIBOTEE6DActionSpace", "FrankaJoint7ActionSpace", "AutoActionSpace", "BimanualSO101ActionSpace", "ACTION_REGISTRY", ]
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/action_hub.py", "license": "Apache License 2.0", "lines": 475, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/configuration_florence2.py
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved. # 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 warnings from transformers.configuration_utils import PretrainedConfig from transformers.utils import logging """ Florence-2 configuration""" logger = logging.get_logger(__name__) class Florence2VisionConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2VisionModel`]. It is used to instantiate a Florence2VisionModel according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Florence2VisionModel architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: drop_path_rate (`float`, *optional*, defaults to 0.1): The dropout rate of the drop path layer. patch_size (`List[int]`, *optional*, defaults to [7, 3, 3, 3]): The patch size of the image. patch_stride (`List[int]`, *optional*, defaults to [4, 2, 2, 2]): The patch stride of the image. patch_padding (`List[int]`, *optional*, defaults to [3, 1, 1, 1]): The patch padding of the image. patch_prenorm (`List[bool]`, *optional*, defaults to [false, true, true, true]): Whether to apply layer normalization before the patch embedding layer. enable_checkpoint (`bool`, *optional*, defaults to False): Whether to enable checkpointing. dim_embed (`List[int]`, *optional*, defaults to [256, 512, 1024, 2048]): The dimension of the embedding layer. num_heads (`List[int]`, *optional*, defaults to [8, 16, 32, 64]): The number of attention heads. num_groups (`List[int]`, *optional*, defaults to [8, 16, 32, 64]): The number of groups. depths (`List[int]`, *optional*, defaults to [1, 1, 9, 1]): The depth of the model. window_size (`int`, *optional*, defaults to 12): The window size of the model. projection_dim (`int`, *optional*, defaults to 1024): The dimension of the projection layer. visual_temporal_embedding (`dict`, *optional*): The configuration of the visual temporal embedding. image_pos_embed (`dict`, *optional*): The configuration of the image position embedding. image_feature_source (`List[str]`, *optional*, defaults to ["spatial_avg_pool", "temporal_avg_pool"]): The source of the image feature. Example: ```python >>> from transformers import Florence2VisionConfig, Florence2VisionModel >>> # Initializing a Florence2 Vision style configuration >>> configuration = Florence2VisionConfig() >>> # Initializing a model (with random weights) >>> model = Florence2VisionModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "davit" keys_to_ignore_at_inference = ["past_key_values"] def __init__( self, drop_path_rate=0.1, patch_size=None, patch_stride=None, patch_padding=None, patch_prenorm=None, enable_checkpoint=False, dim_embed=None, num_heads=None, num_groups=None, depths=None, window_size=12, projection_dim=1024, visual_temporal_embedding=None, image_pos_embed=None, image_feature_source=None, **kwargs, ): self.drop_path_rate = drop_path_rate self.patch_size = patch_size if patch_size is not None else [7, 3, 3, 3] self.patch_stride = patch_stride if patch_stride is not None else [4, 2, 2, 2] self.patch_padding = patch_padding if patch_padding is not None else [3, 1, 1, 1] self.patch_prenorm = patch_prenorm if patch_prenorm is not None else [False, True, True, True] self.enable_checkpoint = enable_checkpoint self.dim_embed = dim_embed if dim_embed is not None else [256, 512, 1024, 2048] self.num_heads = num_heads if num_heads is not None else [8, 16, 32, 64] self.num_groups = num_groups if num_groups is not None else [8, 16, 32, 64] self.depths = depths if depths is not None else [1, 1, 9, 1] self.window_size = window_size self.projection_dim = projection_dim if visual_temporal_embedding is None: visual_temporal_embedding = { "type": "COSINE", "max_temporal_embeddings": 100, } self.visual_temporal_embedding = visual_temporal_embedding if image_pos_embed is None: image_pos_embed = { "type": "learned_abs_2d", "max_pos_embeddings": 1000, } self.image_pos_embed = image_pos_embed self.image_feature_source = ( image_feature_source if image_feature_source is not None else ["spatial_avg_pool", "temporal_avg_pool"] ) super().__init__(**kwargs) class Florence2LanguageConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2LanguagePreTrainedModel`]. It is used to instantiate a BART model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the BART [facebook/bart-large](https://huggingface.co/facebook/bart-large) architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 51289): Vocabulary size of the Florence2Language model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Florence2LanguageModel`]. d_model (`int`, *optional*, defaults to 1024): Dimensionality of the layers and the pooler layer. encoder_layers (`int`, *optional*, defaults to 12): Number of encoder layers. decoder_layers (`int`, *optional*, defaults to 12): Number of decoder layers. encoder_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. decoder_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer decoder. decoder_ffn_dim (`int`, *optional*, defaults to 4096): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. encoder_ffn_dim (`int`, *optional*, defaults to 4096): Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. activation_function (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. dropout (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. activation_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for activations inside the fully connected layer. classifier_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for classifier. max_position_embeddings (`int`, *optional*, defaults to 1024): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). init_std (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. encoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. decoder_layerdrop (`float`, *optional*, defaults to 0.0): The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. scale_embedding (`bool`, *optional*, defaults to `False`): Scale embeddings by diving by sqrt(d_model). use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). num_labels (`int`, *optional*, defaults to 3): The number of labels to use in [`Florence2LanguageForSequenceClassification`]. forced_eos_token_id (`int`, *optional*, defaults to 2): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. Example: ```python >>> from transformers import Florence2LanguageConfig, Florence2LanguageModel >>> # Initializing a Florence2 Language style configuration >>> configuration = Florence2LanguageConfig() >>> # Initializing a model (with random weights) >>> model = Florence2LanguageModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "florence2_language" keys_to_ignore_at_inference = ["past_key_values"] attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self, vocab_size=51289, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_dim=4096, encoder_attention_heads=16, decoder_layers=12, decoder_ffn_dim=4096, decoder_attention_heads=16, encoder_layerdrop=0.0, decoder_layerdrop=0.0, activation_function="gelu", d_model=1024, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, classifier_dropout=0.0, scale_embedding=False, use_cache=True, num_labels=3, pad_token_id=1, bos_token_id=0, eos_token_id=2, is_encoder_decoder=True, decoder_start_token_id=2, forced_eos_token_id=2, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.d_model = d_model self.encoder_ffn_dim = encoder_ffn_dim self.encoder_layers = encoder_layers self.encoder_attention_heads = encoder_attention_heads self.decoder_ffn_dim = decoder_ffn_dim self.decoder_layers = decoder_layers self.decoder_attention_heads = decoder_attention_heads self.dropout = dropout self.attention_dropout = attention_dropout self.activation_dropout = activation_dropout self.activation_function = activation_function self.init_std = init_std self.encoder_layerdrop = encoder_layerdrop self.decoder_layerdrop = decoder_layerdrop self.classifier_dropout = classifier_dropout self.use_cache = use_cache self.num_hidden_layers = encoder_layers self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=num_labels, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, is_encoder_decoder=is_encoder_decoder, decoder_start_token_id=decoder_start_token_id, forced_eos_token_id=forced_eos_token_id, **kwargs, ) # ensure backward compatibility for BART CNN models if not hasattr(self, "forced_bos_token_id"): self.forced_bos_token_id = None if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False): self.forced_bos_token_id = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " "The config can simply be saved and uploaded again to be fixed.", stacklevel=2, ) class Florence2Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Florence2ForConditionalGeneration`]. It is used to instantiate an Florence-2 model according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vision_config (`Florence2VisionConfig`, *optional*): Custom vision config or dict text_config (`Union[AutoConfig, dict]`, *optional*): The config object of the text backbone. ignore_index (`int`, *optional*, defaults to -100): The ignore index for the loss function. vocab_size (`int`, *optional*, defaults to 51289): Vocabulary size of the Florence2model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`~Florence2ForConditionalGeneration`] projection_dim (`int`, *optional*, defaults to 1024): Dimension of the multimodal projection space. Example: ```python >>> from transformers import Florence2ForConditionalGeneration, Florence2Config, CLIPVisionConfig, BartConfig >>> # Initializing a clip-like vision config >>> vision_config = CLIPVisionConfig() >>> # Initializing a Bart config >>> text_config = BartConfig() >>> # Initializing a Florence-2 configuration >>> configuration = Florence2Config(vision_config, text_config) >>> # Initializing a model from the florence-2 configuration >>> model = Florence2ForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "florence2" is_composition = False def __init__( self, vision_config=None, text_config=None, ignore_index=-100, vocab_size=51289, projection_dim=1024, **kwargs, ): self.ignore_index = ignore_index self.vocab_size = vocab_size self.projection_dim = projection_dim if vision_config is not None: vision_config = Florence2VisionConfig(**vision_config) self.vision_config = vision_config self.text_config = text_config if text_config is not None: self.text_config = Florence2LanguageConfig(**text_config) super().__init__(**kwargs)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/configuration_florence2.py", "license": "Apache License 2.0", "lines": 309, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/configuration_xvla.py
#!/usr/bin/env python # ------------------------------------------------------------------------------ # Copyright 2025 The HuggingFace Inc. team and 2toINF (https://github.com/2toINF) # # 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 __future__ import annotations from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any from lerobot.configs.policies import PreTrainedConfig from lerobot.configs.types import FeatureType, NormalizationMode, PolicyFeature from lerobot.optim.optimizers import XVLAAdamWConfig from lerobot.optim.schedulers import CosineDecayWithWarmupSchedulerConfig from lerobot.utils.constants import OBS_IMAGES # Conditional import for type checking and lazy loading from lerobot.utils.import_utils import _transformers_available if TYPE_CHECKING or _transformers_available: from .configuration_florence2 import Florence2Config else: Florence2Config = None @PreTrainedConfig.register_subclass("xvla") @dataclass class XVLAConfig(PreTrainedConfig): """ Configuration class for the XVLA (Extended Vision-Language-Action) policy so it can plug into the LeRobot training stack. The config mirrors the knobs exposed in the original XVLA repository but also declares the input/output feature contract required by LeRobot. """ # Input / output structure n_obs_steps: int = 1 chunk_size: int = 32 n_action_steps: int = 32 dtype: str = "float32" # Options: "bfloat16", "float32" normalization_mapping: dict[str, NormalizationMode] = field( default_factory=lambda: { "VISUAL": NormalizationMode.IDENTITY, "STATE": NormalizationMode.IDENTITY, "ACTION": NormalizationMode.IDENTITY, } ) # Florence2 backbone and tokenizer configuration florence_config: dict[str, Any] = field(default_factory=dict) tokenizer_name: str = "facebook/bart-large" tokenizer_max_length: int = 64 tokenizer_padding_side: str = "right" pad_language_to: str = "max_length" # Transformer head hidden_size: int = 1024 depth: int = 24 num_heads: int = 16 mlp_ratio: float = 4.0 num_domains: int = 30 len_soft_prompts: int = 32 dim_time: int = 32 max_len_seq: int = 512 use_hetero_proj: bool = False # Action & proprioception action_mode: str = "ee6d" num_denoising_steps: int = 10 use_proprio: bool = True max_state_dim: int = 32 max_action_dim: int = 20 # Maximum action dimension for padding (used by "auto" action mode) domain_feature_key: str | None = None # Vision preprocessing resize_imgs_with_padding: tuple[int, int] | None = None num_image_views: int | None = None empty_cameras: int = 0 # Freezing options for VLM components # By default, VLM encoders are frozen and only policy transformer + soft prompts train freeze_vision_encoder: bool = False # Freeze VLM vision encoder weights freeze_language_encoder: bool = False # Freeze VLM language encoder weights train_policy_transformer: bool = True # Allow policy transformer to train train_soft_prompts: bool = True # Allow soft prompts to train # Training presets optimizer_lr: float = 1e-4 optimizer_betas: tuple[float, float] = (0.9, 0.99) optimizer_eps: float = 1e-8 optimizer_weight_decay: float = 0.0 optimizer_grad_clip_norm: float = 10.0 # Soft-prompt LR settings (for optional warm-up) optimizer_soft_prompt_lr_scale: float = 1.0 # Scale factor for soft-prompt LR optimizer_soft_prompt_warmup_lr_scale: float | None = None # Start scale for warmup (e.g., 0.01) scheduler_warmup_steps: int = 1_000 scheduler_decay_steps: int = 30_000 scheduler_decay_lr: float = 2.5e-6 def __post_init__(self) -> None: super().__post_init__() if self.chunk_size <= 0: raise ValueError("`chunk_size` must be strictly positive.") if self.n_action_steps > self.chunk_size: raise ValueError( f"`n_action_steps` ({self.n_action_steps}) must be <= `chunk_size` ({self.chunk_size})." ) if self.num_image_views is not None and self.num_image_views <= 0: raise ValueError("`num_image_views` must be > 0 when specified.") if self.dtype not in ["bfloat16", "float32"]: raise ValueError(f"Invalid dtype: {self.dtype}") self._florence_config_obj: Florence2Config | None = None def get_florence_config(self) -> Florence2Config: """ Build (and cache) the Florence2 transformer config that should back the VLM. """ if self._florence_config_obj is None: config_dict = dict(self.florence_config) if "vision_config" not in config_dict or config_dict["vision_config"] is None: raise ValueError("vision_config is required") if "text_config" not in config_dict or config_dict["text_config"] is None: raise ValueError("text_config is required") self._florence_config_obj = Florence2Config(**config_dict) return self._florence_config_obj def validate_features(self) -> None: if not self.image_features: raise ValueError("XVLA requires at least one visual feature in the inputs.") if self.use_proprio and self.robot_state_feature is None: raise ValueError("`use_proprio=True` requires a proprioceptive state feature.") if self.num_image_views is None: self.num_image_views = len(self.image_features) + self.empty_cameras else: self.num_image_views = max(self.num_image_views, len(self.image_features) + self.empty_cameras) if self.empty_cameras > 0: height, width = (480, 640) if self.resize_imgs_with_padding is not None: height, width = self.resize_imgs_with_padding for idx in range(self.empty_cameras): key = f"{OBS_IMAGES}.empty_camera_{idx}" if key not in self.input_features: self.input_features[key] = PolicyFeature( type=FeatureType.VISUAL, shape=(3, height, width), ) def get_optimizer_preset(self) -> XVLAAdamWConfig: """Return the XVLA-specific optimizer with differential learning rates. This optimizer applies: - 1/10 LR for VLM parameters (stable optimization) - Full LR for transformer/action head - Configurable LR for soft-prompts (with optional warm-up) """ return XVLAAdamWConfig( lr=self.optimizer_lr, betas=self.optimizer_betas, eps=self.optimizer_eps, weight_decay=self.optimizer_weight_decay, grad_clip_norm=self.optimizer_grad_clip_norm, soft_prompt_lr_scale=self.optimizer_soft_prompt_lr_scale, soft_prompt_warmup_lr_scale=self.optimizer_soft_prompt_warmup_lr_scale, ) def get_scheduler_preset(self) -> CosineDecayWithWarmupSchedulerConfig: return CosineDecayWithWarmupSchedulerConfig( peak_lr=self.optimizer_lr, decay_lr=self.scheduler_decay_lr, num_warmup_steps=self.scheduler_warmup_steps, num_decay_steps=self.scheduler_decay_steps, ) @property def observation_delta_indices(self) -> list[int] | None: return None @property def action_delta_indices(self) -> list[int]: return list(range(self.chunk_size)) @property def reward_delta_indices(self) -> list[int] | None: return None
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/configuration_xvla.py", "license": "Apache License 2.0", "lines": 173, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/modeling_florence2.py
# Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved. # # 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. """PyTorch Florence-2 model.""" import math from collections import OrderedDict from dataclasses import dataclass import torch import torch.nn.functional as functional import torch.utils.checkpoint import torch.utils.checkpoint as checkpoint from einops import rearrange from torch import nn from torch.nn import CrossEntropyLoss from transformers.activations import ACT2FN from transformers.generation.utils import GenerationMixin from transformers.modeling_attn_mask_utils import ( _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, ) from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, Seq2SeqLMOutput, Seq2SeqModelOutput, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import ( ModelOutput, add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings, ) from .configuration_florence2 import Florence2Config, Florence2LanguageConfig from .utils import drop_path if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "Florence2Config" class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): super().__init__() self.drop_prob = drop_prob self.scale_by_keep = scale_by_keep def forward(self, x): return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) def extra_repr(self): return f"drop_prob={round(self.drop_prob, 3):0.3f}" class LearnedAbsolutePositionEmbedding2D(nn.Module): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, embedding_dim=256, num_pos=50): super().__init__() self.row_embeddings = nn.Embedding(num_pos, embedding_dim // 2) self.column_embeddings = nn.Embedding(num_pos, embedding_dim - (embedding_dim // 2)) def forward(self, pixel_values): """ pixel_values: (batch_size, height, width, num_channels) returns: (batch_size, height, width, embedding_dim * 2) """ if len(pixel_values.shape) != 4: raise ValueError("pixel_values must be a 4D tensor") height, width = pixel_values.shape[1:3] width_values = torch.arange(width, device=pixel_values.device) height_values = torch.arange(height, device=pixel_values.device) x_emb = self.column_embeddings(width_values) y_emb = self.row_embeddings(height_values) # (height, width, embedding_dim * 2) pos = torch.cat( [x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1 ) # (embedding_dim * 2, height, width) pos = pos.permute(2, 0, 1) pos = pos.unsqueeze(0) # (batch_size, embedding_dim * 2, height, width) pos = pos.repeat(pixel_values.shape[0], 1, 1, 1) # (batch_size, height, width, embedding_dim * 2) pos = pos.permute(0, 2, 3, 1) return pos class PositionalEmbeddingCosine1D(nn.Module): """ This class implements a very simple positional encoding. It follows closely the encoder from the link below: https://pytorch.org/tutorials/beginner/translation_transformer.html Args: embed_dim: The dimension of the embeddings. dropout_prob: The dropout probability. max_seq_len: The maximum length to precompute the positional encodings. """ def __init__(self, embed_dim: int = 512, max_seq_len: int = 1024) -> None: super().__init__() self.embed_dim = embed_dim self.max_seq_len = max_seq_len # Generate the sinusoidal arrays. factor = math.log(10000) denominator = torch.exp(-factor * torch.arange(0, self.embed_dim, 2) / self.embed_dim) # Matrix where rows correspond to a positional embedding as a function # of the position index (i.e., the row index). frequencies = torch.arange(0, self.max_seq_len).reshape(self.max_seq_len, 1) * denominator pos_idx_to_embed = torch.zeros((self.max_seq_len, self.embed_dim)) # Populate uneven entries. pos_idx_to_embed[:, 0::2] = torch.sin(frequencies) pos_idx_to_embed[:, 1::2] = torch.cos(frequencies) # Save the positional embeddings in a constant buffer. self.register_buffer("pos_idx_to_embed", pos_idx_to_embed) def forward(self, seq_embeds: torch.Tensor) -> torch.Tensor: """ Args: seq_embeds: The sequence embeddings in order. Allowed size: 1. [T, D], where T is the length of the sequence, and D is the frame embedding dimension. 2. [B, T, D], where B is the batch size and T and D are the same as above. Returns a tensor of with the same dimensions as the input: i.e., [1, T, D] or [T, D]. """ shape_len = len(seq_embeds.shape) assert 2 <= shape_len <= 3 len_seq = seq_embeds.size(-2) assert len_seq <= self.max_seq_len pos_embeds = self.pos_idx_to_embed[0 : seq_embeds.size(-2), :] # Adapt pre-computed positional embeddings to the input. if shape_len == 3: pos_embeds = pos_embeds.view((1, pos_embeds.size(0), pos_embeds.size(1))) return pos_embeds class LearnedAbsolutePositionEmbedding1D(nn.Module): """ Learnable absolute positional embeddings for 1D sequences. Args: embed_dim: The dimension of the embeddings. max_seq_len: The maximum length to precompute the positional encodings. """ def __init__(self, embedding_dim: int = 512, num_pos: int = 1024) -> None: super().__init__() self.embeddings = nn.Embedding(num_pos, embedding_dim) self.num_pos = num_pos def forward(self, seq_embeds: torch.Tensor) -> torch.Tensor: """ Args: seq_embeds: The sequence embeddings in order. Allowed size: 1. [T, D], where T is the length of the sequence, and D is the frame embedding dimension. 2. [B, T, D], where B is the batch size and T and D are the same as above. Returns a tensor of with the same dimensions as the input: i.e., [1, T, D] or [T, D]. """ shape_len = len(seq_embeds.shape) assert 2 <= shape_len <= 3 len_seq = seq_embeds.size(-2) assert len_seq <= self.num_pos # [T, D] pos_embeds = self.embeddings(torch.arange(len_seq).to(seq_embeds.device)) # Adapt pre-computed positional embeddings to the input. if shape_len == 3: pos_embeds = pos_embeds.view((1, pos_embeds.size(0), pos_embeds.size(1))) return pos_embeds class MySequential(nn.Sequential): def forward(self, *inputs): for module in self._modules.values(): inputs = module(*inputs) if isinstance(inputs, tuple) else module(inputs) return inputs class PreNorm(nn.Module): def __init__(self, norm, fn, drop_path=None): super().__init__() self.norm = norm self.fn = fn self.drop_path = drop_path def forward(self, x, *args, **kwargs): shortcut = x if self.norm is not None: x, size = self.fn(self.norm(x), *args, **kwargs) else: x, size = self.fn(x, *args, **kwargs) if self.drop_path: x = self.drop_path(x) x = shortcut + x return x, size class Mlp(nn.Module): def __init__( self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, ): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.net = nn.Sequential( OrderedDict( [ ("fc1", nn.Linear(in_features, hidden_features)), ("act", act_layer()), ("fc2", nn.Linear(hidden_features, out_features)), ] ) ) def forward(self, x, size): return self.net(x), size class DepthWiseConv2d(nn.Module): def __init__( self, dim_in, kernel_size, padding, stride, bias=True, ): super().__init__() self.dw = nn.Conv2d( dim_in, dim_in, kernel_size=kernel_size, padding=padding, groups=dim_in, stride=stride, bias=bias ) def forward(self, x, size): batch_size, num_tokens, channels = x.shape height, width = size assert num_tokens == height * width x = self.dw(x.transpose(1, 2).view(batch_size, channels, height, width)) size = (x.size(-2), x.size(-1)) x = x.flatten(2).transpose(1, 2) return x, size class ConvEmbed(nn.Module): """Image to Patch Embedding""" def __init__( self, patch_size=7, in_chans=3, embed_dim=64, stride=4, padding=2, norm_layer=None, pre_norm=True ): super().__init__() self.patch_size = patch_size self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride, padding=padding) dim_norm = in_chans if pre_norm else embed_dim self.norm = norm_layer(dim_norm) if norm_layer else None self.pre_norm = pre_norm def forward(self, x, size): height, width = size if len(x.size()) == 3: if self.norm and self.pre_norm: x = self.norm(x) x = rearrange(x, "b (h w) c -> b c h w", h=height, w=width) x = self.proj(x) _, _, height, width = x.shape x = rearrange(x, "b c h w -> b (h w) c") if self.norm and not self.pre_norm: x = self.norm(x) return x, (height, width) class ChannelAttention(nn.Module): def __init__(self, dim, groups=8, qkv_bias=True): super().__init__() self.groups = groups self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) def forward(self, x, size): batch_size, num_tokens, channels = x.shape qkv = ( self.qkv(x) .reshape(batch_size, num_tokens, 3, self.groups, channels // self.groups) .permute(2, 0, 3, 1, 4) ) q, k, v = qkv[0], qkv[1], qkv[2] q = q * (float(num_tokens) ** -0.5) attention = q.transpose(-1, -2) @ k attention = attention.softmax(dim=-1) x = (attention @ v.transpose(-1, -2)).transpose(-1, -2) x = x.transpose(1, 2).reshape(batch_size, num_tokens, channels) x = self.proj(x) return x, size class ChannelBlock(nn.Module): def __init__( self, dim, groups, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, conv_at_attn=True, conv_at_ffn=True, ): super().__init__() drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity() self.conv1 = PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1)) if conv_at_attn else None self.channel_attn = PreNorm( norm_layer(dim), ChannelAttention(dim, groups=groups, qkv_bias=qkv_bias), drop_path ) self.conv2 = PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1)) if conv_at_ffn else None self.ffn = PreNorm( norm_layer(dim), Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer), drop_path, ) def forward(self, x, size): if self.conv1: x, size = self.conv1(x, size) x, size = self.channel_attn(x, size) if self.conv2: x, size = self.conv2(x, size) x, size = self.ffn(x, size) return x, size def window_partition(x, window_size: int): batch_size, height, width, channels = x.shape x = x.view(batch_size, height // window_size, window_size, width // window_size, window_size, channels) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, channels) return windows def window_reverse(windows, batch_size: int, window_size: int, height: int, width: int): # this will cause onnx conversion failed for dynamic axis, because treated as constant # int(windows.shape[0] / (height * width / window_size / window_size)) x = windows.view(batch_size, height // window_size, width // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(batch_size, height, width, -1) return x class WindowAttention(nn.Module): def __init__(self, dim, num_heads, window_size, qkv_bias=True): super().__init__() self.dim = dim self.window_size = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = float(head_dim) ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) self.softmax = nn.Softmax(dim=-1) def forward(self, x, size): height, width = size batch_size, seq_len, channels = x.shape assert seq_len == height * width, "input feature has wrong size" x = x.view(batch_size, height, width, channels) pad_l = pad_t = 0 pad_r = (self.window_size - width % self.window_size) % self.window_size pad_b = (self.window_size - height % self.window_size) % self.window_size x = functional.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, height_padded, width_padded, _ = x.shape x = window_partition(x, self.window_size) x = x.view(-1, self.window_size * self.window_size, channels) # W-MSA/SW-MSA # attn_windows = self.attn(x_windows) batch_windows, num_tokens, channels = x.shape qkv = ( self.qkv(x) .reshape(batch_windows, num_tokens, 3, self.num_heads, channels // self.num_heads) .permute(2, 0, 3, 1, 4) ) q, k, v = qkv[0], qkv[1], qkv[2] q = q * self.scale attn = q @ k.transpose(-2, -1) attn = self.softmax(attn) x = (attn @ v).transpose(1, 2).reshape(batch_windows, num_tokens, channels) x = self.proj(x) # merge windows x = x.view(-1, self.window_size, self.window_size, channels) x = window_reverse(x, batch_size, self.window_size, height_padded, width_padded) if pad_r > 0 or pad_b > 0: x = x[:, :height, :width, :].contiguous() x = x.view(batch_size, height * width, channels) return x, size class SpatialBlock(nn.Module): def __init__( self, dim, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, conv_at_attn=True, conv_at_ffn=True, ): super().__init__() drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity() self.conv1 = PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1)) if conv_at_attn else None self.window_attn = PreNorm( norm_layer(dim), WindowAttention(dim, num_heads, window_size, qkv_bias=qkv_bias), drop_path ) self.conv2 = PreNorm(None, DepthWiseConv2d(dim, 3, 1, 1)) if conv_at_ffn else None self.ffn = PreNorm( norm_layer(dim), Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer), drop_path, ) def forward(self, x, size): if self.conv1: x, size = self.conv1(x, size) x, size = self.window_attn(x, size) if self.conv2: x, size = self.conv2(x, size) x, size = self.ffn(x, size) return x, size class DaViT(nn.Module): """DaViT: Dual-Attention Transformer Args: in_chans (int): Number of input image channels. Default: 3. num_classes (int): Number of classes for classification head. Default: 1000. patch_size (tuple(int)): Patch size of convolution in different stages. Default: (7, 2, 2, 2). patch_stride (tuple(int)): Patch stride of convolution in different stages. Default: (4, 2, 2, 2). patch_padding (tuple(int)): Patch padding of convolution in different stages. Default: (3, 0, 0, 0). patch_prenorm (tuple(bool)): If True, perform norm before convlution layer. Default: (True, False, False, False). embed_dims (tuple(int)): Patch embedding dimension in different stages. Default: (64, 128, 192, 256). num_heads (tuple(int)): Number of spatial attention heads in different stages. Default: (4, 8, 12, 16). num_groups (tuple(int)): Number of channel groups in different stages. Default: (4, 8, 12, 16). window_size (int): Window size. Default: 7. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True. drop_path_rate (float): Stochastic depth rate. Default: 0.1. norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. enable_checkpoint (bool): If True, enable checkpointing. Default: False. conv_at_attn (bool): If True, perform depthwise convolution before attention layer. Default: True. conv_at_ffn (bool): If True, perform depthwise convolution before ffn layer. Default: True. """ def __init__( self, in_chans=3, num_classes=1000, depths=(1, 1, 3, 1), patch_size=(7, 2, 2, 2), patch_stride=(4, 2, 2, 2), patch_padding=(3, 0, 0, 0), patch_prenorm=(False, False, False, False), embed_dims=(64, 128, 192, 256), num_heads=(3, 6, 12, 24), num_groups=(3, 6, 12, 24), window_size=7, mlp_ratio=4.0, qkv_bias=True, drop_path_rate=0.1, norm_layer=nn.LayerNorm, enable_checkpoint=False, conv_at_attn=True, conv_at_ffn=True, ): super().__init__() self.num_classes = num_classes self.embed_dims = embed_dims self.num_heads = num_heads self.num_groups = num_groups self.num_stages = len(self.embed_dims) self.enable_checkpoint = enable_checkpoint assert self.num_stages == len(self.num_heads) == len(self.num_groups) num_stages = len(embed_dims) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths) * 2)] depth_offset = 0 convs = [] blocks = [] for i in range(num_stages): conv_embed = ConvEmbed( patch_size=patch_size[i], stride=patch_stride[i], padding=patch_padding[i], in_chans=in_chans if i == 0 else self.embed_dims[i - 1], embed_dim=self.embed_dims[i], norm_layer=norm_layer, pre_norm=patch_prenorm[i], ) convs.append(conv_embed) block = MySequential( *[ MySequential( OrderedDict( [ ( "spatial_block", SpatialBlock( embed_dims[i], num_heads[i], window_size, drop_path_rate=dpr[depth_offset + j * 2], qkv_bias=qkv_bias, mlp_ratio=mlp_ratio, conv_at_attn=conv_at_attn, conv_at_ffn=conv_at_ffn, ), ), ( "channel_block", ChannelBlock( embed_dims[i], num_groups[i], drop_path_rate=dpr[depth_offset + j * 2 + 1], qkv_bias=qkv_bias, mlp_ratio=mlp_ratio, conv_at_attn=conv_at_attn, conv_at_ffn=conv_at_ffn, ), ), ] ) ) for j in range(depths[i]) ] ) blocks.append(block) depth_offset += depths[i] * 2 self.convs = nn.ModuleList(convs) self.blocks = nn.ModuleList(blocks) self.norms = norm_layer(self.embed_dims[-1]) self.avgpool = nn.AdaptiveAvgPool1d(1) self.head = nn.Linear(self.embed_dims[-1], num_classes) if num_classes > 0 else nn.Identity() @property def dim_out(self): return self.embed_dims[-1] def forward_features_unpool(self, x): """ forward until avg pooling Args: x (_type_): input image tensor """ input_size = (x.size(2), x.size(3)) for conv, block in zip(self.convs, self.blocks, strict=False): x, input_size = conv(x, input_size) if self.enable_checkpoint: x, input_size = checkpoint.checkpoint(block, x, input_size) else: x, input_size = block(x, input_size) return x def forward_features(self, x): x = self.forward_features_unpool(x) # (batch_size, num_tokens, token_dim) x = self.avgpool(x.transpose(1, 2)) # (batch_size, 1, num_tokens) x = torch.flatten(x, 1) x = self.norms(x) return x def forward(self, x): x = self.forward_features(x) x = self.head(x) return x @classmethod def from_config(cls, config): return cls( depths=config.depths, embed_dims=config.dim_embed, num_heads=config.num_heads, num_groups=config.num_groups, patch_size=config.patch_size, patch_stride=config.patch_stride, patch_padding=config.patch_padding, patch_prenorm=config.patch_prenorm, drop_path_rate=config.drop_path_rate, window_size=config.window_size, ) # Copied from transformers.models.llama.modeling_llama._get_unpad_data def _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) return ( indices, cu_seqlens, max_seqlen_in_batch, ) def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() shifted_input_ids[:, 0] = decoder_start_token_id if pad_token_id is None: raise ValueError("self.model.config.pad_token_id has to be defined.") # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) return shifted_input_ids class Florence2LearnedPositionalEmbedding(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, num_embeddings: int, embedding_dim: int): # Florence2 is set up so that if padding_idx is specified then offset the embedding ids by 2 # and adjust num_embeddings appropriately. Other models don't have this hack self.offset = 2 super().__init__(num_embeddings + self.offset, embedding_dim) def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0): """`input_ids' shape is expected to be [bsz x seqlen].""" bsz, seq_len = input_ids.shape[:2] positions = torch.arange( past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device, ).expand(bsz, -1) return super().forward(positions + self.offset) class Florence2ScaledWordEmbedding(nn.Embedding): """ This module overrides nn.Embeddings' forward by multiplying with embeddings scale. """ def __init__( self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float | None = 1.0 ): super().__init__(num_embeddings, embedding_dim, padding_idx) self.embed_scale = embed_scale def forward(self, input_ids: torch.Tensor): return super().forward(input_ids) * self.embed_scale class Florence2Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Florence2LanguageConfig | None = None, ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.config = config if (self.head_dim * num_heads) != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" f" and `num_heads`: {num_heads})." ) self.scaling = self.head_dim**-0.5 self.is_decoder = is_decoder self.is_causal = is_causal self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.Tensor, key_value_states: torch.Tensor | None = None, past_key_value: tuple[torch.Tensor] | None = None, attention_mask: torch.Tensor | None = None, layer_head_mask: torch.Tensor | None = None, output_attentions: bool = False, ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: """Input shape: Batch x Time x Channel""" # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len, _ = hidden_states.size() # get query proj query_states = self.q_proj(hidden_states) * self.scaling # get key, value proj # `past_key_value[0].shape[2] == key_value_states.shape[1]` # is checking that the `sequence_length` of the `past_key_value` is the same as # the provided `key_value_states` to support prefix tuning if ( is_cross_attention and past_key_value is not None and past_key_value[0].shape[2] == key_value_states.shape[1] ): # reuse k,v, cross_attentions key_states = past_key_value[0] value_states = past_key_value[1] elif is_cross_attention: # cross_attentions key_states = self._shape(self.k_proj(key_value_states), -1, bsz) value_states = self._shape(self.v_proj(key_value_states), -1, bsz) elif past_key_value is not None: # reuse k, v, self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) key_states = torch.cat([past_key_value[0], key_states], dim=2) value_states = torch.cat([past_key_value[1], value_states], dim=2) else: # self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_states, value_states) proj_shape = (bsz * self.num_heads, -1, self.head_dim) query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) key_states = key_states.reshape(*proj_shape) value_states = value_states.reshape(*proj_shape) src_len = key_states.size(1) attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): raise ValueError( f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" f" {attn_weights.size()}" ) if attention_mask is not None: if attention_mask.size() != (bsz, 1, tgt_len, src_len): raise ValueError( f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) attn_weights = nn.functional.softmax(attn_weights, dim=-1) if layer_head_mask is not None: if layer_head_mask.size() != (self.num_heads,): raise ValueError( f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" f" {layer_head_mask.size()}" ) attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view( bsz, self.num_heads, tgt_len, src_len ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) if output_attentions: # this operation is a bit awkward, but it's required to # make sure that attn_weights keeps its gradient. # In order to do so, attn_weights have to be reshaped # twice and have to be reused in the following attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) else: attn_weights_reshaped = None attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) attn_output = torch.bmm(attn_probs, value_states) if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) attn_output = attn_output.transpose(1, 2) # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be # partitioned across GPUs when using tensor-parallelism. attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) attn_output = self.out_proj(attn_output) return attn_output, attn_weights_reshaped, past_key_value class Florence2FlashAttention2(Florence2Attention): """ Florence2 flash attention module. This module inherits from `Florence2Attention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() def _reshape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim) def forward( self, hidden_states: torch.Tensor, key_value_states: torch.Tensor | None = None, past_key_value: tuple[torch.Tensor] | None = None, attention_mask: torch.Tensor | None = None, layer_head_mask: torch.Tensor | None = None, output_attentions: bool = False, ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: # Florence2FlashAttention2 attention does not support output_attentions if output_attentions: raise ValueError("Florence2FlashAttention2 attention does not support output_attentions") # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, q_len, _ = hidden_states.size() # get query proj query_states = self._reshape(self.q_proj(hidden_states), -1, bsz) # get key, value proj # `past_key_value[0].shape[2] == key_value_states.shape[1]` # is checking that the `sequence_length` of the `past_key_value` is the same as # the provided `key_value_states` to support prefix tuning if ( is_cross_attention and past_key_value is not None and past_key_value[0].shape[2] == key_value_states.shape[1] ): # reuse k,v, cross_attentions key_states = past_key_value[0].transpose(1, 2) value_states = past_key_value[1].transpose(1, 2) elif is_cross_attention: # cross_attentions key_states = self._reshape(self.k_proj(key_value_states), -1, bsz) value_states = self._reshape(self.v_proj(key_value_states), -1, bsz) elif past_key_value is not None: # reuse k, v, self_attention key_states = self._reshape(self.k_proj(hidden_states), -1, bsz) value_states = self._reshape(self.v_proj(hidden_states), -1, bsz) key_states = torch.cat([past_key_value[0].transpose(1, 2), key_states], dim=1) value_states = torch.cat([past_key_value[1].transpose(1, 2), value_states], dim=1) else: # self_attention key_states = self._reshape(self.k_proj(hidden_states), -1, bsz) value_states = self._reshape(self.v_proj(hidden_states), -1, bsz) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_states.transpose(1, 2), value_states.transpose(1, 2)) kv_seq_len = key_states.shape[-2] if past_key_value is not None: kv_seq_len += past_key_value[0].shape[-2] # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (LlamaRMSNorm handles it correctly) input_dtype = query_states.dtype if input_dtype == torch.float32: if torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, q_len, dropout=self.dropout ) attn_output = attn_output.reshape(bsz, q_len, -1) attn_output = self.out_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`float`): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """ if not self._flash_attn_uses_top_left_mask: causal = self.is_causal else: # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. causal = self.is_causal and query_length != 1 # Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( query_states, key_states, value_states, attention_mask, query_length ) cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, ) attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal ) return attn_output # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( query_layer, attention_mask ) return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), ) class Florence2SdpaAttention(Florence2Attention): def forward( self, hidden_states: torch.Tensor, key_value_states: torch.Tensor | None = None, past_key_value: tuple[torch.Tensor] | None = None, attention_mask: torch.Tensor | None = None, layer_head_mask: torch.Tensor | None = None, output_attentions: bool = False, ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: """Input shape: Batch x Time x Channel""" if output_attentions or layer_head_mask is not None: # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented. logger.warning_once( "Florence2Model is using Florence2SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention" ' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' ) return super().forward( hidden_states, key_value_states=key_value_states, past_key_value=past_key_value, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions, ) # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len, _ = hidden_states.size() # get query proj query_states = self.q_proj(hidden_states) # get key, value proj # `past_key_value[0].shape[2] == key_value_states.shape[1]` # is checking that the `sequence_length` of the `past_key_value` is the same as # the provided `key_value_states` to support prefix tuning if ( is_cross_attention and past_key_value is not None and past_key_value[0].shape[2] == key_value_states.shape[1] ): # reuse k,v, cross_attentions key_states = past_key_value[0] value_states = past_key_value[1] elif is_cross_attention: # cross_attentions key_states = self._shape(self.k_proj(key_value_states), -1, bsz) value_states = self._shape(self.v_proj(key_value_states), -1, bsz) elif past_key_value is not None: # reuse k, v, self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) key_states = torch.cat([past_key_value[0], key_states], dim=2) value_states = torch.cat([past_key_value[1], value_states], dim=2) else: # self_attention key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) if self.is_decoder: # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. # Further calls to cross_attention layer can then reuse all cross-attention # key/value_states (first "if" case) # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of # all previous decoder key/value_states. Further calls to uni-directional self-attention # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) # if encoder bi-directional self-attention `past_key_value` is always `None` past_key_value = (key_states, value_states) query_states = self._shape(query_states, tgt_len, bsz) # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling. # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1. is_causal = bool(self.is_causal and attention_mask is None and tgt_len > 1) # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask, # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577 attn_output = torch.nn.functional.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=attention_mask, dropout_p=self.dropout if self.training else 0.0, is_causal=is_causal, ) if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2) # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be # partitioned across GPUs when using tensor-parallelism. attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) attn_output = self.out_proj(attn_output) return attn_output, None, past_key_value FLORENCE2_ATTENTION_CLASSES = { "eager": Florence2Attention, "sdpa": Florence2SdpaAttention, "flash_attention_2": Florence2FlashAttention2, } class Florence2EncoderLayer(nn.Module): def __init__(self, config: Florence2LanguageConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = FLORENCE2_ATTENTION_CLASSES[config._attn_implementation]( embed_dim=self.embed_dim, num_heads=config.encoder_attention_heads, dropout=config.attention_dropout, config=config, ) self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim) self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def forward( self, hidden_states: torch.FloatTensor, attention_mask: torch.FloatTensor, layer_head_mask: torch.FloatTensor, output_attentions: bool | None = False, ) -> tuple[torch.FloatTensor, torch.FloatTensor | None]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size `(encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states, attn_weights, _ = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout( hidden_states, p=self.activation_dropout, training=self.training ) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) if hidden_states.dtype == torch.float16 and ( torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any() ): clamp_value = torch.finfo(hidden_states.dtype).max - 1000 hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value) outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs class Florence2DecoderLayer(nn.Module): def __init__(self, config: Florence2LanguageConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = FLORENCE2_ATTENTION_CLASSES[config._attn_implementation]( embed_dim=self.embed_dim, num_heads=config.decoder_attention_heads, dropout=config.attention_dropout, is_decoder=True, is_causal=True, config=config, ) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.encoder_attn = FLORENCE2_ATTENTION_CLASSES[config._attn_implementation]( self.embed_dim, config.decoder_attention_heads, dropout=config.attention_dropout, is_decoder=True, config=config, ) self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim) self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, encoder_hidden_states: torch.Tensor | None = None, encoder_attention_mask: torch.Tensor | None = None, layer_head_mask: torch.Tensor | None = None, cross_attn_layer_head_mask: torch.Tensor | None = None, past_key_value: tuple[torch.Tensor] | None = None, output_attentions: bool | None = False, use_cache: bool | None = True, ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. encoder_hidden_states (`torch.FloatTensor`): cross attention input to the layer of shape `(batch, seq_len, embed_dim)` encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size `(encoder_attention_heads,)`. cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of size `(decoder_attention_heads,)`. past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states # Self Attention # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None # add present self-attn cache to positions 1,2 of present_key_value tuple hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, past_key_value=self_attn_past_key_value, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) # Cross-Attention Block cross_attn_present_key_value = None cross_attn_weights = None if encoder_hidden_states is not None: residual = hidden_states # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn( hidden_states=hidden_states, key_value_states=encoder_hidden_states, attention_mask=encoder_attention_mask, layer_head_mask=cross_attn_layer_head_mask, past_key_value=cross_attn_past_key_value, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.encoder_attn_layer_norm(hidden_states) # add cross-attn to positions 3,4 of present_key_value tuple present_key_value = present_key_value + cross_attn_present_key_value # Fully Connected residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout( hidden_states, p=self.activation_dropout, training=self.training ) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights, cross_attn_weights) if use_cache: outputs += (present_key_value,) return outputs class Florence2LanguagePreTrainedModel(PreTrainedModel): config_class = Florence2LanguageConfig base_model_prefix = "model" supports_gradient_checkpointing = True _keys_to_ignore_on_load_unexpected = ["encoder.version", "decoder.version"] _no_split_modules = [r"Florence2EncoderLayer", r"Florence2DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_sdpa = True def _init_weights(self, module): std = self.config.init_std if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, nn.Conv2d): nn.init.normal_(module.weight, std=0.02) for name, _ in module.named_parameters(): if name == "bias": nn.init.constant_(module.bias, 0) elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)): nn.init.constant_(module.weight, 1.0) nn.init.constant_(module.bias, 0) @property def dummy_inputs(self): pad_token = self.config.pad_token_id input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device) dummy_inputs = { "attention_mask": input_ids.ne(pad_token), "input_ids": input_ids, } return dummy_inputs class Florence2Encoder(Florence2LanguagePreTrainedModel): """ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`Florence2EncoderLayer`]. Args: config: Florence2LanguageConfig embed_tokens (nn.Embedding): output embedding """ def __init__(self, config: Florence2LanguageConfig, embed_tokens: nn.Embedding | None = None): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.encoder_layerdrop embed_dim = config.d_model self.padding_idx = config.pad_token_id self.max_source_positions = config.max_position_embeddings embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0 self.embed_tokens = Florence2ScaledWordEmbedding( config.vocab_size, embed_dim, self.padding_idx, embed_scale=embed_scale ) if embed_tokens is not None: self.embed_tokens.weight = embed_tokens.weight self.embed_positions = Florence2LearnedPositionalEmbedding( config.max_position_embeddings, embed_dim, ) self.layers = nn.ModuleList([Florence2EncoderLayer(config) for _ in range(config.encoder_layers)]) self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self._use_sdpa = config._attn_implementation == "sdpa" self.layernorm_embedding = nn.LayerNorm(embed_dim) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, head_mask: torch.Tensor | None = None, inputs_embeds: torch.FloatTensor | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, ) -> tuple | BaseModelOutput: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input = input_ids input_ids = input_ids.view(-1, input_ids.shape[-1]) elif inputs_embeds is not None: input = inputs_embeds[:, :, -1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) embed_pos = self.embed_positions(input) embed_pos = embed_pos.to(inputs_embeds.device) hidden_states = inputs_embeds + embed_pos hidden_states = self.layernorm_embedding(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) # expand attention_mask if attention_mask is not None: if self._use_flash_attention_2: attention_mask = attention_mask if 0 in attention_mask else None elif self._use_sdpa and head_mask is None and not output_attentions: # output_attentions=True & head_mask can not be supported when using SDPA, fall back to # the manual implementation that requires a 4D causal mask in all cases. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype) else: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype) encoder_states = () if output_hidden_states else None all_attentions = () if output_attentions else None # check if head_mask has a correct number of layers specified if desired if head_mask is not None and head_mask.size()[0] != (len(self.layers)): raise ValueError( f"The head_mask should be specified for {len(self.layers)} layers, but it is for" f" {head_mask.size()[0]}." ) for idx, encoder_layer in enumerate(self.layers): if output_hidden_states: encoder_states = encoder_states + (hidden_states,) # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) to_drop = False if self.training: dropout_probability = torch.rand([]) if dropout_probability < self.layerdrop: # skip the layer to_drop = True if to_drop: layer_outputs = (None, None) else: if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( encoder_layer.__call__, hidden_states, attention_mask, (head_mask[idx] if head_mask is not None else None), output_attentions, ) else: layer_outputs = encoder_layer( hidden_states, attention_mask, layer_head_mask=(head_mask[idx] if head_mask is not None else None), output_attentions=output_attentions, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) if output_hidden_states: encoder_states = encoder_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions ) class Florence2Decoder(Florence2LanguagePreTrainedModel): """ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`Florence2DecoderLayer`] Args: config: Florence2LanguageConfig embed_tokens (nn.Embedding): output embedding """ def __init__(self, config: Florence2LanguageConfig, embed_tokens: nn.Embedding | None = None): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.decoder_layerdrop self.padding_idx = config.pad_token_id self.max_target_positions = config.max_position_embeddings embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0 self.embed_tokens = Florence2ScaledWordEmbedding( config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale ) if embed_tokens is not None: self.embed_tokens.weight = embed_tokens.weight self.embed_positions = Florence2LearnedPositionalEmbedding( config.max_position_embeddings, config.d_model, ) self.layers = nn.ModuleList([Florence2DecoderLayer(config) for _ in range(config.decoder_layers)]) self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self._use_sdpa = config._attn_implementation == "sdpa" self.layernorm_embedding = nn.LayerNorm(config.d_model) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, encoder_hidden_states: torch.FloatTensor | None = None, encoder_attention_mask: torch.LongTensor | None = None, head_mask: torch.Tensor | None = None, cross_attn_head_mask: torch.Tensor | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, ) -> tuple | BaseModelOutputWithPastAndCrossAttentions: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*): Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing cross-attention on hidden heads. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict # retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time" ) elif input_ids is not None: input = input_ids input_shape = input.shape input_ids = input_ids.view(-1, input_shape[-1]) elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] input = inputs_embeds[:, :, -1] else: raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") # past_key_values_length past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 if inputs_embeds is None: inputs_embeds = self.embed_tokens(input) if self._use_flash_attention_2: # 2d mask is passed through the layers attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None elif self._use_sdpa and not output_attentions and cross_attn_head_mask is None: # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on # the manual implementation that requires a 4D causal mask in all cases. attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( attention_mask, input_shape, inputs_embeds, past_key_values_length, ) else: # 4d mask is passed through the layers attention_mask = _prepare_4d_causal_attention_mask( attention_mask, input_shape, inputs_embeds, past_key_values_length ) # expand encoder attention mask if encoder_hidden_states is not None and encoder_attention_mask is not None: if self._use_flash_attention_2: encoder_attention_mask = encoder_attention_mask if 0 in encoder_attention_mask else None elif self._use_sdpa and cross_attn_head_mask is None and not output_attentions: # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on # the manual implementation that requires a 4D causal mask in all cases. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa( encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1], ) else: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] encoder_attention_mask = _prepare_4d_attention_mask( encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1] ) # embed positions positions = self.embed_positions(input, past_key_values_length) positions = positions.to(inputs_embeds.device) hidden_states = inputs_embeds + positions hidden_states = self.layernorm_embedding(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None next_decoder_cache = () if use_cache else None # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired for attn_mask, mask_name in zip( [head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"], strict=False ): if attn_mask is not None and attn_mask.size()[0] != (len(self.layers)): raise ValueError( f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" f" {head_mask.size()[0]}." ) for idx, decoder_layer in enumerate(self.layers): # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) if output_hidden_states: all_hidden_states += (hidden_states,) if self.training: dropout_probability = torch.rand([]) if dropout_probability < self.layerdrop: continue past_key_value = past_key_values[idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, attention_mask, encoder_hidden_states, encoder_attention_mask, head_mask[idx] if head_mask is not None else None, cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None, None, output_attentions, use_cache, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, layer_head_mask=(head_mask[idx] if head_mask is not None else None), cross_attn_layer_head_mask=( cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None ), past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache += (layer_outputs[3 if output_attentions else 1],) if output_attentions: all_self_attns += (layer_outputs[1],) if encoder_hidden_states is not None: all_cross_attentions += (layer_outputs[2],) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = next_decoder_cache if use_cache else None if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, cross_attentions=all_cross_attentions, ) class Florence2LanguageModel(Florence2LanguagePreTrainedModel): _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", } def __init__(self, config: Florence2LanguageConfig): super().__init__(config) padding_idx, vocab_size = config.pad_token_id, config.vocab_size self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx) self.encoder = Florence2Encoder(config, self.shared) self.decoder = Florence2Decoder(config, self.shared) # Initialize weights and apply final processing self.post_init() def _tie_weights(self): if self.config.tie_word_embeddings: self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared) # self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared) def get_input_embeddings(self): return self.shared def set_input_embeddings(self, value): self.shared = value self.encoder.embed_tokens = self.shared self.decoder.embed_tokens = self.shared def get_encoder(self): return self.encoder def get_decoder(self): return self.decoder def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, decoder_input_ids: torch.LongTensor | None = None, decoder_attention_mask: torch.LongTensor | None = None, head_mask: torch.Tensor | None = None, decoder_head_mask: torch.Tensor | None = None, cross_attn_head_mask: torch.Tensor | None = None, encoder_outputs: list[torch.FloatTensor] | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, decoder_inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, ) -> tuple | Seq2SeqModelOutput: # different to other models, Florence2 automatically creates decoder_input_ids from # input_ids if no decoder_input_ids are provided if decoder_input_ids is None and decoder_inputs_embeds is None: if input_ids is None: raise ValueError( "If no `decoder_input_ids` or `decoder_inputs_embeds` are " "passed, `input_ids` cannot be `None`. Please pass either " "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`." ) decoder_input_ids = shift_tokens_right( input_ids, self.config.pad_token_id, self.config.decoder_start_token_id ) output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict if encoder_outputs is None: encoder_outputs = self.encoder( input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True elif return_dict and not isinstance(encoder_outputs, BaseModelOutput): encoder_outputs = BaseModelOutput( last_hidden_state=encoder_outputs[0], hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, ) # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, encoder_hidden_states=encoder_outputs[0], encoder_attention_mask=attention_mask, head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if not return_dict: return decoder_outputs + encoder_outputs return Seq2SeqModelOutput( last_hidden_state=decoder_outputs.last_hidden_state, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_outputs.last_hidden_state, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, ) class Florence2LanguageForConditionalGeneration(Florence2LanguagePreTrainedModel, GenerationMixin): base_model_prefix = "model" _tied_weights_keys = { "model.encoder.embed_tokens.weight": "model.shared.weight", "model.decoder.embed_tokens.weight": "model.shared.weight", } _keys_to_ignore_on_load_missing = ["final_logits_bias"] def __init__(self, config: Florence2LanguageConfig): super().__init__(config) self.model = Florence2LanguageModel(config) self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings))) self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False) # Initialize weights and apply final processing self.post_init() def _tie_weights(self): if self.config.tie_word_embeddings: self._tie_or_clone_weights(self.model.encoder.embed_tokens, self.model.shared) # self._tie_or_clone_weights(self.model.decoder.embed_tokens, self.model.shared) # self._tie_or_clone_weights(self.lm_head, self.model.shared) def get_encoder(self): return self.model.get_encoder() def get_decoder(self): return self.model.get_decoder() def resize_token_embeddings( self, new_num_tokens: int, pad_to_multiple_of: int | None = None, **kwargs ) -> nn.Embedding: new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, **kwargs) self._resize_final_logits_bias(new_embeddings.weight.shape[0]) return new_embeddings def _resize_final_logits_bias(self, new_num_tokens: int) -> None: old_num_tokens = self.final_logits_bias.shape[-1] if new_num_tokens <= old_num_tokens: new_bias = self.final_logits_bias[:, :new_num_tokens] else: extra_bias = torch.zeros( (1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device ) new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1) self.register_buffer("final_logits_bias", new_bias) def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor | None = None, decoder_input_ids: torch.LongTensor | None = None, decoder_attention_mask: torch.LongTensor | None = None, head_mask: torch.Tensor | None = None, decoder_head_mask: torch.Tensor | None = None, cross_attn_head_mask: torch.Tensor | None = None, encoder_outputs: list[torch.FloatTensor] | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, decoder_inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, ) -> tuple | Seq2SeqLMOutput: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: if use_cache: logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.") use_cache = False if decoder_input_ids is None and decoder_inputs_embeds is None: decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ) outputs = self.model( input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, encoder_outputs=encoder_outputs, decoder_attention_mask=decoder_attention_mask, head_mask=head_mask, decoder_head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) lm_logits = self.lm_head(outputs[0]) lm_logits = lm_logits + self.final_logits_bias.to(lm_logits.device) masked_lm_loss = None if labels is not None: labels = labels.to(lm_logits.device) loss_fct = CrossEntropyLoss() masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (lm_logits,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return Seq2SeqLMOutput( loss=masked_lm_loss, logits=lm_logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) def prepare_inputs_for_generation( self, decoder_input_ids, past_key_values=None, attention_mask=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, use_cache=None, encoder_outputs=None, **kwargs, ): # cut decoder_input_ids if past_key_values is used if past_key_values is not None: past_length = past_key_values[0][0].shape[2] # Some generation methods already pass only the last input ID if decoder_input_ids.shape[1] > past_length: remove_prefix_length = past_length else: # Default to old behavior: keep only final ID remove_prefix_length = decoder_input_ids.shape[1] - 1 decoder_input_ids = decoder_input_ids[:, remove_prefix_length:] return { "input_ids": None, # encoder_outputs is defined. input_ids not needed "encoder_outputs": encoder_outputs, "past_key_values": past_key_values, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, "use_cache": use_cache, # change this to avoid caching (presumably for debugging) } def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor): return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id) @staticmethod def _reorder_cache(past_key_values, beam_idx): reordered_past = () for layer_past in past_key_values: # cached cross_attention states don't have to be reordered -> they are always the same reordered_past += ( tuple( past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2] ) + layer_past[2:], ) return reordered_past @dataclass class Florence2Seq2SeqLMOutput(ModelOutput): """ Base class for Florence-2 model's outputs that also contains : pre-computed hidden states that can speed up sequential decoding. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the decoder of the model. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1, hidden_size)` is output. past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the decoder at the output of each layer plus the optional initial embedding outputs. decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder of the model. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each layer plus the optional initial embedding outputs. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. image_hidden_states (`tuple(torch.FloatTensor)`, *optional*): Tuple of `torch.FloatTensor` (one for the output of the image embeddings, `(batch_size, num_image_tokens, hidden_size)`. image_hidden_states of the model produced by the vision encoder """ loss: torch.FloatTensor | None = None logits: torch.FloatTensor = None last_hidden_state: torch.FloatTensor = None past_key_values: tuple[tuple[torch.FloatTensor]] | None = None decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None decoder_attentions: tuple[torch.FloatTensor, ...] | None = None cross_attentions: tuple[torch.FloatTensor, ...] | None = None encoder_last_hidden_state: torch.FloatTensor | None = None encoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None encoder_attentions: tuple[torch.FloatTensor, ...] | None = None image_hidden_states: tuple[torch.FloatTensor, ...] | None = None FLORENCE2_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`Florence2Config`] or [`Florence2VisionConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ @add_start_docstrings( "The bare Florence-2 Model outputting raw hidden-states without any specific head on top.", FLORENCE2_START_DOCSTRING, ) class Florence2PreTrainedModel(PreTrainedModel): config_class = Florence2Config base_model_prefix = "model" supports_gradient_checkpointing = True _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_sdpa = True FLORENCE2_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)): The tensors corresponding to the input images. Pixel values can be obtained using [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details ([]`Florence2Processor`] uses [`CLIPImageProcessor`] for processing images). attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy. - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( """The FLORENCE2 model which consists of a vision backbone and a language model.""", FLORENCE2_START_DOCSTRING, ) class Florence2ForConditionalGeneration(Florence2PreTrainedModel): _tied_weights_keys = { "language_model.model.encoder.embed_tokens.weight": "language_model.model.shared.weight", "language_model.model.decoder.embed_tokens.weight": "language_model.model.shared.weight", } def __init__(self, config: Florence2Config): super().__init__(config) assert config.vision_config.model_type == "davit", "only DaViT is supported for now" self.vision_tower = DaViT.from_config(config=config.vision_config) # remove unused layers del self.vision_tower.head del self.vision_tower.norms self.vocab_size = config.vocab_size self._attn_implementation = config._attn_implementation self._build_image_projection_layers(config) language_model = Florence2LanguageForConditionalGeneration(config=config.text_config) self.language_model = language_model self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1 self.post_init() def _build_image_projection_layers(self, config): image_dim_out = config.vision_config.dim_embed[-1] dim_projection = config.vision_config.projection_dim self.image_projection = nn.Parameter(torch.empty(image_dim_out, dim_projection)) self.image_proj_norm = nn.LayerNorm(dim_projection) image_pos_embed_config = config.vision_config.image_pos_embed if image_pos_embed_config["type"] == "learned_abs_2d": self.image_pos_embed = LearnedAbsolutePositionEmbedding2D( embedding_dim=image_dim_out, num_pos=image_pos_embed_config["max_pos_embeddings"] ) else: raise NotImplementedError("Not implemented yet") self.image_feature_source = config.vision_config.image_feature_source # temporal embedding visual_temporal_embedding_config = config.vision_config.visual_temporal_embedding if visual_temporal_embedding_config["type"] == "COSINE": self.visual_temporal_embed = PositionalEmbeddingCosine1D( embed_dim=image_dim_out, max_seq_len=visual_temporal_embedding_config["max_temporal_embeddings"], ) else: raise NotImplementedError("Not implemented yet") def get_encoder(self): return self.language_model.get_encoder() def get_decoder(self): return self.language_model.get_decoder() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def resize_token_embeddings( self, new_num_tokens: int | None = None, pad_to_multiple_of=None, **kwargs ) -> nn.Embedding: model_embeds = self.language_model.resize_token_embeddings( new_num_tokens, pad_to_multiple_of, **kwargs ) # update vocab size self.config.text_config.vocab_size = model_embeds.num_embeddings self.config.vocab_size = model_embeds.num_embeddings self.vocab_size = model_embeds.num_embeddings return model_embeds def _encode_image(self, pixel_values): # Cast pixel_values to model's dtype pixel_values = pixel_values.to(dtype=self.vision_tower.convs[0].proj.weight.dtype) if len(pixel_values.shape) == 4: batch_size, channels, height, width = pixel_values.shape num_frames = 1 x = self.vision_tower.forward_features_unpool(pixel_values) else: raise ValueError(f"invalid image shape {pixel_values.shape}") if self.image_pos_embed is not None: x = x.view(batch_size * num_frames, -1, x.shape[-1]) num_tokens = x.shape[-2] h, w = int(num_tokens**0.5), int(num_tokens**0.5) assert h * w == num_tokens, "only support square feature maps for now" x = x.view(batch_size * num_frames, h, w, x.shape[-1]) pos_embed = self.image_pos_embed(x) x = x + pos_embed x = x.view(batch_size, num_frames * h * w, x.shape[-1]) if self.visual_temporal_embed is not None: visual_temporal_embed = self.visual_temporal_embed( x.view(batch_size, num_frames, -1, x.shape[-1])[:, :, 0] ) x = x.view(batch_size, num_frames, -1, x.shape[-1]) + visual_temporal_embed.view( 1, num_frames, 1, x.shape[-1] ) x_feat_dict = {} spatial_avg_pool_x = x.view(batch_size, num_frames, -1, x.shape[-1]).mean(dim=2) x_feat_dict["spatial_avg_pool"] = spatial_avg_pool_x temporal_avg_pool_x = x.view(batch_size, num_frames, -1, x.shape[-1]).mean(dim=1) x_feat_dict["temporal_avg_pool"] = temporal_avg_pool_x x = x.view(batch_size, num_frames, -1, x.shape[-1])[:, -1] x_feat_dict["last_frame"] = x new_x = [] for _image_feature_source in self.image_feature_source: if _image_feature_source not in x_feat_dict: raise ValueError(f"invalid image feature source: {_image_feature_source}") new_x.append(x_feat_dict[_image_feature_source]) x = torch.cat(new_x, dim=1) x = x @ self.image_projection x = self.image_proj_norm(x) return x def _merge_input_ids_with_image_features(self, image_features, inputs_embeds): batch_size, image_token_length = image_features.size()[:-1] device = image_features.device image_attention_mask = torch.ones(batch_size, image_token_length, device=device) # task_prefix_embeds: [batch_size, padded_context_length, hidden_size] # task_prefix_attention_mask: [batch_size, context_length] if inputs_embeds is None: return image_features, image_attention_mask task_prefix_embeds = inputs_embeds task_prefix_attention_mask = torch.ones(batch_size, task_prefix_embeds.size(1), device=device) if len(task_prefix_attention_mask.shape) == 3: task_prefix_attention_mask = task_prefix_attention_mask[:, 0] # concat [image embeds, task prefix embeds] inputs_embeds = torch.cat([image_features, task_prefix_embeds], dim=1) attention_mask = torch.cat([image_attention_mask, task_prefix_attention_mask], dim=1) return inputs_embeds, attention_mask @add_start_docstrings_to_model_forward(FLORENCE2_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=Florence2Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, pixel_values: torch.FloatTensor = None, attention_mask: torch.Tensor | None = None, decoder_input_ids: torch.LongTensor | None = None, decoder_attention_mask: torch.LongTensor | None = None, head_mask: torch.Tensor | None = None, decoder_head_mask: torch.Tensor | None = None, cross_attn_head_mask: torch.Tensor | None = None, encoder_outputs: list[torch.FloatTensor] | None = None, past_key_values: list[torch.FloatTensor] | None = None, inputs_embeds: torch.FloatTensor | None = None, decoder_inputs_embeds: torch.FloatTensor | None = None, labels: torch.LongTensor | None = None, use_cache: bool | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, ) -> tuple | Florence2Seq2SeqLMOutput: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Returns: Example: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, Florence2ForConditionalGeneration >>> model = Florence2ForConditionalGeneration.from_pretrained("microsoft/Florence-2-large") >>> processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large") >>> prompt = "<CAPTION>" >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(text=prompt, images=image, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(**inputs, max_length=100) >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "A green car parked in front of a yellow building." ```""" output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict image_features = None if inputs_embeds is None: # 1. Extra the input embeddings if input_ids is not None: inputs_embeds = self.get_input_embeddings()(input_ids) # 2. Merge text and images if pixel_values is not None: # (batch_size, num_image_tokens, hidden_size) image_features = self._encode_image(pixel_values) inputs_embeds, attention_mask = self._merge_input_ids_with_image_features( image_features, inputs_embeds ) if inputs_embeds is not None: attention_mask = attention_mask.to(inputs_embeds.dtype) outputs = self.language_model( attention_mask=attention_mask, labels=labels, inputs_embeds=inputs_embeds, decoder_input_ids=decoder_input_ids, encoder_outputs=encoder_outputs, decoder_attention_mask=decoder_attention_mask, head_mask=head_mask, decoder_head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) logits = outputs.logits logits = logits.float() loss = outputs.loss if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return Florence2Seq2SeqLMOutput( loss=loss, logits=logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, image_hidden_states=image_features, ) def generate(self, input_ids, inputs_embeds=None, pixel_values=None, **kwargs): if inputs_embeds is None: # 1. Extra the input embeddings if input_ids is not None: inputs_embeds = self.get_input_embeddings()(input_ids) # 2. Merge text and images if pixel_values is not None: image_features = self._encode_image(pixel_values) inputs_embeds, attention_mask = self._merge_input_ids_with_image_features( image_features, inputs_embeds ) return self.language_model.generate(input_ids=None, inputs_embeds=inputs_embeds, **kwargs) def prepare_inputs_for_generation( self, decoder_input_ids, past_key_values=None, attention_mask=None, pixel_values=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, use_cache=None, encoder_outputs=None, **kwargs, ): # cut decoder_input_ids if past_key_values is used if past_key_values is not None: past_length = past_key_values[0][0].shape[2] # Some generation methods already pass only the last input ID if decoder_input_ids.shape[1] > past_length: remove_prefix_length = past_length else: # Default to old behavior: keep only final ID remove_prefix_length = decoder_input_ids.shape[1] - 1 decoder_input_ids = decoder_input_ids[:, remove_prefix_length:] return { "input_ids": None, # encoder_outputs is defined. input_ids not needed "encoder_outputs": encoder_outputs, "past_key_values": past_key_values, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, "use_cache": use_cache, # change this to avoid caching (presumably for debugging) } def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor): return self.language_model.shift_tokens_right(labels) def _reorder_cache(self, *args, **kwargs): return self.language_model._reorder_cache(*args, **kwargs)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/modeling_florence2.py", "license": "Apache License 2.0", "lines": 2340, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/modeling_xvla.py
#!/usr/bin/env python # ------------------------------------------------------------------------------ # Copyright 2025 The HuggingFace Inc. team and 2toINF (https://github.com/2toINF) # # 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 __future__ import annotations import builtins import logging import os from collections import deque from pathlib import Path import torch import torch.nn.functional as F # noqa: N812 from torch import Tensor, nn from lerobot.configs.policies import PreTrainedConfig from lerobot.policies.pretrained import PreTrainedPolicy, T from lerobot.policies.utils import populate_queues from lerobot.utils.constants import ACTION, OBS_LANGUAGE_TOKENS, OBS_STATE from .action_hub import build_action_space from .configuration_florence2 import Florence2Config from .configuration_xvla import XVLAConfig from .modeling_florence2 import Florence2ForConditionalGeneration from .soft_transformer import SoftPromptedTransformer class XVLAModel(nn.Module): """ XVLA backbone that stitches Florence-2 embeddings with the temporal/action transformer head. """ def __init__( self, config: XVLAConfig, florence_config: Florence2Config, proprio_dim: int, ) -> None: super().__init__() self.config = config self.chunk_size: int = config.chunk_size self.use_proprio: bool = config.use_proprio # Build action space with auto-detection for "auto" mode if config.action_mode.lower() == "auto": # Auto-detect real action dim from config.action_feature real_dim = ( config.action_feature.shape[-1] if config.action_feature is not None else config.max_action_dim ) self.action_space = build_action_space( config.action_mode.lower(), real_dim=real_dim, max_dim=config.max_action_dim, ) else: self.action_space = build_action_space(config.action_mode.lower()) self.dim_action = self.action_space.dim_action self.dim_proprio = proprio_dim self.vlm = Florence2ForConditionalGeneration(florence_config) if hasattr(self.vlm, "language_model"): lm = self.vlm.language_model if hasattr(lm, "model") and hasattr(lm.model, "decoder"): del lm.model.decoder if hasattr(lm, "lm_head"): del lm.lm_head projection_dim = getattr(self.vlm.config, "projection_dim", None) if projection_dim is None: raise ValueError("Florence2 config must provide `projection_dim` for multimodal fusion.") self.transformer = SoftPromptedTransformer( hidden_size=config.hidden_size, multi_modal_input_size=projection_dim, depth=config.depth, num_heads=config.num_heads, mlp_ratio=config.mlp_ratio, num_domains=config.num_domains, dim_action=self.dim_action, dim_propio=self.dim_proprio, len_soft_prompts=config.len_soft_prompts, dim_time=config.dim_time, max_len_seq=config.max_len_seq, use_hetero_proj=config.use_hetero_proj, ) # Apply freezing based on config self._apply_freezing() # Apply dtype casting based on config self._apply_dtype() def _get_target_dtype(self) -> torch.dtype: """Get the target dtype based on config.""" if self.config.dtype == "bfloat16": return torch.bfloat16 return torch.float32 def _apply_dtype(self) -> None: """ Apply dtype casting to model components based on config. """ target_dtype = self._get_target_dtype() self.to(dtype=target_dtype) def _apply_freezing(self) -> None: """ Freeze VLM vision and language encoders based on config options. Keep only policy transformer and soft prompts trainable. """ # Freeze vision encoder if self.config.freeze_vision_encoder and hasattr(self.vlm, "vision_tower"): for param in self.vlm.vision_tower.parameters(): param.requires_grad = False # Freeze language encoder if self.config.freeze_language_encoder and hasattr(self.vlm, "language_model"): lm = self.vlm.language_model # Freeze encoder if hasattr(lm, "model") and hasattr(lm.model, "encoder"): for param in lm.model.encoder.parameters(): param.requires_grad = False # Freeze shared embeddings if hasattr(lm, "model") and hasattr(lm.model, "shared"): for param in lm.model.shared.parameters(): param.requires_grad = False # Freeze or unfreeze policy transformer if not self.config.train_policy_transformer: for name, param in self.transformer.named_parameters(): if "soft_prompts" not in name: param.requires_grad = False # Freeze or unfreeze soft prompts if not self.config.train_soft_prompts and hasattr(self.transformer, "soft_prompt_hub"): for param in self.transformer.soft_prompt_hub.parameters(): param.requires_grad = False def forward_vlm( self, input_ids: torch.LongTensor, pixel_values: torch.FloatTensor, image_mask: torch.Tensor, ) -> dict[str, torch.Tensor]: """ Encode text and multi-view images via Florence2 encoder. """ batch_size, num_views = pixel_values.shape[:2] flat_mask = image_mask.view(-1).to(dtype=torch.bool) flat_images = pixel_values.flatten(0, 1) num_valid = int(flat_mask.sum().item()) if num_valid == 0: raise ValueError("At least one image view must be valid per batch.") valid_images = flat_images[flat_mask] valid_feats = self.vlm._encode_image(valid_images) tokens_per_view, hidden_dim = valid_feats.shape[1:] image_features = valid_feats.new_zeros((batch_size * num_views, tokens_per_view, hidden_dim)) image_features[flat_mask] = valid_feats image_features = image_features.view(batch_size, num_views, tokens_per_view, hidden_dim) inputs_embeds = self.vlm.get_input_embeddings()(input_ids) merged_embeds, attention_mask = self.vlm._merge_input_ids_with_image_features( image_features[:, 0], inputs_embeds, ) enc_out = self.vlm.language_model.model.encoder( attention_mask=attention_mask, inputs_embeds=merged_embeds, )[0] aux_visual_inputs = image_features[:, 1:].reshape(batch_size, -1, hidden_dim) return {"vlm_features": enc_out, "aux_visual_inputs": aux_visual_inputs} def forward( self, input_ids: torch.LongTensor, image_input: torch.FloatTensor, image_mask: torch.Tensor, domain_id: torch.LongTensor, proprio: torch.Tensor, action: torch.Tensor, ) -> dict[str, torch.Tensor]: """ Forward pass for the XVLA model. """ target_dtype = self._get_target_dtype() image_input = image_input.to(dtype=target_dtype) proprio = proprio.to(dtype=target_dtype) action = action.to(dtype=target_dtype) enc = self.forward_vlm(input_ids, image_input, image_mask) batch_size = input_ids.shape[0] t = ( torch.rand(1, device=input_ids.device, dtype=target_dtype) + torch.arange(batch_size, device=input_ids.device, dtype=target_dtype) / batch_size ) % (1 - 1e-5) action_noisy = torch.randn_like(action) * t.view(-1, 1, 1) + action * (1 - t).view(-1, 1, 1) proprio_m, action_noisy_m = self.action_space.preprocess(proprio, action_noisy) pred_action = self.transformer( domain_id=domain_id, action_with_noise=action_noisy_m, t=t, proprio=proprio_m, **enc, ) return self.action_space.compute_loss(pred_action, action) @torch.no_grad() def generate_actions( self, input_ids: torch.LongTensor, image_input: torch.FloatTensor, image_mask: torch.Tensor, domain_id: torch.LongTensor, proprio: torch.Tensor, steps: int, ) -> torch.Tensor: self.eval() target_dtype = self._get_target_dtype() image_input = image_input.to(dtype=target_dtype) proprio = proprio.to(dtype=target_dtype) enc = self.forward_vlm(input_ids, image_input, image_mask) batch_size = input_ids.shape[0] action_dim = self.dim_action x1 = torch.randn(batch_size, self.chunk_size, action_dim, device=proprio.device, dtype=target_dtype) action = torch.zeros_like(x1) steps = max(1, int(steps)) for i in range(steps, 0, -1): t = torch.full((batch_size,), i / steps, device=proprio.device, dtype=target_dtype) x_t = x1 * t.view(-1, 1, 1) + action * (1 - t).view(-1, 1, 1) proprio_m, x_t_m = self.action_space.preprocess(proprio, x_t) action = self.transformer( domain_id=domain_id, action_with_noise=x_t_m, proprio=proprio_m, t=t, **enc, ) return self.action_space.postprocess(action) class XVLAPolicy(PreTrainedPolicy): """LeRobot-compliant wrapper built around the XVLA model.""" config_class = XVLAConfig name = "xvla" def __init__(self, config: XVLAConfig, **kwargs): super().__init__(config) config.validate_features() florence_config = config.get_florence_config() proprio_dim = config.max_state_dim if config.use_proprio else 0 self.model = XVLAModel(config=config, florence_config=florence_config, proprio_dim=proprio_dim) self.reset() def reset(self) -> None: self._queues = { ACTION: deque(maxlen=self.config.n_action_steps), } def get_optim_params(self) -> dict: """Return trainable named parameters for optimization. Returns a dict of name -> param for all trainable parameters. This enables the xvla-adamw optimizer to apply differential learning rates based on parameter names (e.g., 1/10 LR for VLM components). """ return dict(filter(lambda kv: kv[1].requires_grad, self.named_parameters())) def _prepare_state(self, batch: dict[str, Tensor], batch_size: int, device: torch.device) -> Tensor: if not self.config.use_proprio or OBS_STATE not in batch: return torch.zeros(batch_size, 0, device=device) state = batch[OBS_STATE] if state.ndim > 2: state = state[:, -1, :] return pad_vector(state, self.model.dim_proprio) def _prepare_images(self, batch: dict[str, Tensor]) -> tuple[Tensor, Tensor]: present_img_keys = [key for key in self.config.image_features if key in batch] if len(present_img_keys) == 0: raise ValueError( "All image features are missing from the batch. " f"Batch keys: {list(batch.keys())}, expected at least one of {list(self.config.image_features)}." ) images = [] masks = [] for key in present_img_keys: img = batch[key][:, -1] if batch[key].ndim == 5 else batch[key] if self.config.resize_imgs_with_padding is not None: img = resize_with_pad(img, *self.config.resize_imgs_with_padding) images.append(img) masks.append(torch.ones(img.size(0), dtype=torch.bool, device=img.device)) stacked_imgs = torch.stack(images, dim=1) stacked_masks = torch.stack(masks, dim=1) total_views = self.config.num_image_views or stacked_imgs.size(1) total_views = max(total_views, stacked_imgs.size(1)) num_pad = total_views - stacked_imgs.size(1) if num_pad > 0: pad_shape = (stacked_imgs.size(0), num_pad, *stacked_imgs.shape[2:]) pad_imgs = stacked_imgs.new_zeros(pad_shape) pad_masks = stacked_masks.new_zeros((stacked_masks.size(0), num_pad)) stacked_imgs = torch.cat([stacked_imgs, pad_imgs], dim=1) stacked_masks = torch.cat([stacked_masks, pad_masks], dim=1) return stacked_imgs, stacked_masks def _get_domain_id(self, batch: dict[str, Tensor], batch_size: int, device: torch.device) -> Tensor: candidate = None if self.config.domain_feature_key and self.config.domain_feature_key in batch: candidate = batch[self.config.domain_feature_key] elif "domain_id" in batch: candidate = batch["domain_id"] if candidate is None: return torch.zeros(batch_size, dtype=torch.long, device=device) if not isinstance(candidate, torch.Tensor): candidate = torch.as_tensor(candidate, device=device) else: candidate = candidate.to(device=device) if candidate.ndim == 0: candidate = candidate.expand(batch_size) if candidate.ndim > 1: candidate = candidate.view(candidate.shape[0], -1)[:, 0] if candidate.shape[0] != batch_size: candidate = candidate.expand(batch_size) return candidate.to(dtype=torch.long) def _prepare_action_targets(self, batch: dict[str, Tensor]) -> Tensor: if ACTION not in batch: raise ValueError("Batch is missing action targets required for training.") actions = batch[ACTION] if actions.ndim == 2: actions = actions.unsqueeze(1) actions = pad_tensor_along_dim(actions, self.config.chunk_size, dim=1) if actions.shape[-1] != self.model.dim_action: actions = pad_vector(actions, self.model.dim_action) return actions def _build_model_inputs(self, batch: dict[str, Tensor]) -> dict[str, Tensor]: input_ids = batch[OBS_LANGUAGE_TOKENS] batch_size = input_ids.shape[0] images, image_mask = self._prepare_images(batch) domain_id = self._get_domain_id(batch, batch_size, images.device) proprio = self._prepare_state(batch, batch_size, images.device) return { "input_ids": input_ids, "image_input": images, "image_mask": image_mask, "domain_id": domain_id, "proprio": proprio, } def forward(self, batch: dict[str, Tensor]) -> tuple[Tensor, dict]: inputs = self._build_model_inputs(batch) targets = self._prepare_action_targets(batch) losses = self.model(action=targets, **inputs) total_loss = sum(losses.values()) log_dict = {k: v.detach().item() for k, v in losses.items()} log_dict["loss"] = total_loss.detach().item() return total_loss, log_dict def _get_action_chunk(self, batch: dict[str, Tensor]) -> Tensor: inputs = self._build_model_inputs(batch) actions = self.model.generate_actions(**inputs, steps=self.config.num_denoising_steps) return actions @torch.no_grad() def predict_action_chunk(self, batch: dict[str, Tensor], noise: Tensor | None = None) -> Tensor: # noqa: ARG002 self.eval() self._queues = populate_queues(self._queues, batch, exclude_keys=[ACTION]) return self._get_action_chunk(batch) @torch.no_grad() def select_action(self, batch: dict[str, Tensor], noise: Tensor | None = None) -> Tensor: # noqa: ARG002 self.eval() self._queues = populate_queues(self._queues, batch, exclude_keys=[ACTION]) if len(self._queues[ACTION]) == 0: actions = self._get_action_chunk(batch) self._queues[ACTION].extend(actions.transpose(0, 1)[: self.config.n_action_steps]) return self._queues[ACTION].popleft() @classmethod def from_pretrained( cls: builtins.type[T], pretrained_name_or_path: str | Path, *, config: PreTrainedConfig | None = None, force_download: bool = False, resume_download: bool | None = None, proxies: dict | None = None, token: str | bool | None = None, cache_dir: str | Path | None = None, local_files_only: bool = False, revision: str | None = None, strict: bool = False, **kwargs, ): """ Loads XVLA model weights with: - automatic prefix 'model.' added to all keys - skip list for layers that should remain randomly initialized """ import safetensors.torch # step 1: load config # TODO: jadechoghari, fix this if config is None: config = PreTrainedConfig.from_pretrained( pretrained_name_or_path=pretrained_name_or_path, force_download=force_download, resume_download=resume_download, proxies=proxies, token=token, cache_dir=cache_dir, local_files_only=local_files_only, revision=revision, **kwargs, ) model_id = str(pretrained_name_or_path) instance = cls(config, **kwargs) # step 2: locate model.safetensors if os.path.isdir(model_id): logging.info("Loading weights from local directory") model_file = os.path.join(model_id, "model.safetensors") else: try: from huggingface_hub import hf_hub_download from huggingface_hub.utils import HfHubHTTPError model_file = hf_hub_download( repo_id=model_id, filename="model.safetensors", revision=revision, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, token=token, local_files_only=local_files_only, ) except HfHubHTTPError as e: raise FileNotFoundError(f"model.safetensors not found on the Hub at {model_id}") from e logging.info(f"Loading checkpoint from {model_file}") # step 3: load state dict state_dict = safetensors.torch.load_file(model_file) encoder_key = "model.vlm.language_model.model.encoder.embed_tokens.weight" shared_key = "model.vlm.language_model.model.shared.weight" if encoder_key in state_dict: state_dict[shared_key] = state_dict[encoder_key] # or deepcopy # step 4: load into instance instance.load_state_dict(state_dict, strict=True) logging.info("Loaded XVLA checkpoint") # step 5: finalize # Reapply dtype after loading state dict instance.model._apply_dtype() instance.to(config.device) instance.eval() return instance def resize_with_pad(img: torch.Tensor, height: int, width: int, pad_value: float = 0.0) -> torch.Tensor: if img.ndim != 4: raise ValueError(f"(b,c,h,w) expected, but got {img.shape}") current_height, current_width = img.shape[2:] if current_height == height and current_width == width: return img ratio = max(current_width / width, current_height / height) resized_height = int(current_height / ratio) resized_width = int(current_width / ratio) resized_img = F.interpolate( img, size=(resized_height, resized_width), mode="bilinear", align_corners=False ) pad_height = max(0, height - resized_height) pad_width = max(0, width - resized_width) padded_img = F.pad(resized_img, (pad_width, 0, pad_height, 0), value=pad_value) return padded_img def pad_vector(vector: Tensor, new_dim: int) -> Tensor: if vector.shape[-1] == new_dim: return vector if new_dim == 0: shape = list(vector.shape) shape[-1] = 0 return vector.new_zeros(*shape) shape = list(vector.shape) current_dim = shape[-1] shape[-1] = new_dim new_vector = vector.new_zeros(*shape) length = min(current_dim, new_dim) new_vector[..., :length] = vector[..., :length] return new_vector def pad_tensor_along_dim(tensor: Tensor, target_len: int, dim: int = 1) -> Tensor: current_len = tensor.size(dim) if current_len == target_len: return tensor if current_len > target_len: slices = [slice(None)] * tensor.dim() slices[dim] = slice(0, target_len) return tensor[tuple(slices)] pad_shape = list(tensor.shape) pad_shape[dim] = target_len - current_len pad_tensor = tensor.new_zeros(pad_shape) return torch.cat([tensor, pad_tensor], dim=dim)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/modeling_xvla.py", "license": "Apache License 2.0", "lines": 470, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/processor_xvla.py
# ------------------------------------------------------------------------------ # Copyright 2025 The HuggingFace Inc. team and 2toINF (https://github.com/2toINF) # # 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 dataclasses import dataclass from typing import Any import numpy as np import torch from lerobot.configs.types import PipelineFeatureType, PolicyFeature from lerobot.datasets.factory import IMAGENET_STATS from lerobot.policies.xvla.configuration_xvla import XVLAConfig from lerobot.policies.xvla.utils import rotate6d_to_axis_angle from lerobot.processor import ( AddBatchDimensionProcessorStep, DeviceProcessorStep, NormalizerProcessorStep, ObservationProcessorStep, PolicyAction, PolicyProcessorPipeline, ProcessorStep, ProcessorStepRegistry, RenameObservationsProcessorStep, TokenizerProcessorStep, UnnormalizerProcessorStep, ) from lerobot.processor.converters import policy_action_to_transition, transition_to_policy_action from lerobot.processor.core import EnvTransition, TransitionKey from lerobot.utils.constants import ( OBS_IMAGES, OBS_PREFIX, OBS_STATE, POLICY_POSTPROCESSOR_DEFAULT_NAME, POLICY_PREPROCESSOR_DEFAULT_NAME, ) def make_xvla_pre_post_processors( config: XVLAConfig, dataset_stats: dict[str, dict[str, torch.Tensor]] | None = None, ) -> tuple[ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """ Build the LeRobot processor pipelines for XVLA. """ features = {**config.input_features, **config.output_features} input_steps = [ RenameObservationsProcessorStep(rename_map={}), AddBatchDimensionProcessorStep(), TokenizerProcessorStep( tokenizer_name=config.tokenizer_name, max_length=config.tokenizer_max_length, padding=config.pad_language_to, padding_side=config.tokenizer_padding_side, ), XVLAImageToFloatProcessorStep(), XVLAImageNetNormalizeProcessorStep(), XVLAAddDomainIdProcessorStep(), DeviceProcessorStep(device=config.device), NormalizerProcessorStep( features=features, norm_map=config.normalization_mapping, stats=dataset_stats ), ] output_steps = [ UnnormalizerProcessorStep( features=config.output_features, norm_map=config.normalization_mapping, stats=dataset_stats, ), DeviceProcessorStep(device="cpu"), ] return ( PolicyProcessorPipeline[dict[str, Any], dict[str, Any]]( steps=input_steps, name=POLICY_PREPROCESSOR_DEFAULT_NAME, ), PolicyProcessorPipeline[PolicyAction, PolicyAction]( steps=output_steps, name=POLICY_POSTPROCESSOR_DEFAULT_NAME, to_transition=policy_action_to_transition, to_output=transition_to_policy_action, ), ) # Custom XVLA processor steps @dataclass class LiberoProcessorStep(ObservationProcessorStep): """ Processes LIBERO observations into the LeRobot format. This step handles the specific observation structure from LIBERO environments, which includes nested robot_state dictionaries and image observations. **State Processing:** - Processes the `robot_state` dictionary which contains nested end-effector, gripper, and joint information. - Extracts and concatenates: - End-effector position (3D) - End-effector quaternion converted to axis-angle (3D) - Gripper joint positions (2D) - Maps the concatenated state to `"observation.state"`. **Image Processing:** - Rotates images by 180 degrees by flipping both height and width dimensions. - This accounts for the HuggingFaceVLA/libero camera orientation convention. """ def _process_observation(self, observation): """ Processes both image and robot_state observations from LIBERO. """ processed_obs = observation.copy() for key in list(processed_obs.keys()): if key.startswith(f"{OBS_IMAGES}."): img = processed_obs[key] if key == f"{OBS_IMAGES}.image": # Flip both H and W img = torch.flip(img, dims=[2, 3]) processed_obs[key] = img # Process robot_state into a flat state vector robot_state_str = OBS_PREFIX + "robot_state" if robot_state_str in processed_obs: robot_state = processed_obs.pop(robot_state_str) # Extract components eef_pos = robot_state["eef"]["pos"] # (B, 3,) eef_mat = robot_state["eef"]["mat"] # (B, 3, 3) eef_rot6d = self._mat_to_rotate6d(eef_mat) # (B, 6) extra = torch.zeros((eef_pos.shape[0], 1), dtype=torch.float32, device=eef_pos.device) proprio_state = torch.cat((eef_pos, eef_rot6d, extra), dim=-1) # (B, 10) state = torch.cat((proprio_state, torch.zeros_like(proprio_state)), dim=-1) # (B, 20) # ensure float32 state = state.float() if state.dim() == 1: state = state.unsqueeze(0) processed_obs[OBS_STATE] = state return processed_obs def transform_features( self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]] ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]: """ Transforms feature keys from the LIBERO format to the LeRobot standard. """ new_features: dict[PipelineFeatureType, dict[str, PolicyFeature]] = {} # copy over non-STATE features for ft, feats in features.items(): if ft != PipelineFeatureType.STATE: new_features[ft] = feats.copy() # rebuild STATE features state_feats = {} # add our new flattened state state_feats[OBS_STATE] = PolicyFeature( key=OBS_STATE, shape=(20,), dtype="float32", ) new_features[PipelineFeatureType.STATE] = state_feats return new_features def _mat_to_rotate6d(self, rot_mats: torch.Tensor) -> torch.Tensor: """ Convert batched rotation matrices (B, 3, 3) into 6D rotation representation (B, 6). Args: rot_mats (Tensor): Rotation matrices of shape (B, 3, 3) Returns: Tensor: 6D rotation representation, shape (B, 6) Raises: TypeError: if input is not a torch tensor ValueError: if shape is not (B, 3, 3) """ if not isinstance(rot_mats, torch.Tensor): raise TypeError(f"mat_to_rot6d expects a torch.Tensor, got {type(rot_mats)}") if rot_mats.ndim != 3 or rot_mats.shape[1:] != (3, 3): raise ValueError(f"mat_to_rot6d expects shape (B, 3, 3), got {tuple(rot_mats.shape)}") rot_mats = rot_mats.to(torch.float32) col1 = rot_mats[:, :3, 0] # (B, 3) col2 = rot_mats[:, :3, 1] # (B, 3) rot6d = torch.cat([col1, col2], dim=-1) # (B, 6) return rot6d def observation(self, observation): return self._process_observation(observation) @dataclass @ProcessorStepRegistry.register(name="xvla_image_scale") class XVLAImageScaleProcessorStep(ProcessorStep): """Scale image observations by 255 to convert from [0, 1] to [0, 255] range. This processor step multiplies all image observations by 255, which is required for XVLA models that expect images in uint8-like range. Args: image_keys: List of observation keys that contain images to scale. If None, will automatically detect keys starting with "observation.images." """ image_keys: list[str] | None = None def __call__(self, transition: EnvTransition) -> EnvTransition: """Scale image observations by 255.""" new_transition = transition.copy() obs = new_transition.get(TransitionKey.OBSERVATION, {}) if obs is None: return new_transition # Make a copy of observations to avoid modifying the original obs = obs.copy() # Determine which keys to scale keys_to_scale = self.image_keys if keys_to_scale is None: # Auto-detect image keys keys_to_scale = [k for k in obs if k.startswith(OBS_IMAGES)] # Scale each image for key in keys_to_scale: if key in obs and isinstance(obs[key], torch.Tensor): obs[key] = obs[key] * 255 new_transition[TransitionKey.OBSERVATION] = obs return new_transition def transform_features(self, features): """Image scaling doesn't change feature structure.""" return features def get_config(self) -> dict[str, Any]: """Return serializable configuration.""" return { "image_keys": self.image_keys, } @dataclass @ProcessorStepRegistry.register(name="xvla_image_to_float") class XVLAImageToFloatProcessorStep(ProcessorStep): """Convert image observations from [0, 255] to [0, 1] range. This processor step divides image observations by 255 to convert from uint8-like range [0, 255] to float range [0, 1]. This is typically used when loading images that are stored as uint8 values. Args: image_keys: List of observation keys that contain images to convert. If None, will automatically detect keys starting with "observation.images." validate_range: If True, validates that input values are in [0, 255] range (default: True) Raises: ValueError: If validate_range is True and image values are not in [0, 255] range. """ image_keys: list[str] | None = None validate_range: bool = True def __call__(self, transition: EnvTransition) -> EnvTransition: """Convert image observations from [0, 255] to [0, 1].""" new_transition = transition.copy() obs = new_transition.get(TransitionKey.OBSERVATION, {}) if obs is None: return new_transition # Make a copy of observations to avoid modifying the original obs = obs.copy() # Determine which keys to convert keys_to_convert = self.image_keys if keys_to_convert is None: # Auto-detect image keys keys_to_convert = [k for k in obs if k.startswith(OBS_IMAGES)] # Convert each image for key in keys_to_convert: if key in obs and isinstance(obs[key], torch.Tensor): tensor = obs[key] min_val = tensor.min().item() max_val = tensor.max().item() if max_val <= 1.0: obs[key] = tensor.float() # ensure float dtype, but no division continue # Validate that values are in [0, 255] range if requested if self.validate_range and (min_val < 0.0 or max_val > 255.0): raise ValueError( f"Image '{key}' has values outside [0, 255] range: " f"min={min_val:.4f}, max={max_val:.4f}. " f"Cannot convert to [0, 1] range." ) # Convert to float and divide by 255 obs[key] = tensor.float() / 255.0 new_transition[TransitionKey.OBSERVATION] = obs return new_transition def transform_features(self, features): """Image conversion doesn't change feature structure.""" return features def get_config(self) -> dict[str, Any]: """Return serializable configuration.""" return { "image_keys": self.image_keys, "validate_range": self.validate_range, } @dataclass @ProcessorStepRegistry.register(name="xvla_imagenet_normalize") class XVLAImageNetNormalizeProcessorStep(ProcessorStep): """Normalize image observations using ImageNet statistics. This processor step applies ImageNet normalization (mean and std) to image observations. It validates that input values are in the [0, 1] range before normalizing. The normalization formula is: (image - mean) / std Args: image_keys: List of observation keys that contain images to normalize. If None, will automatically detect keys starting with "observation.images." Raises: ValueError: If image values are not in the [0, 1] range. """ image_keys: list[str] | None = None def __call__(self, transition: EnvTransition) -> EnvTransition: """Normalize image observations using ImageNet statistics.""" new_transition = transition.copy() obs = new_transition.get(TransitionKey.OBSERVATION, {}) if obs is None: return new_transition # Make a copy of observations to avoid modifying the original obs = obs.copy() # Determine which keys to normalize keys_to_normalize = self.image_keys if keys_to_normalize is None: # Auto-detect image keys keys_to_normalize = [k for k in obs if k.startswith(OBS_IMAGES)] # Normalize each image for key in keys_to_normalize: if key in obs and isinstance(obs[key], torch.Tensor): tensor = obs[key] # Validate that values are in [0, 1] range min_val = tensor.min().item() max_val = tensor.max().item() if min_val < 0.0 or max_val > 1.0: raise ValueError( f"Image '{key}' has values outside [0, 1] range: " f"min={min_val:.4f}, max={max_val:.4f}. " f"ImageNet normalization requires input values in [0, 1]." ) # Apply ImageNet normalization mean = torch.tensor(IMAGENET_STATS["mean"], device=tensor.device, dtype=tensor.dtype) std = torch.tensor(IMAGENET_STATS["std"], device=tensor.device, dtype=tensor.dtype) # Expand mean/std to match tensor dims (e.g., BCHW or BNCHW) while mean.dim() < tensor.dim(): mean = mean.unsqueeze(0) std = std.unsqueeze(0) # Normalize: (image - mean) / std obs[key] = (tensor - mean) / std new_transition[TransitionKey.OBSERVATION] = obs return new_transition def transform_features(self, features): """ImageNet normalization doesn't change feature structure.""" return features def get_config(self) -> dict[str, Any]: """Return serializable configuration.""" return { "image_keys": self.image_keys, } @dataclass @ProcessorStepRegistry.register(name="xvla_add_domain_id") class XVLAAddDomainIdProcessorStep(ProcessorStep): """Add domain_id to complementary data. This processor step adds a domain_id tensor to the complementary data, which is used by XVLA to identify different robot embodiments or task domains. Args: domain_id: The domain ID to add (default: 3) """ domain_id: int = 0 def __call__(self, transition: EnvTransition) -> EnvTransition: """Add domain_id to complementary data.""" new_transition = transition.copy() comp = new_transition.get(TransitionKey.COMPLEMENTARY_DATA, {}) comp = {} if comp is None else comp.copy() # Infer batch size from observation tensors obs = new_transition.get(TransitionKey.OBSERVATION, {}) batch_size = 1 if obs: for v in obs.values(): if isinstance(v, torch.Tensor): batch_size = v.shape[0] break # Add domain_id tensor comp["domain_id"] = torch.tensor([int(self.domain_id)] * batch_size, dtype=torch.long) new_transition[TransitionKey.COMPLEMENTARY_DATA] = comp return new_transition def transform_features(self, features): """Domain ID addition doesn't change feature structure.""" return features def get_config(self) -> dict[str, Any]: """Return serializable configuration.""" return { "domain_id": self.domain_id, } @dataclass @ProcessorStepRegistry.register(name="xvla_rotation_6d_to_axis_angle") class XVLARotation6DToAxisAngleProcessorStep(ProcessorStep): """Convert 6D rotation representation to axis-angle and reorganize action dimensions. This processor step takes actions with 6D rotation representation and converts them to axis-angle representation, reorganizing the action dimensions as: - action[:, :3] -> target_eef (end-effector position) - action[:, 3:9] -> 6D rotation (converted to axis-angle, 3D) - action[:, 9:10] -> gripper action Final output: [target_eef (3), axis_angle (3), gripper (1)] = 7D action Args: expected_action_dim: Expected input action dimension (default: 10, supports 6D rotation + extras) """ expected_action_dim: int = 10 def __call__(self, transition: EnvTransition) -> EnvTransition: """Convert 6D rotation to axis-angle in action.""" new_transition = transition.copy() action = new_transition.get(TransitionKey.ACTION) if action is None or not isinstance(action, torch.Tensor): return new_transition # Convert to numpy for processing device = action.device dtype = action.dtype action_np = action.cpu().numpy() # Extract components # action shape: (B, D) where D >= 10 target_eef = action_np[:, :3] # (B, 3) rotation_6d = action_np[:, 3:9] # (B, 6) target_act = action_np[:, 9:10] # (B, 1) # Convert 6D rotation to axis-angle target_axis = rotate6d_to_axis_angle(rotation_6d) # (B, 3) # Concatenate: [eef (3), axis_angle (3), gripper (1)] = 7D action_np = np.concatenate([target_eef, target_axis, target_act], axis=-1) # Convert gripper action to -1 or 1 action_np[:, -1] = np.where(action_np[:, -1] > 0.5, 1.0, -1.0) # Convert back to tensor action = torch.from_numpy(action_np).to(device=device, dtype=dtype) new_transition[TransitionKey.ACTION] = action return new_transition def transform_features(self, features): """Rotation conversion changes action dimension from 10 to 7.""" # Note: This is a simplified version. In practice, you might want to # update the action feature shape in the features dict. return features def get_config(self) -> dict[str, Any]: """Return serializable configuration.""" return { "expected_action_dim": self.expected_action_dim, } def make_xvla_libero_pre_post_processors() -> tuple[ PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """ Build the LeRobot processor pipelines for XVLA with LIBERO environment. """ pre_processor_steps: list[ProcessorStep] = [] post_processor_steps: list[ProcessorStep] = [] pre_processor_steps.extend( [LiberoProcessorStep(), XVLAImageNetNormalizeProcessorStep(), XVLAAddDomainIdProcessorStep()] ) post_processor_steps.extend([XVLARotation6DToAxisAngleProcessorStep()]) return ( PolicyProcessorPipeline[dict[str, Any], dict[str, Any]]( steps=pre_processor_steps, ), PolicyProcessorPipeline[PolicyAction, PolicyAction]( steps=post_processor_steps, ), )
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/processor_xvla.py", "license": "Apache License 2.0", "lines": 444, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/xvla/soft_transformer.py
# ------------------------------------------------------------------------------ # Copyright 2025 2toINF (https://github.com/2toINF) # # 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 __future__ import annotations import math from collections.abc import Iterable from functools import partial from typing import Final import torch import torch.nn as nn import torch.nn.functional as functional # ------------------------------- Small utils ---------------------------------- def _to_2tuple(x) -> tuple: """Minimal replacement for timm.layers.to_2tuple.""" if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): t = tuple(x) return (t[0], t[1]) if len(t) >= 2 else (t[0], t[0]) return (x, x) def _has_sdp_attention() -> bool: """Check if we can use PyTorch fused scaled_dot_product_attention.""" return hasattr(functional, "scaled_dot_product_attention") # ---------------------------------- MLP -------------------------------------- class Mlp(nn.Module): """ MLP used in ViT-style blocks. Supports Linear or 1x1 Conv 'linear_layer' for token/channel mixing. """ def __init__( self, in_features: int, hidden_features: int | None = None, out_features: int | None = None, norm_layer: type[nn.Module] | None = None, bias: bool | tuple[bool, bool] = True, drop: float | tuple[float, float] = 0.0, use_conv: bool = False, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features bias = _to_2tuple(bias) drop_probs = _to_2tuple(drop) linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear self.fc1 = linear_layer(in_features, hidden_features, bias=bias[0]) self.act = nn.GELU(approximate="tanh") self.drop1 = nn.Dropout(drop_probs[0]) self.norm = norm_layer(hidden_features) if norm_layer is not None else nn.Identity() self.fc2 = linear_layer(hidden_features, out_features, bias=bias[1]) self.drop2 = nn.Dropout(drop_probs[1]) def forward(self, x: torch.Tensor) -> torch.Tensor: # Expect [B, T, C] for Linear variant; caller is responsible for shapes. x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.norm(x) x = self.fc2(x) x = self.drop2(x) return x # -------------------------------- Attention ---------------------------------- class Attention(nn.Module): """ Multi-Head Self-Attention with optional fused SDPA fallback. If PyTorch provides `scaled_dot_product_attention`, it will be used (usually faster and more stable); otherwise we use a manual implementation. """ fused_attn: Final[bool] def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, qk_norm: bool = False, attn_drop: float = 0.0, proj_drop: float = 0.0, norm_layer: type[nn.Module] = nn.LayerNorm, ) -> None: super().__init__() assert dim % num_heads == 0, "dim should be divisible by num_heads" self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim**-0.5 self.fused_attn = _has_sdp_attention() self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Parameters ---------- x : Tensor, shape [batch_size, seq_len, channels] Input sequence. Returns ------- Tensor, shape [batch_size, seq_len, channels] Output sequence after MHSA + projection. """ batch_size, seq_len, channels = x.shape qkv = ( self.qkv(x) .reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim) .permute(2, 0, 3, 1, 4) # 3 x [batch_size, num_heads, seq_len, head_dim] ) q, k, v = qkv.unbind(0) # each: [batch_size, num_heads, seq_len, head_dim] q, k = self.q_norm(q), self.k_norm(k) if self.fused_attn: x = functional.scaled_dot_product_attention( q, k, v, dropout_p=self.attn_drop.p if self.training else 0.0, ) # [batch_size, num_heads, seq_len, head_dim] else: q = q * self.scale attn = q @ k.transpose(-2, -1) # [batch_size, num_heads, seq_len, seq_len] attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = attn @ v # [batch_size, num_heads, seq_len, head_dim] x = x.transpose(1, 2).reshape(batch_size, seq_len, channels) # [batch_size, seq_len, channels] x = self.proj(x) x = self.proj_drop(x) return x # ------------------------------- Utilities ----------------------------------- def basic_init(module: nn.Module) -> None: """ Apply a basic initialization scheme to Linear layers. - Weight: Xavier uniform initialization. - Bias: Set to zero. """ if isinstance(module, nn.Linear): nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0.0) def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 100) -> torch.Tensor: """ Create sinusoidal timestep embeddings. Parameters ---------- t : torch.Tensor Shape [B]. Each element is a timestep index, may be fractional. dim : int Dimensionality of the output embedding. max_period : int, default=100 Controls the minimum frequency of the sinusoids. Returns ------- torch.Tensor Shape [B, dim]. Sinusoidal embeddings. """ half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=t.dtype, device=t.device) / half ) args = t[:, None] * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2 == 1: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding # ------------------------------- Core Layers ---------------------------------- class DomainAwareLinear(nn.Module): """ Linear layer with domain-conditioned parameters (per-sample). Each domain has its own weight and bias vectors, stored in embeddings. """ def __init__(self, input_size: int, output_size: int, num_domains: int = 20) -> None: super().__init__() self.input_size = input_size self.output_size = output_size self.fc = nn.Embedding(num_domains, output_size * input_size) self.bias = nn.Embedding(num_domains, output_size) nn.init.xavier_uniform_(self.fc.weight) nn.init.zeros_(self.bias.weight) def forward(self, x: torch.Tensor, domain_id: torch.LongTensor) -> torch.Tensor: """ Parameters ---------- x : Tensor [B, I] or [B, T, I] domain_id : LongTensor [B], domain indices. Returns ------- Tensor [batch_size, output_size] or [batch_size, seq_len, output_size] """ batch_size = domain_id.shape[0] squeeze_seq = False if x.dim() == 2: x = x.unsqueeze(1) squeeze_seq = True weight = self.fc(domain_id).view(batch_size, self.input_size, self.output_size) bias = self.bias(domain_id).view(batch_size, self.output_size) y = torch.matmul(x, weight) + bias.view(batch_size, 1, self.output_size) if squeeze_seq: y = y.squeeze(1) return y class TransformerBlock(nn.Module): """ Standard Transformer block (pre-LN): LN → MHSA → residual, LN → MLP → residual. """ def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float = 4.0) -> None: super().__init__() self.norm1 = nn.LayerNorm(hidden_size) self.norm2 = nn.LayerNorm(hidden_size) self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, attn_drop=0.1) self.mlp = Mlp( in_features=hidden_size, hidden_features=int(hidden_size * mlp_ratio), drop=0.1, ) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Parameters ---------- x : Tensor, [B, T, H] Returns ------- Tensor, [B, T, H] """ x = x + self.attn(self.norm1(x)) x = x + self.mlp(self.norm2(x)) return x # --------------------------- Main Model --------------------------------------- class SoftPromptedTransformer(nn.Module): """ Multi-modal, domain-aware Transformer with optional soft prompts. See parameter and forward I/O descriptions inside the docstrings. """ def __init__( self, hidden_size: int = 768, multi_modal_input_size: int = 768, depth: int = 24, num_heads: int = 16, mlp_ratio: float = 4.0, num_domains: int = 20, dim_action: int = 20, dim_propio: int = 20, dim_time: int = 32, len_soft_prompts: int = 32, max_len_seq: int = 512, use_hetero_proj: bool = False, ) -> None: super().__init__() self.hidden_size = hidden_size self.dim_action = dim_action self.dim_time = dim_time self.len_soft_prompts = len_soft_prompts self.use_hetero_proj = use_hetero_proj self.blocks = nn.ModuleList( [TransformerBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)] ) if use_hetero_proj: self.vlm_proj = DomainAwareLinear(multi_modal_input_size, hidden_size, num_domains=num_domains) self.aux_visual_proj = DomainAwareLinear( multi_modal_input_size, hidden_size, num_domains=num_domains ) else: self.vlm_proj = nn.Linear(multi_modal_input_size, hidden_size) self.aux_visual_proj = nn.Linear(multi_modal_input_size, hidden_size) self.pos_emb = nn.Parameter(torch.zeros(1, max_len_seq, hidden_size), requires_grad=True) nn.init.normal_(self.pos_emb, std=0.02) self.norm = nn.LayerNorm(hidden_size) self.action_encoder = DomainAwareLinear( dim_action + dim_time + dim_propio, hidden_size, num_domains=num_domains ) self.action_decoder = DomainAwareLinear(hidden_size, dim_action, num_domains=num_domains) if len_soft_prompts > 0: self.soft_prompt_hub = nn.Embedding(num_domains, len_soft_prompts * hidden_size) nn.init.normal_(self.soft_prompt_hub.weight, std=0.02) self.apply(basic_init) def forward( self, domain_id: torch.LongTensor, vlm_features: torch.Tensor, aux_visual_inputs: torch.Tensor, action_with_noise: torch.Tensor, proprio: torch.Tensor, t: torch.Tensor, ) -> torch.Tensor: """ Forward pass. Inputs ------ domain_id : [B] vlm_features : [B, T_vlm, D] aux_visual_inputs : [B, T_aux, D] action_with_noise : [B, T_action, dim_action] proprio : [B, dim_propio] t : [B] Returns ------- Tensor Predicted actions, [batch_size, num_actions, dim_action] """ batch_size, num_actions = action_with_noise.shape[:2] # Encode (action + proprio + time) → tokens time_emb = timestep_embedding(t, self.dim_time) # [batch_size, dim_time] time_tokens = time_emb.unsqueeze(1).expand(batch_size, num_actions, self.dim_time) proprio_tokens = proprio.unsqueeze(1).expand(batch_size, num_actions, proprio.shape[-1]) action_tokens = torch.cat([action_with_noise, proprio_tokens, time_tokens], dim=-1) x = self.action_encoder(action_tokens, domain_id) # [batch_size, num_actions, hidden_size] # Project visual streams and concatenate if self.use_hetero_proj: x = torch.cat( [ x, self.vlm_proj(vlm_features, domain_id), self.aux_visual_proj(aux_visual_inputs, domain_id), ], dim=1, ) else: x = torch.cat([x, self.vlm_proj(vlm_features), self.aux_visual_proj(aux_visual_inputs)], dim=1) # Add positional embeddings (truncate if needed) seq_len = x.shape[1] if seq_len > self.pos_emb.shape[1]: raise ValueError(f"Sequence length {seq_len} exceeds max_len_seq={self.pos_emb.shape[1]}.") x = x + self.pos_emb[:, :seq_len, :] # Append soft prompts if self.len_soft_prompts > 0: soft_prompts = self.soft_prompt_hub(domain_id).view( batch_size, self.len_soft_prompts, self.hidden_size ) x = torch.cat([x, soft_prompts], dim=1) # Transformer backbone for block in self.blocks: x = block(x) # Decode only the action segment return self.action_decoder(self.norm(x[:, :num_actions]), domain_id)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/xvla/soft_transformer.py", "license": "Apache License 2.0", "lines": 344, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/policies/xvla/test_xvla_original_vs_lerobot.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Test script to verify XVLA policy integration with LeRobot vs the original implementation""" # ruff: noqa: E402 import random from copy import deepcopy from typing import Any import numpy as np import pytest import torch pytest.importorskip("transformers") from lerobot.policies.xvla.configuration_xvla import XVLAConfig from lerobot.policies.xvla.modeling_xvla import XVLAPolicy from lerobot.policies.xvla.processor_xvla import make_xvla_pre_post_processors from lerobot.processor import PolicyAction, PolicyProcessorPipeline # noqa: E402 from lerobot.utils.constants import OBS_IMAGES, OBS_STATE # noqa: E402 from tests.utils import require_cuda # noqa: E402 # Constants DUMMY_ACTION_DIM = 7 # Standard robot arm action dimension DUMMY_STATE_DIM = 20 # Proprioceptive state dimension IMAGE_HEIGHT = 224 IMAGE_WIDTH = 224 NUM_VIEWS = 2 # Number of camera views DEVICE = "cuda" if torch.cuda.is_available() else "cpu" MODEL_PATH_LEROBOT = "lerobot/xvla-widowx" LIBERO_DOMAIN_ID = 0 # Domain ID for examples purposes # Expected values from original XVLA implementation (reference values) EXPECTED_ACTIONS_SHAPE = (30, 20) EXPECTED_ACTIONS_MEAN = 0.117606 EXPECTED_ACTIONS_STD = 0.245411 EXPECTED_ACTIONS_FIRST_5 = torch.tensor([0.2742, 0.4977, 0.0500, 0.7040, -0.2653]) def set_seed_all(seed: int): """Set random seed for all RNG sources to ensure reproducibility.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Set deterministic behavior torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.use_deterministic_algorithms(True, warn_only=True) def instantiate_lerobot_xvla( from_pretrained: bool = False, model_path: str = MODEL_PATH_LEROBOT, ) -> tuple[ Any, # Policy PolicyProcessorPipeline[dict[str, Any], dict[str, Any]], PolicyProcessorPipeline[PolicyAction, PolicyAction], ]: """Instantiate LeRobot XVLA policy with preprocessor and postprocessor.""" if from_pretrained: policy = XVLAPolicy.from_pretrained( pretrained_name_or_path=model_path, strict=False, ) else: config = XVLAConfig( base_model_path=model_path, n_action_steps=DUMMY_ACTION_DIM, chunk_size=DUMMY_ACTION_DIM, device=DEVICE, num_image_views=NUM_VIEWS, ) # add resize_imgs_with_padding=IMAGE_SIZE, IMAGE_SIZE? policy = XVLAPolicy(config) policy.to(DEVICE) policy.config.device = DEVICE preprocessor, postprocessor = make_xvla_pre_post_processors( config=policy.config, dataset_stats=None, # Pass None for dataset_stats to disable normalization (original XVLA doesn't normalize) ) return policy, preprocessor, postprocessor def create_dummy_data(device=DEVICE): """Create dummy data for testing both implementations.""" batch_size = 1 prompt = "Pick up the red block and place it in the bin" # Create random RGB images in [0, 255] uint8 range (as PIL images would be) # Then convert to [0, 1] float32 range for LeRobot def fake_rgb(h, w): arr = np.random.randint(0, 255, (h, w, 3), dtype=np.uint8) t = torch.from_numpy(arr).permute(2, 0, 1) # CHW return t batch = { f"{OBS_IMAGES}.image": torch.stack( [fake_rgb(IMAGE_HEIGHT, IMAGE_WIDTH) for _ in range(batch_size)] ).to(device), f"{OBS_IMAGES}.image2": torch.stack( [fake_rgb(IMAGE_HEIGHT, IMAGE_WIDTH) for _ in range(batch_size)] ).to(device), OBS_STATE: torch.randn(batch_size, DUMMY_STATE_DIM, dtype=torch.float32, device=device), "task": [prompt for _ in range(batch_size)], } return batch # Pytest fixtures @pytest.fixture(scope="module") def xvla_components(): """Fixture to instantiate and provide all XVLA components for tests.""" print(f"\nTesting with DEVICE='{DEVICE}'") print("\n[Setup] Instantiating LeRobot XVLA policy...") policy_obj, preprocessor_obj, postprocessor_obj = instantiate_lerobot_xvla(from_pretrained=True) print("✔️ Model loaded successfully") yield policy_obj, preprocessor_obj, postprocessor_obj @pytest.fixture(scope="module") def policy(xvla_components): """Fixture to provide the XVLA policy for tests.""" return xvla_components[0] @pytest.fixture(scope="module") def preprocessor(xvla_components): """Fixture to provide the XVLA preprocessor for tests.""" return xvla_components[1] @require_cuda def test_xvla_preprocessor_alignment(policy, preprocessor): """Test that LeRobot XVLA preprocessor produces expected outputs.""" print("\n" + "=" * 80) print("Test: XVLA Preprocessor Outputs") print("=" * 80) set_seed_all(42) print("\nCreating dummy data...") batch = create_dummy_data() print("\n[LeRobot] Preprocessing...") lerobot_observation = preprocessor(deepcopy(batch)) lerobot_inputs = policy._build_model_inputs(lerobot_observation) print("\nVerifying preprocessor outputs:") print("-" * 80) # Expected shapes from tester.txt expected_shapes = { "domain_id": (1,), "input_ids": (1, 50), "proprio": (1, 20), "image_mask": (1, 2), "image_input": (1, 2, 3, 224, 224), } for key, expected_shape in expected_shapes.items(): if key in lerobot_inputs: actual_shape = tuple(lerobot_inputs[key].shape) print(f"\nKey: {key}") print(f"Expected shape: {expected_shape}") print(f"Actual shape: {actual_shape}") if actual_shape == expected_shape: print("Shape matches!") else: print("Shape mismatch!") assert actual_shape == expected_shape, f"Shape mismatch for {key}" else: print(f"\nKey '{key}' not found in inputs!") print("\nAll preprocessor outputs have correct shapes!") @require_cuda def test_xvla_action_generation(policy, preprocessor): """Test XVLA LeRobot implementation generates expected actions.""" print("\n" + "=" * 80) print("Test: XVLA Action Generation Against Expected Values") print("=" * 80) set_seed_all(42) print("\nCreating dummy data...") batch = create_dummy_data() print("\n[LeRobot] Running inference...") lerobot_observation = preprocessor(deepcopy(batch)) lerobot_inputs = policy._build_model_inputs(lerobot_observation) # Reset seed for inference torch.manual_seed(42) with torch.no_grad(): lerobot_actions = policy.model.generate_actions(**lerobot_inputs, steps=10) lerobot_actions = lerobot_actions.squeeze(0).float().cpu() print(f"LeRobot actions shape: {lerobot_actions.shape}") print(f"LeRobot actions mean: {lerobot_actions.mean().item():.6f}") print(f"LeRobot actions std: {lerobot_actions.std().item():.6f}") print(f"LeRobot actions first 5: {lerobot_actions[0, :5]}") print("\nExpected values (from original XVLA):") print(f"Expected actions shape: {EXPECTED_ACTIONS_SHAPE}") print(f"Expected actions mean: {EXPECTED_ACTIONS_MEAN:.6f}") print(f"Expected actions std: {EXPECTED_ACTIONS_STD:.6f}") print(f"Expected actions first 5: {EXPECTED_ACTIONS_FIRST_5}") print("\nAction Comparison:") print("-" * 80) # Compare shapes actual_shape = tuple(lerobot_actions.shape) assert actual_shape == EXPECTED_ACTIONS_SHAPE, ( f"Shape mismatch: {actual_shape} vs {EXPECTED_ACTIONS_SHAPE}" ) print(f"✔️ Shape matches: {actual_shape}") # Compare statistics actual_mean = lerobot_actions.mean().item() actual_std = lerobot_actions.std().item() mean_diff = abs(actual_mean - EXPECTED_ACTIONS_MEAN) std_diff = abs(actual_std - EXPECTED_ACTIONS_STD) print(f"\nMean: {actual_mean:.6f} (expected: {EXPECTED_ACTIONS_MEAN:.6f}, diff: {mean_diff:.6e})") print(f"Std: {actual_std:.6f} (expected: {EXPECTED_ACTIONS_STD:.6f}, diff: {std_diff:.6e})") # Compare first 5 actions actual_first_5 = lerobot_actions[0, :5] first_5_diff = torch.abs(actual_first_5 - EXPECTED_ACTIONS_FIRST_5) print("\nFirst 5 actions comparison:") print(f" Actual: {actual_first_5}") print(f" Expected: {EXPECTED_ACTIONS_FIRST_5}") print(f" Max diff: {first_5_diff.max().item():.6e}") print(f" Mean diff: {first_5_diff.mean().item():.6e}") # Check with different tolerances tolerances = [1e-5, 1e-4, 1e-3, 1e-2] for tol in tolerances: is_close = torch.allclose(actual_first_5, EXPECTED_ACTIONS_FIRST_5, atol=tol) status = "Success" if is_close else "Failure" print(f"{status}: First 5 actions close (atol={tol}): {is_close}") # Assert with reasonable tolerance tolerance = 1e-3 assert torch.allclose(actual_first_5, EXPECTED_ACTIONS_FIRST_5, atol=tolerance), ( f"First 5 actions differ by more than tolerance ({tolerance})" ) print(f"\nSuccess: Actions match expected values within tolerance ({tolerance})!") @require_cuda def test_xvla_inference_reproducibility(policy, preprocessor): """Test that XVLA inference is reproducible with the same seed.""" print("\n" + "=" * 80) print("Test: XVLA Inference Reproducibility") print("=" * 80) print("\nCreating dummy data...") batch = create_dummy_data() # First inference print("\n[Run 1] Running inference...") set_seed_all(42) lerobot_observation = preprocessor(deepcopy(batch)) lerobot_inputs = policy._build_model_inputs(lerobot_observation) with torch.no_grad(): actions_1 = policy.model.generate_actions(**lerobot_inputs, steps=10) actions_1 = actions_1.squeeze(0).float().cpu() # Second inference with same seed print("\n[Run 2] Running inference with same seed...") set_seed_all(42) lerobot_observation = preprocessor(deepcopy(batch)) lerobot_inputs = policy._build_model_inputs(lerobot_observation) with torch.no_grad(): actions_2 = policy.model.generate_actions(**lerobot_inputs, steps=10) actions_2 = actions_2.squeeze(0).float().cpu() print("\nComparing two runs:") print("-" * 80) if torch.allclose(actions_1, actions_2, atol=1e-8): print("Inference is perfectly reproducible!") else: diff = torch.abs(actions_1 - actions_2) print("Small differences detected:") print(f" Max diff: {diff.max().item():.6e}") print(f" Mean diff: {diff.mean().item():.6e}") assert torch.allclose(actions_1, actions_2, atol=1e-6), "Inference should be reproducible!" print("\nInference is reproducible!")
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/xvla/test_xvla_original_vs_lerobot.py", "license": "Apache License 2.0", "lines": 255, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:examples/unitree_g1/gr00t_locomotion.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 argparse import logging import time from collections import deque import numpy as np import onnxruntime as ort from huggingface_hub import hf_hub_download from lerobot.robots.unitree_g1.config_unitree_g1 import UnitreeG1Config from lerobot.robots.unitree_g1.g1_utils import G1_29_JointIndex from lerobot.robots.unitree_g1.unitree_g1 import UnitreeG1 logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) GROOT_DEFAULT_ANGLES = np.zeros(29, dtype=np.float32) GROOT_DEFAULT_ANGLES[[0, 6]] = -0.1 # Hip pitch GROOT_DEFAULT_ANGLES[[3, 9]] = 0.3 # Knee GROOT_DEFAULT_ANGLES[[4, 10]] = -0.2 # Ankle pitch MISSING_JOINTS = [] G1_MODEL = "g1_23" # Or "g1_29" if G1_MODEL == "g1_23": MISSING_JOINTS = [12, 14, 20, 21, 27, 28] # Waist yaw/pitch, wrist pitch/yaw # Control parameters ACTION_SCALE = 0.25 CONTROL_DT = 0.02 # 50Hz ANG_VEL_SCALE: float = 0.25 DOF_POS_SCALE: float = 1.0 DOF_VEL_SCALE: float = 0.05 CMD_SCALE: list = [2.0, 2.0, 0.25] DEFAULT_GROOT_REPO_ID = "nepyope/GR00T-WholeBodyControl_g1" def load_groot_policies( repo_id: str = DEFAULT_GROOT_REPO_ID, ) -> tuple[ort.InferenceSession, ort.InferenceSession]: """Load GR00T dual-policy system (Balance + Walk) from the hub. Args: repo_id: Hugging Face Hub repository ID containing the ONNX policies. """ logger.info(f"Loading GR00T dual-policy system from the hub ({repo_id})...") # Download ONNX policies from Hugging Face Hub balance_path = hf_hub_download( repo_id=repo_id, filename="GR00T-WholeBodyControl-Balance.onnx", ) walk_path = hf_hub_download( repo_id=repo_id, filename="GR00T-WholeBodyControl-Walk.onnx", ) # Load ONNX policies policy_balance = ort.InferenceSession(balance_path) policy_walk = ort.InferenceSession(walk_path) logger.info("GR00T policies loaded successfully") return policy_balance, policy_walk class GrootLocomotionController: """GR00T lower-body locomotion controller for the Unitree G1.""" def __init__(self, policy_balance, policy_walk, robot, config): self.policy_balance = policy_balance self.policy_walk = policy_walk self.robot = robot self.config = config self.cmd = np.array([0.0, 0.0, 0.0], dtype=np.float32) # vx, vy, theta_dot # Robot state self.groot_qj_all = np.zeros(29, dtype=np.float32) self.groot_dqj_all = np.zeros(29, dtype=np.float32) self.groot_action = np.zeros(15, dtype=np.float32) self.groot_obs_single = np.zeros(86, dtype=np.float32) self.groot_obs_history = deque(maxlen=6) self.groot_obs_stacked = np.zeros(516, dtype=np.float32) self.groot_height_cmd = 0.74 # Default base height self.groot_orientation_cmd = np.array([0.0, 0.0, 0.0], dtype=np.float32) # Input to GR00T is 6 frames (6*86D=516) for _ in range(6): self.groot_obs_history.append(np.zeros(86, dtype=np.float32)) logger.info("GrootLocomotionController initialized") def run_step(self): # Get current observation obs = self.robot.get_observation() if not obs: return # Get command from remote controller if obs["remote.buttons"][0]: # R1 - raise waist self.groot_height_cmd += 0.001 self.groot_height_cmd = np.clip(self.groot_height_cmd, 0.50, 1.00) if obs["remote.buttons"][4]: # R2 - lower waist self.groot_height_cmd -= 0.001 self.groot_height_cmd = np.clip(self.groot_height_cmd, 0.50, 1.00) self.cmd[0] = obs["remote.ly"] # Forward/backward self.cmd[1] = obs["remote.lx"] * -1 # Left/right self.cmd[2] = obs["remote.rx"] * -1 # Rotation rate # Get joint positions and velocities from flat dict for motor in G1_29_JointIndex: name = motor.name idx = motor.value self.groot_qj_all[idx] = obs[f"{name}.q"] self.groot_dqj_all[idx] = obs[f"{name}.dq"] # Adapt observation for g1_23dof for idx in MISSING_JOINTS: self.groot_qj_all[idx] = 0.0 self.groot_dqj_all[idx] = 0.0 # Scale joint positions and velocities qj_obs = self.groot_qj_all.copy() dqj_obs = self.groot_dqj_all.copy() # Express IMU data in gravity frame of reference quat = [obs["imu.quat.w"], obs["imu.quat.x"], obs["imu.quat.y"], obs["imu.quat.z"]] ang_vel = np.array([obs["imu.gyro.x"], obs["imu.gyro.y"], obs["imu.gyro.z"]], dtype=np.float32) gravity_orientation = self.robot.get_gravity_orientation(quat) # Scale joint positions and velocities before policy inference qj_obs = (qj_obs - GROOT_DEFAULT_ANGLES) * DOF_POS_SCALE dqj_obs = dqj_obs * DOF_VEL_SCALE ang_vel_scaled = ang_vel * ANG_VEL_SCALE # Build single frame observation self.groot_obs_single[:3] = self.cmd * np.array(CMD_SCALE) self.groot_obs_single[3] = self.groot_height_cmd self.groot_obs_single[4:7] = self.groot_orientation_cmd self.groot_obs_single[7:10] = ang_vel_scaled self.groot_obs_single[10:13] = gravity_orientation self.groot_obs_single[13:42] = qj_obs self.groot_obs_single[42:71] = dqj_obs self.groot_obs_single[71:86] = self.groot_action # 15D previous actions # Add to history and stack observations (6 frames × 86D = 516D) self.groot_obs_history.append(self.groot_obs_single.copy()) # Stack all 6 frames into 516D vector for i, obs_frame in enumerate(self.groot_obs_history): start_idx = i * 86 end_idx = start_idx + 86 self.groot_obs_stacked[start_idx:end_idx] = obs_frame cmd_magnitude = np.linalg.norm(self.cmd) selected_policy = ( self.policy_balance if cmd_magnitude < 0.05 else self.policy_walk ) # Balance/standing policy for small commands, walking policy for movement commands # Run policy inference ort_inputs = {selected_policy.get_inputs()[0].name: np.expand_dims(self.groot_obs_stacked, axis=0)} ort_outs = selected_policy.run(None, ort_inputs) self.groot_action = ort_outs[0].squeeze() # Transform action back to target joint positions target_dof_pos_15 = GROOT_DEFAULT_ANGLES[:15] + self.groot_action * ACTION_SCALE # Build action dict (only first 15 joints for GR00T) action_dict = {} for i in range(15): motor_name = G1_29_JointIndex(i).name action_dict[f"{motor_name}.q"] = float(target_dof_pos_15[i]) # Zero out missing joints for g1_23dof for joint_idx in MISSING_JOINTS: motor_name = G1_29_JointIndex(joint_idx).name action_dict[f"{motor_name}.q"] = 0.0 # Send action to robot self.robot.send_action(action_dict) def run(repo_id: str = DEFAULT_GROOT_REPO_ID) -> None: """Main function to run the GR00T locomotion controller. Args: repo_id: Hugging Face Hub repository ID for GR00T policies. """ # Load policies policy_balance, policy_walk = load_groot_policies(repo_id=repo_id) # Initialize robot config = UnitreeG1Config() robot = UnitreeG1(config) robot.connect() # Initialize gr00T locomotion controller groot_controller = GrootLocomotionController( policy_balance=policy_balance, policy_walk=policy_walk, robot=robot, config=config, ) try: robot.reset(CONTROL_DT, GROOT_DEFAULT_ANGLES) logger.info("Use joystick: LY=fwd/back, LX=left/right, RX=rotate, R1=raise waist, R2=lower waist") logger.info("Press Ctrl+C to stop") # Run step while not robot._shutdown_event.is_set(): start_time = time.time() groot_controller.run_step() elapsed = time.time() - start_time sleep_time = max(0, CONTROL_DT - elapsed) time.sleep(sleep_time) except KeyboardInterrupt: logger.info("Stopping locomotion...") finally: if robot.is_connected: robot.disconnect() logger.info("Done!") if __name__ == "__main__": parser = argparse.ArgumentParser(description="GR00T Locomotion Controller for Unitree G1") parser.add_argument( "--repo-id", type=str, default=DEFAULT_GROOT_REPO_ID, help=f"Hugging Face Hub repo ID for GR00T policies (default: {DEFAULT_GROOT_REPO_ID})", ) args = parser.parse_args() run(repo_id=args.repo_id)
{ "repo_id": "huggingface/lerobot", "file_path": "examples/unitree_g1/gr00t_locomotion.py", "license": "Apache License 2.0", "lines": 203, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/unitree_g1/config_unitree_g1.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass, field from lerobot.cameras import CameraConfig from ..config import RobotConfig _GAINS: dict[str, dict[str, list[float]]] = { "left_leg": { "kp": [150, 150, 150, 300, 40, 40], "kd": [2, 2, 2, 4, 2, 2], }, # pitch, roll, yaw, knee, ankle_pitch, ankle_roll "right_leg": {"kp": [150, 150, 150, 300, 40, 40], "kd": [2, 2, 2, 4, 2, 2]}, "waist": {"kp": [250, 250, 250], "kd": [5, 5, 5]}, # yaw, roll, pitch "left_arm": {"kp": [80, 80, 80, 80], "kd": [3, 3, 3, 3]}, # shoulder_pitch/roll/yaw, elbow "left_wrist": {"kp": [40, 40, 40], "kd": [1.5, 1.5, 1.5]}, # roll, pitch, yaw "right_arm": {"kp": [80, 80, 80, 80], "kd": [3, 3, 3, 3]}, "right_wrist": {"kp": [40, 40, 40], "kd": [1.5, 1.5, 1.5]}, "other": {"kp": [80, 80, 80, 80, 80, 80], "kd": [3, 3, 3, 3, 3, 3]}, } def _build_gains() -> tuple[list[float], list[float]]: """Build kp and kd lists from body-part groupings.""" kp = [v for g in _GAINS.values() for v in g["kp"]] kd = [v for g in _GAINS.values() for v in g["kd"]] return kp, kd _DEFAULT_KP, _DEFAULT_KD = _build_gains() @RobotConfig.register_subclass("unitree_g1") @dataclass class UnitreeG1Config(RobotConfig): kp: list[float] = field(default_factory=lambda: _DEFAULT_KP.copy()) kd: list[float] = field(default_factory=lambda: _DEFAULT_KD.copy()) # Default joint positions default_positions: list[float] = field(default_factory=lambda: [0.0] * 29) # Control loop timestep control_dt: float = 1.0 / 250.0 # 250Hz # Launch mujoco simulation is_simulation: bool = True # Socket config for ZMQ bridge robot_ip: str = "192.168.123.164" # default G1 IP # Cameras (ZMQ-based remote cameras) cameras: dict[str, CameraConfig] = field(default_factory=dict) # Compensates for gravity on the unitree's arms using the arm ik solver gravity_compensation: bool = False
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/unitree_g1/config_unitree_g1.py", "license": "Apache License 2.0", "lines": 53, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/unitree_g1/g1_utils.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 enum import IntEnum # ruff: noqa: N801, N815 NUM_MOTORS = 29 class G1_29_JointArmIndex(IntEnum): # Left arm kLeftShoulderPitch = 15 kLeftShoulderRoll = 16 kLeftShoulderYaw = 17 kLeftElbow = 18 kLeftWristRoll = 19 kLeftWristPitch = 20 kLeftWristyaw = 21 # Right arm kRightShoulderPitch = 22 kRightShoulderRoll = 23 kRightShoulderYaw = 24 kRightElbow = 25 kRightWristRoll = 26 kRightWristPitch = 27 kRightWristYaw = 28 class G1_29_JointIndex(IntEnum): # Left leg kLeftHipPitch = 0 kLeftHipRoll = 1 kLeftHipYaw = 2 kLeftKnee = 3 kLeftAnklePitch = 4 kLeftAnkleRoll = 5 # Right leg kRightHipPitch = 6 kRightHipRoll = 7 kRightHipYaw = 8 kRightKnee = 9 kRightAnklePitch = 10 kRightAnkleRoll = 11 kWaistYaw = 12 kWaistRoll = 13 kWaistPitch = 14 # Left arm kLeftShoulderPitch = 15 kLeftShoulderRoll = 16 kLeftShoulderYaw = 17 kLeftElbow = 18 kLeftWristRoll = 19 kLeftWristPitch = 20 kLeftWristyaw = 21 # Right arm kRightShoulderPitch = 22 kRightShoulderRoll = 23 kRightShoulderYaw = 24 kRightElbow = 25 kRightWristRoll = 26 kRightWristPitch = 27 kRightWristYaw = 28
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/unitree_g1/g1_utils.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/unitree_g1/run_g1_server.py
#!/usr/bin/env python3 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ DDS-to-ZMQ bridge server for Unitree G1 robot. This server runs on the robot and forwards: - Robot state (LowState) from DDS to ZMQ (for remote clients) - Robot commands (LowCmd) from ZMQ to DDS (from remote clients) Uses JSON for secure serialization instead of pickle. """ import base64 import contextlib import json import threading import time from typing import Any import zmq from unitree_sdk2py.comm.motion_switcher.motion_switcher_client import MotionSwitcherClient from unitree_sdk2py.core.channel import ChannelFactoryInitialize, ChannelPublisher, ChannelSubscriber from unitree_sdk2py.idl.default import unitree_hg_msg_dds__LowCmd_ from unitree_sdk2py.idl.unitree_hg.msg.dds_ import LowCmd_ as hg_LowCmd, LowState_ as hg_LowState from unitree_sdk2py.utils.crc import CRC # DDS topic names follow Unitree SDK naming conventions # ruff: noqa: N816 kTopicLowCommand_Debug = "rt/lowcmd" # action to robot kTopicLowState = "rt/lowstate" # observation from robot LOWCMD_PORT = 6000 LOWSTATE_PORT = 6001 NUM_MOTORS = 35 def lowstate_to_dict(msg: hg_LowState) -> dict[str, Any]: """Convert LowState SDK message to a JSON-serializable dictionary.""" motor_states = [] for i in range(NUM_MOTORS): temp = msg.motor_state[i].temperature avg_temp = float(sum(temp) / len(temp)) if isinstance(temp, list) else float(temp) motor_states.append( { "q": float(msg.motor_state[i].q), "dq": float(msg.motor_state[i].dq), "tau_est": float(msg.motor_state[i].tau_est), "temperature": avg_temp, } ) return { "motor_state": motor_states, "imu_state": { "quaternion": [float(x) for x in msg.imu_state.quaternion], "gyroscope": [float(x) for x in msg.imu_state.gyroscope], "accelerometer": [float(x) for x in msg.imu_state.accelerometer], "rpy": [float(x) for x in msg.imu_state.rpy], "temperature": float(msg.imu_state.temperature), }, # Encode bytes as base64 for JSON compatibility "wireless_remote": base64.b64encode(bytes(msg.wireless_remote)).decode("ascii"), "mode_machine": int(msg.mode_machine), } def dict_to_lowcmd(data: dict[str, Any]) -> hg_LowCmd: """Convert dictionary back to LowCmd SDK message.""" cmd = unitree_hg_msg_dds__LowCmd_() cmd.mode_pr = data.get("mode_pr", 0) cmd.mode_machine = data.get("mode_machine", 0) for i, motor_data in enumerate(data.get("motor_cmd", [])): cmd.motor_cmd[i].mode = motor_data.get("mode", 0) cmd.motor_cmd[i].q = motor_data.get("q", 0.0) cmd.motor_cmd[i].dq = motor_data.get("dq", 0.0) cmd.motor_cmd[i].kp = motor_data.get("kp", 0.0) cmd.motor_cmd[i].kd = motor_data.get("kd", 0.0) cmd.motor_cmd[i].tau = motor_data.get("tau", 0.0) return cmd def state_forward_loop( lowstate_sub: ChannelSubscriber, lowstate_sock: zmq.Socket, state_period: float, shutdown_event: threading.Event, ) -> None: """Read observation from DDS and forward to ZMQ clients.""" last_state_time = 0.0 while not shutdown_event.is_set(): # read from DDS msg = lowstate_sub.Read() if msg is None: continue now = time.time() # optional downsampling (if robot dds rate > state_period) if now - last_state_time >= state_period: # Convert to dict and serialize with JSON state_dict = lowstate_to_dict(msg) payload = json.dumps({"topic": kTopicLowState, "data": state_dict}).encode("utf-8") # if no subscribers / tx buffer full, just drop with contextlib.suppress(zmq.Again): lowstate_sock.send(payload, zmq.NOBLOCK) last_state_time = now def cmd_forward_loop( lowcmd_sock: zmq.Socket, lowcmd_pub_debug: ChannelPublisher, crc: CRC, ) -> None: """Receive commands from ZMQ and forward to DDS.""" while True: try: payload = lowcmd_sock.recv() except zmq.ContextTerminated: break msg_dict = json.loads(payload.decode("utf-8")) topic = msg_dict.get("topic", "") cmd_data = msg_dict.get("data", {}) # Reconstruct LowCmd object from dict cmd = dict_to_lowcmd(cmd_data) # recompute crc cmd.crc = crc.Crc(cmd) if topic == kTopicLowCommand_Debug: lowcmd_pub_debug.Write(cmd) def main() -> None: """Main entry point for the robot server bridge.""" # initialize DDS ChannelFactoryInitialize(0) # stop all active publishers on the robot msc = MotionSwitcherClient() msc.SetTimeout(5.0) msc.Init() status, result = msc.CheckMode() while result is not None and "name" in result and result["name"]: msc.ReleaseMode() status, result = msc.CheckMode() time.sleep(1.0) crc = CRC() # initialize DDS publisher lowcmd_pub_debug = ChannelPublisher(kTopicLowCommand_Debug, hg_LowCmd) lowcmd_pub_debug.Init() # initialize DDS subscriber lowstate_sub = ChannelSubscriber(kTopicLowState, hg_LowState) lowstate_sub.Init() # initialize ZMQ ctx = zmq.Context.instance() # receive commands from remote client lowcmd_sock = ctx.socket(zmq.PULL) lowcmd_sock.bind(f"tcp://0.0.0.0:{LOWCMD_PORT}") # publish state to remote clients lowstate_sock = ctx.socket(zmq.PUB) lowstate_sock.bind(f"tcp://0.0.0.0:{LOWSTATE_PORT}") state_period = 0.002 # ~500 hz shutdown_event = threading.Event() # start observation forwarding in background thread t_state = threading.Thread( target=state_forward_loop, args=(lowstate_sub, lowstate_sock, state_period, shutdown_event), ) t_state.start() print("bridge running (lowstate -> zmq, lowcmd -> dds)") # run command forwarding in main thread try: cmd_forward_loop(lowcmd_sock, lowcmd_pub_debug, crc) except KeyboardInterrupt: print("shutting down bridge...") finally: shutdown_event.set() ctx.term() # terminates blocking zmq.recv() calls t_state.join(timeout=2.0) if __name__ == "__main__": main()
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/unitree_g1/run_g1_server.py", "license": "Apache License 2.0", "lines": 171, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/unitree_g1/unitree_g1.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 logging import struct import threading import time from dataclasses import dataclass, field from functools import cached_property from typing import Any import numpy as np from lerobot.cameras.utils import make_cameras_from_configs from lerobot.envs.factory import make_env from lerobot.processor import RobotAction, RobotObservation from lerobot.robots.unitree_g1.g1_utils import G1_29_JointArmIndex, G1_29_JointIndex from lerobot.robots.unitree_g1.robot_kinematic_processor import G1_29_ArmIK from ..robot import Robot from .config_unitree_g1 import UnitreeG1Config logger = logging.getLogger(__name__) # DDS topic names follow Unitree SDK naming conventions # ruff: noqa: N816 kTopicLowCommand_Debug = "rt/lowcmd" kTopicLowState = "rt/lowstate" @dataclass class MotorState: q: float | None = None # position dq: float | None = None # velocity tau_est: float | None = None # estimated torque temperature: float | None = None # motor temperature @dataclass class IMUState: quaternion: np.ndarray | None = None # [w, x, y, z] gyroscope: np.ndarray | None = None # [x, y, z] angular velocity (rad/s) accelerometer: np.ndarray | None = None # [x, y, z] linear acceleration (m/s²) rpy: np.ndarray | None = None # [roll, pitch, yaw] (rad) temperature: float | None = None # IMU temperature # g1 observation class @dataclass class G1_29_LowState: # noqa: N801 motor_state: list[MotorState] = field(default_factory=lambda: [MotorState() for _ in G1_29_JointIndex]) imu_state: IMUState = field(default_factory=IMUState) wireless_remote: Any = None # Raw wireless remote data mode_machine: int = 0 # Robot mode class UnitreeG1(Robot): config_class = UnitreeG1Config name = "unitree_g1" # unitree remote controller class RemoteController: def __init__(self): self.lx = 0 self.ly = 0 self.rx = 0 self.ry = 0 self.button = [0] * 16 def set(self, data): # wireless_remote keys = struct.unpack("H", data[2:4])[0] for i in range(16): self.button[i] = (keys & (1 << i)) >> i self.lx = struct.unpack("f", data[4:8])[0] self.rx = struct.unpack("f", data[8:12])[0] self.ry = struct.unpack("f", data[12:16])[0] self.ly = struct.unpack("f", data[20:24])[0] def __init__(self, config: UnitreeG1Config): super().__init__(config) logger.info("Initialize UnitreeG1...") self.config = config self.control_dt = config.control_dt # Initialize cameras config (ZMQ-based) - actual connection in connect() self._cameras = make_cameras_from_configs(config.cameras) # Import channel classes based on mode if config.is_simulation: from unitree_sdk2py.core.channel import ( ChannelFactoryInitialize, ChannelPublisher, ChannelSubscriber, ) else: from lerobot.robots.unitree_g1.unitree_sdk2_socket import ( ChannelFactoryInitialize, ChannelPublisher, ChannelSubscriber, ) # Store for use in connect() self._ChannelFactoryInitialize = ChannelFactoryInitialize self._ChannelPublisher = ChannelPublisher self._ChannelSubscriber = ChannelSubscriber # Initialize state variables self.sim_env = None self._env_wrapper = None self._lowstate = None self._shutdown_event = threading.Event() self.subscribe_thread = None self.remote_controller = self.RemoteController() self.arm_ik = G1_29_ArmIK() def _subscribe_motor_state(self): # polls robot state @ 250Hz while not self._shutdown_event.is_set(): start_time = time.time() # Step simulation if in simulation mode if self.config.is_simulation and self.sim_env is not None: self.sim_env.step() msg = self.lowstate_subscriber.Read() if msg is not None: lowstate = G1_29_LowState() # Capture motor states using jointindex for id in G1_29_JointIndex: lowstate.motor_state[id].q = msg.motor_state[id].q lowstate.motor_state[id].dq = msg.motor_state[id].dq lowstate.motor_state[id].tau_est = msg.motor_state[id].tau_est lowstate.motor_state[id].temperature = msg.motor_state[id].temperature # Capture IMU state lowstate.imu_state.quaternion = list(msg.imu_state.quaternion) lowstate.imu_state.gyroscope = list(msg.imu_state.gyroscope) lowstate.imu_state.accelerometer = list(msg.imu_state.accelerometer) lowstate.imu_state.rpy = list(msg.imu_state.rpy) lowstate.imu_state.temperature = msg.imu_state.temperature # Capture wireless remote data lowstate.wireless_remote = msg.wireless_remote # Capture mode_machine lowstate.mode_machine = msg.mode_machine self._lowstate = lowstate current_time = time.time() all_t_elapsed = current_time - start_time sleep_time = max(0, (self.control_dt - all_t_elapsed)) # maintain constant control dt time.sleep(sleep_time) @cached_property def action_features(self) -> dict[str, type]: return {f"{G1_29_JointIndex(motor).name}.q": float for motor in G1_29_JointIndex} def calibrate(self) -> None: # robot is already calibrated pass def configure(self) -> None: pass def connect(self, calibrate: bool = True) -> None: # connect to DDS from unitree_sdk2py.idl.default import unitree_hg_msg_dds__LowCmd_ from unitree_sdk2py.idl.unitree_hg.msg.dds_ import ( LowCmd_ as hg_LowCmd, LowState_ as hg_LowState, ) from unitree_sdk2py.utils.crc import CRC # Initialize DDS channel and simulation environment if self.config.is_simulation: self._ChannelFactoryInitialize(0, "lo") self._env_wrapper = make_env("lerobot/unitree-g1-mujoco", trust_remote_code=True) # Extract the actual gym env from the dict structure self.sim_env = self._env_wrapper["hub_env"][0].envs[0] else: self._ChannelFactoryInitialize(0) # Initialize direct motor control interface self.lowcmd_publisher = self._ChannelPublisher(kTopicLowCommand_Debug, hg_LowCmd) self.lowcmd_publisher.Init() self.lowstate_subscriber = self._ChannelSubscriber(kTopicLowState, hg_LowState) self.lowstate_subscriber.Init() # Start subscribe thread to read robot state self.subscribe_thread = threading.Thread(target=self._subscribe_motor_state) self.subscribe_thread.start() # Connect cameras for cam in self._cameras.values(): if not cam.is_connected: cam.connect() logger.info(f"Connected {len(self._cameras)} camera(s).") # Initialize lowcmd message self.crc = CRC() self.msg = unitree_hg_msg_dds__LowCmd_() self.msg.mode_pr = 0 # Wait for first state message to arrive lowstate = None while lowstate is None: lowstate = self._lowstate if lowstate is None: time.sleep(0.01) logger.warning("[UnitreeG1] Waiting for robot state...") logger.warning("[UnitreeG1] Connected to robot.") self.msg.mode_machine = lowstate.mode_machine # Initialize all motors with unified kp/kd from config self.kp = np.array(self.config.kp, dtype=np.float32) self.kd = np.array(self.config.kd, dtype=np.float32) for id in G1_29_JointIndex: self.msg.motor_cmd[id].mode = 1 self.msg.motor_cmd[id].kp = self.kp[id.value] self.msg.motor_cmd[id].kd = self.kd[id.value] self.msg.motor_cmd[id].q = lowstate.motor_state[id.value].q def disconnect(self): # Signal thread to stop and unblock any waits self._shutdown_event.set() # Wait for subscribe thread to finish if self.subscribe_thread is not None: self.subscribe_thread.join(timeout=2.0) if self.subscribe_thread.is_alive(): logger.warning("Subscribe thread did not stop cleanly") # Close simulation environment if self.config.is_simulation and self.sim_env is not None: try: # Force-kill the image publish subprocess first to avoid long waits if hasattr(self.sim_env, "simulator") and hasattr(self.sim_env.simulator, "sim_env"): sim_env_inner = self.sim_env.simulator.sim_env if hasattr(sim_env_inner, "image_publish_process"): proc = sim_env_inner.image_publish_process if proc.process and proc.process.is_alive(): logger.info("Force-terminating image publish subprocess...") proc.stop_event.set() proc.process.terminate() proc.process.join(timeout=1) if proc.process.is_alive(): proc.process.kill() self.sim_env.close() except Exception as e: logger.warning(f"Error closing sim_env: {e}") self.sim_env = None self._env_wrapper = None # Disconnect cameras for cam in self._cameras.values(): cam.disconnect() def get_observation(self) -> RobotObservation: lowstate = self._lowstate if lowstate is None: return {} obs = {} # Motors - q, dq, tau for all joints for motor in G1_29_JointIndex: name = motor.name idx = motor.value obs[f"{name}.q"] = lowstate.motor_state[idx].q obs[f"{name}.dq"] = lowstate.motor_state[idx].dq obs[f"{name}.tau"] = lowstate.motor_state[idx].tau_est # IMU - gyroscope if lowstate.imu_state.gyroscope: obs["imu.gyro.x"] = lowstate.imu_state.gyroscope[0] obs["imu.gyro.y"] = lowstate.imu_state.gyroscope[1] obs["imu.gyro.z"] = lowstate.imu_state.gyroscope[2] # IMU - accelerometer if lowstate.imu_state.accelerometer: obs["imu.accel.x"] = lowstate.imu_state.accelerometer[0] obs["imu.accel.y"] = lowstate.imu_state.accelerometer[1] obs["imu.accel.z"] = lowstate.imu_state.accelerometer[2] # IMU - quaternion if lowstate.imu_state.quaternion: obs["imu.quat.w"] = lowstate.imu_state.quaternion[0] obs["imu.quat.x"] = lowstate.imu_state.quaternion[1] obs["imu.quat.y"] = lowstate.imu_state.quaternion[2] obs["imu.quat.z"] = lowstate.imu_state.quaternion[3] # IMU - rpy if lowstate.imu_state.rpy: obs["imu.rpy.roll"] = lowstate.imu_state.rpy[0] obs["imu.rpy.pitch"] = lowstate.imu_state.rpy[1] obs["imu.rpy.yaw"] = lowstate.imu_state.rpy[2] # Controller - parse wireless_remote and add to obs if lowstate.wireless_remote and len(lowstate.wireless_remote) >= 24: self.remote_controller.set(lowstate.wireless_remote) obs["remote.buttons"] = self.remote_controller.button.copy() obs["remote.lx"] = self.remote_controller.lx obs["remote.ly"] = self.remote_controller.ly obs["remote.rx"] = self.remote_controller.rx obs["remote.ry"] = self.remote_controller.ry # Cameras - read images from ZMQ cameras for cam_name, cam in self._cameras.items(): obs[cam_name] = cam.read_latest() return obs @property def is_calibrated(self) -> bool: return True @property def is_connected(self) -> bool: return self._lowstate is not None @property def _motors_ft(self) -> dict[str, type]: return {f"{G1_29_JointIndex(motor).name}.q": float for motor in G1_29_JointIndex} @property def cameras(self) -> dict: return self._cameras @property def _cameras_ft(self) -> dict[str, tuple]: return { cam: (self.config.cameras[cam].height, self.config.cameras[cam].width, 3) for cam in self.cameras } @cached_property def observation_features(self) -> dict[str, type | tuple]: return {**self._motors_ft, **self._cameras_ft} def send_action(self, action: RobotAction) -> RobotAction: for motor in G1_29_JointIndex: key = f"{motor.name}.q" if key in action: self.msg.motor_cmd[motor.value].q = action[key] self.msg.motor_cmd[motor.value].qd = 0 self.msg.motor_cmd[motor.value].kp = self.kp[motor.value] self.msg.motor_cmd[motor.value].kd = self.kd[motor.value] self.msg.motor_cmd[motor.value].tau = 0 if self.config.gravity_compensation: # Build action_np from motor commands (arm joints are indices 15-28, local indices 0-13) action_np = np.zeros(14) arm_start_idx = G1_29_JointArmIndex.kLeftShoulderPitch.value # 15 for joint in G1_29_JointArmIndex: local_idx = joint.value - arm_start_idx action_np[local_idx] = self.msg.motor_cmd[joint.value].q tau = self.arm_ik.solve_tau(action_np) # Apply tau back to motor commands for joint in G1_29_JointArmIndex: local_idx = joint.value - arm_start_idx self.msg.motor_cmd[joint.value].tau = tau[local_idx] self.msg.crc = self.crc.Crc(self.msg) self.lowcmd_publisher.Write(self.msg) return action def get_gravity_orientation(self, quaternion): # get gravity orientation from quaternion """Get gravity orientation from quaternion.""" qw = quaternion[0] qx = quaternion[1] qy = quaternion[2] qz = quaternion[3] gravity_orientation = np.zeros(3) gravity_orientation[0] = 2 * (-qz * qx + qw * qy) gravity_orientation[1] = -2 * (qz * qy + qw * qx) gravity_orientation[2] = 1 - 2 * (qw * qw + qz * qz) return gravity_orientation def reset( self, control_dt: float | None = None, default_positions: list[float] | None = None, ) -> None: # move robot to default position if control_dt is None: control_dt = self.config.control_dt if default_positions is None: default_positions = np.array(self.config.default_positions, dtype=np.float32) if self.config.is_simulation and self.sim_env is not None: self.sim_env.reset() for motor in G1_29_JointIndex: self.msg.motor_cmd[motor.value].q = default_positions[motor.value] self.msg.motor_cmd[motor.value].qd = 0 self.msg.motor_cmd[motor.value].kp = self.kp[motor.value] self.msg.motor_cmd[motor.value].kd = self.kd[motor.value] self.msg.motor_cmd[motor.value].tau = 0 self.msg.crc = self.crc.Crc(self.msg) self.lowcmd_publisher.Write(self.msg) else: total_time = 3.0 num_steps = int(total_time / control_dt) # get current state obs = self.get_observation() # record current positions init_dof_pos = np.zeros(29, dtype=np.float32) for motor in G1_29_JointIndex: init_dof_pos[motor.value] = obs[f"{motor.name}.q"] # Interpolate to default position for step in range(num_steps): start_time = time.time() alpha = step / num_steps action_dict = {} for motor in G1_29_JointIndex: target_pos = default_positions[motor.value] interp_pos = init_dof_pos[motor.value] * (1 - alpha) + target_pos * alpha action_dict[f"{motor.name}.q"] = float(interp_pos) self.send_action(action_dict) # Maintain constant control rate elapsed = time.time() - start_time sleep_time = max(0, control_dt - elapsed) time.sleep(sleep_time) logger.info("Reached default position")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/unitree_g1/unitree_g1.py", "license": "Apache License 2.0", "lines": 366, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/robots/unitree_g1/unitree_sdk2_socket.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 base64 import json from typing import Any import zmq from lerobot.robots.unitree_g1.config_unitree_g1 import UnitreeG1Config _ctx: zmq.Context | None = None _lowcmd_sock: zmq.Socket | None = None _lowstate_sock: zmq.Socket | None = None LOWCMD_PORT = 6000 LOWSTATE_PORT = 6001 # DDS topic names follow Unitree SDK naming conventions # ruff: noqa: N816 kTopicLowCommand_Debug = "rt/lowcmd" class LowStateMsg: """ Wrapper class that mimics the Unitree SDK LowState_ message structure. Reconstructs the message from deserialized JSON data to maintain compatibility with existing code that expects SDK message objects. """ class MotorState: """Motor state data for a single joint.""" def __init__(self, data: dict[str, Any]) -> None: self.q: float = data.get("q", 0.0) self.dq: float = data.get("dq", 0.0) self.tau_est: float = data.get("tau_est", 0.0) self.temperature: float = data.get("temperature", 0.0) class IMUState: """IMU sensor data.""" def __init__(self, data: dict[str, Any]) -> None: self.quaternion: list[float] = data.get("quaternion", [1.0, 0.0, 0.0, 0.0]) self.gyroscope: list[float] = data.get("gyroscope", [0.0, 0.0, 0.0]) self.accelerometer: list[float] = data.get("accelerometer", [0.0, 0.0, 0.0]) self.rpy: list[float] = data.get("rpy", [0.0, 0.0, 0.0]) self.temperature: float = data.get("temperature", 0.0) def __init__(self, data: dict[str, Any]) -> None: """Initialize from deserialized JSON data.""" self.motor_state = [self.MotorState(m) for m in data.get("motor_state", [])] self.imu_state = self.IMUState(data.get("imu_state", {})) # Decode base64-encoded wireless_remote bytes wireless_b64 = data.get("wireless_remote", "") self.wireless_remote: bytes = base64.b64decode(wireless_b64) if wireless_b64 else b"" self.mode_machine: int = data.get("mode_machine", 0) def lowcmd_to_dict(topic: str, msg: Any) -> dict[str, Any]: """Convert LowCmd message to a JSON-serializable dictionary.""" motor_cmds = [] # Iterate over all motor commands in the message for i in range(len(msg.motor_cmd)): motor_cmds.append( { "mode": int(msg.motor_cmd[i].mode), "q": float(msg.motor_cmd[i].q), "dq": float(msg.motor_cmd[i].dq), "kp": float(msg.motor_cmd[i].kp), "kd": float(msg.motor_cmd[i].kd), "tau": float(msg.motor_cmd[i].tau), } ) return { "topic": topic, "data": { "mode_pr": int(msg.mode_pr), "mode_machine": int(msg.mode_machine), "motor_cmd": motor_cmds, }, } def ChannelFactoryInitialize(*args: Any, **kwargs: Any) -> None: # noqa: N802 """ Initialize ZMQ sockets for robot communication. This function mimics the Unitree SDK's ChannelFactoryInitialize but uses ZMQ sockets to connect to the robot server bridge instead of DDS. """ global _ctx, _lowcmd_sock, _lowstate_sock # read socket config config = UnitreeG1Config() robot_ip = config.robot_ip ctx = zmq.Context.instance() _ctx = ctx # lowcmd: send robot commands lowcmd_sock = ctx.socket(zmq.PUSH) lowcmd_sock.setsockopt(zmq.CONFLATE, 1) # keep only last message lowcmd_sock.connect(f"tcp://{robot_ip}:{LOWCMD_PORT}") _lowcmd_sock = lowcmd_sock # lowstate: receive robot observations lowstate_sock = ctx.socket(zmq.SUB) lowstate_sock.setsockopt(zmq.CONFLATE, 1) # keep only last message lowstate_sock.connect(f"tcp://{robot_ip}:{LOWSTATE_PORT}") lowstate_sock.setsockopt_string(zmq.SUBSCRIBE, "") _lowstate_sock = lowstate_sock class ChannelPublisher: """ZMQ-based publisher that sends commands to the robot server.""" def __init__(self, topic: str, msg_type: type) -> None: self.topic = topic self.msg_type = msg_type def Init(self) -> None: # noqa: N802 """Initialize the publisher (no-op for ZMQ).""" pass def Write(self, msg: Any) -> None: # noqa: N802 """Serialize and send a command message to the robot.""" if _lowcmd_sock is None: raise RuntimeError("ChannelFactoryInitialize must be called first") payload = json.dumps(lowcmd_to_dict(self.topic, msg)).encode("utf-8") _lowcmd_sock.send(payload) class ChannelSubscriber: """ZMQ-based subscriber that receives state from the robot server.""" def __init__(self, topic: str, msg_type: type) -> None: self.topic = topic self.msg_type = msg_type def Init(self) -> None: # noqa: N802 """Initialize the subscriber (no-op for ZMQ).""" pass def Read(self) -> LowStateMsg: # noqa: N802 """Receive and deserialize a state message from the robot.""" if _lowstate_sock is None: raise RuntimeError("ChannelFactoryInitialize must be called first") payload = _lowstate_sock.recv() msg_dict = json.loads(payload.decode("utf-8")) return LowStateMsg(msg_dict.get("data", {}))
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/robots/unitree_g1/unitree_sdk2_socket.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/processor/env_processor.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 dataclasses import dataclass import torch from lerobot.configs.types import FeatureType, PipelineFeatureType, PolicyFeature from lerobot.utils.constants import OBS_IMAGES, OBS_PREFIX, OBS_STATE, OBS_STR from .pipeline import ObservationProcessorStep, ProcessorStepRegistry @dataclass @ProcessorStepRegistry.register(name="libero_processor") class LiberoProcessorStep(ObservationProcessorStep): """ Processes LIBERO observations into the LeRobot format. This step handles the specific observation structure from LIBERO environments, which includes nested robot_state dictionaries and image observations. **State Processing:** - Processes the `robot_state` dictionary which contains nested end-effector, gripper, and joint information. - Extracts and concatenates: - End-effector position (3D) - End-effector quaternion converted to axis-angle (3D) - Gripper joint positions (2D) - Maps the concatenated state to `"observation.state"`. **Image Processing:** - Rotates images by 180 degrees by flipping both height and width dimensions. - This accounts for the HuggingFaceVLA/libero camera orientation convention. """ def _process_observation(self, observation): """ Processes both image and robot_state observations from LIBERO. """ processed_obs = observation.copy() for key in list(processed_obs.keys()): if key.startswith(f"{OBS_IMAGES}."): img = processed_obs[key] # Flip both H and W img = torch.flip(img, dims=[2, 3]) processed_obs[key] = img # Process robot_state into a flat state vector observation_robot_state_str = OBS_PREFIX + "robot_state" if observation_robot_state_str in processed_obs: robot_state = processed_obs.pop(observation_robot_state_str) # Extract components eef_pos = robot_state["eef"]["pos"] # (B, 3,) eef_quat = robot_state["eef"]["quat"] # (B, 4,) gripper_qpos = robot_state["gripper"]["qpos"] # (B, 2,) # Convert quaternion to axis-angle eef_axisangle = self._quat2axisangle(eef_quat) # (B, 3) # Concatenate into a single state vector state = torch.cat((eef_pos, eef_axisangle, gripper_qpos), dim=-1) # ensure float32 state = state.float() if state.dim() == 1: state = state.unsqueeze(0) processed_obs[OBS_STATE] = state return processed_obs def transform_features( self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]] ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]: """ Transforms feature keys from the LIBERO format to the LeRobot standard. """ new_features: dict[PipelineFeatureType, dict[str, PolicyFeature]] = {} # copy over non-STATE features for ft, feats in features.items(): if ft != FeatureType.STATE: new_features[ft] = feats.copy() # rebuild STATE features state_feats = {} # add our new flattened state state_feats[OBS_STATE] = PolicyFeature( type=FeatureType.STATE, shape=(8,), # [eef_pos(3), axis_angle(3), gripper(2)] ) new_features[FeatureType.STATE] = state_feats return new_features def observation(self, observation): return self._process_observation(observation) def _quat2axisangle(self, quat: torch.Tensor) -> torch.Tensor: """ Convert batched quaternions to axis-angle format. Only accepts torch tensors of shape (B, 4). Args: quat (Tensor): (B, 4) tensor of quaternions in (x, y, z, w) format Returns: Tensor: (B, 3) axis-angle vectors Raises: TypeError: if input is not a torch tensor ValueError: if shape is not (B, 4) """ if not isinstance(quat, torch.Tensor): raise TypeError(f"_quat2axisangle expected a torch.Tensor, got {type(quat)}") if quat.ndim != 2 or quat.shape[1] != 4: raise ValueError(f"_quat2axisangle expected shape (B, 4), got {tuple(quat.shape)}") quat = quat.to(dtype=torch.float32) device = quat.device batch_size = quat.shape[0] w = quat[:, 3].clamp(-1.0, 1.0) den = torch.sqrt(torch.clamp(1.0 - w * w, min=0.0)) result = torch.zeros((batch_size, 3), device=device) mask = den > 1e-10 if mask.any(): angle = 2.0 * torch.acos(w[mask]) # (M,) axis = quat[mask, :3] / den[mask].unsqueeze(1) result[mask] = axis * angle.unsqueeze(1) return result @dataclass @ProcessorStepRegistry.register(name="isaaclab_arena_processor") class IsaaclabArenaProcessorStep(ObservationProcessorStep): """ Processes IsaacLab Arena observations into LeRobot format. **State Processing:** - Extracts state components from obs["policy"] based on `state_keys`. - Concatenates into a flat vector mapped to "observation.state". **Image Processing:** - Extracts images from obs["camera_obs"] based on `camera_keys`. - Converts from (B, H, W, C) uint8 to (B, C, H, W) float32 [0, 1]. - Maps to "observation.images.<camera_name>". """ # Configurable from IsaacLabEnv config / cli args: --env.state_keys="robot_joint_pos,left_eef_pos" state_keys: tuple[str, ...] # Configurable from IsaacLabEnv config / cli args: --env.camera_keys="robot_pov_cam_rgb" camera_keys: tuple[str, ...] def _process_observation(self, observation): """ Processes both image and policy state observations from IsaacLab Arena. """ processed_obs = {} if f"{OBS_STR}.camera_obs" in observation: camera_obs = observation[f"{OBS_STR}.camera_obs"] for cam_name, img in camera_obs.items(): if cam_name not in self.camera_keys: continue img = img.permute(0, 3, 1, 2).contiguous() if img.dtype == torch.uint8: img = img.float() / 255.0 elif img.dtype != torch.float32: img = img.float() processed_obs[f"{OBS_IMAGES}.{cam_name}"] = img # Process policy state -> observation.state if f"{OBS_STR}.policy" in observation: policy_obs = observation[f"{OBS_STR}.policy"] # Collect state components in order state_components = [] for key in self.state_keys: if key in policy_obs: component = policy_obs[key] # Flatten extra dims: (B, N, M) -> (B, N*M) if component.dim() > 2: batch_size = component.shape[0] component = component.view(batch_size, -1) state_components.append(component) if state_components: state = torch.cat(state_components, dim=-1) state = state.float() processed_obs[OBS_STATE] = state return processed_obs def transform_features( self, features: dict[PipelineFeatureType, dict[str, PolicyFeature]] ) -> dict[PipelineFeatureType, dict[str, PolicyFeature]]: """Not used for policy evaluation.""" return features def observation(self, observation): return self._process_observation(observation)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/processor/env_processor.py", "license": "Apache License 2.0", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/processor/test_libero_processor.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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 numpy as np import torch from lerobot.envs.utils import preprocess_observation from lerobot.processor.env_processor import LiberoProcessorStep from lerobot.processor.pipeline import PolicyProcessorPipeline seed = 42 np.random.seed(seed) B = 5 obs1 = { "pixels": { "image": (np.random.rand(B, 256, 256, 3) * 255).astype(np.uint8), "image2": (np.random.rand(B, 256, 256, 3) * 255).astype(np.uint8), }, "robot_state": { "eef": { "pos": np.random.randn(B, 3), "quat": np.random.randn(B, 4), "mat": np.random.randn(B, 3, 3), }, "gripper": { "qpos": np.random.randn(B, 2), "qvel": np.random.randn(B, 2), }, "joints": { "pos": np.random.randn(B, 7), "vel": np.random.randn(B, 7), }, }, } observation = preprocess_observation(obs1) libero_preprocessor = PolicyProcessorPipeline( steps=[ LiberoProcessorStep(), ] ) processed_obs = libero_preprocessor(observation) assert "observation.state" in processed_obs state = processed_obs["observation.state"] assert isinstance(state, torch.Tensor) assert state.dtype == torch.float32 assert state.shape[0] == B assert state.shape[1] == 8 assert "observation.images.image" in processed_obs assert "observation.images.image2" in processed_obs assert isinstance(processed_obs["observation.images.image"], torch.Tensor) assert isinstance(processed_obs["observation.images.image2"], torch.Tensor) assert processed_obs["observation.images.image"].shape == (B, 3, 256, 256) assert processed_obs["observation.images.image2"].shape == (B, 3, 256, 256)
{ "repo_id": "huggingface/lerobot", "file_path": "tests/processor/test_libero_processor.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:examples/rtc/eval_dataset.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ Evaluate Real-Time Chunking (RTC) performance on dataset samples. This script takes two random samples from a dataset: - Uses actions from the first sample as previous chunk - Generates new actions for the second sample with and without RTC It compares action predictions with and without RTC on dataset samples, measuring consistency and ground truth alignment. Usage: # Basic usage with smolvla policy uv run python examples/rtc/eval_dataset.py \ --policy.path=<USER>/smolvla_check_rtc_last3 \ --dataset.repo_id=<USER>/check_rtc \ --rtc.execution_horizon=8 \ --device=mps \ --rtc.max_guidance_weight=10.0 \ --rtc.prefix_attention_schedule=EXP \ --seed=10 # Basic usage with pi0.5 policy uv run python examples/rtc/eval_dataset.py \ --policy.path=lerobot/pi05_libero_finetuned \ --dataset.repo_id=HuggingFaceVLA/libero \ --rtc.execution_horizon=10 \ --device=mps --seed=10 # Basic usage with pi0.5 policy with cuda device uv run python examples/rtc/eval_dataset.py \ --policy.path=lerobot/pi05_libero_finetuned \ --dataset.repo_id=HuggingFaceVLA/libero \ --rtc.execution_horizon=8 \ --device=cuda # Basic usage with pi0 policy with cuda device uv run python examples/rtc/eval_dataset.py \ --policy.path=lerobot/pi0_libero_finetuned \ --dataset.repo_id=HuggingFaceVLA/libero \ --rtc.execution_horizon=8 \ --device=cuda uv run python examples/rtc/eval_dataset.py \ --policy.path=<USER>/reuben_pi0 \ --dataset.repo_id=<USER>/so101_cube_in_cup \ --rtc.execution_horizon=8 \ --device=cuda # With torch.compile for faster inference (PyTorch 2.0+) # Note: CUDA graphs disabled by default due to in-place ops in denoising loop uv run python examples/rtc/eval_dataset.py \ --policy.path=<USER>/smolvla_check_rtc_last3 \ --dataset.repo_id=<USER>/check_rtc \ --rtc.execution_horizon=8 \ --device=mps \ --use_torch_compile=true \ --torch_compile_mode=max-autotune # With torch.compile on CUDA (CUDA graphs disabled by default) uv run python examples/rtc/eval_dataset.py \ --policy.path=<USER>/smolvla_check_rtc_last3 \ --dataset.repo_id=<USER>/check_rtc \ --rtc.execution_horizon=8 \ --device=cuda \ --use_torch_compile=true \ --torch_compile_mode=reduce-overhead # Enable CUDA graphs (advanced - may cause tensor aliasing errors) uv run python examples/rtc/eval_dataset.py \ --policy.path=<USER>/smolvla_check_rtc_last3 \ --dataset.repo_id=<USER>/check_rtc \ --use_torch_compile=true \ --torch_compile_backend=inductor \ --torch_compile_mode=max-autotune \ --torch_compile_disable_cudagraphs=false """ import gc import logging import os import random from dataclasses import dataclass, field import numpy as np import torch try: import matplotlib.pyplot as plt MATPLOTLIB_AVAILABLE = True except ImportError: MATPLOTLIB_AVAILABLE = False plt = None from lerobot.configs import parser from lerobot.configs.default import DatasetConfig from lerobot.configs.policies import PreTrainedConfig from lerobot.configs.types import RTCAttentionSchedule from lerobot.datasets.factory import resolve_delta_timestamps from lerobot.datasets.lerobot_dataset import LeRobotDataset, LeRobotDatasetMetadata from lerobot.policies.factory import get_policy_class, make_pre_post_processors from lerobot.policies.rtc.configuration_rtc import RTCConfig from lerobot.policies.rtc.debug_visualizer import RTCDebugVisualizer from lerobot.utils.hub import HubMixin from lerobot.utils.utils import init_logging def set_seed(seed: int): """Set random seed for reproducibility.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) if torch.backends.mps.is_available(): torch.mps.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def _check_matplotlib_available(): """Check if matplotlib is available, raise helpful error if not.""" if not MATPLOTLIB_AVAILABLE: raise ImportError( "matplotlib is required for RTC debug visualizations. " "Please install it by running:\n" " uv pip install matplotlib" ) @dataclass class RTCEvalConfig(HubMixin): """Configuration for RTC evaluation.""" # Policy configuration policy: PreTrainedConfig | None = None # Dataset configuration dataset: DatasetConfig = field(default_factory=DatasetConfig) # RTC configuration rtc: RTCConfig = field( default_factory=lambda: RTCConfig( enabled=True, execution_horizon=20, max_guidance_weight=10.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=True, debug_maxlen=1000, ) ) # Device configuration device: str | None = field( default=None, metadata={"help": "Device to run on (cuda, cpu, mps, auto)"}, ) # Output configuration output_dir: str = field( default="rtc_debug_output", metadata={"help": "Directory to save debug visualizations"}, ) # Seed configuration seed: int = field( default=42, metadata={"help": "Random seed for reproducibility"}, ) inference_delay: int = field( default=4, metadata={"help": "Inference delay for RTC"}, ) # Torch compile configuration use_torch_compile: bool = field( default=False, metadata={"help": "Use torch.compile for faster inference (PyTorch 2.0+)"}, ) torch_compile_backend: str = field( default="inductor", metadata={"help": "Backend for torch.compile (inductor, aot_eager, cudagraphs)"}, ) torch_compile_mode: str = field( default="default", metadata={"help": "Compilation mode (default, reduce-overhead, max-autotune)"}, ) torch_compile_disable_cudagraphs: bool = field( default=True, metadata={ "help": "Disable CUDA graphs in torch.compile. Required due to in-place tensor " "operations in denoising loop (x_t += dt * v_t) which cause tensor aliasing issues." }, ) def __post_init__(self): # Parse policy path policy_path = parser.get_path_arg("policy") if policy_path: cli_overrides = parser.get_cli_overrides("policy") self.policy = PreTrainedConfig.from_pretrained(policy_path, cli_overrides=cli_overrides) self.policy.pretrained_path = policy_path else: raise ValueError("Policy path is required (--policy.path)") # Auto-detect device if not specified if self.device is None or self.device == "auto": if torch.cuda.is_available(): self.device = "cuda" elif torch.backends.mps.is_available(): self.device = "mps" else: self.device = "cpu" logging.info(f"Auto-detected device: {self.device}") @classmethod def __get_path_fields__(cls) -> list[str]: """This enables the parser to load config from the policy using `--policy.path=local/dir`""" return ["policy"] class RTCEvaluator: """Evaluator for RTC on dataset samples.""" def __init__(self, cfg: RTCEvalConfig): self.cfg = cfg self.device = cfg.device # Load dataset with proper delta_timestamps based on policy configuration # Calculate delta_timestamps using the same logic as make_dataset factory logging.info(f"Loading dataset: {cfg.dataset.repo_id}") # Get dataset metadata to extract FPS ds_meta = LeRobotDatasetMetadata(cfg.dataset.repo_id) # Calculate delta_timestamps from policy's delta_indices delta_timestamps = resolve_delta_timestamps(cfg.policy, ds_meta) # Create dataset with calculated delta_timestamps self.dataset = LeRobotDataset( cfg.dataset.repo_id, delta_timestamps=delta_timestamps, ) logging.info(f"Dataset loaded: {len(self.dataset)} samples, {self.dataset.num_episodes} episodes") # Create preprocessor/postprocessor self.preprocessor, self.postprocessor = make_pre_post_processors( policy_cfg=cfg.policy, pretrained_path=cfg.policy.pretrained_path, preprocessor_overrides={ "device_processor": {"device": self.device}, }, ) logging.info("=" * 80) logging.info("Ready to run evaluation with sequential policy loading:") logging.info(" 1. policy_prev_chunk - Generate reference chunk, then destroy") logging.info(" 2. policy_no_rtc - Generate without RTC, then destroy") logging.info(" 3. policy_rtc - Generate with RTC, then destroy") logging.info(" Note: Only one policy in memory at a time for efficient memory usage") logging.info("=" * 80) def _init_policy(self, name: str, rtc_enabled: bool, rtc_debug: bool): """Initialize a single policy instance with specified RTC configuration. Args: name: Name identifier for logging purposes rtc_enabled: Whether to enable RTC for this policy rtc_debug: Whether to enable debug tracking for this policy Returns: Configured policy instance with optional torch.compile applied """ logging.info(f"Initializing {name}...") # Load policy from pretrained policy_class = get_policy_class(self.cfg.policy.type) config = PreTrainedConfig.from_pretrained(self.cfg.policy.pretrained_path) if self.cfg.policy.type == "pi05" or self.cfg.policy.type == "pi0": config.compile_model = self.cfg.use_torch_compile policy = policy_class.from_pretrained(self.cfg.policy.pretrained_path, config=config) policy = policy.to(self.device) policy.eval() # Configure RTC rtc_config = RTCConfig( enabled=rtc_enabled, execution_horizon=self.cfg.rtc.execution_horizon, max_guidance_weight=self.cfg.rtc.max_guidance_weight, prefix_attention_schedule=self.cfg.rtc.prefix_attention_schedule, debug=rtc_debug, debug_maxlen=self.cfg.rtc.debug_maxlen, ) policy.config.rtc_config = rtc_config policy.init_rtc_processor() logging.info(f" RTC enabled: {rtc_enabled}") logging.info(f" RTC debug: {rtc_debug}") logging.info(f" Policy config: {config}") # Apply torch.compile to predict_action_chunk method if enabled if self.cfg.use_torch_compile: policy = self._apply_torch_compile(policy, name) logging.info(f"✓ {name} initialized successfully") return policy def _apply_torch_compile(self, policy, policy_name: str): """Apply torch.compile to the policy's predict_action_chunk method. Args: policy: Policy instance to compile policy_name: Name for logging purposes Returns: Policy with compiled predict_action_chunk method """ # PI models handle their own compilation if policy.type == "pi05" or policy.type == "pi0": return policy try: # Check if torch.compile is available (PyTorch 2.0+) if not hasattr(torch, "compile"): logging.warning( f" [{policy_name}] torch.compile is not available. Requires PyTorch 2.0+. " f"Current version: {torch.__version__}. Skipping compilation." ) return policy logging.info(f" [{policy_name}] Applying torch.compile to predict_action_chunk...") logging.info(f" Backend: {self.cfg.torch_compile_backend}") logging.info(f" Mode: {self.cfg.torch_compile_mode}") logging.info(f" Disable CUDA graphs: {self.cfg.torch_compile_disable_cudagraphs}") logging.info(" Note: Debug tracker excluded from compilation via @torch._dynamo.disable") # Compile the predict_action_chunk method # - Debug tracker is excluded from compilation via @torch._dynamo.disable # - CUDA graphs disabled to prevent tensor aliasing from in-place ops (x_t += dt * v_t) compile_kwargs = { "backend": self.cfg.torch_compile_backend, "mode": self.cfg.torch_compile_mode, } # Disable CUDA graphs if requested (prevents tensor aliasing issues) if self.cfg.torch_compile_disable_cudagraphs: compile_kwargs["options"] = {"triton.cudagraphs": False} original_method = policy.predict_action_chunk compiled_method = torch.compile(original_method, **compile_kwargs) policy.predict_action_chunk = compiled_method logging.info(f" ✓ [{policy_name}] Successfully compiled predict_action_chunk") except Exception as e: logging.error(f" [{policy_name}] Failed to apply torch.compile: {e}") logging.warning(f" [{policy_name}] Continuing without torch.compile") return policy def _destroy_policy(self, policy, policy_name: str): """Explicitly destroy a policy and free all associated memory. This method performs aggressive cleanup to ensure maximum memory is freed, which is critical for large models (e.g., VLAs with billions of parameters). Args: policy: Policy instance to destroy policy_name: Name for logging purposes """ logging.info(f" Destroying {policy_name} and freeing memory...") try: # Step 1: Move policy to CPU to free GPU/MPS memory policy.cpu() # Step 2: Delete the policy object del policy # Step 3: Force garbage collection to reclaim memory immediately gc.collect() # Step 4: Clear device-specific caches if torch.cuda.is_available(): torch.cuda.empty_cache() torch.cuda.synchronize() # Ensure all operations complete if torch.backends.mps.is_available(): torch.mps.empty_cache() logging.info(f" ✓ {policy_name} destroyed and memory freed") except Exception as e: logging.warning(f" Warning: Error during {policy_name} cleanup: {e}") def run_evaluation(self): """Run evaluation on two random dataset samples using three separate policies. Note: Policies are deinitalized after each step to free memory. Large models (e.g., VLA models with billions of parameters) cannot fit three instances in memory simultaneously. By deleting and garbage collecting after each step, we ensure only one policy is loaded at a time. """ # Create output directory os.makedirs(self.cfg.output_dir, exist_ok=True) logging.info(f"Output directory: {self.cfg.output_dir}") logging.info("=" * 80) logging.info("Starting RTC evaluation") logging.info(f"Inference delay: {self.cfg.inference_delay}") logging.info("=" * 80) # Load two random samples from dataset data_loader = torch.utils.data.DataLoader(self.dataset, batch_size=1, shuffle=True) loader_iter = iter(data_loader) first_sample = next(loader_iter) second_sample = next(loader_iter) preprocessed_first_sample = self.preprocessor(first_sample) preprocessed_second_sample = self.preprocessor(second_sample) # ============================================================================ # Step 1: Generate previous chunk using policy_prev_chunk # ============================================================================ # This policy is only used to generate the reference chunk and then freed logging.info("=" * 80) logging.info("Step 1: Generating previous chunk with policy_prev_chunk") logging.info("=" * 80) # Initialize policy 1 policy_prev_chunk_policy = self._init_policy( name="policy_prev_chunk", rtc_enabled=False, rtc_debug=False, ) with torch.no_grad(): prev_chunk_left_over = policy_prev_chunk_policy.predict_action_chunk( preprocessed_first_sample, )[:, :25, :].squeeze(0) logging.info(f" Generated prev_chunk shape: {prev_chunk_left_over.shape}") # Destroy policy_prev_chunk to free memory for large models self._destroy_policy(policy_prev_chunk_policy, "policy_prev_chunk") # ============================================================================ # Step 2: Generate actions WITHOUT RTC using policy_no_rtc # ============================================================================ logging.info("=" * 80) logging.info("Step 2: Generating actions WITHOUT RTC with policy_no_rtc") logging.info("=" * 80) set_seed(self.cfg.seed) # Initialize policy 2 policy_no_rtc_policy = self._init_policy( name="policy_no_rtc", rtc_enabled=False, rtc_debug=True, ) # Sample noise (use same noise for both RTC and non-RTC for fair comparison) noise_size = (1, policy_no_rtc_policy.config.chunk_size, policy_no_rtc_policy.config.max_action_dim) noise = policy_no_rtc_policy.model.sample_noise(noise_size, self.device) noise_clone = noise.clone() policy_no_rtc_policy.rtc_processor.reset_tracker() with torch.no_grad(): no_rtc_actions = policy_no_rtc_policy.predict_action_chunk( preprocessed_second_sample, noise=noise, ) no_rtc_tracked_steps = policy_no_rtc_policy.rtc_processor.tracker.get_all_steps() logging.info(f" Tracked {len(no_rtc_tracked_steps)} steps without RTC") logging.info(f" Generated no_rtc_actions shape: {no_rtc_actions.shape}") # Destroy policy_no_rtc to free memory before loading policy_rtc self._destroy_policy(policy_no_rtc_policy, "policy_no_rtc") # ============================================================================ # Step 3: Generate actions WITH RTC using policy_rtc # ============================================================================ logging.info("=" * 80) logging.info("Step 3: Generating actions WITH RTC with policy_rtc") logging.info("=" * 80) set_seed(self.cfg.seed) # Initialize policy 3 policy_rtc_policy = self._init_policy( name="policy_rtc", rtc_enabled=True, rtc_debug=True, ) policy_rtc_policy.rtc_processor.reset_tracker() with torch.no_grad(): rtc_actions = policy_rtc_policy.predict_action_chunk( preprocessed_second_sample, noise=noise_clone, inference_delay=self.cfg.inference_delay, prev_chunk_left_over=prev_chunk_left_over, execution_horizon=self.cfg.rtc.execution_horizon, ) rtc_tracked_steps = policy_rtc_policy.rtc_processor.get_all_debug_steps() logging.info(f" Tracked {len(rtc_tracked_steps)} steps with RTC") logging.info(f" Generated rtc_actions shape: {rtc_actions.shape}") # Save num_steps before destroying policy (needed for plotting) try: num_steps = policy_rtc_policy.config.num_steps except Exception as e: logging.error(f" Error getting num_steps: {e}") num_steps = policy_rtc_policy.config.num_inference_steps logging.warning(f" Using num_inference_steps: {num_steps} instead of num_steps") # Destroy policy_rtc after final use self._destroy_policy(policy_rtc_policy, "policy_rtc") # Plot and save results logging.info("=" * 80) logging.info("Plotting results...") self.plot_tracked_data(rtc_tracked_steps, no_rtc_tracked_steps, prev_chunk_left_over, num_steps) # Plot final actions comparison logging.info("=" * 80) logging.info("Plotting final actions comparison...") self.plot_final_actions_comparison(rtc_actions, no_rtc_actions, prev_chunk_left_over) logging.info("=" * 80) logging.info("Evaluation completed successfully") def plot_final_actions_comparison(self, rtc_actions, no_rtc_actions, prev_chunk_left_over): """Plot final action predictions comparison on a single chart. Args: rtc_actions: Final actions from RTC policy no_rtc_actions: Final actions from non-RTC policy prev_chunk_left_over: Previous chunk used as ground truth """ _check_matplotlib_available() # Remove batch dimension if present rtc_actions_plot = rtc_actions.squeeze(0).cpu() if len(rtc_actions.shape) == 3 else rtc_actions.cpu() no_rtc_actions_plot = ( no_rtc_actions.squeeze(0).cpu() if len(no_rtc_actions.shape) == 3 else no_rtc_actions.cpu() ) prev_chunk_plot = prev_chunk_left_over.cpu() # Create figure with 6 subplots (one per action dimension) fig, axes = plt.subplots(6, 1, figsize=(16, 12)) fig.suptitle("Final Action Predictions Comparison (Raw)", fontsize=16) # Plot each action dimension for dim_idx, ax in enumerate(axes): # Plot previous chunk (ground truth) in red RTCDebugVisualizer.plot_waypoints( [ax], prev_chunk_plot[:, dim_idx : dim_idx + 1], start_from=0, color="red", label="Previous Chunk (Ground Truth)", linewidth=2.5, alpha=0.8, ) # Plot no-RTC actions in blue RTCDebugVisualizer.plot_waypoints( [ax], no_rtc_actions_plot[:, dim_idx : dim_idx + 1], start_from=0, color="blue", label="No RTC", linewidth=2, alpha=0.7, ) # Plot RTC actions in green RTCDebugVisualizer.plot_waypoints( [ax], rtc_actions_plot[:, dim_idx : dim_idx + 1], start_from=0, color="green", label="RTC", linewidth=2, alpha=0.7, ) # Add vertical lines for inference delay and execution horizon inference_delay = self.cfg.inference_delay execution_horizon = self.cfg.rtc.execution_horizon if inference_delay > 0: ax.axvline( x=inference_delay - 1, color="orange", linestyle="--", alpha=0.5, label=f"Inference Delay ({inference_delay})", ) if execution_horizon > 0: ax.axvline( x=execution_horizon, color="purple", linestyle="--", alpha=0.5, label=f"Execution Horizon ({execution_horizon})", ) ax.set_ylabel(f"Dim {dim_idx}", fontsize=10) ax.grid(True, alpha=0.3) # Set x-axis ticks to show all integer values max_len = max(rtc_actions_plot.shape[0], no_rtc_actions_plot.shape[0], prev_chunk_plot.shape[0]) ax.set_xticks(range(0, max_len, max(1, max_len // 20))) # Show ~20 ticks ax.set_xlim(-0.5, max_len - 0.5) axes[-1].set_xlabel("Step", fontsize=10) # Collect legend handles and labels from first subplot handles, labels = axes[0].get_legend_handles_labels() # Remove duplicates while preserving order seen = set() unique_handles = [] unique_labels = [] for handle, label in zip(handles, labels, strict=True): if label not in seen: seen.add(label) unique_handles.append(handle) unique_labels.append(label) # Add legend outside the plot area (to the right) fig.legend( unique_handles, unique_labels, loc="center right", fontsize=9, bbox_to_anchor=(1.0, 0.5), framealpha=0.9, ) # Save figure output_path = os.path.join(self.cfg.output_dir, "final_actions_comparison.png") fig.tight_layout(rect=[0, 0, 0.85, 1]) # Leave space for legend on right fig.savefig(output_path, dpi=150, bbox_inches="tight") logging.info(f"Saved final actions comparison to {output_path}") plt.close(fig) def plot_tracked_data(self, rtc_tracked_steps, no_rtc_tracked_steps, prev_chunk_left_over, num_steps): _check_matplotlib_available() # Create side-by-side figures for denoising visualization fig_xt, axs_xt = self._create_figure("x_t Denoising: No RTC (left) vs RTC (right)") fig_vt, axs_vt = self._create_figure("v_t Denoising: No RTC (left) vs RTC (right)") fig_corr, axs_corr = self._create_figure("Correction: No RTC (left) vs RTC (right)") fig_x1t, axs_x1t = self._create_figure( "x1_t Predicted State & Error: No RTC (left - empty) vs RTC (right)" ) self._plot_denoising_steps_from_tracker( rtc_tracked_steps, axs_xt[:, 1], # Right column for x_t axs_vt[:, 1], # Right column for v_t axs_corr[:, 1], # Right column for correction axs_x1t[:, 1], # Right column for x1_t num_steps, add_labels=True, # Add labels for RTC (right column) ) self._plot_denoising_steps_from_tracker( no_rtc_tracked_steps, axs_xt[:, 0], # Left column for x_t axs_vt[:, 0], # Left column for v_t axs_corr[:, 0], # Left column for correction axs_x1t[:, 0], # Left column for x1_t num_steps, add_labels=False, # No labels for No RTC (left column) ) # Plot no-RTC x_t data on right chart as orange dashed line for comparison self._plot_no_rtc_xt_reference(no_rtc_tracked_steps, axs_xt[:, 1], num_steps) # Plot ground truth on x_t axes RTCDebugVisualizer.plot_waypoints( axs_xt[:, 1], prev_chunk_left_over, start_from=0, color="red", label="Ground truth" ) # Plot ground truth on x1_t axes RTCDebugVisualizer.plot_waypoints( axs_x1t[:, 1], prev_chunk_left_over, start_from=0, color="red", label="Ground truth" ) # Plot ground truth on x_t axes (no labels for left column) RTCDebugVisualizer.plot_waypoints( axs_xt[:, 0], prev_chunk_left_over, start_from=0, color="red", label=None ) RTCDebugVisualizer.plot_waypoints( axs_x1t[:, 0], prev_chunk_left_over, start_from=0, color="red", label=None ) # Add legends outside the plot area for each figure self._add_figure_legend(fig_xt, axs_xt) self._add_figure_legend(fig_vt, axs_vt) self._add_figure_legend(fig_corr, axs_corr) self._add_figure_legend(fig_x1t, axs_x1t) # Save denoising plots self._save_figure(fig_xt, os.path.join(self.cfg.output_dir, "denoising_xt_comparison.png")) self._save_figure(fig_vt, os.path.join(self.cfg.output_dir, "denoising_vt_comparison.png")) self._save_figure(fig_corr, os.path.join(self.cfg.output_dir, "denoising_correction_comparison.png")) self._save_figure(fig_x1t, os.path.join(self.cfg.output_dir, "denoising_x1t_comparison.png")) def _create_figure(self, title): fig, axs = plt.subplots(6, 2, figsize=(24, 12)) fig.suptitle(title, fontsize=16) for ax in axs[:, 0]: ax.set_title("No RTC (N/A)" if ax == axs[0, 0] else "", fontsize=12) for ax in axs[:, 1]: ax.set_title("RTC" if ax == axs[0, 1] else "", fontsize=12) return fig, axs def _add_figure_legend(self, fig, axs): """Add a legend outside the plot area on the right side. Args: fig: Matplotlib figure to add legend to axs: Array of axes to collect legend handles from """ # Collect all handles and labels from the first row of axes (right column) handles, labels = axs[0, 1].get_legend_handles_labels() # Remove duplicates while preserving order seen = set() unique_handles = [] unique_labels = [] for handle, label in zip(handles, labels, strict=True): if label not in seen: seen.add(label) unique_handles.append(handle) unique_labels.append(label) # Add legend outside the plot area (to the right, close to charts) if unique_handles: fig.legend( unique_handles, unique_labels, loc="center left", fontsize=8, bbox_to_anchor=(0.87, 0.5), framealpha=0.9, ncol=1, ) def _save_figure(self, fig, path): fig.tight_layout(rect=[0, 0, 0.85, 1]) # Leave space for legend/colorbar on right fig.savefig(path, dpi=150, bbox_inches="tight") logging.info(f"Saved figure to {path}") plt.close(fig) def _plot_denoising_steps_from_tracker( self, tracked_steps, xt_axs, vt_axs, corr_axs, x1t_axs, num_steps, add_labels=True ): """Plot denoising steps from tracker data. Args: tracked_steps: List of DebugStep objects containing debug steps xt_axs: Matplotlib axes for x_t plots (array of 6 axes) vt_axs: Matplotlib axes for v_t plots (array of 6 axes) corr_axs: Matplotlib axes for correction plots (array of 6 axes) x1t_axs: Matplotlib axes for x1_t plots (array of 6 axes) num_steps: Total number of denoising steps for colormap add_labels: Whether to add legend labels for the plots """ logging.info("=" * 80) logging.info(f"Plotting {len(tracked_steps)} steps") debug_steps = tracked_steps if not debug_steps: return # Define colors for different denoise steps (using a colormap) colors = plt.cm.viridis(np.linspace(0, 1, num_steps)) for step_idx, debug_step in enumerate(debug_steps): color = colors[step_idx % len(colors)] label = f"Step {step_idx}" if add_labels else None # Plot x_t if debug_step.x_t is not None: RTCDebugVisualizer.plot_waypoints( xt_axs, debug_step.x_t, start_from=0, color=color, label=label ) # Plot v_t if debug_step.v_t is not None: RTCDebugVisualizer.plot_waypoints( vt_axs, debug_step.v_t, start_from=0, color=color, label=label ) # Plot correction on separate axes if debug_step.correction is not None: RTCDebugVisualizer.plot_waypoints( corr_axs, debug_step.correction, start_from=0, color=color, label=label, ) # Plot x1_t (predicted state) if x1t_axs is not None and debug_step.x1_t is not None: x1t_label = f"x1_t Step {step_idx}" if add_labels else None RTCDebugVisualizer.plot_waypoints( x1t_axs, debug_step.x1_t, start_from=0, color=color, label=x1t_label, ) # Plot error in orange dashed if x1t_axs is not None and debug_step.err is not None: error_chunk = ( debug_step.err[0].cpu().numpy() if len(debug_step.err.shape) == 3 else debug_step.err.cpu().numpy() ) num_dims = min(error_chunk.shape[-1], 6) error_label = f"error Step {step_idx}" if add_labels else None for j in range(num_dims): x1t_axs[j].plot( np.arange(0, error_chunk.shape[0]), error_chunk[:, j], color="orange", linestyle="--", alpha=0.7, label=error_label, ) # Recalculate axis limits after plotting to ensure proper scaling self._rescale_axes(xt_axs) self._rescale_axes(vt_axs) self._rescale_axes(corr_axs) self._rescale_axes(x1t_axs) def _plot_no_rtc_xt_reference(self, no_rtc_tracked_steps, xt_axs, num_steps): """Plot final no-RTC x_t data as orange dashed line on the RTC chart for comparison. Args: no_rtc_tracked_steps: List of DebugStep objects containing no-RTC debug steps xt_axs: Matplotlib axes for x_t plots (array of 6 axes, right column) num_steps: Total number of denoising steps for colormap """ debug_steps = no_rtc_tracked_steps if not debug_steps: return # Plot only the final x_t step as orange dashed line final_step = debug_steps[-1] logging.info("Plotting final no-RTC x_t step as orange dashed reference") if final_step.x_t is not None: x_t_chunk = ( final_step.x_t[0].cpu().numpy() if len(final_step.x_t.shape) == 3 else final_step.x_t.cpu().numpy() ) num_dims = min(x_t_chunk.shape[-1], 6) for j in range(num_dims): xt_axs[j].plot( np.arange(0, x_t_chunk.shape[0]), x_t_chunk[:, j], color="orange", linestyle="--", alpha=0.7, linewidth=2, label="No RTC (final)" if j == 0 else "", ) def _rescale_axes(self, axes): """Rescale axes to show all data with proper margins. Args: axes: Array of matplotlib axes to rescale """ for ax in axes: ax.relim() ax.autoscale_view() # Add 10% margin to y-axis for better visualization ylim = ax.get_ylim() y_range = ylim[1] - ylim[0] if y_range > 0: # Avoid division by zero margin = y_range * 0.1 ax.set_ylim(ylim[0] - margin, ylim[1] + margin) # Set x-axis ticks to show all integer values xlim = ax.get_xlim() max_len = int(xlim[1]) + 1 if max_len > 0: ax.set_xticks(range(0, max_len, max(1, max_len // 20))) # Show ~20 ticks ax.set_xlim(-0.5, max_len - 0.5) @parser.wrap() def main(cfg: RTCEvalConfig): """Main entry point for RTC evaluation.""" # Set random seed for reproducibility set_seed(cfg.seed) init_logging() logging.info("=" * 80) logging.info("RTC Dataset Evaluation") logging.info(f"Config: {cfg}") logging.info("=" * 80) evaluator = RTCEvaluator(cfg) evaluator.run_evaluation() if __name__ == "__main__": main()
{ "repo_id": "huggingface/lerobot", "file_path": "examples/rtc/eval_dataset.py", "license": "Apache License 2.0", "lines": 789, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:examples/rtc/eval_with_real_robot.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ Demo script showing how to use Real-Time Chunking (RTC) with action chunking policies on real robots. This script demonstrates: 1. Creating a robot and policy (SmolVLA, Pi0, etc.) with RTC 2. Consuming actions from the policy while the robot executes 3. Periodically requesting new action chunks in the background using threads 4. Managing action buffers and timing for real-time operation For simulation environments, see eval_with_simulation.py Usage: # Run RTC with Real robot with RTC uv run examples/rtc/eval_with_real_robot.py \ --policy.path=<USER>/smolvla_check_rtc_last3 \ --policy.device=mps \ --rtc.enabled=true \ --rtc.execution_horizon=20 \ --robot.type=so100_follower \ --robot.port=/dev/tty.usbmodem58FA0834591 \ --robot.id=so100_follower \ --robot.cameras="{ gripper: {type: opencv, index_or_path: 1, width: 640, height: 480, fps: 30}, front: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}}" \ --task="Move green small object into the purple platform" \ --duration=120 # Run RTC with Real robot without RTC uv run examples/rtc/eval_with_real_robot.py \ --policy.path=<USER>/smolvla_check_rtc_last3 \ --policy.device=mps \ --rtc.enabled=false \ --robot.type=so100_follower \ --robot.port=/dev/tty.usbmodem58FA0834591 \ --robot.id=so100_follower \ --robot.cameras="{ gripper: {type: opencv, index_or_path: 1, width: 640, height: 480, fps: 30}, front: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}}" \ --task="Move green small object into the purple platform" \ --duration=120 # Run RTC with Real robot with pi0.5 policy uv run examples/rtc/eval_with_real_robot.py \ --policy.path=<USER>/pi05_check_rtc \ --policy.device=mps \ --rtc.enabled=true \ --rtc.execution_horizon=20 \ --robot.type=so100_follower \ --robot.port=/dev/tty.usbmodem58FA0834591 \ --robot.id=so100_follower \ --robot.cameras="{ gripper: {type: opencv, index_or_path: 0, width: 640, height: 480, fps: 30}, front: {type: opencv, index_or_path: 1, width: 640, height: 480, fps: 30}}" \ --task="Move green small object into the purple platform" \ --duration=120 """ import logging import math import sys import time import traceback from dataclasses import dataclass, field from threading import Event, Lock, Thread import torch from torch import Tensor from lerobot.cameras.opencv.configuration_opencv import OpenCVCameraConfig # noqa: F401 from lerobot.cameras.realsense.configuration_realsense import RealSenseCameraConfig # noqa: F401 from lerobot.configs import parser from lerobot.configs.policies import PreTrainedConfig from lerobot.configs.types import RTCAttentionSchedule from lerobot.datasets.utils import build_dataset_frame, hw_to_dataset_features from lerobot.policies.factory import get_policy_class, make_pre_post_processors from lerobot.policies.rtc.action_queue import ActionQueue from lerobot.policies.rtc.configuration_rtc import RTCConfig from lerobot.policies.rtc.latency_tracker import LatencyTracker from lerobot.processor.factory import ( make_default_robot_action_processor, make_default_robot_observation_processor, ) from lerobot.rl.process import ProcessSignalHandler from lerobot.robots import ( # noqa: F401 Robot, RobotConfig, bi_so_follower, koch_follower, so_follower, ) from lerobot.robots.utils import make_robot_from_config from lerobot.utils.constants import OBS_IMAGES from lerobot.utils.hub import HubMixin from lerobot.utils.utils import init_logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class RobotWrapper: def __init__(self, robot: Robot): self.robot = robot self.lock = Lock() def get_observation(self) -> dict[str, Tensor]: with self.lock: return self.robot.get_observation() def send_action(self, action: Tensor): with self.lock: self.robot.send_action(action) def observation_features(self) -> list[str]: with self.lock: return self.robot.observation_features def action_features(self) -> list[str]: with self.lock: return self.robot.action_features @dataclass class RTCDemoConfig(HubMixin): """Configuration for RTC demo with action chunking policies and real robots.""" # Policy configuration policy: PreTrainedConfig | None = None # Robot configuration robot: RobotConfig | None = None # RTC configuration rtc: RTCConfig = field( default_factory=lambda: RTCConfig( execution_horizon=10, max_guidance_weight=1.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, ) ) # Demo parameters duration: float = 30.0 # Duration to run the demo (seconds) fps: float = 10.0 # Action execution frequency (Hz) # Compute device device: str | None = None # Device to run on (cuda, cpu, auto) # Get new actions horizon. The amount of executed steps after which will be requested new actions. # It should be higher than inference delay + execution horizon. action_queue_size_to_get_new_actions: int = 30 # Task to execute task: str = field(default="", metadata={"help": "Task to execute"}) # Torch compile configuration use_torch_compile: bool = field( default=False, metadata={"help": "Use torch.compile for faster inference (PyTorch 2.0+)"}, ) torch_compile_backend: str = field( default="inductor", metadata={"help": "Backend for torch.compile (inductor, aot_eager, cudagraphs)"}, ) torch_compile_mode: str = field( default="default", metadata={"help": "Compilation mode (default, reduce-overhead, max-autotune)"}, ) torch_compile_disable_cudagraphs: bool = field( default=True, metadata={ "help": "Disable CUDA graphs in torch.compile. Required due to in-place tensor " "operations in denoising loop (x_t += dt * v_t) which cause tensor aliasing issues." }, ) def __post_init__(self): # HACK: We parse again the cli args here to get the pretrained path if there was one. policy_path = parser.get_path_arg("policy") if policy_path: cli_overrides = parser.get_cli_overrides("policy") self.policy = PreTrainedConfig.from_pretrained(policy_path, cli_overrides=cli_overrides) self.policy.pretrained_path = policy_path else: raise ValueError("Policy path is required") # Validate that robot configuration is provided if self.robot is None: raise ValueError("Robot configuration must be provided") @classmethod def __get_path_fields__(cls) -> list[str]: """This enables the parser to load config from the policy using `--policy.path=local/dir`""" return ["policy"] def is_image_key(k: str) -> bool: return k.startswith(OBS_IMAGES) def get_actions( policy, robot: RobotWrapper, robot_observation_processor, action_queue: ActionQueue, shutdown_event: Event, cfg: RTCDemoConfig, ): """Thread function to request action chunks from the policy. Args: policy: The policy instance (SmolVLA, Pi0, etc.) robot: The robot instance for getting observations robot_observation_processor: Processor for raw robot observations action_queue: Queue to put new action chunks shutdown_event: Event to signal shutdown cfg: Demo configuration """ try: logger.info("[GET_ACTIONS] Starting get actions thread") latency_tracker = LatencyTracker() # Track latency of action chunks fps = cfg.fps time_per_chunk = 1.0 / fps dataset_features = hw_to_dataset_features(robot.observation_features(), "observation") policy_device = policy.config.device # Load preprocessor and postprocessor from pretrained files # The stats are embedded in the processor .safetensors files logger.info(f"[GET_ACTIONS] Loading preprocessor/postprocessor from {cfg.policy.pretrained_path}") preprocessor, postprocessor = make_pre_post_processors( policy_cfg=cfg.policy, pretrained_path=cfg.policy.pretrained_path, dataset_stats=None, # Will load from pretrained processor files preprocessor_overrides={ "device_processor": {"device": cfg.policy.device}, }, ) logger.info("[GET_ACTIONS] Preprocessor/postprocessor loaded successfully with embedded stats") get_actions_threshold = cfg.action_queue_size_to_get_new_actions if not cfg.rtc.enabled: get_actions_threshold = 0 while not shutdown_event.is_set(): if action_queue.qsize() <= get_actions_threshold: current_time = time.perf_counter() action_index_before_inference = action_queue.get_action_index() prev_actions = action_queue.get_left_over() inference_latency = latency_tracker.max() inference_delay = math.ceil(inference_latency / time_per_chunk) obs = robot.get_observation() # Apply robot observation processor obs_processed = robot_observation_processor(obs) obs_with_policy_features = build_dataset_frame( dataset_features, obs_processed, prefix="observation" ) for name in obs_with_policy_features: obs_with_policy_features[name] = torch.from_numpy(obs_with_policy_features[name]) if "image" in name: obs_with_policy_features[name] = ( obs_with_policy_features[name].type(torch.float32) / 255 ) obs_with_policy_features[name] = ( obs_with_policy_features[name].permute(2, 0, 1).contiguous() ) obs_with_policy_features[name] = obs_with_policy_features[name].unsqueeze(0) obs_with_policy_features[name] = obs_with_policy_features[name].to(policy_device) obs_with_policy_features["task"] = [cfg.task] # Task should be a list, not a string! obs_with_policy_features["robot_type"] = ( robot.robot.name if hasattr(robot.robot, "name") else "" ) preproceseded_obs = preprocessor(obs_with_policy_features) # Generate actions WITH RTC actions = policy.predict_action_chunk( preproceseded_obs, inference_delay=inference_delay, prev_chunk_left_over=prev_actions, ) # Store original actions (before postprocessing) for RTC original_actions = actions.squeeze(0).clone() postprocessed_actions = postprocessor(actions) postprocessed_actions = postprocessed_actions.squeeze(0) new_latency = time.perf_counter() - current_time new_delay = math.ceil(new_latency / time_per_chunk) latency_tracker.add(new_latency) if cfg.action_queue_size_to_get_new_actions < cfg.rtc.execution_horizon + new_delay: logger.warning( "[GET_ACTIONS] cfg.action_queue_size_to_get_new_actions Too small, It should be higher than inference delay + execution horizon." ) action_queue.merge( original_actions, postprocessed_actions, new_delay, action_index_before_inference ) else: # Small sleep to prevent busy waiting time.sleep(0.1) logger.info("[GET_ACTIONS] get actions thread shutting down") except Exception as e: logger.error(f"[GET_ACTIONS] Fatal exception in get_actions thread: {e}") logger.error(traceback.format_exc()) sys.exit(1) def actor_control( robot: RobotWrapper, robot_action_processor, action_queue: ActionQueue, shutdown_event: Event, cfg: RTCDemoConfig, ): """Thread function to execute actions on the robot. Args: robot: The robot instance action_queue: Queue to get actions from shutdown_event: Event to signal shutdown cfg: Demo configuration """ try: logger.info("[ACTOR] Starting actor thread") action_count = 0 action_interval = 1.0 / cfg.fps while not shutdown_event.is_set(): start_time = time.perf_counter() # Try to get an action from the queue with timeout action = action_queue.get() if action is not None: action = action.cpu() action_dict = {key: action[i].item() for i, key in enumerate(robot.action_features())} action_processed = robot_action_processor((action_dict, None)) robot.send_action(action_processed) action_count += 1 dt_s = time.perf_counter() - start_time time.sleep(max(0, (action_interval - dt_s) - 0.001)) logger.info(f"[ACTOR] Actor thread shutting down. Total actions executed: {action_count}") except Exception as e: logger.error(f"[ACTOR] Fatal exception in actor_control thread: {e}") logger.error(traceback.format_exc()) sys.exit(1) def _apply_torch_compile(policy, cfg: RTCDemoConfig): """Apply torch.compile to the policy's predict_action_chunk method. Args: policy: Policy instance to compile cfg: Configuration containing torch compile settings Returns: Policy with compiled predict_action_chunk method """ # PI models handle their own compilation if policy.type == "pi05" or policy.type == "pi0": return policy try: # Check if torch.compile is available (PyTorch 2.0+) if not hasattr(torch, "compile"): logger.warning( f"torch.compile is not available. Requires PyTorch 2.0+. " f"Current version: {torch.__version__}. Skipping compilation." ) return policy logger.info("Applying torch.compile to predict_action_chunk...") logger.info(f" Backend: {cfg.torch_compile_backend}") logger.info(f" Mode: {cfg.torch_compile_mode}") logger.info(f" Disable CUDA graphs: {cfg.torch_compile_disable_cudagraphs}") # Compile the predict_action_chunk method # - CUDA graphs disabled to prevent tensor aliasing from in-place ops (x_t += dt * v_t) compile_kwargs = { "backend": cfg.torch_compile_backend, "mode": cfg.torch_compile_mode, } # Disable CUDA graphs if requested (prevents tensor aliasing issues) if cfg.torch_compile_disable_cudagraphs: compile_kwargs["options"] = {"triton.cudagraphs": False} original_method = policy.predict_action_chunk compiled_method = torch.compile(original_method, **compile_kwargs) policy.predict_action_chunk = compiled_method logger.info("✓ Successfully compiled predict_action_chunk") except Exception as e: logger.error(f"Failed to apply torch.compile: {e}") logger.warning("Continuing without torch.compile") return policy @parser.wrap() def demo_cli(cfg: RTCDemoConfig): """Main entry point for RTC demo with draccus configuration.""" # Initialize logging init_logging() logger.info(f"Using device: {cfg.device}") # Setup signal handler for graceful shutdown signal_handler = ProcessSignalHandler(use_threads=True, display_pid=False) shutdown_event = signal_handler.shutdown_event policy = None robot = None get_actions_thread = None actor_thread = None policy_class = get_policy_class(cfg.policy.type) # Load config and set compile_model for pi0/pi05 models config = PreTrainedConfig.from_pretrained(cfg.policy.pretrained_path) if cfg.policy.type == "pi05" or cfg.policy.type == "pi0": config.compile_model = cfg.use_torch_compile if config.use_peft: from peft import PeftConfig, PeftModel peft_pretrained_path = cfg.policy.pretrained_path peft_config = PeftConfig.from_pretrained(peft_pretrained_path) policy = policy_class.from_pretrained( pretrained_name_or_path=peft_config.base_model_name_or_path, config=config ) policy = PeftModel.from_pretrained(policy, peft_pretrained_path, config=peft_config) else: policy = policy_class.from_pretrained(cfg.policy.pretrained_path, config=config) # Turn on RTC policy.config.rtc_config = cfg.rtc # Init RTC processort, as by default if RTC disabled in the config # The processor won't be created policy.init_rtc_processor() assert policy.name in ["smolvla", "pi05", "pi0"], "Only smolvla, pi05, and pi0 are supported for RTC" policy = policy.to(cfg.device) policy.eval() # Apply torch.compile to predict_action_chunk method if enabled if cfg.use_torch_compile: policy = _apply_torch_compile(policy, cfg) # Create robot logger.info(f"Initializing robot: {cfg.robot.type}") robot = make_robot_from_config(cfg.robot) robot.connect() robot_wrapper = RobotWrapper(robot) # Create robot observation processor robot_observation_processor = make_default_robot_observation_processor() robot_action_processor = make_default_robot_action_processor() # Create action queue for communication between threads action_queue = ActionQueue(cfg.rtc) # Start chunk requester thread get_actions_thread = Thread( target=get_actions, args=(policy, robot_wrapper, robot_observation_processor, action_queue, shutdown_event, cfg), daemon=True, name="GetActions", ) get_actions_thread.start() logger.info("Started get actions thread") # Start action executor thread actor_thread = Thread( target=actor_control, args=(robot_wrapper, robot_action_processor, action_queue, shutdown_event, cfg), daemon=True, name="Actor", ) actor_thread.start() logger.info("Started actor thread") logger.info("Started stop by duration thread") # Main thread monitors for duration or shutdown logger.info(f"Running demo for {cfg.duration} seconds...") start_time = time.time() while not shutdown_event.is_set() and (time.time() - start_time) < cfg.duration: time.sleep(10) # Log queue status periodically if int(time.time() - start_time) % 5 == 0: logger.info(f"[MAIN] Action queue size: {action_queue.qsize()}") if time.time() - start_time > cfg.duration: break logger.info("Demo duration reached or shutdown requested") # Signal shutdown shutdown_event.set() # Wait for threads to finish if get_actions_thread and get_actions_thread.is_alive(): logger.info("Waiting for chunk requester thread to finish...") get_actions_thread.join() if actor_thread and actor_thread.is_alive(): logger.info("Waiting for action executor thread to finish...") actor_thread.join() # Cleanup robot if robot: robot.disconnect() logger.info("Robot disconnected") logger.info("Cleanup completed") if __name__ == "__main__": demo_cli() logging.info("RTC demo finished")
{ "repo_id": "huggingface/lerobot", "file_path": "examples/rtc/eval_with_real_robot.py", "license": "Apache License 2.0", "lines": 442, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/rtc/action_queue.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Action queue management for Real-Time Chunking (RTC). This module provides ActionQueue, a thread-safe queue for managing action chunks in real-time control scenarios. It supports both RTC-enabled and non-RTC modes, handling action merging and leftover tracking. """ import logging from threading import Lock import torch from torch import Tensor from lerobot.policies.rtc.configuration_rtc import RTCConfig logger = logging.getLogger(__name__) class ActionQueue: """Thread-safe queue for managing action chunks in real-time control. This queue handles two types of action sequences: - Original actions: Used for RTC to compute leftovers from previous chunks - Processed actions: Post-processed actions ready for robot execution The queue operates in two modes: 1. RTC-enabled: Replaces the entire queue with new actions, accounting for inference delay 2. RTC-disabled: Appends new actions to the queue, maintaining continuity Args: cfg (RTCConfig): Configuration for Real-Time Chunking behavior. Attributes: queue (Tensor | None): Processed actions for robot rollout (time_steps, action_dim). original_queue (Tensor | None): Original actions for RTC computation (time_steps, action_dim). last_index (int): Current consumption index in the queue. """ def __init__(self, cfg: RTCConfig): """Initialize the action queue. Args: cfg: RTC configuration controlling queue behavior. """ self.queue = None # Processed actions for robot rollout self.original_queue = None # Original actions for RTC self.lock = Lock() self.last_index = 0 self.cfg = cfg def get(self) -> Tensor | None: """Get the next action from the queue. Returns: Tensor | None: The next action (action_dim,) or None if queue is empty. Returns a clone to prevent external modifications. """ with self.lock: if self.queue is None or self.last_index >= len(self.queue): return None action = self.queue[self.last_index] self.last_index += 1 return action.clone() def qsize(self) -> int: """Get the number of remaining actions in the queue. Returns: int: Number of unconsumed actions. """ if self.queue is None: return 0 length = len(self.queue) return length - self.last_index def empty(self) -> bool: """Check if the queue is empty. Returns: bool: True if no actions remain, False otherwise. """ if self.queue is None: return True length = len(self.queue) return length - self.last_index <= 0 def get_action_index(self) -> int: """Get the current action consumption index. Returns: int: Index of the next action to be consumed. """ return self.last_index def get_left_over(self) -> Tensor | None: """Get leftover original actions for RTC prev_chunk_left_over. These are the unconsumed actions from the current chunk, which will be used by RTC to compute corrections for the next chunk. Returns: Tensor | None: Remaining original actions (remaining_steps, action_dim), or None if no original queue exists. """ with self.lock: if self.original_queue is None: return None return self.original_queue[self.last_index :] def merge( self, original_actions: Tensor, processed_actions: Tensor, real_delay: int, action_index_before_inference: int | None = 0, ): """Merge new actions into the queue. This method operates differently based on RTC mode: - RTC enabled: Replaces the queue, accounting for inference delay - RTC disabled: Appends to the queue, maintaining continuity Args: original_actions: Unprocessed actions from policy (time_steps, action_dim). processed_actions: Post-processed actions for robot (time_steps, action_dim). real_delay: Number of time steps of inference delay. action_index_before_inference: Index before inference started, for validation. """ with self.lock: self._check_delays(real_delay, action_index_before_inference) if self.cfg.enabled: self._replace_actions_queue(original_actions, processed_actions, real_delay) return self._append_actions_queue(original_actions, processed_actions) def _replace_actions_queue(self, original_actions: Tensor, processed_actions: Tensor, real_delay: int): """Replace the queue with new actions (RTC mode). Discards the first `real_delay` actions since they correspond to the time spent during inference, when the robot was executing previous actions. Args: original_actions: Unprocessed actions from policy. processed_actions: Post-processed actions for robot. real_delay: Number of time steps to skip due to inference delay. """ self.original_queue = original_actions[real_delay:].clone() self.queue = processed_actions[real_delay:].clone() logger.debug(f"original_actions shape: {self.original_queue.shape}") logger.debug(f"processed_actions shape: {self.queue.shape}") logger.debug(f"real_delay: {real_delay}") self.last_index = 0 def _append_actions_queue(self, original_actions: Tensor, processed_actions: Tensor): """Append new actions to the queue (non-RTC mode). Removes already-consumed actions and appends new ones, maintaining queue continuity without replacement. Args: original_actions: Unprocessed actions from policy. processed_actions: Post-processed actions for robot. """ if self.queue is None: self.original_queue = original_actions.clone() self.queue = processed_actions.clone() return self.original_queue = torch.cat([self.original_queue, original_actions.clone()]) self.original_queue = self.original_queue[self.last_index :] self.queue = torch.cat([self.queue, processed_actions.clone()]) self.queue = self.queue[self.last_index :] self.last_index = 0 def _check_delays(self, real_delay: int, action_index_before_inference: int | None = None): """Validate that computed delays match expectations. Compares the delay computed from inference latency with the actual number of actions consumed during inference. Args: real_delay: Delay computed from inference latency. action_index_before_inference: Action index when inference started. """ if action_index_before_inference is None: return indexes_diff = self.last_index - action_index_before_inference if indexes_diff != real_delay: # Let's check that action index difference (real delay calculated based on action queue) # is the same as delay calculated based on inference latency logger.warning( f"[ACTION_QUEUE] Indexes diff is not equal to real delay. " f"Indexes diff: {indexes_diff}, real delay: {real_delay}" )
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/rtc/action_queue.py", "license": "Apache License 2.0", "lines": 171, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/rtc/configuration_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ Real Time Chunking (RTC) and Bidirectional Decoding (BID) configuration classes. Based on: - Real Time Chunking: https://www.physicalintelligence.company/research/real_time_chunking """ from dataclasses import dataclass from lerobot.configs.types import RTCAttentionSchedule @dataclass class RTCConfig: """Configuration for Real Time Chunking (RTC) inference. RTC improves real-time inference by treating chunk generation as an inpainting problem, strategically handling overlapping timesteps between action chunks using prefix attention. """ # Infrastructure enabled: bool = False # Core RTC settings # Todo change to exp prefix_attention_schedule: RTCAttentionSchedule = RTCAttentionSchedule.LINEAR max_guidance_weight: float = 10.0 execution_horizon: int = 10 # Debug settings debug: bool = False debug_maxlen: int = 100 def __post_init__(self): """Validate RTC configuration parameters.""" if self.max_guidance_weight <= 0: raise ValueError(f"max_guidance_weight must be positive, got {self.max_guidance_weight}") if self.debug_maxlen <= 0: raise ValueError(f"debug_maxlen must be positive, got {self.debug_maxlen}")
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/rtc/configuration_rtc.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/rtc/debug_tracker.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Debug information handler for Real-Time Chunking (RTC).""" from dataclasses import dataclass, field from typing import Any import torch from torch import Tensor @dataclass class DebugStep: """Container for debug information from a single denoising step. Attributes: step_idx (int): Step index/counter. x_t (Tensor | None): Current latent/state tensor. v_t (Tensor | None): Velocity from denoiser. x1_t (Tensor | None): Denoised prediction (x_t - time * v_t). correction (Tensor | None): Correction gradient tensor. err (Tensor | None): Weighted error term. weights (Tensor | None): Prefix attention weights. guidance_weight (float | Tensor | None): Applied guidance weight. time (float | Tensor | None): Time parameter. inference_delay (int | None): Inference delay parameter. execution_horizon (int | None): Execution horizon parameter. metadata (dict[str, Any]): Additional metadata. """ step_idx: int = 0 x_t: Tensor | None = None v_t: Tensor | None = None x1_t: Tensor | None = None correction: Tensor | None = None err: Tensor | None = None weights: Tensor | None = None guidance_weight: float | Tensor | None = None time: float | Tensor | None = None inference_delay: int | None = None execution_horizon: int | None = None metadata: dict[str, Any] = field(default_factory=dict) def to_dict(self, include_tensors: bool = False) -> dict[str, Any]: """Convert debug step to dictionary. Args: include_tensors (bool): If True, include tensor values. If False, only include tensor statistics (shape, mean, std, min, max). Returns: Dictionary representation of the debug step. """ result = { "step_idx": self.step_idx, "guidance_weight": ( self.guidance_weight.item() if isinstance(self.guidance_weight, Tensor) else self.guidance_weight ), "time": self.time.item() if isinstance(self.time, Tensor) else self.time, "inference_delay": self.inference_delay, "execution_horizon": self.execution_horizon, "metadata": self.metadata.copy(), } # Add tensor information tensor_fields = ["x_t", "v_t", "x1_t", "correction", "err", "weights"] for field_name in tensor_fields: tensor = getattr(self, field_name) if tensor is not None: if include_tensors: result[field_name] = tensor.detach().cpu() else: result[f"{field_name}_stats"] = { "shape": tuple(tensor.shape), "mean": tensor.mean().item(), "std": tensor.std().item(), "min": tensor.min().item(), "max": tensor.max().item(), } return result class Tracker: """Collects and manages debug information for RTC processing. This tracker stores debug information from recent denoising steps in a dictionary, using time as the key for efficient lookups and updates. Args: enabled (bool): Whether debug collection is enabled. maxlen (int | None): Optional sliding window size. If provided, only the most recent ``maxlen`` debug steps are kept. If ``None``, keeps all. """ def __init__(self, enabled: bool = False, maxlen: int = 100): self.enabled = enabled self._steps = {} if enabled else None # Dictionary with time as key self._maxlen = maxlen self._step_counter = 0 def reset(self) -> None: """Clear all recorded debug information.""" if self.enabled and self._steps is not None: self._steps.clear() self._step_counter = 0 @torch._dynamo.disable def track( self, time: float | Tensor, x_t: Tensor | None = None, v_t: Tensor | None = None, x1_t: Tensor | None = None, correction: Tensor | None = None, err: Tensor | None = None, weights: Tensor | None = None, guidance_weight: float | Tensor | None = None, inference_delay: int | None = None, execution_horizon: int | None = None, **metadata, ) -> None: """Track debug information for a denoising step at a given time. If a step with the given time already exists, it will be updated with the new data. Otherwise, a new step will be created. Only non-None fields are updated/set. Note: This method is excluded from torch.compile to avoid graph breaks from operations like .item() which are incompatible with compiled graphs. Args: time (float | Tensor): Time parameter - used as the key to identify the step. x_t (Tensor | None): Current latent/state tensor. v_t (Tensor | None): Velocity from denoiser. x1_t (Tensor | None): Denoised prediction. correction (Tensor | None): Correction gradient tensor. err (Tensor | None): Weighted error term. weights (Tensor | None): Prefix attention weights. guidance_weight (float | Tensor | None): Applied guidance weight. inference_delay (int | None): Inference delay parameter. execution_horizon (int | None): Execution horizon parameter. **metadata: Additional metadata to store. """ if not self.enabled: return # Convert time to float and round to avoid float precision issues time_value = time.item() if isinstance(time, Tensor) else time time_key = round(time_value, 6) # Use rounded time as dictionary key # Check if step with this time already exists if time_key in self._steps: # Update existing step with non-None fields existing_step = self._steps[time_key] if x_t is not None: existing_step.x_t = x_t.detach().clone() if v_t is not None: existing_step.v_t = v_t.detach().clone() if x1_t is not None: existing_step.x1_t = x1_t.detach().clone() if correction is not None: existing_step.correction = correction.detach().clone() if err is not None: existing_step.err = err.detach().clone() if weights is not None: existing_step.weights = weights.detach().clone() if guidance_weight is not None: existing_step.guidance_weight = guidance_weight if inference_delay is not None: existing_step.inference_delay = inference_delay if execution_horizon is not None: existing_step.execution_horizon = execution_horizon if metadata: existing_step.metadata.update(metadata) else: # Create new step step = DebugStep( step_idx=self._step_counter, x_t=x_t.detach().clone() if x_t is not None else None, v_t=v_t.detach().clone() if v_t is not None else None, x1_t=x1_t.detach().clone() if x1_t is not None else None, correction=correction.detach().clone() if correction is not None else None, err=err.detach().clone() if err is not None else None, weights=weights.detach().clone() if weights is not None else None, guidance_weight=guidance_weight, time=time_value, inference_delay=inference_delay, execution_horizon=execution_horizon, metadata=metadata, ) # Add to dictionary self._steps[time_key] = step self._step_counter += 1 # Enforce maxlen if set if self._maxlen is not None and len(self._steps) > self._maxlen: # Remove oldest entry (first key in dict - Python 3.7+ preserves insertion order) oldest_key = next(iter(self._steps)) del self._steps[oldest_key] def get_all_steps(self) -> list[DebugStep]: """Get all recorded debug steps. Returns: List of all DebugStep objects (may be empty if disabled). """ if not self.enabled or self._steps is None: return [] return list(self._steps.values()) def __len__(self) -> int: """Return the number of recorded debug steps.""" if not self.enabled or self._steps is None: return 0 return len(self._steps)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/rtc/debug_tracker.py", "license": "Apache License 2.0", "lines": 202, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/rtc/debug_visualizer.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Visualization utilities for RTC debug information.""" import torch class RTCDebugVisualizer: """Visualizer for RTC debug information. This class provides methods to visualize debug information collected by the Tracker, including corrections, errors, weights, and guidance weights over denoising steps. """ @staticmethod def plot_waypoints( axes, tensor, start_from: int = 0, color: str = "blue", label: str = "", alpha: float = 0.7, linewidth: float = 2, marker: str | None = None, markersize: int = 4, ): """Plot trajectories across multiple dimensions. This function plots a tensor's values across time for multiple dimensions, with each dimension plotted on a separate axis. Args: axes: Array of matplotlib axes (one for each dimension). tensor: The tensor to plot (can be torch.Tensor or numpy array). Shape should be (time_steps, num_dims) or (batch, time_steps, num_dims). start_from: Starting index for the x-axis. color: Color for the plot lines. label: Label for the plot legend. alpha: Transparency level for the plot. linewidth: Width of the plot lines. marker: Marker style for data points (e.g., 'o', 's', '^'). markersize: Size of the markers. """ import numpy as np # Handle None tensor if tensor is None: return # Convert tensor to numpy if needed tensor_np = tensor.detach().cpu().numpy() if isinstance(tensor, torch.Tensor) else tensor # Handle different tensor shapes if tensor_np.ndim == 3: # If batch dimension present, take first batch tensor_np = tensor_np[0] elif tensor_np.ndim == 1: # If 1D, reshape to (time_steps, 1) tensor_np = tensor_np.reshape(-1, 1) # Get dimensions time_steps, num_dims = tensor_np.shape # Create x-axis indices x_indices = np.arange(start_from, start_from + time_steps) # Plot each dimension on its corresponding axis num_axes = len(axes) if hasattr(axes, "__len__") else 1 for dim_idx in range(min(num_dims, num_axes)): ax = axes[dim_idx] if hasattr(axes, "__len__") else axes # Plot the trajectory if marker: ax.plot( x_indices, tensor_np[:, dim_idx], color=color, label=label if dim_idx == 0 else "", # Only show label once alpha=alpha, linewidth=linewidth, marker=marker, markersize=markersize, ) else: ax.plot( x_indices, tensor_np[:, dim_idx], color=color, label=label if dim_idx == 0 else "", # Only show label once alpha=alpha, linewidth=linewidth, ) # Add grid and labels if not already present if not ax.xaxis.get_label().get_text(): ax.set_xlabel("Step", fontsize=10) if not ax.yaxis.get_label().get_text(): ax.set_ylabel(f"Dim {dim_idx}", fontsize=10) ax.grid(True, alpha=0.3)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/rtc/debug_visualizer.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/rtc/latency_tracker.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Latency tracking utilities for Real-Time Chunking (RTC).""" from collections import deque import numpy as np class LatencyTracker: """Tracks recent latencies and provides max/percentile queries. Args: maxlen (int | None): Optional sliding window size. If provided, only the most recent ``maxlen`` latencies are kept. If ``None``, keeps all. """ def __init__(self, maxlen: int = 100): self._values = deque(maxlen=maxlen) self.reset() def reset(self) -> None: """Clear all recorded latencies.""" self._values.clear() self.max_latency = 0.0 def add(self, latency: float) -> None: """Add a latency sample (seconds).""" # Ensure numeric and non-negative val = float(latency) if val < 0: return self._values.append(val) self.max_latency = max(self.max_latency, val) def __len__(self) -> int: return len(self._values) def max(self) -> float | None: """Return the maximum latency or None if empty.""" return self.max_latency def percentile(self, q: float) -> float | None: """Return the q-quantile (q in [0,1]) of recorded latencies or None if empty.""" if not self._values: return 0.0 q = float(q) if q <= 0.0: return min(self._values) if q >= 1.0: return self.max_latency vals = np.array(list(self._values), dtype=np.float32) return float(np.quantile(vals, q)) def p95(self) -> float | None: """Return the 95th percentile latency or None if empty.""" return self.percentile(0.95)
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/rtc/latency_tracker.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:src/lerobot/policies/rtc/modeling_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """ Real-Time Chunking (RTC) implementation for LeRobot. Based on Physical Intelligence's Kinetix implementation: https://github.com/Physical-Intelligence/real-time-chunking-kinetix/blob/main/src/model.py#L214 """ import logging import math import torch from torch import Tensor from lerobot.configs.types import RTCAttentionSchedule from lerobot.policies.rtc.configuration_rtc import RTCConfig from lerobot.policies.rtc.debug_tracker import Tracker logger = logging.getLogger(__name__) class RTCProcessor: """Real-Time Chunking processor for action chunking policies. This class implements RTC techniques including velocity calculation, prefix attention, and adaptive chunk processing. """ def __init__(self, rtc_config: RTCConfig): self.rtc_config = rtc_config self.tracker = None if rtc_config.debug: self.tracker = Tracker( enabled=rtc_config.debug, maxlen=rtc_config.debug_maxlen, ) # ====================== Tracker Proxy Methods ====================== def track( self, time: float | Tensor, x_t: Tensor | None = None, v_t: Tensor | None = None, x1_t: Tensor | None = None, correction: Tensor | None = None, err: Tensor | None = None, weights: Tensor | None = None, guidance_weight: float | Tensor | None = None, inference_delay: int | None = None, execution_horizon: int | None = None, **metadata, ) -> None: """Proxy method to track debug information. If tracker is None or disabled, this method does nothing. Otherwise, it forwards the call to tracker.track(). """ if self.tracker is not None: self.tracker.track( time=time, x_t=x_t, v_t=v_t, x1_t=x1_t, correction=correction, err=err, weights=weights, guidance_weight=guidance_weight, inference_delay=inference_delay, execution_horizon=execution_horizon, **metadata, ) def get_all_debug_steps(self) -> list: """Get all debug steps from tracker. Returns empty list if tracker is disabled or None. """ if self.tracker is not None: return self.tracker.get_all_steps() return [] def is_debug_enabled(self) -> bool: """Check if debug tracking is enabled. Returns True if tracker exists and is enabled. """ return self.tracker is not None and self.tracker.enabled def reset_tracker(self) -> None: """Reset the tracker, clearing all recorded steps. Does nothing if tracker is None. """ if self.tracker is not None: self.tracker.reset() # ====================== End Tracker Proxy Methods ====================== def denoise_step( self, x_t, prev_chunk_left_over, inference_delay, time, original_denoise_step_partial, execution_horizon=None, ) -> Tensor: """RTC guidance wrapper around an existing denoiser. This method wraps an original denoising callable that only takes ``x_t`` and returns a base denoised velocity ``v_t``. It then applies Real-Time Chunking (RTC) prefix guidance using the leftover prefix from the previous chunk. Args: x_t (Tensor): Current latent/state to denoise. Shape ``(B, T, A)`` or ``(T, A)``. prev_chunk_left_over (Tensor | None): Unexecuted prefix from the previous chunk. Shape ``(B, T_prev, A)`` or ``(T_prev, A)``. If ``None``, no guidance is applied and the method returns ``v_t`` from the original denoiser. inference_delay (int): Number of timesteps from the prefix to use for guidance. time (float | Tensor): Scalar in [0, 1] indicating normalized time. Must be broadcastable with ``x_t``. original_denoise_step_partial (Callable[[Tensor], Tensor]): Callable that computes the base denoised velocity given only ``x_t``. execution_horizon (int | None): Horizon used to build prefix weights. If ``None``, defaults to ``self.rtc_config.execution_horizon``. Returns: Tensor: Guided velocity with the same shape as ``v_t``. Notes: - If inputs are 2D, a batch dimension is temporarily added and removed at the end. - If ``prev_chunk_left_over`` is shorter than the current chunk length ``T``, it is right-padded with zeros to match ``T``. - Prefix weights are constructed via ``get_prefix_weights(inference_delay, execution_horizon, T)`` and broadcast to ``(B, T, A)``. - Guidance correction is computed via autograd using ``x1_t = x_t + time * v_t`` and ``error = (prev_chunk_left_over - x1_t) * weights``. - The final guidance weight is clamped by ``max_guidance_weight`` from the config. Reference: https://www.physicalintelligence.company/download/real_time_chunking.pdf """ # In the original implementation, the time goes from 0 to 1 and # In our implementation, the time goes from 1 to 0 # So we need to invert the time tau = 1 - time if prev_chunk_left_over is None: # First step, no guidance - return v_t v_t = original_denoise_step_partial(x_t) return v_t x_t = x_t.clone().detach() squeezed = False if len(x_t.shape) < 3: # Add batch dimension x_t = x_t.unsqueeze(0) squeezed = True if len(prev_chunk_left_over.shape) < 3: # Add batch dimension prev_chunk_left_over = prev_chunk_left_over.unsqueeze(0) if execution_horizon is None: execution_horizon = self.rtc_config.execution_horizon # If the previous action chunk is to short then it doesn't make sense to use long execution horizon # because there is nothing to merge if execution_horizon > prev_chunk_left_over.shape[1]: execution_horizon = prev_chunk_left_over.shape[1] batch_size = x_t.shape[0] action_chunk_size = x_t.shape[1] action_dim = x_t.shape[2] if prev_chunk_left_over.shape[1] < action_chunk_size or prev_chunk_left_over.shape[2] < action_dim: padded = torch.zeros(batch_size, action_chunk_size, action_dim).to(x_t.device) padded[:, : prev_chunk_left_over.shape[1], : prev_chunk_left_over.shape[2]] = prev_chunk_left_over prev_chunk_left_over = padded assert prev_chunk_left_over.shape == x_t.shape, ( "The padded previous chunk must be the same size as the input tensor" ) weights = ( self.get_prefix_weights(inference_delay, execution_horizon, action_chunk_size) .to(x_t.device) .unsqueeze(0) .unsqueeze(-1) ) with torch.enable_grad(): v_t = original_denoise_step_partial(x_t) x_t.requires_grad_(True) x1_t = x_t - time * v_t # noqa: N806 err = (prev_chunk_left_over - x1_t) * weights grad_outputs = err.clone().detach() correction = torch.autograd.grad(x1_t, x_t, grad_outputs, retain_graph=False)[0] max_guidance_weight = torch.as_tensor(self.rtc_config.max_guidance_weight) tau_tensor = torch.as_tensor(tau) squared_one_minus_tau = (1 - tau_tensor) ** 2 inv_r2 = (squared_one_minus_tau + tau_tensor**2) / (squared_one_minus_tau) c = torch.nan_to_num((1 - tau_tensor) / tau_tensor, posinf=max_guidance_weight) guidance_weight = torch.nan_to_num(c * inv_r2, posinf=max_guidance_weight) guidance_weight = torch.minimum(guidance_weight, max_guidance_weight) result = v_t - guidance_weight * correction # Remove the batch dimension if it was added if squeezed: result = result.squeeze(0) correction = correction.squeeze(0) x1_t = x1_t.squeeze(0) err = err.squeeze(0) self.track( time=time, x1_t=x1_t, correction=correction, err=err, weights=weights, guidance_weight=guidance_weight, inference_delay=inference_delay, execution_horizon=execution_horizon, ) return result def get_prefix_weights(self, start, end, total): start = min(start, end) if self.rtc_config.prefix_attention_schedule == RTCAttentionSchedule.ZEROS: weights = torch.zeros(total) weights[:start] = 1.0 elif self.rtc_config.prefix_attention_schedule == RTCAttentionSchedule.ONES: weights = torch.ones(total) weights[end:] = 0.0 elif self.rtc_config.prefix_attention_schedule == RTCAttentionSchedule.LINEAR: lin_weights = self._linweights(start, end, total) weights = self._add_trailing_zeros(lin_weights, total, end) weights = self._add_leading_ones(weights, start, total) elif self.rtc_config.prefix_attention_schedule == RTCAttentionSchedule.EXP: lin_weights = self._linweights(start, end, total) lin_weights = lin_weights * torch.expm1(lin_weights).div(math.e - 1) weights = self._add_trailing_zeros(lin_weights, total, end) weights = self._add_leading_ones(weights, start, total) return weights def _linweights(self, start, end, total): skip_steps_at_end = max(total - end, 0) linspace_steps = total - skip_steps_at_end - start if end <= start or linspace_steps <= 0: return torch.tensor([]) return torch.linspace(1, 0, linspace_steps + 2)[1:-1] def _add_trailing_zeros(self, weights, total, end): zeros_len = total - end if zeros_len <= 0: return weights zeros = torch.zeros(zeros_len) return torch.cat([weights, zeros]) def _add_leading_ones(self, weights, start, total): ones_len = min(start, total) if ones_len <= 0: return weights ones = torch.ones(ones_len) return torch.cat([ones, weights])
{ "repo_id": "huggingface/lerobot", "file_path": "src/lerobot/policies/rtc/modeling_rtc.py", "license": "Apache License 2.0", "lines": 238, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
huggingface/lerobot:tests/policies/pi0_pi05/test_pi05_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Test PI0.5 policy with Real-Time Chunking (RTC) enabled during inference.""" import os import pytest import torch # Skip this entire module in CI pytestmark = pytest.mark.skipif( os.environ.get("CI") == "true" or os.environ.get("GITHUB_ACTIONS") == "true", reason="TODO: This test seems to hang the CI", ) from lerobot.configs.types import FeatureType, PolicyFeature, RTCAttentionSchedule # noqa: E402 from lerobot.policies.pi05 import PI05Config, PI05Policy, make_pi05_pre_post_processors # noqa: E402 from lerobot.policies.rtc.configuration_rtc import RTCConfig # noqa: E402 from lerobot.utils.random_utils import set_seed # noqa: E402 from tests.utils import require_cuda # noqa: E402 @require_cuda def test_pi05_rtc_initialization(): """Test PI0.5 policy can initialize RTC processor.""" set_seed(42) config = PI05Config(max_action_dim=7, max_state_dim=14, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Instantiate policy policy = PI05Policy(config) # Verify RTC processor is initialized assert hasattr(policy, "rtc_processor") assert policy.rtc_processor is not None assert policy.rtc_processor.rtc_config.enabled is True print("✓ PI0.5 RTC initialization: Test passed") @require_cuda def test_pi05_rtc_initialization_without_rtc_config(): """Test PI0.5 policy can initialize without RTC config.""" set_seed(42) config = PI05Config(max_action_dim=7, max_state_dim=14, dtype="float32") # Instantiate policy policy = PI05Policy(config) # Verify RTC processor is not initialized assert hasattr(policy, "rtc_processor") assert policy.rtc_processor is None assert policy.model.rtc_processor is None assert policy._rtc_enabled() is False print("✓ PI0.5 RTC initialization without RTC config: Test passed") @require_cuda def test_pi05_rtc_inference_with_prev_chunk(): """Test PI0.5 policy inference with RTC and previous chunk.""" set_seed(42) config = PI05Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats (PI0.5 uses QUANTILES normalization) dataset_stats = { "observation.state": { "mean": torch.zeros(14), "std": torch.ones(14), "q01": -torch.ones(14), "q99": torch.ones(14), }, "action": { "mean": torch.zeros(7), "std": torch.ones(7), "q01": -torch.ones(7), "q99": torch.ones(7), }, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and preprocessor policy = PI05Policy(config) policy.eval() preprocessor, _ = make_pi05_pre_post_processors(config=config, dataset_stats=dataset_stats) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC and previous chunk actions_with_rtc = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=prev_chunk, inference_delay=4, execution_horizon=10, ) # Test without RTC for comparison policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True # Verify shapes assert actions_with_rtc.shape == (1, config.chunk_size, 7) assert actions_without_rtc.shape == (1, config.chunk_size, 7) # With previous chunk, actions should be different (RTC guidance applied) assert not torch.allclose(actions_with_rtc, actions_without_rtc, rtol=1e-3) print("✓ PI0.5 RTC inference with prev_chunk: Test passed") @require_cuda def test_pi05_rtc_inference_without_prev_chunk(): """Test PI0.5 policy inference with RTC but no previous chunk (RTC should have no effect).""" set_seed(42) config = PI05Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats (PI0.5 uses QUANTILES normalization) dataset_stats = { "observation.state": { "mean": torch.zeros(14), "std": torch.ones(14), "q01": -torch.ones(14), "q99": torch.ones(14), }, "action": { "mean": torch.zeros(7), "std": torch.ones(7), "q01": -torch.ones(7), "q99": torch.ones(7), }, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and preprocessor policy = PI05Policy(config) policy.eval() preprocessor, _ = make_pi05_pre_post_processors(config=config, dataset_stats=dataset_stats) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC enabled but no previous chunk actions_with_rtc_no_prev = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=None, ) # Test without RTC policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True # Without previous chunk, RTC should have no effect assert torch.allclose(actions_with_rtc_no_prev, actions_without_rtc, rtol=1e-5) print("✓ PI0.5 RTC inference without prev_chunk: Test passed") @require_cuda def test_pi05_rtc_validation_rules(): """Test PI0.5 policy with RTC follows all three validation rules.""" set_seed(42) config = PI05Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats (PI0.5 uses QUANTILES normalization) dataset_stats = { "observation.state": { "mean": torch.zeros(14), "std": torch.ones(14), "q01": -torch.ones(14), "q99": torch.ones(14), }, "action": { "mean": torch.zeros(7), "std": torch.ones(7), "q01": -torch.ones(7), "q99": torch.ones(7), }, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and preprocessor policy = PI05Policy(config) policy.eval() preprocessor, _ = make_pi05_pre_post_processors(config=config, dataset_stats=dataset_stats) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) inference_delay = 4 execution_horizon = 10 with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC actions_with_rtc = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=prev_chunk, inference_delay=inference_delay, execution_horizon=execution_horizon, ) # Test without RTC policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True assert not torch.allclose(actions_with_rtc, actions_without_rtc, rtol=1e-3)
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/pi0_pi05/test_pi05_rtc.py", "license": "Apache License 2.0", "lines": 271, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/pi0_pi05/test_pi0_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Test PI0 policy with Real-Time Chunking (RTC) enabled during inference.""" import os import pytest import torch # Skip this entire module in CI pytestmark = pytest.mark.skipif( os.environ.get("CI") == "true" or os.environ.get("GITHUB_ACTIONS") == "true", reason="TODO: This test seems to hang the CI", ) from lerobot.configs.types import FeatureType, PolicyFeature, RTCAttentionSchedule # noqa: E402 from lerobot.policies.pi0 import PI0Config, PI0Policy, make_pi0_pre_post_processors # noqa: E402 from lerobot.policies.rtc.configuration_rtc import RTCConfig # noqa: E402 from lerobot.utils.random_utils import set_seed # noqa: E402 from tests.utils import require_cuda # noqa: E402 @require_cuda def test_pi0_rtc_initialization(): """Test PI0 policy can initialize RTC processor.""" set_seed(42) config = PI0Config(max_action_dim=7, max_state_dim=14, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Instantiate policy policy = PI0Policy(config) # Verify RTC processor is initialized assert hasattr(policy, "rtc_processor") assert policy.rtc_processor is not None assert policy.rtc_processor.rtc_config.enabled is True print("✓ PI0 RTC initialization: Test passed") @require_cuda def test_pi0_rtc_initialization_without_rtc_config(): """Test PI0 policy can initialize without RTC config.""" set_seed(42) config = PI0Config(max_action_dim=7, max_state_dim=14, dtype="float32") # Instantiate policy policy = PI0Policy(config) # Verify RTC processor is not initialized assert hasattr(policy, "rtc_processor") assert policy.rtc_processor is None assert policy.model.rtc_processor is None assert policy._rtc_enabled() is False print("✓ PI0 RTC initialization without RTC config: Test passed") @require_cuda def test_pi0_rtc_inference_with_prev_chunk(): """Test PI0 policy inference with RTC and previous chunk.""" set_seed(42) config = PI0Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and preprocessor policy = PI0Policy(config) policy.eval() preprocessor, _ = make_pi0_pre_post_processors(config=config, dataset_stats=dataset_stats) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC and previous chunk actions_with_rtc = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=prev_chunk, inference_delay=4, execution_horizon=10, ) # Test without RTC for comparison policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True # Verify shapes assert actions_with_rtc.shape == (1, config.chunk_size, 7) assert actions_without_rtc.shape == (1, config.chunk_size, 7) # With previous chunk, actions should be different (RTC guidance applied) assert not torch.allclose(actions_with_rtc, actions_without_rtc, rtol=1e-3) print("✓ PI0 RTC inference with prev_chunk: Test passed") @require_cuda def test_pi0_rtc_inference_without_prev_chunk(): """Test PI0 policy inference with RTC but no previous chunk (RTC should have no effect).""" set_seed(42) config = PI0Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and preprocessor policy = PI0Policy(config) policy.eval() preprocessor, _ = make_pi0_pre_post_processors(config=config, dataset_stats=dataset_stats) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC enabled but no previous chunk actions_with_rtc_no_prev = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=None, ) # Test without RTC policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True # Without previous chunk, RTC should have no effect assert torch.allclose(actions_with_rtc_no_prev, actions_without_rtc, rtol=1e-5) print("✓ PI0 RTC inference without prev_chunk: Test passed") @require_cuda def test_pi0_rtc_validation_rules(): """Test PI0 policy with RTC follows all three validation rules.""" set_seed(42) config = PI0Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and preprocessor policy = PI0Policy(config) policy.eval() preprocessor, _ = make_pi0_pre_post_processors(config=config, dataset_stats=dataset_stats) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) inference_delay = 4 execution_horizon = 10 with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC actions_with_rtc = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=prev_chunk, inference_delay=inference_delay, execution_horizon=execution_horizon, ) # Test without RTC policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True assert not torch.allclose(actions_with_rtc, actions_without_rtc, rtol=1e-3) """Test PI0 with different RTC attention schedules.""" set_seed(42) schedules = [ RTCAttentionSchedule.ZEROS, RTCAttentionSchedule.ONES, RTCAttentionSchedule.LINEAR, RTCAttentionSchedule.EXP, ] config = PI0Config(max_action_dim=7, max_state_dim=14, chunk_size=50, dtype="float32") config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } device = config.device for schedule in schedules: print(f"Testing schedule: {schedule}") # Add RTC config with specific schedule config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=schedule, debug=False, ) # Instantiate policy policy = PI0Policy(config) policy.eval() preprocessor, _ = make_pi0_pre_post_processors(config=config, dataset_stats=dataset_stats) # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) with torch.no_grad(): noise = policy.model.sample_noise((1, config.chunk_size, 7), device) actions = policy.predict_action_chunk( batch, noise=noise, prev_chunk_left_over=prev_chunk, inference_delay=4, execution_horizon=10, ) # Verify shape assert actions.shape == (1, config.chunk_size, 7) print(f" ✓ Schedule {schedule}: Test passed") print("✓ PI0 RTC different schedules: All schedules tested")
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/pi0_pi05/test_pi0_rtc.py", "license": "Apache License 2.0", "lines": 300, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/rtc/test_action_queue.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Tests for RTC ActionQueue module.""" import threading import time import pytest import torch from lerobot.policies.rtc.action_queue import ActionQueue from lerobot.policies.rtc.configuration_rtc import RTCConfig # ====================== Fixtures ====================== @pytest.fixture def rtc_config_enabled(): """Create an RTC config with RTC enabled.""" return RTCConfig(enabled=True, execution_horizon=10, max_guidance_weight=1.0) @pytest.fixture def rtc_config_disabled(): """Create an RTC config with RTC disabled.""" return RTCConfig(enabled=False, execution_horizon=10, max_guidance_weight=1.0) @pytest.fixture def sample_actions(): """Create sample action tensors for testing.""" return { "original": torch.randn(50, 6), # (time_steps, action_dim) "processed": torch.randn(50, 6), "short": torch.randn(10, 6), "longer": torch.randn(100, 6), } @pytest.fixture def action_queue_rtc_enabled(rtc_config_enabled): """Create an ActionQueue with RTC enabled.""" return ActionQueue(rtc_config_enabled) @pytest.fixture def action_queue_rtc_disabled(rtc_config_disabled): """Create an ActionQueue with RTC disabled.""" return ActionQueue(rtc_config_disabled) # ====================== Initialization Tests ====================== def test_action_queue_initialization_rtc_enabled(rtc_config_enabled): """Test ActionQueue initializes correctly with RTC enabled.""" queue = ActionQueue(rtc_config_enabled) assert queue.queue is None assert queue.original_queue is None assert queue.last_index == 0 assert queue.cfg.enabled is True def test_action_queue_initialization_rtc_disabled(rtc_config_disabled): """Test ActionQueue initializes correctly with RTC disabled.""" queue = ActionQueue(rtc_config_disabled) assert queue.queue is None assert queue.original_queue is None assert queue.last_index == 0 assert queue.cfg.enabled is False # ====================== get() Tests ====================== def test_get_returns_none_when_empty(action_queue_rtc_enabled): """Test get() returns None when queue is empty.""" action = action_queue_rtc_enabled.get() assert action is None def test_get_returns_actions_sequentially(action_queue_rtc_enabled, sample_actions): """Test get() returns actions in sequence.""" # Initialize queue with actions action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) # Get first action action1 = action_queue_rtc_enabled.get() assert action1 is not None assert action1.shape == (6,) assert torch.equal(action1, sample_actions["processed"][0]) # Get second action action2 = action_queue_rtc_enabled.get() assert action2 is not None assert torch.equal(action2, sample_actions["processed"][1]) def test_get_returns_none_after_exhaustion(action_queue_rtc_enabled, sample_actions): """Test get() returns None after all actions are consumed.""" # Use short action sequence action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume all actions for _ in range(10): action = action_queue_rtc_enabled.get() assert action is not None # Next get should return None action = action_queue_rtc_enabled.get() assert action is None def test_get_increments_last_index(action_queue_rtc_enabled, sample_actions): """Test get() increments last_index correctly.""" action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) assert action_queue_rtc_enabled.last_index == 0 action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.last_index == 1 action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.last_index == 2 # ====================== qsize() Tests ====================== def test_qsize_returns_zero_when_empty(action_queue_rtc_enabled): """Test qsize() returns 0 when queue is empty.""" assert action_queue_rtc_enabled.qsize() == 0 def test_qsize_returns_correct_size(action_queue_rtc_enabled, sample_actions): """Test qsize() returns correct number of remaining actions.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) assert action_queue_rtc_enabled.qsize() == 10 action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.qsize() == 9 action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.qsize() == 8 def test_qsize_after_exhaustion(action_queue_rtc_enabled, sample_actions): """Test qsize() returns 0 after queue is exhausted.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume all actions for _ in range(10): action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.qsize() == 0 # ====================== empty() Tests ====================== def test_empty_returns_true_when_empty(action_queue_rtc_enabled): """Test empty() returns True when queue is empty.""" assert action_queue_rtc_enabled.empty() is True def test_empty_returns_false_when_not_empty(action_queue_rtc_enabled, sample_actions): """Test empty() returns False when queue has actions.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) assert action_queue_rtc_enabled.empty() is False def test_empty_after_partial_consumption(action_queue_rtc_enabled, sample_actions): """Test empty() returns False after partial consumption.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) action_queue_rtc_enabled.get() action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.empty() is False def test_empty_after_full_consumption(action_queue_rtc_enabled, sample_actions): """Test empty() returns True after all actions consumed.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume all for _ in range(10): action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.empty() is True # ====================== get_action_index() Tests ====================== def test_get_action_index_initial_value(action_queue_rtc_enabled): """Test get_action_index() returns 0 initially.""" assert action_queue_rtc_enabled.get_action_index() == 0 def test_get_action_index_after_consumption(action_queue_rtc_enabled, sample_actions): """Test get_action_index() tracks consumption correctly.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) assert action_queue_rtc_enabled.get_action_index() == 0 action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.get_action_index() == 1 action_queue_rtc_enabled.get() action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.get_action_index() == 3 # ====================== get_left_over() Tests ====================== def test_get_left_over_returns_none_when_empty(action_queue_rtc_enabled): """Test get_left_over() returns None when queue is empty.""" leftover = action_queue_rtc_enabled.get_left_over() assert leftover is None def test_get_left_over_returns_all_when_unconsumed(action_queue_rtc_enabled, sample_actions): """Test get_left_over() returns all original actions when none consumed.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) leftover = action_queue_rtc_enabled.get_left_over() assert leftover is not None assert leftover.shape == (10, 6) assert torch.equal(leftover, sample_actions["short"]) def test_get_left_over_returns_remaining_after_consumption(action_queue_rtc_enabled, sample_actions): """Test get_left_over() returns only remaining original actions.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume 3 actions action_queue_rtc_enabled.get() action_queue_rtc_enabled.get() action_queue_rtc_enabled.get() leftover = action_queue_rtc_enabled.get_left_over() assert leftover is not None assert leftover.shape == (7, 6) assert torch.equal(leftover, sample_actions["short"][3:]) def test_get_left_over_returns_empty_after_exhaustion(action_queue_rtc_enabled, sample_actions): """Test get_left_over() returns empty tensor after all consumed.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume all for _ in range(10): action_queue_rtc_enabled.get() leftover = action_queue_rtc_enabled.get_left_over() assert leftover is not None assert leftover.shape == (0, 6) # ====================== merge() with RTC Enabled Tests ====================== def test_merge_replaces_queue_when_rtc_enabled(action_queue_rtc_enabled, sample_actions): """Test merge() replaces queue when RTC is enabled.""" # Add initial actions action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) assert action_queue_rtc_enabled.qsize() == 10 # Consume some actions action_queue_rtc_enabled.get() action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.qsize() == 8 # Merge new actions - should replace, not append action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=5) # Queue should be replaced with new actions minus delay # Original has 50 actions, delay is 5, so remaining is 45 assert action_queue_rtc_enabled.qsize() == 45 assert action_queue_rtc_enabled.get_action_index() == 0 def test_merge_respects_real_delay(action_queue_rtc_enabled, sample_actions): """Test merge() correctly applies real_delay when RTC is enabled.""" delay = 10 action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=delay) # Queue should have original length minus delay expected_size = len(sample_actions["original"]) - delay assert action_queue_rtc_enabled.qsize() == expected_size # First action should be the one at index [delay] first_action = action_queue_rtc_enabled.get() assert torch.equal(first_action, sample_actions["processed"][delay]) def test_merge_resets_last_index_when_rtc_enabled(action_queue_rtc_enabled, sample_actions): """Test merge() resets last_index to 0 when RTC is enabled.""" action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) action_queue_rtc_enabled.get() action_queue_rtc_enabled.get() assert action_queue_rtc_enabled.last_index == 2 # Merge new actions action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=5) assert action_queue_rtc_enabled.last_index == 0 def test_merge_with_zero_delay(action_queue_rtc_enabled, sample_actions): """Test merge() with zero delay keeps all actions.""" action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) assert action_queue_rtc_enabled.qsize() == len(sample_actions["original"]) def test_merge_with_large_delay(action_queue_rtc_enabled, sample_actions): """Test merge() with delay larger than action sequence.""" # Delay is larger than sequence length delay = 100 action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=delay) # Queue should be empty (delay >= length) assert action_queue_rtc_enabled.qsize() == 0 # ====================== merge() with RTC Disabled Tests ====================== def test_merge_appends_when_rtc_disabled(action_queue_rtc_disabled, sample_actions): """Test merge() appends actions when RTC is disabled.""" # Add initial actions action_queue_rtc_disabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) initial_size = action_queue_rtc_disabled.qsize() assert initial_size == 10 # Merge more actions action_queue_rtc_disabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Should have appended assert action_queue_rtc_disabled.qsize() == initial_size + 10 def test_merge_removes_consumed_actions_when_appending(action_queue_rtc_disabled, sample_actions): """Test merge() removes consumed actions before appending when RTC is disabled.""" # Add initial actions action_queue_rtc_disabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) assert action_queue_rtc_disabled.qsize() == 10 # Consume 3 actions action_queue_rtc_disabled.get() action_queue_rtc_disabled.get() action_queue_rtc_disabled.get() assert action_queue_rtc_disabled.qsize() == 7 # Merge more actions action_queue_rtc_disabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Should have 7 remaining + 10 new = 17 assert action_queue_rtc_disabled.qsize() == 17 def test_merge_resets_last_index_after_append(action_queue_rtc_disabled, sample_actions): """Test merge() resets last_index after appending when RTC is disabled.""" action_queue_rtc_disabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) action_queue_rtc_disabled.get() action_queue_rtc_disabled.get() assert action_queue_rtc_disabled.last_index == 2 # Merge more actions action_queue_rtc_disabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # last_index should be reset to 0 assert action_queue_rtc_disabled.last_index == 0 def test_merge_ignores_delay_when_rtc_disabled(action_queue_rtc_disabled, sample_actions): """Test merge() ignores real_delay parameter when RTC is disabled.""" action_queue_rtc_disabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=10) # All actions should be in queue (delay ignored) assert action_queue_rtc_disabled.qsize() == len(sample_actions["original"]) def test_merge_first_call_with_rtc_disabled(action_queue_rtc_disabled, sample_actions): """Test merge() on first call with RTC disabled.""" action_queue_rtc_disabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) assert action_queue_rtc_disabled.qsize() == len(sample_actions["original"]) assert action_queue_rtc_disabled.last_index == 0 # ====================== merge() with Different Action Shapes Tests ====================== def test_merge_with_different_action_dims(): """Test merge() handles actions with different dimensions.""" cfg = RTCConfig(enabled=True, execution_horizon=10) queue = ActionQueue(cfg) # Actions with 4 dimensions instead of 6 actions_4d = torch.randn(20, 4) queue.merge(actions_4d, actions_4d, real_delay=5) action = queue.get() assert action.shape == (4,) def test_merge_with_different_lengths(): """Test merge() handles action sequences of varying lengths.""" cfg = RTCConfig(enabled=False, execution_horizon=10) queue = ActionQueue(cfg) # Add sequences of different lengths queue.merge(torch.randn(10, 6), torch.randn(10, 6), real_delay=0) assert queue.qsize() == 10 queue.merge(torch.randn(25, 6), torch.randn(25, 6), real_delay=0) assert queue.qsize() == 35 # ====================== merge() Delay Validation Tests ====================== def test_merge_validates_delay_consistency(action_queue_rtc_enabled, sample_actions, caplog): """Test merge() validates that real_delay matches action index difference.""" import logging caplog.set_level(logging.WARNING) # Initialize queue action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume 5 actions for _ in range(5): action_queue_rtc_enabled.get() # Merge with mismatched delay (should log warning) # We consumed 5 actions, so index is 5. If we pass action_index_before_inference=0, # then indexes_diff=5, but if real_delay=3, it will warn action_queue_rtc_enabled.merge( sample_actions["original"], sample_actions["processed"], real_delay=3, action_index_before_inference=0, ) # Check warning was logged assert "Indexes diff is not equal to real delay" in caplog.text def test_merge_no_warning_when_delays_match(action_queue_rtc_enabled, sample_actions, caplog): """Test merge() doesn't warn when delays are consistent.""" import logging caplog.set_level(logging.WARNING) # Initialize queue action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume 5 actions for _ in range(5): action_queue_rtc_enabled.get() # Merge with matching delay action_queue_rtc_enabled.merge( sample_actions["original"], sample_actions["processed"], real_delay=5, action_index_before_inference=0, ) # Should not have warning assert "Indexes diff is not equal to real delay" not in caplog.text def test_merge_skips_validation_when_action_index_none(action_queue_rtc_enabled, sample_actions, caplog): """Test merge() skips delay validation when action_index_before_inference is None.""" import logging caplog.set_level(logging.WARNING) action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) for _ in range(5): action_queue_rtc_enabled.get() # Pass None for action_index_before_inference action_queue_rtc_enabled.merge( sample_actions["original"], sample_actions["processed"], real_delay=999, # Doesn't matter action_index_before_inference=None, ) # Should not warn (validation skipped) assert "Indexes diff is not equal to real delay" not in caplog.text # ====================== Thread Safety Tests ====================== def test_get_is_thread_safe(action_queue_rtc_enabled, sample_actions): """Test get() is thread-safe with multiple consumers.""" action_queue_rtc_enabled.merge(sample_actions["longer"], sample_actions["longer"], real_delay=0) results = [] errors = [] def consumer(): try: for _ in range(25): action = action_queue_rtc_enabled.get() if action is not None: results.append(action) time.sleep(0.001) except Exception as e: errors.append(e) threads = [threading.Thread(target=consumer) for _ in range(4)] for t in threads: t.start() for t in threads: t.join() # Should not have errors assert len(errors) == 0 # Should have consumed all actions (100 total, 4 threads * 25 each) assert len(results) == 100 # All results should be unique (no duplicate consumption) # We can verify by checking that indices are not duplicated # Since we don't track indices in results, we check total count is correct assert action_queue_rtc_enabled.qsize() == 0 def test_merge_is_thread_safe(action_queue_rtc_disabled, sample_actions): """Test merge() is thread-safe with multiple producers.""" errors = [] def producer(): try: for _ in range(5): action_queue_rtc_disabled.merge( sample_actions["short"], sample_actions["short"], real_delay=0 ) time.sleep(0.001) except Exception as e: errors.append(e) threads = [threading.Thread(target=producer) for _ in range(3)] for t in threads: t.start() for t in threads: t.join() # Should not have errors assert len(errors) == 0 # Should have accumulated all actions (3 threads * 5 merges * 10 actions = 150) assert action_queue_rtc_disabled.qsize() == 150 def test_concurrent_get_and_merge(action_queue_rtc_disabled, sample_actions): """Test concurrent get() and merge() operations.""" errors = [] consumed_count = [0] def consumer(): try: for _ in range(50): action = action_queue_rtc_disabled.get() if action is not None: consumed_count[0] += 1 time.sleep(0.001) except Exception as e: errors.append(e) def producer(): try: for _ in range(10): action_queue_rtc_disabled.merge( sample_actions["short"], sample_actions["short"], real_delay=0 ) time.sleep(0.005) except Exception as e: errors.append(e) consumer_threads = [threading.Thread(target=consumer) for _ in range(2)] producer_threads = [threading.Thread(target=producer) for _ in range(2)] for t in consumer_threads + producer_threads: t.start() for t in consumer_threads + producer_threads: t.join() # Should not have errors assert len(errors) == 0 # Should have consumed some or all actions (non-deterministic due to timing) # Total produced: 2 producers * 10 merges * 10 actions = 200 # Total consumed attempts: 2 consumers * 50 = 100 assert consumed_count[0] <= 200 # ====================== get_left_over() Thread Safety Tests ====================== def test_get_left_over_is_thread_safe(action_queue_rtc_enabled, sample_actions): """Test get_left_over() is thread-safe with concurrent access.""" action_queue_rtc_enabled.merge(sample_actions["longer"], sample_actions["longer"], real_delay=0) errors = [] leftovers = [] def reader(): try: for _ in range(20): leftover = action_queue_rtc_enabled.get_left_over() if leftover is not None: leftovers.append(leftover.shape[0]) time.sleep(0.001) except Exception as e: errors.append(e) threads = [threading.Thread(target=reader) for _ in range(3)] # Also consume some actions concurrently def consumer(): try: for _ in range(10): action_queue_rtc_enabled.get() time.sleep(0.002) except Exception as e: errors.append(e) consumer_thread = threading.Thread(target=consumer) all_threads = threads + [consumer_thread] for t in all_threads: t.start() for t in all_threads: t.join() # Should not have errors assert len(errors) == 0 # Leftovers should be monotonically decreasing or stable # (as actions are consumed, leftover size decreases) assert len(leftovers) > 0 # ====================== Edge Cases Tests ====================== def test_queue_with_single_action(action_queue_rtc_enabled): """Test queue behavior with a single action.""" single_action_original = torch.randn(1, 6) single_action_processed = torch.randn(1, 6) action_queue_rtc_enabled.merge(single_action_original, single_action_processed, real_delay=0) assert action_queue_rtc_enabled.qsize() == 1 action = action_queue_rtc_enabled.get() assert action is not None assert action.shape == (6,) assert action_queue_rtc_enabled.qsize() == 0 def test_queue_behavior_after_multiple_merge_cycles(action_queue_rtc_enabled, sample_actions): """Test queue maintains correct state through multiple merge cycles.""" for _ in range(5): action_queue_rtc_enabled.merge(sample_actions["short"], sample_actions["short"], real_delay=0) # Consume half for _ in range(5): action_queue_rtc_enabled.get() # Merge again action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=3) assert action_queue_rtc_enabled.qsize() > 0 def test_queue_with_all_zeros_actions(action_queue_rtc_enabled): """Test queue handles all-zero action tensors.""" zeros_actions = torch.zeros(20, 6) action_queue_rtc_enabled.merge(zeros_actions, zeros_actions, real_delay=0) action = action_queue_rtc_enabled.get() assert torch.all(action == 0) def test_queue_clones_input_tensors(action_queue_rtc_enabled, sample_actions): """Test that merge() clones input tensors, not storing references.""" original_copy = sample_actions["original"].clone() processed_copy = sample_actions["processed"].clone() action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) # Modify original tensors sample_actions["original"].fill_(999.0) sample_actions["processed"].fill_(-999.0) # Queue should have cloned values action = action_queue_rtc_enabled.get() assert not torch.equal(action, sample_actions["processed"][0]) assert torch.equal(action, processed_copy[0]) leftover = action_queue_rtc_enabled.get_left_over() assert not torch.equal(leftover, sample_actions["original"][1:]) assert torch.equal(leftover, original_copy[1:]) @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_queue_handles_gpu_tensors(): """Test queue correctly handles GPU tensors.""" cfg = RTCConfig(enabled=True, execution_horizon=10) queue = ActionQueue(cfg) actions_gpu = torch.randn(20, 6, device="cuda") queue.merge(actions_gpu, actions_gpu, real_delay=0) action = queue.get() assert action.device.type == "cuda" leftover = queue.get_left_over() assert leftover.device.type == "cuda" def test_queue_handles_different_dtypes(): """Test queue handles actions with different dtypes.""" cfg = RTCConfig(enabled=True, execution_horizon=10) queue = ActionQueue(cfg) # Use float64 instead of default float32 actions_f64 = torch.randn(20, 6, dtype=torch.float64) queue.merge(actions_f64, actions_f64, real_delay=0) action = queue.get() assert action.dtype == torch.float64 def test_empty_with_none_queue(action_queue_rtc_enabled): """Test empty() correctly handles None queue.""" assert action_queue_rtc_enabled.queue is None assert action_queue_rtc_enabled.empty() is True def test_qsize_with_none_queue(action_queue_rtc_enabled): """Test qsize() correctly handles None queue.""" assert action_queue_rtc_enabled.queue is None assert action_queue_rtc_enabled.qsize() == 0 # ====================== Integration Tests ====================== def test_typical_rtc_workflow(action_queue_rtc_enabled, sample_actions): """Test a typical RTC workflow: merge, consume, merge with delay.""" # First inference action_queue_rtc_enabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) initial_size = action_queue_rtc_enabled.qsize() assert initial_size == 50 # Consume 10 actions (execution_horizon) for _ in range(10): action = action_queue_rtc_enabled.get() assert action is not None assert action_queue_rtc_enabled.qsize() == 40 # Second inference with delay action_index_before = action_queue_rtc_enabled.get_action_index() action_queue_rtc_enabled.merge( sample_actions["original"], sample_actions["processed"], real_delay=5, action_index_before_inference=action_index_before, ) # Queue should be replaced, minus delay assert action_queue_rtc_enabled.qsize() == 45 assert action_queue_rtc_enabled.get_action_index() == 0 def test_typical_non_rtc_workflow(action_queue_rtc_disabled, sample_actions): """Test a typical non-RTC workflow: merge, consume, merge again.""" # First inference action_queue_rtc_disabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) assert action_queue_rtc_disabled.qsize() == 50 # Consume 40 actions for _ in range(40): action = action_queue_rtc_disabled.get() assert action is not None assert action_queue_rtc_disabled.qsize() == 10 # Second inference (should append) action_queue_rtc_disabled.merge(sample_actions["original"], sample_actions["processed"], real_delay=0) # Should have 10 remaining + 50 new = 60 assert action_queue_rtc_disabled.qsize() == 60
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/rtc/test_action_queue.py", "license": "Apache License 2.0", "lines": 574, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/rtc/test_configuration_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Tests for RTC configuration module.""" from lerobot.configs.types import RTCAttentionSchedule from lerobot.policies.rtc.configuration_rtc import RTCConfig # ====================== Initialization Tests ====================== def test_rtc_config_default_initialization(): """Test RTCConfig initializes with default values.""" config = RTCConfig() assert config.enabled is False assert config.prefix_attention_schedule == RTCAttentionSchedule.LINEAR assert config.max_guidance_weight == 10.0 assert config.execution_horizon == 10 assert config.debug is False assert config.debug_maxlen == 100 def test_rtc_config_custom_initialization(): """Test RTCConfig initializes with custom values.""" config = RTCConfig( enabled=True, prefix_attention_schedule=RTCAttentionSchedule.EXP, max_guidance_weight=5.0, execution_horizon=20, debug=True, debug_maxlen=200, ) assert config.enabled is True assert config.prefix_attention_schedule == RTCAttentionSchedule.EXP assert config.max_guidance_weight == 5.0 assert config.execution_horizon == 20 assert config.debug is True assert config.debug_maxlen == 200 def test_rtc_config_partial_initialization(): """Test RTCConfig with partial custom values.""" config = RTCConfig(enabled=True, max_guidance_weight=15.0) assert config.enabled is True assert config.max_guidance_weight == 15.0 # Other values should be defaults assert config.prefix_attention_schedule == RTCAttentionSchedule.LINEAR assert config.execution_horizon == 10 assert config.debug is False
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/rtc/test_configuration_rtc.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/rtc/test_debug_tracker.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Tests for RTC debug tracker module.""" import pytest import torch from lerobot.policies.rtc.debug_tracker import DebugStep, Tracker # ====================== Fixtures ====================== @pytest.fixture def sample_tensors(): """Create sample tensors for testing.""" return { "x_t": torch.randn(1, 50, 6), "v_t": torch.randn(1, 50, 6), "x1_t": torch.randn(1, 50, 6), "correction": torch.randn(1, 50, 6), "err": torch.randn(1, 50, 6), "weights": torch.randn(1, 50, 1), } @pytest.fixture def enabled_tracker(): """Create an enabled tracker with default settings.""" return Tracker(enabled=True, maxlen=100) @pytest.fixture def disabled_tracker(): """Create a disabled tracker.""" return Tracker(enabled=False) # ====================== DebugStep Tests ====================== def test_debug_step_initialization(): """Test that DebugStep can be initialized with default values.""" step = DebugStep() assert step.step_idx == 0 assert step.x_t is None assert step.v_t is None assert step.x1_t is None assert step.correction is None assert step.err is None assert step.weights is None assert step.guidance_weight is None assert step.time is None assert step.inference_delay is None assert step.execution_horizon is None assert step.metadata == {} def test_debug_step_with_values(sample_tensors): """Test DebugStep initialization with actual values.""" step = DebugStep( step_idx=5, x_t=sample_tensors["x_t"], v_t=sample_tensors["v_t"], x1_t=sample_tensors["x1_t"], correction=sample_tensors["correction"], err=sample_tensors["err"], weights=sample_tensors["weights"], guidance_weight=2.5, time=0.8, inference_delay=4, execution_horizon=8, metadata={"custom_key": "custom_value"}, ) assert step.step_idx == 5 assert torch.equal(step.x_t, sample_tensors["x_t"]) assert torch.equal(step.v_t, sample_tensors["v_t"]) assert torch.equal(step.x1_t, sample_tensors["x1_t"]) assert torch.equal(step.correction, sample_tensors["correction"]) assert torch.equal(step.err, sample_tensors["err"]) assert torch.equal(step.weights, sample_tensors["weights"]) assert step.guidance_weight == 2.5 assert step.time == 0.8 assert step.inference_delay == 4 assert step.execution_horizon == 8 assert step.metadata == {"custom_key": "custom_value"} def test_debug_step_to_dict_without_tensors(sample_tensors): """Test converting DebugStep to dictionary without tensor values.""" step = DebugStep( step_idx=3, x_t=sample_tensors["x_t"], v_t=sample_tensors["v_t"], guidance_weight=torch.tensor(3.0), time=torch.tensor(0.5), inference_delay=2, execution_horizon=10, ) result = step.to_dict(include_tensors=False) assert result["step_idx"] == 3 assert result["guidance_weight"] == 3.0 assert result["time"] == 0.5 assert result["inference_delay"] == 2 assert result["execution_horizon"] == 10 # Check tensor statistics are included assert "x_t_stats" in result assert "v_t_stats" in result assert "x1_t_stats" not in result # x1_t was None # Verify statistics structure assert "shape" in result["x_t_stats"] assert "mean" in result["x_t_stats"] assert "std" in result["x_t_stats"] assert "min" in result["x_t_stats"] assert "max" in result["x_t_stats"] # Verify shape matches original tensor assert result["x_t_stats"]["shape"] == tuple(sample_tensors["x_t"].shape) def test_debug_step_to_dict_with_tensors(sample_tensors): """Test converting DebugStep to dictionary with tensor values.""" step = DebugStep( step_idx=1, x_t=sample_tensors["x_t"], v_t=sample_tensors["v_t"], guidance_weight=1.5, time=0.9, ) result = step.to_dict(include_tensors=True) assert result["step_idx"] == 1 assert result["guidance_weight"] == 1.5 assert result["time"] == 0.9 # Check tensors are included (as CPU tensors) assert "x_t" in result assert "v_t" in result assert isinstance(result["x_t"], torch.Tensor) assert isinstance(result["v_t"], torch.Tensor) assert result["x_t"].device.type == "cpu" assert result["v_t"].device.type == "cpu" def test_debug_step_to_dict_with_none_guidance_weight(): """Test to_dict handles None guidance_weight correctly.""" step = DebugStep(step_idx=0, time=1.0, guidance_weight=None) result = step.to_dict(include_tensors=False) assert result["guidance_weight"] is None def test_tracker_initialization_enabled(): """Test tracker initialization when enabled.""" tracker = Tracker(enabled=True, maxlen=50) assert tracker.enabled is True assert tracker._steps == {} assert tracker._maxlen == 50 assert tracker._step_counter == 0 assert len(tracker) == 0 def test_tracker_reset_when_enabled(enabled_tracker, sample_tensors): """Test reset clears all steps when tracker is enabled.""" # Add some steps enabled_tracker.track(time=1.0, x_t=sample_tensors["x_t"]) enabled_tracker.track(time=0.9, x_t=sample_tensors["x_t"]) assert len(enabled_tracker) == 2 # Reset enabled_tracker.reset() assert len(enabled_tracker) == 0 assert enabled_tracker._step_counter == 0 assert enabled_tracker._steps == {} def test_tracker_reset_when_disabled(disabled_tracker): """Test reset on disabled tracker doesn't cause errors.""" disabled_tracker.reset() assert len(disabled_tracker) == 0 # ====================== Tracker.track() Tests ====================== def test_track_creates_new_step(enabled_tracker, sample_tensors): """Test that track creates a new step when time doesn't exist.""" enabled_tracker.track( time=1.0, x_t=sample_tensors["x_t"], v_t=sample_tensors["v_t"], guidance_weight=5.0, inference_delay=4, execution_horizon=8, ) assert len(enabled_tracker) == 1 steps = enabled_tracker.get_all_steps() assert len(steps) == 1 assert steps[0].step_idx == 0 assert steps[0].time == 1.0 assert torch.equal(steps[0].x_t, sample_tensors["x_t"]) assert torch.equal(steps[0].v_t, sample_tensors["v_t"]) assert steps[0].guidance_weight == 5.0 assert steps[0].inference_delay == 4 assert steps[0].execution_horizon == 8 def test_track_updates_existing_step(enabled_tracker, sample_tensors): """Test that track updates an existing step at the same time.""" # Create initial step enabled_tracker.track(time=0.9, x_t=sample_tensors["x_t"]) assert len(enabled_tracker) == 1 steps = enabled_tracker.get_all_steps() assert steps[0].v_t is None # Update the same timestep with v_t enabled_tracker.track(time=0.9, v_t=sample_tensors["v_t"]) assert len(enabled_tracker) == 1 # Still only one step steps = enabled_tracker.get_all_steps() assert torch.equal(steps[0].x_t, sample_tensors["x_t"]) # Original x_t preserved assert torch.equal(steps[0].v_t, sample_tensors["v_t"]) # New v_t added def test_track_with_tensor_time(enabled_tracker, sample_tensors): """Test track handles tensor time values correctly.""" time_tensor = torch.tensor(0.8) enabled_tracker.track(time=time_tensor, x_t=sample_tensors["x_t"]) steps = enabled_tracker.get_all_steps() assert len(steps) == 1 assert abs(steps[0].time - 0.8) < 1e-6 # Use approximate comparison for floating point def test_track_time_rounding(enabled_tracker, sample_tensors): """Test that track rounds time to avoid floating point precision issues.""" # These times should be treated as the same after rounding to 6 decimals enabled_tracker.track(time=0.9000001, x_t=sample_tensors["x_t"]) enabled_tracker.track(time=0.9000002, v_t=sample_tensors["v_t"]) # Should still be one step (times rounded to same value) assert len(enabled_tracker) == 1 steps = enabled_tracker.get_all_steps() assert torch.equal(steps[0].x_t, sample_tensors["x_t"]) assert torch.equal(steps[0].v_t, sample_tensors["v_t"]) def test_track_does_nothing_when_disabled(disabled_tracker, sample_tensors): """Test that track does nothing when tracker is disabled.""" disabled_tracker.track(time=1.0, x_t=sample_tensors["x_t"]) assert len(disabled_tracker) == 0 def test_track_with_metadata(enabled_tracker, sample_tensors): """Test track stores custom metadata.""" enabled_tracker.track(time=0.7, x_t=sample_tensors["x_t"], custom_field="custom_value", count=42) steps = enabled_tracker.get_all_steps() assert steps[0].metadata["custom_field"] == "custom_value" assert steps[0].metadata["count"] == 42 def test_track_updates_metadata(enabled_tracker): """Test that track updates metadata for existing steps.""" enabled_tracker.track(time=0.6, meta1="value1") enabled_tracker.track(time=0.6, meta2="value2") steps = enabled_tracker.get_all_steps() assert steps[0].metadata["meta1"] == "value1" assert steps[0].metadata["meta2"] == "value2" def test_track_clones_tensors(enabled_tracker, sample_tensors): """Test that track clones tensors instead of storing references.""" x_t_original = sample_tensors["x_t"].clone() enabled_tracker.track(time=0.5, x_t=sample_tensors["x_t"]) # Modify original tensor sample_tensors["x_t"].fill_(999.0) # Tracked tensor should not be affected steps = enabled_tracker.get_all_steps() assert not torch.equal(steps[0].x_t, sample_tensors["x_t"]) assert torch.equal(steps[0].x_t, x_t_original) def test_track_with_none_values(enabled_tracker): """Test track handles None values correctly.""" enabled_tracker.track( time=0.4, x_t=None, v_t=None, guidance_weight=None, inference_delay=None, ) steps = enabled_tracker.get_all_steps() assert len(steps) == 1 assert steps[0].x_t is None assert steps[0].v_t is None assert steps[0].guidance_weight is None assert steps[0].inference_delay is None def test_track_updates_only_non_none_fields(enabled_tracker, sample_tensors): """Test that update preserves existing values when None is passed.""" # Create step with x_t enabled_tracker.track(time=0.3, x_t=sample_tensors["x_t"], guidance_weight=2.0) # Update with v_t only (pass None for other fields) enabled_tracker.track(time=0.3, v_t=sample_tensors["v_t"], x_t=None, guidance_weight=None) # Original values should be preserved steps = enabled_tracker.get_all_steps() assert torch.equal(steps[0].x_t, sample_tensors["x_t"]) # Still has x_t assert torch.equal(steps[0].v_t, sample_tensors["v_t"]) # Now has v_t assert steps[0].guidance_weight == 2.0 # Still has guidance_weight # ====================== Tracker.maxlen Tests ====================== def test_tracker_enforces_maxlen(): """Test that tracker enforces maxlen limit.""" tracker = Tracker(enabled=True, maxlen=3) # Add 5 steps for i in range(5): time = 1.0 - i * 0.1 # 1.0, 0.9, 0.8, 0.7, 0.6 tracker.track(time=time, x_t=torch.randn(1, 10, 6)) # Should only keep the last 3 assert len(tracker) == 3 # Verify oldest steps were removed (should have 0.6, 0.7, 0.8) steps = tracker.get_all_steps() times = sorted([step.time for step in steps]) assert times == [0.6, 0.7, 0.8] def test_tracker_step_idx_increments_despite_maxlen(): """Test that step_idx continues incrementing even when maxlen is enforced.""" tracker = Tracker(enabled=True, maxlen=2) # Add 4 steps for i in range(4): time = 1.0 - i * 0.1 tracker.track(time=time, x_t=torch.randn(1, 10, 6)) # Should have 2 steps with step_idx 2 and 3 (oldest removed) steps = sorted(tracker.get_all_steps(), key=lambda s: s.step_idx) assert len(steps) == 2 assert steps[0].step_idx == 2 assert steps[1].step_idx == 3 def test_tracker_without_maxlen_keeps_all(): """Test that tracker without maxlen keeps all steps.""" tracker = Tracker(enabled=True, maxlen=None) # Add 100 steps for i in range(100): time = 1.0 - i * 0.01 tracker.track(time=time, x_t=torch.randn(1, 10, 6)) assert len(tracker) == 100 def test_get_all_steps_returns_empty_when_disabled(disabled_tracker): """Test get_all_steps returns empty list when disabled.""" steps = disabled_tracker.get_all_steps() assert steps == [] assert isinstance(steps, list) def test_get_all_steps_returns_empty_when_no_steps(enabled_tracker): """Test get_all_steps returns empty list when no steps tracked.""" steps = enabled_tracker.get_all_steps() assert steps == [] def test_get_all_steps_returns_all_tracked_steps(enabled_tracker, sample_tensors): """Test get_all_steps returns all tracked steps.""" # Track 5 steps for i in range(5): time = 1.0 - i * 0.1 enabled_tracker.track(time=time, x_t=sample_tensors["x_t"]) steps = enabled_tracker.get_all_steps() assert len(steps) == 5 # Verify all are DebugStep instances for step in steps: assert isinstance(step, DebugStep) def test_get_all_steps_preserves_insertion_order(enabled_tracker): """Test that get_all_steps preserves insertion order (Python 3.7+).""" times = [0.9, 0.8, 0.7, 0.6, 0.5] for time in times: enabled_tracker.track(time=time, x_t=torch.randn(1, 10, 6)) steps = enabled_tracker.get_all_steps() retrieved_times = [step.time for step in steps] # Should be in insertion order assert retrieved_times == times # ====================== Tracker.__len__() Tests ====================== def test_len_returns_zero_when_disabled(disabled_tracker): """Test __len__ returns 0 when tracker is disabled.""" assert len(disabled_tracker) == 0 def test_len_returns_zero_when_empty(enabled_tracker): """Test __len__ returns 0 when no steps are tracked.""" assert len(enabled_tracker) == 0 def test_len_returns_correct_count(enabled_tracker, sample_tensors): """Test __len__ returns correct number of tracked steps.""" assert len(enabled_tracker) == 0 enabled_tracker.track(time=1.0, x_t=sample_tensors["x_t"]) assert len(enabled_tracker) == 1 enabled_tracker.track(time=0.9, x_t=sample_tensors["x_t"]) assert len(enabled_tracker) == 2 enabled_tracker.track(time=0.8, x_t=sample_tensors["x_t"]) assert len(enabled_tracker) == 3 def test_len_after_reset(enabled_tracker, sample_tensors): """Test __len__ returns 0 after reset.""" enabled_tracker.track(time=1.0, x_t=sample_tensors["x_t"]) enabled_tracker.track(time=0.9, x_t=sample_tensors["x_t"]) assert len(enabled_tracker) == 2 enabled_tracker.reset() assert len(enabled_tracker) == 0 @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_tracker_handles_gpu_tensors(): """Test tracker correctly handles GPU tensors.""" tracker = Tracker(enabled=True, maxlen=10) x_t_gpu = torch.randn(1, 50, 6, device="cuda") tracker.track(time=1.0, x_t=x_t_gpu) steps = tracker.get_all_steps() # Tracker should clone and detach tensors assert steps[0].x_t.device.type == "cuda" def test_tracker_with_varying_tensor_shapes(enabled_tracker): """Test tracker handles varying tensor shapes across steps.""" enabled_tracker.track(time=1.0, x_t=torch.randn(1, 50, 6)) enabled_tracker.track(time=0.9, x_t=torch.randn(1, 25, 6)) enabled_tracker.track(time=0.8, x_t=torch.randn(2, 50, 8)) steps = enabled_tracker.get_all_steps() assert len(steps) == 3 assert steps[0].x_t.shape == (1, 50, 6) assert steps[1].x_t.shape == (1, 25, 6) assert steps[2].x_t.shape == (2, 50, 8)
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/rtc/test_debug_tracker.py", "license": "Apache License 2.0", "lines": 368, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/rtc/test_latency_tracker.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Tests for RTC LatencyTracker module.""" import pytest from lerobot.policies.rtc.latency_tracker import LatencyTracker # ====================== Fixtures ====================== @pytest.fixture def tracker(): """Create a LatencyTracker with default maxlen.""" return LatencyTracker(maxlen=100) @pytest.fixture def small_tracker(): """Create a LatencyTracker with small maxlen for overflow testing.""" return LatencyTracker(maxlen=5) # ====================== Initialization Tests ====================== def test_latency_tracker_initialization(): """Test LatencyTracker initializes correctly.""" tracker = LatencyTracker(maxlen=50) assert len(tracker) == 0 assert tracker.max_latency == 0.0 assert tracker.max() == 0.0 def test_latency_tracker_default_maxlen(): """Test LatencyTracker uses default maxlen.""" tracker = LatencyTracker() # Should accept default maxlen=100 assert len(tracker) == 0 # ====================== add() Tests ====================== def test_add_single_latency(tracker): """Test adding a single latency value.""" tracker.add(0.5) assert len(tracker) == 1 assert tracker.max() == 0.5 def test_add_multiple_latencies(tracker): """Test adding multiple latency values.""" latencies = [0.1, 0.5, 0.3, 0.8, 0.2] for lat in latencies: tracker.add(lat) assert len(tracker) == 5 assert tracker.max() == 0.8 def test_add_negative_latency_ignored(tracker): """Test that negative latencies are ignored.""" tracker.add(0.5) tracker.add(-0.1) tracker.add(0.3) # Should only have 2 valid latencies assert len(tracker) == 2 assert tracker.max() == 0.5 def test_add_zero_latency(tracker): """Test adding zero latency.""" tracker.add(0.0) assert len(tracker) == 1 assert tracker.max() == 0.0 def test_add_converts_to_float(tracker): """Test add() converts input to float.""" tracker.add(5) # Integer tracker.add("3.5") # String assert len(tracker) == 2 assert tracker.max() == 5.0 def test_add_updates_max_latency(tracker): """Test that max_latency is updated correctly.""" tracker.add(0.5) assert tracker.max_latency == 0.5 tracker.add(0.3) assert tracker.max_latency == 0.5 # Should not decrease tracker.add(0.9) assert tracker.max_latency == 0.9 # Should increase # ====================== reset() Tests ====================== def test_reset_clears_values(tracker): """Test reset() clears all values.""" tracker.add(0.5) tracker.add(0.8) tracker.add(0.3) assert len(tracker) == 3 tracker.reset() assert len(tracker) == 0 assert tracker.max_latency == 0.0 def test_reset_clears_max_latency(tracker): """Test reset() resets max_latency.""" tracker.add(1.5) assert tracker.max_latency == 1.5 tracker.reset() assert tracker.max_latency == 0.0 def test_reset_allows_new_values(tracker): """Test that tracker works correctly after reset.""" tracker.add(0.5) tracker.reset() tracker.add(0.3) assert len(tracker) == 1 assert tracker.max() == 0.3 # ====================== max() Tests ====================== def test_max_returns_zero_when_empty(tracker): """Test max() returns 0.0 when tracker is empty.""" assert tracker.max() == 0.0 def test_max_returns_maximum_value(tracker): """Test max() returns the maximum latency.""" latencies = [0.2, 0.8, 0.3, 0.5, 0.1] for lat in latencies: tracker.add(lat) assert tracker.max() == 0.8 def test_max_persists_after_sliding_window(small_tracker): """Test max() persists even after values slide out of window.""" # Add values that will exceed maxlen=5 small_tracker.add(0.1) small_tracker.add(0.9) # This is max small_tracker.add(0.2) small_tracker.add(0.3) small_tracker.add(0.4) small_tracker.add(0.5) # This pushes out 0.1 # Max should still be 0.9 even though only last 5 values kept assert small_tracker.max() == 0.9 def test_max_after_reset(tracker): """Test max() returns 0.0 after reset.""" tracker.add(1.5) tracker.reset() assert tracker.max() == 0.0 # ====================== p95() Tests ====================== def test_p95_returns_zero_when_empty(tracker): """Test p95() returns 0.0 when tracker is empty.""" assert tracker.p95() == 0.0 def test_p95_returns_95th_percentile(tracker): """Test p95() returns the 95th percentile.""" # Add 100 values for i in range(100): tracker.add(i / 100.0) p95 = tracker.p95() assert 0.93 <= p95 <= 0.96 def test_p95_equals_percentile_95(tracker): """Test p95() equals percentile(0.95).""" for i in range(50): tracker.add(i / 50.0) assert tracker.p95() == tracker.percentile(0.95) # ====================== Edge Cases Tests ====================== def test_single_value(tracker): """Test tracker behavior with single value.""" tracker.add(0.75) assert len(tracker) == 1 assert tracker.max() == 0.75 assert tracker.percentile(0.0) == 0.75 assert tracker.percentile(0.5) == 0.75 assert tracker.percentile(1.0) == 0.75 def test_all_same_values(tracker): """Test tracker with all identical values.""" for _ in range(10): tracker.add(0.5) assert len(tracker) == 10 assert tracker.max() == 0.5 assert tracker.percentile(0.0) == 0.5 assert tracker.percentile(0.5) == 0.5 assert tracker.percentile(1.0) == 0.5 def test_very_small_values(tracker): """Test tracker with very small float values.""" tracker.add(1e-10) tracker.add(2e-10) tracker.add(3e-10) assert len(tracker) == 3 assert tracker.max() == pytest.approx(3e-10) def test_very_large_values(tracker): """Test tracker with very large float values.""" tracker.add(1e10) tracker.add(2e10) tracker.add(3e10) assert len(tracker) == 3 assert tracker.max() == pytest.approx(3e10) # ====================== Integration Tests ====================== def test_typical_usage_pattern(tracker): """Test a typical usage pattern of the tracker.""" # Simulate adding latencies over time latencies = [0.05, 0.08, 0.12, 0.07, 0.15, 0.09, 0.11, 0.06, 0.14, 0.10] for lat in latencies: tracker.add(lat) # Check statistics assert len(tracker) == 10 assert tracker.max() == 0.15 # p95 should be close to max since we have only 10 values p95 = tracker.p95() assert p95 >= tracker.percentile(0.5) # p95 should be >= median assert p95 <= tracker.max() # p95 should be <= max def test_reset_and_reuse(tracker): """Test resetting and reusing tracker.""" # First batch tracker.add(1.0) tracker.add(2.0) assert tracker.max() == 2.0 # Reset tracker.reset() # Second batch tracker.add(0.5) tracker.add(0.8) assert len(tracker) == 2 assert tracker.max() == 0.8 assert tracker.percentile(0.5) <= 0.8 # ====================== Type Conversion Tests ====================== def test_add_with_integer(tracker): """Test adding integer values.""" tracker.add(5) assert len(tracker) == 1 assert tracker.max() == 5.0 def test_add_with_string_number(tracker): """Test adding string representation of number.""" tracker.add("3.14") assert len(tracker) == 1 assert tracker.max() == pytest.approx(3.14) def test_percentile_converts_q_to_float(tracker): """Test percentile converts q parameter to float.""" tracker.add(0.5) tracker.add(0.8) # Pass integer q result = tracker.percentile(1) assert result == 0.8
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/rtc/test_latency_tracker.py", "license": "Apache License 2.0", "lines": 221, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/rtc/test_modeling_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Tests for RTC modeling module (RTCProcessor).""" import pytest import torch from lerobot.configs.types import RTCAttentionSchedule from lerobot.policies.rtc.configuration_rtc import RTCConfig from lerobot.policies.rtc.modeling_rtc import RTCProcessor # ====================== Fixtures ====================== @pytest.fixture def rtc_config_debug_enabled(): """Create RTC config with debug enabled.""" return RTCConfig( enabled=True, prefix_attention_schedule=RTCAttentionSchedule.LINEAR, max_guidance_weight=10.0, execution_horizon=10, debug=True, debug_maxlen=100, ) @pytest.fixture def rtc_config_debug_disabled(): """Create RTC config with debug disabled.""" return RTCConfig( enabled=True, prefix_attention_schedule=RTCAttentionSchedule.LINEAR, max_guidance_weight=10.0, execution_horizon=10, debug=False, ) @pytest.fixture def rtc_processor_debug_enabled(rtc_config_debug_enabled): """Create RTCProcessor with debug enabled.""" return RTCProcessor(rtc_config_debug_enabled) @pytest.fixture def rtc_processor_debug_disabled(rtc_config_debug_disabled): """Create RTCProcessor with debug disabled.""" return RTCProcessor(rtc_config_debug_disabled) @pytest.fixture def sample_x_t(): """Create sample x_t tensor (batch, time, action_dim).""" return torch.randn(1, 50, 6) @pytest.fixture def sample_prev_chunk(): """Create sample previous chunk tensor.""" return torch.randn(1, 50, 6) # ====================== Initialization Tests ====================== def test_rtc_processor_initialization_with_debug(rtc_config_debug_enabled): """Test RTCProcessor initializes with debug tracker.""" processor = RTCProcessor(rtc_config_debug_enabled) assert processor.rtc_config == rtc_config_debug_enabled assert processor.tracker is not None assert processor.tracker.enabled is True def test_rtc_processor_initialization_without_debug(rtc_config_debug_disabled): """Test RTCProcessor initializes without debug tracker.""" processor = RTCProcessor(rtc_config_debug_disabled) assert processor.rtc_config == rtc_config_debug_disabled assert processor.tracker is None # ====================== Tracker Proxy Methods Tests ====================== def test_track_when_tracker_enabled(rtc_processor_debug_enabled, sample_x_t): """Test track() forwards to tracker when enabled.""" rtc_processor_debug_enabled.track( time=torch.tensor(0.5), x_t=sample_x_t, v_t=sample_x_t, guidance_weight=2.0, ) # Should have tracked one step steps = rtc_processor_debug_enabled.get_all_debug_steps() assert len(steps) == 1 assert steps[0].time == 0.5 def test_track_when_tracker_disabled(rtc_processor_debug_disabled, sample_x_t): """Test track() does nothing when tracker disabled.""" # Should not raise error rtc_processor_debug_disabled.track( time=torch.tensor(0.5), x_t=sample_x_t, v_t=sample_x_t, ) # Should return empty list steps = rtc_processor_debug_disabled.get_all_debug_steps() assert len(steps) == 0 def test_get_all_debug_steps_when_enabled(rtc_processor_debug_enabled, sample_x_t): """Test get_all_debug_steps() returns tracked steps.""" rtc_processor_debug_enabled.track(time=torch.tensor(0.5), x_t=sample_x_t) rtc_processor_debug_enabled.track(time=torch.tensor(0.4), x_t=sample_x_t) steps = rtc_processor_debug_enabled.get_all_debug_steps() assert len(steps) == 2 def test_get_all_debug_steps_when_disabled(rtc_processor_debug_disabled): """Test get_all_debug_steps() returns empty list when disabled.""" steps = rtc_processor_debug_disabled.get_all_debug_steps() assert steps == [] assert isinstance(steps, list) def test_is_debug_enabled_when_tracker_exists(rtc_processor_debug_enabled): """Test is_debug_enabled() returns True when tracker enabled.""" assert rtc_processor_debug_enabled.is_debug_enabled() is True def test_is_debug_enabled_when_tracker_disabled(rtc_processor_debug_disabled): """Test is_debug_enabled() returns False when tracker disabled.""" assert rtc_processor_debug_disabled.is_debug_enabled() is False def test_reset_tracker_when_enabled(rtc_processor_debug_enabled, sample_x_t): """Test reset_tracker() clears tracked steps.""" rtc_processor_debug_enabled.track(time=torch.tensor(0.5), x_t=sample_x_t) rtc_processor_debug_enabled.track(time=torch.tensor(0.4), x_t=sample_x_t) assert len(rtc_processor_debug_enabled.get_all_debug_steps()) == 2 rtc_processor_debug_enabled.reset_tracker() assert len(rtc_processor_debug_enabled.get_all_debug_steps()) == 0 def test_reset_tracker_when_disabled(rtc_processor_debug_disabled): """Test reset_tracker() doesn't error when tracker disabled.""" rtc_processor_debug_disabled.reset_tracker() # Should not raise # ====================== get_prefix_weights Tests ====================== def test_get_prefix_weights_zeros_schedule(): """Test get_prefix_weights with ZEROS schedule.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.ZEROS) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=5, end=10, total=20) # First 5 should be 1.0, rest should be 0.0 assert weights.shape == (20,) assert torch.all(weights[:5] == 1.0) assert torch.all(weights[5:] == 0.0) def test_get_prefix_weights_ones_schedule(): """Test get_prefix_weights with ONES schedule.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.ONES) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=5, end=15, total=20) # First 15 should be 1.0, rest should be 0.0 assert weights.shape == (20,) assert torch.all(weights[:15] == 1.0) assert torch.all(weights[15:] == 0.0) def test_get_prefix_weights_linear_schedule(): """Test get_prefix_weights with LINEAR schedule.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.LINEAR) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=5, end=14, total=25) # Should have shape (20,) assert weights.shape == (25,) # First 5 should be 1.0 (leading ones) assert torch.all(weights[:5] == 1.0) # Middle section (5:15) should be linearly decreasing from 1 to 0 middle_weights = torch.tensor([0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]) assert torch.allclose(weights[5:14], middle_weights) # Last 5 should be 0.0 (trailing zeros) assert torch.all(weights[14:] == 0.0) def test_get_prefix_weights_exp_schedule(): """Test get_prefix_weights with EXP schedule.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.EXP) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=5, end=14, total=25) # Should have shape (20,) assert weights.shape == (25,) # First 5 should be 1.0 (leading ones) assert torch.all(weights[:5] == 1.0) # Middle section should be exponentially weighted middle_weights = torch.tensor([0.7645, 0.5706, 0.4130, 0.2871, 0.1888, 0.1145, 0.0611, 0.0258, 0.0061]) assert torch.allclose(weights[5:14], middle_weights, atol=1e-4) # Last 5 should be 0.0 (trailing zeros) assert torch.all(weights[14:] == 0.0) def test_get_prefix_weights_with_start_equals_end(): """Test get_prefix_weights when start equals end.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.LINEAR) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=10, end=10, total=20) # Should have ones up to start, then zeros assert torch.all(weights[:10] == 1.0) assert torch.all(weights[10:] == 0.0) def test_get_prefix_weights_with_start_greater_than_end(): """Test get_prefix_weights when start > end (gets clamped).""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.LINEAR) processor = RTCProcessor(config) # start > end should use min(start, end) = end weights = processor.get_prefix_weights(start=15, end=10, total=20) # Should have ones up to end (10), then zeros assert torch.all(weights[:10] == 1.0) assert torch.all(weights[10:] == 0.0) # ====================== Helper Method Tests ====================== def test_linweights_with_end_equals_start(): """Test _linweights when end equals start.""" config = RTCConfig() processor = RTCProcessor(config) weights = processor._linweights(start=10, end=10, total=20) # Should return empty tensor assert len(weights) == 0 def test_linweights_with_end_less_than_start(): """Test _linweights when end < start.""" config = RTCConfig() processor = RTCProcessor(config) weights = processor._linweights(start=15, end=10, total=20) # Should return empty tensor assert len(weights) == 0 def test_add_trailing_zeros_normal(): """Test _add_trailing_zeros adds zeros correctly.""" config = RTCConfig() processor = RTCProcessor(config) weights = torch.tensor([1.0, 0.8, 0.6, 0.4, 0.2]) result = processor._add_trailing_zeros(weights, total=10, end=5) # Should add 5 zeros (total - end = 10 - 5 = 5) assert len(result) == 10 assert torch.all(result[:5] == weights) assert torch.all(result[5:] == 0.0) def test_add_trailing_zeros_no_zeros_needed(): """Test _add_trailing_zeros when no zeros needed.""" config = RTCConfig() processor = RTCProcessor(config) weights = torch.tensor([1.0, 0.8, 0.6]) result = processor._add_trailing_zeros(weights, total=3, end=5) # zeros_len = 3 - 5 = -2 <= 0, so no zeros added assert torch.equal(result, weights) def test_add_leading_ones_normal(): """Test _add_leading_ones adds ones correctly.""" config = RTCConfig() processor = RTCProcessor(config) weights = torch.tensor([0.8, 0.6, 0.4, 0.2, 0.0]) result = processor._add_leading_ones(weights, start=3, total=10) # Should add 3 ones at the start assert len(result) == 8 assert torch.all(result[:3] == 1.0) assert torch.all(result[3:] == weights) def test_add_leading_ones_no_ones_needed(): """Test _add_leading_ones when no ones needed.""" config = RTCConfig() processor = RTCProcessor(config) weights = torch.tensor([0.8, 0.6, 0.4]) result = processor._add_leading_ones(weights, start=0, total=10) # ones_len = 0, so no ones added assert torch.equal(result, weights) def test_get_prefix_weights_with_start_equals_total(): """Test get_prefix_weights when start equals total.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.LINEAR) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=10, end=10, total=20) # Should have ones up to start, then zeros assert len(weights) == 20 assert torch.all(weights[:10] == 1.0) assert torch.all(weights[10:] == 0.0) def test_get_prefix_weights_with_total_less_than_start(): """Test get_prefix_weights when total less than start.""" config = RTCConfig(prefix_attention_schedule=RTCAttentionSchedule.LINEAR) processor = RTCProcessor(config) weights = processor.get_prefix_weights(start=10, end=10, total=5) # Should have ones up to start, then zeros assert len(weights) == 5 assert torch.all(weights == 1.0) # ====================== denoise_step Tests ====================== def test_denoise_step_without_prev_chunk(rtc_processor_debug_disabled): """Test denoise_step without previous chunk (no guidance).""" x_t = torch.randn(1, 50, 6) # Mock denoiser that returns fixed velocity def mock_denoiser(x): return torch.ones_like(x) * 0.5 result = rtc_processor_debug_disabled.denoise_step( x_t=x_t, prev_chunk_left_over=None, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) # Should return v_t unchanged (no guidance) expected = mock_denoiser(x_t) assert torch.allclose(result, expected) def test_denoise_step_with_prev_chunk(rtc_processor_debug_disabled): """Test denoise_step with previous chunk applies guidance.""" x_t = torch.ones(1, 20, 1) prev_chunk = torch.full((1, 20, 1), 0.1) def mock_denoiser(x): return x * 0.5 result = rtc_processor_debug_disabled.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) expected_result = torch.tensor( [ [ [1.8000], [1.8000], [1.8000], [1.8000], [1.8000], [1.5833], [1.3667], [1.1500], [0.9333], [0.7167], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], ] ] ) assert torch.allclose(result, expected_result, atol=1e-4) def test_denoise_step_adds_batch_dimension(): """Test denoise_step handles 2D input by adding batch dimension.""" config = RTCConfig(execution_horizon=10, max_guidance_weight=5.0) processor = RTCProcessor(config) # 2D input (no batch dimension) x_t = torch.randn(10, 6) prev_chunk = torch.randn(5, 6) def mock_denoiser(x): return x * 0.5 result = processor.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) # Output should be 2D (batch dimension removed) assert result.ndim == 2 assert result.shape == (10, 6) def test_denoise_step_uses_custom_execution_horizon(): """Test denoise_step uses custom execution_horizon parameter.""" config = RTCConfig(execution_horizon=10) processor = RTCProcessor(config) x_t = torch.ones(1, 20, 1) prev_chunk = torch.full((1, 15, 1), 0.1) def mock_denoiser(x): return x * 0.5 result = processor.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, execution_horizon=15, ) expected_result = torch.tensor( [ [ [1.8000], [1.8000], [1.8000], [1.8000], [1.8000], [1.6818], [1.5636], [1.4455], [1.3273], [1.2091], [1.0909], [0.9727], [0.8545], [0.7364], [0.6182], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], ] ] ) assert torch.allclose(result, expected_result, atol=1e-4) def test_denoise_step_guidance_weight_at_time_zero(): """Test denoise_step handles time=0 (tau=1) without NaN/Inf.""" config = RTCConfig(max_guidance_weight=10.0) processor = RTCProcessor(config) x_t = torch.ones(1, 20, 1) prev_chunk = torch.full((1, 20, 1), 0.1) def mock_denoiser(x): return x * 0.5 result = processor.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.0), original_denoise_step_partial=mock_denoiser, ) expected_result = torch.tensor( [ [ [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], [0.5000], ] ] ) assert torch.allclose(result, expected_result, atol=1e-4) def test_denoise_step_with_real_denoise_step_partial(): """Test denoise_step with a real denoiser.""" config = RTCConfig(max_guidance_weight=10.0) processor = RTCProcessor(config) batch_size = 10 action_dim = 6 chunk_size = 20 x_t = torch.ones(batch_size, chunk_size, action_dim) prev_chunk = torch.full((batch_size, chunk_size, action_dim), 0.1) velocity_function = torch.nn.Sequential( torch.nn.Linear(action_dim, 1000), torch.nn.ReLU(), torch.nn.Linear(1000, 256), torch.nn.ReLU(), torch.nn.Linear(256, action_dim), ) def mock_denoiser(x): return velocity_function(x) result = processor.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) assert result.shape == (batch_size, chunk_size, action_dim) def test_denoise_step_guidance_weight_at_time_one(): """Test denoise_step handles time=1 (tau=0) with max_guidance_weight clamping.""" config = RTCConfig(max_guidance_weight=10.0) processor = RTCProcessor(config) x_t = torch.randn(1, 50, 6) prev_chunk = torch.randn(1, 50, 6) def mock_denoiser(x): return torch.ones_like(x) * 0.5 # Time = 1 => tau = 0, c = (1-tau)/tau = 1/0 = inf (clamped to max_guidance_weight) result = processor.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(1.0), original_denoise_step_partial=mock_denoiser, ) # Should clamp to max_guidance_weight (no Inf) assert not torch.any(torch.isinf(result)) def test_denoise_step_tracks_debug_info(rtc_processor_debug_enabled): """Test denoise_step tracks debug information when enabled.""" x_t = torch.randn(1, 50, 6) prev_chunk = torch.randn(1, 50, 6) def mock_denoiser(x): return torch.ones_like(x) * 0.5 rtc_processor_debug_enabled.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) # Should have tracked one step steps = rtc_processor_debug_enabled.get_all_debug_steps() assert len(steps) == 1 # Check tracked values step = steps[0] assert step.time == 0.5 assert step.x1_t is not None assert step.correction is not None assert step.err is not None assert step.weights is not None assert step.guidance_weight is not None assert step.inference_delay == 5 def test_denoise_step_doesnt_track_without_debug(rtc_processor_debug_disabled): """Test denoise_step doesn't track when debug disabled.""" x_t = torch.randn(1, 50, 6) prev_chunk = torch.randn(1, 50, 6) def mock_denoiser(x): return torch.ones_like(x) * 0.5 rtc_processor_debug_disabled.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) # Should not track steps = rtc_processor_debug_disabled.get_all_debug_steps() assert len(steps) == 0 # ====================== Integration Tests ====================== def test_denoise_step_full_workflow(): """Test complete denoise_step workflow.""" config = RTCConfig( enabled=True, prefix_attention_schedule=RTCAttentionSchedule.LINEAR, max_guidance_weight=5.0, execution_horizon=10, debug=True, ) processor = RTCProcessor(config) # Simulate two denoising steps x_t1 = torch.randn(1, 50, 6) x_t2 = torch.randn(1, 50, 6) def mock_denoiser(x): return torch.randn_like(x) * 0.1 # First step - no guidance result1 = processor.denoise_step( x_t=x_t1, prev_chunk_left_over=None, inference_delay=5, time=torch.tensor(0.8), original_denoise_step_partial=mock_denoiser, ) # Second step - with guidance result2 = processor.denoise_step( x_t=x_t2, prev_chunk_left_over=result1, inference_delay=5, time=torch.tensor(0.6), original_denoise_step_partial=mock_denoiser, ) # Both should complete successfully assert result1.shape == (1, 50, 6) assert result2.shape == (1, 50, 6) # Should have tracked one step (second one, first had no prev_chunk) steps = processor.get_all_debug_steps() assert len(steps) == 1 @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_denoise_step_with_cuda_tensors(): """Test denoise_step works with CUDA tensors.""" config = RTCConfig(execution_horizon=10, max_guidance_weight=5.0) processor = RTCProcessor(config) x_t = torch.randn(1, 50, 6, device="cuda") prev_chunk = torch.randn(1, 50, 6, device="cuda") def mock_denoiser(x): return torch.ones_like(x) * 0.5 result = processor.denoise_step( x_t=x_t, prev_chunk_left_over=prev_chunk, inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=mock_denoiser, ) # Result should be on CUDA assert result.device.type == "cuda" assert result.shape == x_t.shape def test_denoise_step_deterministic_with_same_inputs(): """Test denoise_step produces same output with same inputs.""" config = RTCConfig(execution_horizon=10, max_guidance_weight=5.0) processor = RTCProcessor(config) torch.manual_seed(42) x_t = torch.randn(1, 50, 6) prev_chunk = torch.randn(1, 50, 6) def deterministic_denoiser(x): return torch.ones_like(x) * 0.5 result1 = processor.denoise_step( x_t=x_t.clone(), prev_chunk_left_over=prev_chunk.clone(), inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=deterministic_denoiser, ) result2 = processor.denoise_step( x_t=x_t.clone(), prev_chunk_left_over=prev_chunk.clone(), inference_delay=5, time=torch.tensor(0.5), original_denoise_step_partial=deterministic_denoiser, ) # Should produce identical results assert torch.allclose(result1, result2)
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/rtc/test_modeling_rtc.py", "license": "Apache License 2.0", "lines": 581, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
huggingface/lerobot:tests/policies/smolvla/test_smolvla_rtc.py
#!/usr/bin/env python # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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. """Test SmolVLA policy with Real-Time Chunking (RTC) enabled during inference.""" import pytest import torch from lerobot.configs.types import FeatureType, PolicyFeature, RTCAttentionSchedule # noqa: E402 from lerobot.policies.factory import make_pre_post_processors # noqa: E402 from lerobot.policies.rtc.configuration_rtc import RTCConfig # noqa: E402 from lerobot.policies.smolvla.configuration_smolvla import SmolVLAConfig # noqa: F401 from lerobot.utils.random_utils import set_seed # noqa: E402 from tests.utils import require_cuda, require_package # noqa: E402 @require_package("transformers") @require_cuda def test_smolvla_rtc_initialization(): from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy # noqa: F401 """Test SmolVLA policy can initialize RTC processor.""" set_seed(42) config = SmolVLAConfig(max_action_dim=7, chunk_size=50) # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Instantiate policy policy = SmolVLAPolicy(config) # Verify RTC processor is initialized assert hasattr(policy, "rtc_processor") assert policy.rtc_processor is not None assert policy.rtc_processor.rtc_config.enabled is True print("✓ SmolVLA RTC initialization: Test passed") @require_package("transformers") @require_cuda def test_smolvla_rtc_initialization_without_rtc_config(): from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy # noqa: F401 """Test SmolVLA policy can initialize without RTC config.""" set_seed(42) config = SmolVLAConfig(max_action_dim=7, chunk_size=50) # Instantiate policy policy = SmolVLAPolicy(config) # Verify RTC processor is not initialized assert hasattr(policy, "rtc_processor") assert policy.rtc_processor is None assert policy.model.rtc_processor is None assert policy._rtc_enabled() is False print("✓ SmolVLA RTC initialization without RTC config: Test passed") @require_package("transformers") @require_cuda @pytest.mark.skipif(True, reason="Requires pretrained SmolVLA model weights") def test_smolvla_rtc_inference_with_prev_chunk(): from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy # noqa: F401 """Test SmolVLA policy inference with RTC and previous chunk.""" set_seed(42) config = SmolVLAConfig(max_action_dim=7, chunk_size=50) # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and create preprocessor policy = SmolVLAPolicy(config) policy.eval() preprocessor, _ = make_pre_post_processors( policy_cfg=config, pretrained_path=None, dataset_stats=dataset_stats ) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC and previous chunk actions_with_rtc = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=prev_chunk, inference_delay=4, execution_horizon=10, ) # Test without RTC for comparison policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True # Verify shapes assert actions_with_rtc.shape == (1, config.chunk_size, 7) assert actions_without_rtc.shape == (1, config.chunk_size, 7) # With previous chunk, actions should be different (RTC guidance applied) assert not torch.allclose(actions_with_rtc, actions_without_rtc, rtol=1e-3) print("✓ SmolVLA RTC inference with prev_chunk: Test passed") @require_package("transformers") @require_cuda @pytest.mark.skipif(True, reason="Requires pretrained SmolVLA model weights") def test_smolvla_rtc_inference_without_prev_chunk(): from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy # noqa: F401 """Test SmolVLA policy inference with RTC but no previous chunk (RTC should have no effect).""" set_seed(42) config = SmolVLAConfig(max_action_dim=7, chunk_size=50) # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and create preprocessor policy = SmolVLAPolicy(config) policy.eval() preprocessor, _ = make_pre_post_processors( policy_cfg=config, pretrained_path=None, dataset_stats=dataset_stats ) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC enabled but no previous chunk actions_with_rtc_no_prev = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=None, ) # Test without RTC policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True # Without previous chunk, RTC should have no effect assert torch.allclose(actions_with_rtc_no_prev, actions_without_rtc, rtol=1e-5) print("✓ SmolVLA RTC inference without prev_chunk: Test passed") @require_package("transformers") @require_cuda @pytest.mark.skipif(True, reason="Requires pretrained SmolVLA model weights") def test_smolvla_rtc_validation_rules(): from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy # noqa: F401 """Test SmolVLA policy with RTC follows all three validation rules.""" set_seed(42) config = SmolVLAConfig(max_action_dim=7, chunk_size=50) # Add RTC config config.rtc_config = RTCConfig( enabled=True, execution_horizon=10, max_guidance_weight=5.0, prefix_attention_schedule=RTCAttentionSchedule.EXP, debug=False, ) config.input_features = { "observation.state": PolicyFeature(type=FeatureType.STATE, shape=(14,)), "observation.images.base_0_rgb": PolicyFeature(type=FeatureType.VISUAL, shape=(3, 224, 224)), } config.output_features = { "action": PolicyFeature(type=FeatureType.ACTION, shape=(7,)), } # Create dataset stats dataset_stats = { "observation.state": {"mean": torch.zeros(14), "std": torch.ones(14)}, "action": {"mean": torch.zeros(7), "std": torch.ones(7)}, "observation.images.base_0_rgb": {"mean": torch.zeros(3, 224, 224), "std": torch.ones(3, 224, 224)}, } # Instantiate policy and create preprocessor policy = SmolVLAPolicy(config) policy.eval() preprocessor, _ = make_pre_post_processors( policy_cfg=config, pretrained_path=None, dataset_stats=dataset_stats ) device = config.device # Create dummy batch batch = { "observation.state": torch.randn(1, 14, dtype=torch.float32, device=device), "observation.images.base_0_rgb": torch.rand(1, 3, 224, 224, dtype=torch.float32, device=device), "task": ["Pick up the object"], } batch = preprocessor(batch) # Create previous chunk prev_chunk = torch.randn(1, 25, 7, dtype=torch.float32, device=device) inference_delay = 4 execution_horizon = 10 with torch.no_grad(): # Use same noise for fair comparison noise = policy.model.sample_noise((1, config.chunk_size, 7), device) # Test with RTC actions_with_rtc = policy.predict_action_chunk( batch, noise=noise.clone(), prev_chunk_left_over=prev_chunk, inference_delay=inference_delay, execution_horizon=execution_horizon, ) # Test without RTC policy.config.rtc_config.enabled = False actions_without_rtc = policy.predict_action_chunk(batch, noise=noise.clone()) policy.config.rtc_config.enabled = True assert not torch.allclose(actions_with_rtc, actions_without_rtc, rtol=1e-3)
{ "repo_id": "huggingface/lerobot", "file_path": "tests/policies/smolvla/test_smolvla_rtc.py", "license": "Apache License 2.0", "lines": 255, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test