|
|
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: |
|
|
inv_freq, self.attention_scaling = self.rope_init_fn(**self.rope_kwargs) |
|
|
self.register_buffer("inv_freq", inv_freq, persistent=False) |
|
|
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: |
|
|
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) |
|
|
|
|
|
|
|
|
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) |
|
|
position_ids_expanded = position_ids[:, None, :].float() |
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
cos = cos * self.attention_scaling |
|
|
sin = sin * self.attention_scaling |
|
|
|
|
|
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) |
|
|
|
|
|
|
|
|
|
|
|
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(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, |
|
|
) -> 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} |
|
|
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) |
|
|
|
|
|
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) |
|
|
if attention_mask is not None: |
|
|
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] |
|
|
attn_weights = attn_weights + causal_mask |
|
|
|
|
|
|
|
|
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): |
|
|
|
|
|
for ln in (self.norm1, self.norm2): |
|
|
nn.init.ones_(ln.weight) |
|
|
nn.init.zeros_(ln.bias) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
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, |
|
|
): |
|
|
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.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), |
|
|
) |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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)) |
|
|
x = x + g_attn * attn_out |
|
|
|
|
|
h2 = self.norm2(x) |
|
|
mlp_out = self.mlp(h2) |
|
|
g_mlp = torch.sigmoid(self.mlp_gate(h2)) |
|
|
x = x + g_mlp * mlp_out |
|
|
return x |
|
|
|
|
|
@torch.no_grad() |
|
|
def _init_weights(self, gate_bias_init: float): |
|
|
|
|
|
for ln in (self.norm1, self.norm2): |
|
|
nn.init.ones_(ln.weight) |
|
|
nn.init.zeros_(ln.bias) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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, |
|
|
zero_init_attn_out: bool = False, |
|
|
): |
|
|
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([ |
|
|
_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) |
|
|
|
|
|
|
|
|
|
|
|
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): |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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]): |
|
|
with autocast(dtype=torch.bfloat16): |
|
|
pm = data_dict['point_map'][i] |
|
|
_, 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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = 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) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)) |
|
|
|
|
|
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 |