add dexvla

This commit is contained in:
lesjie-wen 2025-02-20 17:29:21 +08:00
parent fe483b1d0d
commit 1aa4f0c086
4 changed files with 2531 additions and 0 deletions

View File

@ -0,0 +1,270 @@
# coding=utf-8
# Copyright 2024 The Qwen team, Alibaba Group 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.
"""Qwen2VL model configuration"""
import os
from typing import Union
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_rope_utils import rope_config_validation
from transformers.utils import logging
from transformers import AutoModel, AutoConfig
logger = logging.get_logger(__name__)
class Qwen2VLAVisionConfig(PretrainedConfig):
model_type = "dex_vla"
def __init__(
self,
depth=32,
embed_dim=1280,
hidden_size=3584,
hidden_act="quick_gelu",
mlp_ratio=4,
num_heads=16,
in_channels=3,
patch_size=14,
spatial_merge_size=2,
temporal_patch_size=2,
**kwargs,
):
super().__init__(**kwargs)
self.depth = depth
self.embed_dim = embed_dim
self.hidden_size = hidden_size
self.hidden_act = hidden_act
self.mlp_ratio = mlp_ratio
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
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
cls._set_token_in_kwargs(kwargs)
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
if config_dict.get("model_type") == "qwen2_vl":
config_dict = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
)
return cls.from_dict(config_dict, **kwargs)
class DexVLAConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen2VLModel`]. 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 Qwen2VL model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Qwen2VLModel`]
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 Qwen2VLForConditionalGeneration, Qwen2VLConfig
>>> # Initializing a Qwen2VL style configuration
>>> configuration = Qwen2VLConfig()
>>> # Initializing a model from the Qwen2-VL-7B style configuration
>>> model = Qwen2VLForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "qwen2_vla"
keys_to_ignore_at_inference = ["past_key_values"]
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,
# For loading policy head
policy_head_type='dit_diffusion_policy', # dit_diffusion_policy
policy_head_size='DiT_L',
action_dim=10,
state_dim=7,
non_lora_lr=1e-4,
**kwargs,
):
if isinstance(vision_config, dict):
self.vision_config = Qwen2VLAVisionConfig(**vision_config)
elif vision_config is None:
self.vision_config = Qwen2VLAVisionConfig()
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
# for loading policy head
self.policy_head_type = policy_head_type
# if policy_head_type == 'dit_diffusion_policy':
# # self.policy_head_size = kwargs.get("policy_head_size", "none")
# self.policy_head_size = policy_head_size
# # self.policy_head_config = register_configuration_class(self.policy_head_type, model_size=policy_head_size)
# self.policy_head_config = AutoConfig.for_model(model_type=self.policy_head_type,
# model_size=self.policy_head_size,
# global_cond_dim=hidden_size, action_dim=action_dim,
# state_dim=state_dim)
# elif policy_head_type == 'unet_diffusion_policy':
# self.policy_head_config = AutoConfig.for_model(model_type=self.policy_head_type,
# global_cond_dim=hidden_size, action_dim=action_dim,
# state_dim=state_dim)
# 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
# Validate the correctness of rotary position embeddings parameters
# BC: if there is a 'type' field, move it to 'rope_type'.
# and change type from 'mrope' to 'default' because `mrope` does defeault RoPE calculations
# one can set it to "linear"/"dynamic" etc. to have scaled RoPE
# TODO: @raushan update config in the hub
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)
from transformers import AutoConfig
AutoConfig.register("dex_vla", DexVLAConfig)

View File

