File size: 31,561 Bytes
c94c8c9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 |
import torch
from torch import Tensor
from torch.cuda.amp import autocast
from transformers import AutoModelForCausalLM, AutoModel, AutoTokenizer, AutoImageProcessor
from transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
from model.build import MODEL_REGISTRY, BaseModel
from modules.build import build_module
from optim.utils import no_decay_param_group
from peft import LoraConfig, get_peft_model
from model.data_augmentation import *
import torch.nn as nn
from typing import List, Optional, Tuple, Union
def last_token_pool(last_hidden_states: Tensor,
attention_mask: Tensor) -> Tensor:
left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
if left_padding:
return last_hidden_states[:, -1]
else:
sequence_lengths = attention_mask.sum(dim=1) - 1
batch_size = last_hidden_states.shape[0]
return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
class Qwen3RotaryEmbedding(nn.Module):
def __init__(
self,
dim=None,
max_position_embeddings=2048,
base=10000,
device=None,
scaling_factor=1.0,
rope_type="default",
):
super().__init__()
self.rope_type = "default"
self.max_seq_len_cached = 32768
self.original_max_seq_len = 32768
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
self.rope_kwargs = {
"rope_type": rope_type,
"factor": scaling_factor,
"dim": 32,
"base": base,
"max_position_embeddings": max_position_embeddings,
}
inv_freq, self.attention_scaling = self.rope_init_fn(**self.rope_kwargs)
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.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
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
# 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(1, 2)
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)
# Copied from transformers.models.llama.modeling_llama.rotate_half
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)
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
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`, *optional*):
Deprecated and unused.
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.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class Qwen3RMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Qwen3RMSNorm 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}"
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 Qwen3Attention(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, layer_idx = None):
super().__init__()
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 = 512
self.num_heads = 16
self.head_dim = self.hidden_size // self.num_heads
self.num_key_value_heads = 8
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.max_position_embeddings = 32768
self.rope_theta = 1000000
self.is_causal = True
self.attention_dropout = 0.0
self.use_qk_norm = True
self.headwise_attn_output_gate = False
self.elementwise_attn_output_gate = True
qkv_bias = False
rms_norm_eps = 1e-06
if self.headwise_attn_output_gate:
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim + self.num_heads, bias=qkv_bias)
elif self.elementwise_attn_output_gate:
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim * 2, bias=qkv_bias)
else:
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=qkv_bias)
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=qkv_bias)
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=qkv_bias)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=qkv_bias)
if self.use_qk_norm:
self.q_norm = Qwen3RMSNorm(self.head_dim, eps=rms_norm_eps)
self.k_norm = Qwen3RMSNorm(self.head_dim, eps=rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
output_attentions: bool = False,
use_cache: bool = False,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
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)
if self.headwise_attn_output_gate:
query_states = query_states.view(bsz, q_len, self.num_key_value_heads, -1)
query_states, gate_score = torch.split(query_states, [self.head_dim * self.num_key_value_groups, self.num_key_value_groups], dim=-1)
gate_score = gate_score.reshape(bsz, q_len, -1, 1)
query_states = query_states.reshape(bsz, q_len, -1, self.head_dim).transpose(1, 2)
elif self.elementwise_attn_output_gate:
query_states = query_states.view(bsz, q_len, self.num_key_value_heads, -1)
query_states, gate_score = torch.split(query_states, [self.head_dim * self.num_key_value_groups, self.head_dim * self.num_key_value_groups], dim=-1)
gate_score = gate_score.reshape(bsz, q_len, -1, self.head_dim)
query_states = query_states.reshape(bsz, q_len, -1, self.head_dim).transpose(1, 2)
else:
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)
if self.use_qk_norm:
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
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
# 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()
if self.headwise_attn_output_gate or self.elementwise_attn_output_gate:
attn_output = attn_output * torch.sigmoid(gate_score)
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
class _GlobalViewAttnBlock(nn.Module):
"""One pre-norm Transformer-style block over view tokens (B,V,D)."""
def __init__(
self,
dim: int,
num_heads: int,
mlp_ratio: float,
dropout: float,
zero_init_residual: bool,
zero_init_attn_out: bool,
):
super().__init__()
self.zero_init_residual = zero_init_residual
self.zero_init_attn_out = zero_init_attn_out
self.norm1 = nn.LayerNorm(dim)
self.attn = nn.MultiheadAttention(
embed_dim=dim,
num_heads=num_heads,
dropout=dropout,
batch_first=True,
bias=True,
)
self.norm2 = nn.LayerNorm(dim)
hidden_dim = int(dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, dim),
nn.Dropout(dropout),
)
self._init_weights()
def forward(self, x, key_padding_mask=None):
h = self.norm1(x)
attn_out, _ = self.attn(
h, h, h,
key_padding_mask=key_padding_mask,
need_weights=False,
)
x = x + attn_out
x = x + self.mlp(self.norm2(x))
return x
@torch.no_grad()
def _init_weights(self):
# LayerNorm
for ln in (self.norm1, self.norm2):
nn.init.ones_(ln.weight)
nn.init.zeros_(ln.bias)
# MultiheadAttention: in_proj for qkv (3D, D)
if getattr(self.attn, "in_proj_weight", None) is not None:
nn.init.xavier_uniform_(self.attn.in_proj_weight)
if getattr(self.attn, "in_proj_bias", None) is not None:
nn.init.zeros_(self.attn.in_proj_bias)
# out proj
nn.init.xavier_uniform_(self.attn.out_proj.weight)
if self.attn.out_proj.bias is not None:
nn.init.zeros_(self.attn.out_proj.bias)
# optional: start attn residual near-zero
if self.zero_init_attn_out:
nn.init.zeros_(self.attn.out_proj.weight)
if self.attn.out_proj.bias is not None:
nn.init.zeros_(self.attn.out_proj.bias)
# MLP
fc1: nn.Linear = self.mlp[0]
fc2: nn.Linear = self.mlp[3]
nn.init.xavier_uniform_(fc1.weight)
if fc1.bias is not None:
nn.init.zeros_(fc1.bias)
# zero-init last projection for stable residual start (recommended)
if self.zero_init_residual:
nn.init.zeros_(fc2.weight)
if fc2.bias is not None:
nn.init.zeros_(fc2.bias)
else:
nn.init.xavier_uniform_(fc2.weight)
if fc2.bias is not None:
nn.init.zeros_(fc2.bias)
class _GlobalViewGatedAttnBlock(nn.Module):
"""Pre-norm Transformer block over view tokens (B,V,D) with gated residuals."""
def __init__(
self,
dim: int,
num_heads: int,
mlp_ratio: float,
dropout: float,
zero_init_residual: bool,
zero_init_attn_out: bool,
gate_bias_init: float = -2.0, # sigmoid(-2)≈0.12, starts near-identity (small updates)
):
super().__init__()
self.zero_init_residual = zero_init_residual
self.zero_init_attn_out = zero_init_attn_out
self.norm1 = nn.LayerNorm(dim)
self.attn = nn.MultiheadAttention(
embed_dim=dim,
num_heads=num_heads,
dropout=dropout,
batch_first=True,
bias=True,
)
# --- Gating for attention residual ---
# Produces per-token, per-channel gates in (0,1)
self.attn_gate = nn.Linear(dim, dim, bias=True)
self.norm2 = nn.LayerNorm(dim)
hidden_dim = int(dim * mlp_ratio)
self.mlp = nn.Sequential(
nn.Linear(dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, dim),
nn.Dropout(dropout),
)
# --- Gating for MLP residual ---
self.mlp_gate = nn.Linear(dim, dim, bias=True)
self._init_weights(gate_bias_init=gate_bias_init)
def forward(self, x: torch.Tensor, key_padding_mask=None) -> torch.Tensor:
# x: (B, V, D)
h1 = self.norm1(x)
attn_out, _ = self.attn(
h1, h1, h1,
key_padding_mask=key_padding_mask,
need_weights=False,
)
g_attn = torch.sigmoid(self.attn_gate(h1)) # (B, V, D)
x = x + g_attn * attn_out
h2 = self.norm2(x)
mlp_out = self.mlp(h2)
g_mlp = torch.sigmoid(self.mlp_gate(h2)) # (B, V, D)
x = x + g_mlp * mlp_out
return x
@torch.no_grad()
def _init_weights(self, gate_bias_init: float):
# LayerNorm
for ln in (self.norm1, self.norm2):
nn.init.ones_(ln.weight)
nn.init.zeros_(ln.bias)
# MultiheadAttention: in_proj for qkv
if getattr(self.attn, "in_proj_weight", None) is not None:
nn.init.xavier_uniform_(self.attn.in_proj_weight)
if getattr(self.attn, "in_proj_bias", None) is not None:
nn.init.zeros_(self.attn.in_proj_bias)
# out proj
nn.init.xavier_uniform_(self.attn.out_proj.weight)
if self.attn.out_proj.bias is not None:
nn.init.zeros_(self.attn.out_proj.bias)
# optional: start attn residual near-zero
if self.zero_init_attn_out:
nn.init.zeros_(self.attn.out_proj.weight)
if self.attn.out_proj.bias is not None:
nn.init.zeros_(self.attn.out_proj.bias)
# MLP
fc1: nn.Linear = self.mlp[0]
fc2: nn.Linear = self.mlp[3]
nn.init.xavier_uniform_(fc1.weight)
if fc1.bias is not None:
nn.init.zeros_(fc1.bias)
if self.zero_init_residual:
nn.init.zeros_(fc2.weight)
if fc2.bias is not None:
nn.init.zeros_(fc2.bias)
else:
nn.init.xavier_uniform_(fc2.weight)
if fc2.bias is not None:
nn.init.zeros_(fc2.bias)
# Gates: start “mostly closed” so training is stable, then learn to open
nn.init.zeros_(self.attn_gate.weight)
nn.init.constant_(self.attn_gate.bias, gate_bias_init)
nn.init.zeros_(self.mlp_gate.weight)
nn.init.constant_(self.mlp_gate.bias, gate_bias_init)
class GlobalViewAttention(nn.Module):
"""
Multi-layer global self-attention over multi-view tokens.
Input: x ∈ (B, V, D)
Output: x' ∈ (B, V, D)
"""
def __init__(
self,
dim: int,
num_layers: int = 1,
num_heads: int = 8,
mlp_ratio: float = 4.0,
dropout: float = 0.0,
zero_init_residual: bool = True, # recommended (stable when adding layers)
zero_init_attn_out: bool = False, # optional extra safety
):
super().__init__()
assert num_layers >= 1, "num_layers must be >= 1"
self.dim = dim
self.num_layers = num_layers
self.num_heads = num_heads
# self.layers = nn.ModuleList([Qwen3Attention(layer_idx) for layer_idx in range(num_layers)])
# self.rotary_emb = Qwen3RotaryEmbedding()
self.layers = nn.ModuleList([
_GlobalViewAttnBlock(
dim=dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
dropout=dropout,
zero_init_residual=zero_init_residual,
zero_init_attn_out=zero_init_attn_out,
)
for _ in range(num_layers)
])
def forward(self, x, key_padding_mask=None):
"""
x: (B, V, D)
key_padding_mask: (B, V), True = ignore (padding)
"""
for layer in self.layers:
x = layer(x, key_padding_mask=key_padding_mask)
return x
@MODEL_REGISTRY.register()
class OpenVocab(BaseModel):
def __init__(self, cfg):
super().__init__(cfg)
self.cfg = cfg
model_root = "fg-clip-base"
self.pm_encoder = AutoModelForCausalLM.from_pretrained(model_root, trust_remote_code=True)
# self.global_attn = GlobalViewAttention(dim=512, num_heads=8, mlp_ratio=4.0, dropout=0.1)
if cfg.mode in ['warmup', 'pretrain']:
self.frozen_model = AutoModelForCausalLM.from_pretrained(model_root, trust_remote_code=True)
self.use_scene_cap = self.cfg.data.args.get("use_scene_cap", False)
self.set_training_mode()
else:
self.text_encoder = AutoModel.from_pretrained('jinaai/jina-clip-v2', trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained('jinaai/jina-clip-v2', trust_remote_code=True)
self.text_encoder.text_model.output_tokens = True
self.set_downstream_mode()
self.head_list = self.cfg.model.heads.head_list
for head in self.head_list:
setattr(self, head, build_module("heads", getattr(self.cfg.model.heads, head)))
def set_training_mode(self):
for name, param in self.frozen_model.named_parameters():
param.requires_grad = False
for name, param in self.pm_encoder.named_parameters():
if "text_model" in name:
param.requires_grad = False
self.pm_encoder.train()
self.frozen_model.eval()
def set_downstream_mode(self):
"""Set the model to downstream mode."""
for param in self.pm_encoder.parameters():
param.requires_grad = False
for name, param in self.text_encoder.named_parameters():
if "vision_model" in name:
param.requires_grad = False
self.pm_encoder.eval()
self.text_encoder.train()
def forward(self, data_dict, mode=None):
# Ensure step counters exist
if 'cur_step' not in data_dict:
data_dict['cur_step'] = 1
data_dict['total_steps'] = 1
data_dict['logit_scale'] = self.pm_encoder.logit_scale.exp()
if mode == "warmup":
data_dict['images'] = data_dict['images'].squeeze(1)
data_dict['point_map'] = data_dict['point_map'].squeeze(1).permute(0, 3, 1, 2)
B, C, H, W = data_dict["images"].shape
data_dict["txt_ids"] = data_dict["txt_ids"].view(B, -1)
with torch.autocast("cuda", dtype=torch.bfloat16):
pm = data_dict["point_map"]
_, data_dict["inter_view_pm_embed"] = self.pm_encoder.get_image_features(pm)
with torch.no_grad():
data_dict["inter_view_txt_embed"] = self.frozen_model.get_text_features(data_dict["txt_ids"])
_, data_dict["inter_view_rgb_embed"] = self.frozen_model.get_image_features(data_dict["images"])
elif mode == 'pretrain':
pm_basic_features = []
B, V, H, W, C = data_dict['point_map'].shape
# point_cloud = data_dict['point_map'].reshape(B, -1, C).contiguous()
# point_cloud, _ = scale_point_cloud(point_cloud, min_s=0.8, max_s=1.2)
# point_cloud, _ = rotate_point_cloud(point_cloud)
# point_cloud, _ = translate_point_cloud(point_cloud, scale=0.1)
# point_cloud, _ = rotate_point_cloud_z(point_cloud)
# point_maps = point_cloud.reshape(B, V, H, W, C)
# data_dict['point_map'] = point_cloud.reshape(B, V, H, W, C).to(torch.bfloat16, non_blocking=True).permute(0, 1, 4, 2, 3)
data_dict['point_map'] = data_dict['point_map'].to(torch.bfloat16, non_blocking=True).permute(0, 1, 4, 2, 3)
for i in range(data_dict['point_map'].shape[0]): # batch dimension
with autocast(dtype=torch.bfloat16):
pm = data_dict['point_map'][i] # [8, C, H, W]
_, pm_feat = self.pm_encoder.get_image_features(data_dict['point_map'][i])
pm_basic_features.append(pm_feat)
pm_basic_features = torch.stack(pm_basic_features, dim=0)
data_dict['inter_view_pm_embed'] = pm_basic_features
# with autocast(dtype=torch.bfloat16):
# pm_basic_features = self.global_attn(pm_basic_features)
# data_dict['inter_view_context_pm_embed'] = pm_basic_features
# data_dict['scene_pm_embed'] = data_dict['inter_view_context_pm_embed'].mean(dim=1)
data_dict['scene_pm_embed'] = data_dict['inter_view_pm_embed'].mean(dim=1)
B_txt = data_dict['txt_ids'].shape[0]
lang_basic_features = torch.empty((B_txt, 32, 512), dtype=torch.bfloat16, device=data_dict['txt_ids'].device)
ground_lang_basic_features = torch.empty((B_txt, 32, 512), dtype=torch.bfloat16, device=data_dict['txt_ids'].device)
rgb_basic_features = torch.empty((B_txt, 32, 512), dtype=torch.bfloat16, device=data_dict['txt_ids'].device)
with torch.no_grad():
with autocast(dtype=torch.bfloat16):
for i in range(B_txt):
lang_basic_features[i] = self.frozen_model.get_text_features(data_dict['txt_ids'][i], walk_short_pos=True)
ground_lang_basic_features[i] = self.frozen_model.get_text_features(data_dict['ground_txt_ids'][i], walk_short_pos=True)
rgb_basic_features[i] = self.frozen_model.get_image_features(data_dict['images'][i])[1]
if getattr(self, "use_scene_cap", False):
data_dict['scene_text_embed'] = self.frozen_model.get_text_features(data_dict['scene_txt_ids'], walk_short_pos=False)
data_dict['inter_view_txt_embed'] = lang_basic_features
data_dict['inter_view_ground_txt_embed'] = ground_lang_basic_features
data_dict['inter_view_rgb_embed'] = rgb_basic_features
data_dict['scene_rgb_embed'] = rgb_basic_features.mean(dim=1)
elif mode == 'qa':
# B, V, C, H, W
B, V, C, H, W = data_dict['vision_inputs'].shape
vision_inputs = data_dict['vision_inputs'].reshape(B * V, C, H, W).contiguous().float()
with torch.no_grad():
with autocast(dtype=torch.bfloat16):
_, vision_feat = self.pm_encoder.get_image_features(vision_inputs)
data_dict['inter_view_pm_embed'] = vision_feat.reshape(B, V, -1)
# jinaclip
tokenized = self.tokenizer.batch_encode_plus(
data_dict['sentence'],
padding="max_length",
return_tensors="pt",
max_length=256,
).to(data_dict['inter_view_pm_embed'].device)
# tokenized = self.tokenizer(
# data_dict['sentence'],
# padding=True,
# max_length=256,
# truncation = False,
# return_tensors="pt",
# ).to(data_dict['inter_view_pm_embed'].device)
data_dict['txt_ids'] = tokenized['input_ids']
with autocast(dtype=torch.bfloat16):
data_dict['inter_view_txt_tokens'] = self.text_encoder.text_model(data_dict['txt_ids'])[-1]
data_dict['attention_mask'] = tokenized['attention_mask'].ne(1).bool()
# text_embeddings = self.text_encoder(**tokenized)
# data_dict['inter_view_txt_tokens'] = text_embeddings.last_hidden_state
# --- QA Head (if used) ---
if hasattr(self, "qa_head") and self.qa_head is not None:
answer_scores = self.qa_head(
data_dict['inter_view_pm_embed'],
data_dict['inter_view_txt_tokens'],
data_dict['attention_mask']
)
data_dict['answer_scores'] = answer_scores
return data_dict
def get_vision_params(self, model):
return [(n, p) for n, p in model.named_parameters() if p.requires_grad]
def get_text_params(self, model):
text_params = [
(n, p) for n, p in model.named_parameters()
if "text_model" in n
]
return text_params
def get_opt_params(self):
def get_lr(cfg, default_lr):
return default_lr if cfg.get("lr") is None else cfg.get("lr")
optimizer_grouped_parameters = []
if self.cfg.mode == 'warmup':
optimizer_grouped_parameters += no_decay_param_group(self.get_vision_params(self.pm_encoder),get_lr(self.cfg.model.vision, self.cfg.solver.lr))
elif self.cfg.mode == 'pretrain':
optimizer_grouped_parameters += no_decay_param_group(self.get_vision_params(self.pm_encoder),get_lr(self.cfg.model.vision, self.cfg.solver.lr))
# optimizer_grouped_parameters += no_decay_param_group(self.get_vision_params(self.global_attn), get_lr(self.cfg.model.vision, self.cfg.solver.lr))
else:
optimizer_grouped_parameters += no_decay_param_group(self.get_text_params(self.text_encoder), get_lr(self.cfg.model.vision, self.cfg.solver.lr))
if "qa_head" in self.head_list:
optimizer_grouped_parameters += no_decay_param_group(
self.qa_head.named_parameters(), get_lr(self.cfg.model.heads.qa_head, self.cfg.solver.lr)
)
if "ground_head" in self.head_list:
optimizer_grouped_parameters += no_decay_param_group(
self.ground_head.named_parameters(), get_lr(self.cfg.model.heads.ground_head, self.cfg.solver.lr)
)
return optimizer_grouped_parameters |