Appendix41/VLX-Go-1.0-bucket / modeling_vlxgo.py
Appendix41's picture
download
raw
6.87 kB
"""vlxgo: predict waypoints from text and visual features."""
import math
from typing import List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoConfig, AutoModel, AutoTokenizer, PreTrainedModel
from .configuration_vlxgo import VlxgoConfig
from .history_tokens import interleave_tvi_tokens
from .multimodal_inputs import build_visual_prefix
class TVIEmbedder(nn.Module):
"""Temporal-Viewpoint Indicator with token insertion.
- make_time_token(t, kind_id, view_id)
- make_angle_token(theta, kind_id, view_id) -> uses [sinθ, cosθ] projection
kind_id: 0 = coarse, 1 = fine; relative frame timing is encoded by time.
"""
def __init__(self, d_model: int, max_time: int = 4096, max_views: int = 1):
super().__init__()
self.time_emb = nn.Embedding(max_time, d_model)
self.view_emb = nn.Embedding(max_views, d_model)
self.kind_emb = nn.Embedding(2, d_model)
self.angle_proj = nn.Linear(2, d_model)
def make_time_token(self, t_scalar: int, kind_id: int, view_id: int = 0,
device: Optional[torch.device] = None) -> torch.Tensor:
tok = self.time_emb.weight[t_scalar] + self.view_emb.weight[view_id] + self.kind_emb.weight[kind_id]
return tok.to(device) if device is not None else tok
def make_angle_token(self, theta: float, kind_id: int, view_id: int = 0,
device: Optional[torch.device] = None) -> torch.Tensor:
theta = (theta + math.pi) % (2*math.pi) - math.pi
sincos = torch.tensor([math.sin(theta), math.cos(theta)],
dtype=self.angle_proj.weight.dtype,
device=device)
ang = F.linear(sincos, self.angle_proj.weight, self.angle_proj.bias)
tok = ang + self.view_emb.weight[view_id] + self.kind_emb.weight[kind_id]
return tok
class CrossModalityProjector(nn.Module):
def __init__(self, in_dim: int, out_dim: int):
super().__init__()
self.net = nn.Sequential(
nn.LayerNorm(in_dim),
nn.Linear(in_dim, out_dim), nn.GELU(),
nn.Linear(out_dim, out_dim)
)
def forward(self, x): return self.net(x)
class PlannerHead3L(nn.Module):
"""Three-layer MLP waypoint prediction head."""
def __init__(self, d_model: int, n_waypoints: int, action_dims: int, use_tanh: bool = True):
super().__init__()
hid = d_model * 2
out_dim = n_waypoints * action_dims
self.mlp = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, hid), nn.GELU(),
nn.Linear(hid, hid), nn.GELU(),
nn.Linear(hid, out_dim)
)
self.nw = n_waypoints
self.ad = action_dims
self.use_tanh = use_tanh
def forward(self, act_h: torch.Tensor) -> torch.Tensor:
y = self.mlp(act_h)
if self.use_tanh:
y = torch.tanh(y) # bound to [-1,1]
return y.view(-1, self.nw, self.ad)
class VlxgoForWaypoint(PreTrainedModel):
config_class = VlxgoConfig
base_model_prefix = ""
main_input_name = "coarse_tokens"
def __init__(self, config):
super().__init__(config)
self.cfg = config
llm_dict = dict(config.llm_config)
model_type = llm_dict.pop("model_type")
llm_config = AutoConfig.for_model(model_type, **llm_dict)
# Backbone in bf16, other modules in fp32: default HF loading preserves
# the mixed dtype of each module.
self.llm = AutoModel.from_config(llm_config, dtype=torch.bfloat16)
self.tokenizer = None
self.D = self.llm.config.hidden_size
self.proj = CrossModalityProjector(config.vision_feat_dim, self.D).float()
self.tvi = TVIEmbedder(self.D, max_time=config.max_time).float()
self.act_token = nn.Parameter(torch.zeros(1, 1, self.D, dtype=torch.float32))
nn.init.normal_(self.act_token, std=0.02)
action_dims = 2 if config.use_indicator else (3 if config.embodiment in ("wheeled", "car") else 4)
self.action_dims = action_dims
self.planner = PlannerHead3L(self.D, config.n_waypoints, action_dims,
use_tanh=config.use_tanh_actions).float()
self.log_std = nn.Parameter(torch.zeros(action_dims, dtype=torch.float32), requires_grad=False)
if not config.use_angle_tvi:
self.tvi.angle_proj.requires_grad_(False)
if config.use_indicator:
alpha_values = list(config.alpha_indicator)
elif config.embodiment == "uav":
alpha_values = list(config.alpha_uav)
elif config.embodiment == "car":
alpha_values = list(config.alpha_car)
else:
alpha_values = list(config.alpha_wheeled)
alpha_values = alpha_values[:action_dims]
alpha_values.extend([1.0] * (action_dims - len(alpha_values)))
if config.alpha_xy is not None and action_dims >= 2:
alpha_values[:2] = [config.alpha_xy, config.alpha_xy]
self.register_buffer("alpha_task", torch.tensor(alpha_values, dtype=torch.float32).view(1, 1, -1))
def _ensure_tokenizer(self):
if self.tokenizer is None:
model_location = getattr(self.config, "_name_or_path", "")
if not model_location:
raise ValueError(
"Set model.tokenizer first, or load a model directory via from_pretrained.")
# Keep the original Qwen tokenization rules; disable the Mistral regex fix.
self.tokenizer = AutoTokenizer.from_pretrained(model_location, fix_mistral_regex=False)
def get_input_embeddings(self):
return self.llm.get_input_embeddings()
def forward(self, coarse_tokens, coarse_tidx, fine_tokens, fine_tidx, instructions, yaw_hist: Optional[torch.Tensor]=None, yaw_curr: Optional[torch.Tensor]=None, *, history_valid_mask: torch.Tensor):
self._ensure_tokenizer()
device = next(self.parameters()).device
B = coarse_tokens.size(0)
(prefix, prefix_attn) = build_visual_prefix(self.llm, self.tokenizer, self.proj, self.tvi, coarse_tokens, coarse_tidx, fine_tokens, fine_tidx, instructions, history_valid_mask, yaw_hist=yaw_hist, yaw_curr=yaw_curr, use_angle=self.cfg.use_angle_tvi)
act = self.act_token.expand(B, 1, -1)
seq = torch.cat([prefix, act.to(prefix.dtype)], dim=1)
attn = torch.cat([prefix_attn, torch.ones(B, 1, dtype=prefix_attn.dtype, device=device)], dim=1)
out = self.llm(inputs_embeds=seq, attention_mask=attn, output_hidden_states=True, use_cache=False)
h_act = out.last_hidden_state[:, -1, :]
h_act = h_act.float()
a_hat = self.planner(h_act)
tau_pred = a_hat * self.alpha_task
return tau_pred

Xet Storage Details

Size:
6.87 kB
·
Xet hash:
ee67d781def940961360e923807deb8de7c32d5e3719298a594daf650559f3c6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.