@ -0,0 +1,40 @@
import torch.nn as nn
class ActionProjector(nn.Module):
def __init__(self, in_dim, out_dim=1024):
super(ActionProjector, self).__init__()
self.global_1d_pool = nn.AdaptiveAvgPool1d(1)
self.mlps = nn.ModuleList([
# nn.LayerNorm(in_dim),
nn.Linear(in_dim, in_dim),
nn.GELU(),
nn.Linear(in_dim, out_dim),
nn.Dropout(0.0),
]
)
def forward(self, x):
x = self.global_1d_pool(x.permute(1, 0)).permute(1, 0)
for mlp in self.mlps:
x = mlp(x)
return x
class FiLM(nn.Module):
def __init__(self, feature_dim, condition_dim):
super(FiLM, self).__init__()
self.scale_fc = nn.Linear(condition_dim, feature_dim)
self.shift_fc = nn.Linear(condition_dim, feature_dim)
nn.init.zeros_(self.scale_fc.weight)
nn.init.zeros_(self.scale_fc.bias)
nn.init.zeros_(self.shift_fc.weight)
nn.init.zeros_(self.shift_fc.bias)
def forward(self, x, condition):
# 计算缩放和偏移参数
scale = self.scale_fc(condition)
shift = self.shift_fc(condition)
# 应用 FiLM 调制
return x * (1 + scale) + shift

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,151 @@
from PIL import Image
import numpy as np
from torchvision.transforms.functional import to_pil_image, to_tensor
import torchvision.transforms as transforms
import torch
from qwen_vl_utils import process_vision_info
from qwen_vl_utils import fetch_image
class Qwen2VLAProcess:
def __init__(
self,
language=None,
tokenizer=None,
max_seq_len=512,
multimodal_processor=None,
camera_names=None,
data_args=None,
):
super().__init__()
self.tokenizer = tokenizer
self.max_seq_len = max_seq_len
self.camera_names = camera_names
# self.language = language
self.multimodal_processor = multimodal_processor
self.data_args = data_args
def preprocess_image(self, image, size=224):
# Model has been trained to handle images of different aspects ratios
# resized to 224x224 in the range [-1, 1]. Bilinear and antialias resize
# options are helpful to improve quality in some tasks.
image = np.asarray(image)
if image.ndim == 2: # Convert image without last channel into greyscale.
image = np.stack((image,) * 3, axis=-1)
image = image[..., :3] # Remove alpha layer.
assert image.shape[-1] == 3
image_pil = to_pil_image(image)
# Step 2: Define the resize transformation
resize_transform = transforms.Resize((size, size), interpolation=transforms.InterpolationMode.BILINEAR)
# Step 3: Apply the resize transformation
image_resized_pil = resize_transform(image_pil)
# Step 4: Convert back to tensor if needed
image_resized = to_tensor(image_resized_pil)
return image.numpy() / 127.5 - 1.0 # [0, 255]->[-1,1]
def qwen2_image_preprocess(self, each, camera_name):
ele = {}
each = Image.fromarray(each.squeeze(0).permute(1, 2, 0).numpy().astype(np.uint8))
ele['image'] = each
if 'wrist' in camera_name:
w, h = eval(self.data_args.image_size_wrist)
ele['resized_height'] = h
ele['resized_width'] = w
else:
ele['resized_height'] = each.height
ele['resized_width'] = each.width
each = fetch_image(ele)
return torch.from_numpy(np.array(each))
def forward_process(self, sample, use_reasoning=True):
if sample['image'].ndim == 5 and sample['image'].shape[1] > 2:
video = True
else:
video = False
messages = self.datastruct_droid2llava(sample, video=video)
data_dict = dict(
messages=messages,
images=None
)
image_data = torch.chunk(sample['image'], sample['image'].shape[0], 0)
images_list = []
for i, each in enumerate(image_data):
if each.ndim == 4:
img_pil = self.qwen2_image_preprocess(each, self.camera_names[i])
else:
img_pil = []
for temp in each.squeeze(0):
img_pil.append(self.qwen2_image_preprocess(temp, self.camera_names[i]))
img_pil = torch.stack(img_pil, 0)
images_list.append(img_pil)
# TODO RESIZE
# image_data = image_data / 255.0
if video:
image_data = None
video_inputs = images_list
else:
image_data = images_list
video_inputs = None
text = self.multimodal_processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
model_inputs = self.multimodal_processor(
text=text,
images=image_data,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
input_labels = torch.ones_like(model_inputs['input_ids']) * -100
if use_reasoning:
answer = sample['reasoning'] + "Next action:" + '<|im_end|>'
else:
answer = '' + '<|im_end|>'
output_text = self.tokenizer(answer, padding=True, return_tensors="pt")
output_labels = output_text['input_ids']
model_inputs['input_ids'] = torch.cat((model_inputs['input_ids'], output_text['input_ids']), dim=-1)
model_inputs['attention_mask'] = torch.cat((model_inputs['attention_mask'], output_text['attention_mask']), dim=-1)
labels = torch.cat((input_labels, output_labels), dim=-1)
data_dict['state'] = sample['state']
data_dict['action'] = sample['action']
data_dict['is_pad'] = sample['is_pad']
data_dict['labels'] = labels
for k, v in model_inputs.items():
data_dict[k] = v
return data_dict
def datastruct_droid2llava(self, sample, video=False):
len_image = sample['image'].shape[0]
messages = [
{
"role": "user",
"content": [],
},
# {"role": "assistant", "content": f''},
]
for i in range(len_image):
if video:
messages[0]['content'].append({
"type": "video",
"video": None,
})
else:
messages[0]['content'].append({
"type": "image",
"image": None,
})
messages[0]['content'].append({"type": "text", "text": f""})
messages[0]['content'][-1]['text'] = sample['raw_lang']
return messages