|
|
import math |
|
|
import copy |
|
|
from dataclasses import dataclass |
|
|
from typing import Any, Dict, List, Optional, Tuple, Union |
|
|
|
|
|
import torch |
|
|
import torch.nn as nn |
|
|
import torch.nn.functional as F |
|
|
import torch.utils.checkpoint |
|
|
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss |
|
|
|
|
|
from transformers.activations import ACT2FN |
|
|
from transformers.cache_utils import Cache, EncoderDecoderCache, SlidingWindowCache, StaticCache |
|
|
from transformers.generation import GenerationMixin |
|
|
from transformers.modeling_attn_mask_utils import ( |
|
|
AttentionMaskConverter, |
|
|
) |
|
|
from transformers.modeling_outputs import ( |
|
|
BaseModelOutputWithPast, |
|
|
BaseModelOutput, |
|
|
ModelOutput, |
|
|
) |
|
|
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS |
|
|
from transformers.modeling_utils import PreTrainedModel |
|
|
from transformers.cache_utils import DynamicCache |
|
|
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, |
|
|
logging, |
|
|
replace_return_docstrings, |
|
|
) |
|
|
|
|
|
|
|
|
from transformers.generation.logits_process import ( |
|
|
RepetitionPenaltyLogitsProcessor, |
|
|
TopKLogitsWarper, |
|
|
TopPLogitsWarper, |
|
|
TemperatureLogitsWarper, |
|
|
ExponentialDecayLengthPenalty |
|
|
) |
|
|
|
|
|
|
|
|
from .configuration_hithinkomni import HithinkOmniConfig, HithinkOmniVisionConfig, HithinkAudioEncoderConfig |
|
|
|
|
|
if is_flash_attn_2_available(): |
|
|
from flash_attn import flash_attn_varlen_func |
|
|
|
|
|
from transformers.modeling_flash_attention_utils import _flash_attention_forward |
|
|
else: |
|
|
flash_attn_varlen_func = None |
|
|
|
|
|
try: |
|
|
from flash_attn.layers.rotary import apply_rotary_emb_func |
|
|
except ImportError: |
|
|
apply_rotary_emb_func = None |
|
|
|
|
|
try: |
|
|
from flash_attn.ops.rms_norm import dropout_add_rms_norm |
|
|
except ImportError: |
|
|
dropout_add_rms_norm = None |
|
|
|
|
|
try: |
|
|
from flash_attn.ops.activations import swiglu |
|
|
except ImportError: |
|
|
swiglu = None |
|
|
|
|
|
if torch.cuda.is_available(): |
|
|
try: |
|
|
from flash_attn.losses.cross_entropy import CrossEntropyLoss |
|
|
except ImportError: |
|
|
pass |
|
|
|
|
|
logger = logging.get_logger(__name__) |
|
|
|
|
|
_CONFIG_FOR_DOC = "HithinkOmniConfig" |
|
|
|
|
|
|
|
|
@dataclass |
|
|
class HithinkOmniCausalLMOutputWithPast(ModelOutput): |
|
|
""" |
|
|
Base class for HithinkOmni 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: Optional[torch.FloatTensor] = None |
|
|
logits: torch.FloatTensor = None |
|
|
past_key_values: Optional[List[torch.FloatTensor]] = None |
|
|
audio_past_key_values: Optional[Cache] = None |
|
|
hidden_states: Optional[Tuple[torch.FloatTensor]] = None |
|
|
attentions: Optional[Tuple[torch.FloatTensor]] = None |
|
|
rope_deltas: Optional[torch.LongTensor] = None |
|
|
|
|
|
|
|
|
class CausalConv1d(nn.Conv1d): |
|
|
def __init__( |
|
|
self, |
|
|
in_channels, |
|
|
out_channels, |
|
|
kernel_size, |
|
|
stride=1, |
|
|
padding=0, |
|
|
dilation=1, |
|
|
groups=1, |
|
|
bias=True, |
|
|
**kwargs |
|
|
): |
|
|
super(CausalConv1d, self).__init__( |
|
|
in_channels, |
|
|
out_channels, |
|
|
kernel_size, |
|
|
stride=stride, |
|
|
padding=0, |
|
|
dilation=dilation, |
|
|
groups=groups, |
|
|
bias=bias, |
|
|
**kwargs |
|
|
) |
|
|
|
|
|
self.left_padding = dilation * (kernel_size - 1) |
|
|
|
|
|
def forward(self, input: torch.Tensor) -> torch.Tensor: |
|
|
x = torch.nn.functional.pad(input.unsqueeze(2), (self.left_padding, 0, 0, 0)).squeeze(2) |
|
|
return super().forward(x) |
|
|
|
|
|
|
|
|
|
|
|
class HithinkAudioAttention(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, |
|
|
layer_idx: Optional[int] = None, |
|
|
config: Optional[HithinkOmniConfig] = 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 |
|
|
|
|
|
if layer_idx is None and is_decoder: |
|
|
logger.warning_once( |
|
|
f"Instantiating a decoder {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.layer_idx = layer_idx |
|
|
|
|
|
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False) |
|
|
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, |
|
|
attention_mask: Optional[torch.Tensor] = None, |
|
|
layer_head_mask: Optional[torch.Tensor] = None, |
|
|
past_key_value: Optional[Cache] = None, |
|
|
output_attentions: bool = False, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: |
|
|
"""Input shape: Batch x Time x Channel""" |
|
|
|
|
|
bsz, tgt_len, _ = hidden_states.size() |
|
|
|
|
|
|
|
|
query_states = self._shape(self.q_proj(hidden_states) * self.scaling, tgt_len, bsz) |
|
|
key_states = self._shape(self.k_proj(hidden_states), -1, bsz) |
|
|
value_states = self._shape(self.v_proj(hidden_states), -1, bsz) |
|
|
if past_key_value is not None: |
|
|
|
|
|
key_states, value_states = past_key_value.update( |
|
|
key_states, value_states, self.layer_idx, {"cache_position": cache_position} |
|
|
) |
|
|
|
|
|
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) |
|
|
|
|
|
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) |
|
|
|
|
|
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 |
|
|
|
|
|
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) |
|
|
attn_output = torch.matmul(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.transpose(1, 2) |
|
|
|
|
|
|
|
|
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) |
|
|
|
|
|
attn_output = self.out_proj(attn_output) |
|
|
|
|
|
return attn_output, attn_weights, past_key_value |
|
|
|
|
|
|
|
|
|
|
|
class HithinkAudioFlashAttention2(HithinkAudioAttention): |
|
|
""" |
|
|
HithinkAudio flash attention module. This module inherits from `HithinkAudioAttention` 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. |
|
|
""" |
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs): |
|
|
super().__init__(*args, **kwargs) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() |
|
|
|
|
|
def forward( |
|
|
self, |
|
|
hidden_states: torch.Tensor, |
|
|
key_value_states: Optional[torch.Tensor] = None, |
|
|
attention_mask: Optional[torch.Tensor] = None, |
|
|
layer_head_mask: Optional[torch.Tensor] = None, |
|
|
past_key_value: Optional[Cache] = None, |
|
|
output_attentions: bool = False, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: |
|
|
if isinstance(past_key_value, StaticCache): |
|
|
raise ValueError( |
|
|
"The `static` cache implementation is not compatible with `attn_implementation='flash_attention_2'`. " |
|
|
"Use `attn_implementation='sdpa'` in the meantime, and open an issue at https://github.com/huggingface/transformers" |
|
|
) |
|
|
|
|
|
if output_attentions: |
|
|
raise ValueError("HithinkAudioFlashAttention2 attention does not support output_attentions") |
|
|
|
|
|
bsz, tgt_len, _ = hidden_states.size() |
|
|
|
|
|
|
|
|
query_states = torch.reshape(self.q_proj(hidden_states), (bsz, tgt_len, self.num_heads, self.head_dim)) |
|
|
key_states = self._shape(self.k_proj(hidden_states), -1, bsz) |
|
|
value_states = self._shape(self.v_proj(hidden_states), -1, bsz) |
|
|
if past_key_value is not None: |
|
|
|
|
|
key_states, value_states = past_key_value.update( |
|
|
key_states, value_states, self.layer_idx, {"cache_position": cache_position} |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
key_states = key_states.transpose(1, 2) |
|
|
value_states = value_states.transpose(1, 2) |
|
|
|
|
|
causal_mask = attention_mask |
|
|
if attention_mask is not None: |
|
|
causal_mask = attention_mask[:, : key_states.shape[1]] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
input_dtype = query_states.dtype |
|
|
if input_dtype == torch.float32: |
|
|
if torch.is_autocast_enabled(): |
|
|
target_dtype = torch.get_autocast_gpu_dtype() |
|
|
|
|
|
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 = _flash_attention_forward( |
|
|
query_states, |
|
|
key_states, |
|
|
value_states, |
|
|
causal_mask, |
|
|
tgt_len, |
|
|
dropout=self.dropout if self.training else 0.0, |
|
|
is_causal=self.is_causal, |
|
|
use_top_left_mask=self._flash_attn_uses_top_left_mask, |
|
|
) |
|
|
|
|
|
attn_output = attn_output.reshape(bsz, tgt_len, -1) |
|
|
attn_output = self.out_proj(attn_output) |
|
|
|
|
|
if not output_attentions: |
|
|
attn_weights = None |
|
|
|
|
|
return attn_output, attn_weights, past_key_value |
|
|
|
|
|
|
|
|
|
|
|
class HithinkAudioSdpaAttention(HithinkAudioAttention): |
|
|
def forward( |
|
|
self, |
|
|
hidden_states: torch.Tensor, |
|
|
attention_mask: Optional[torch.Tensor] = None, |
|
|
layer_head_mask: Optional[torch.Tensor] = None, |
|
|
past_key_value: Optional[Cache] = None, |
|
|
output_attentions: bool = False, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: |
|
|
"""Input shape: Batch x Time x Channel""" |
|
|
if output_attentions or layer_head_mask is not None: |
|
|
|
|
|
logger.warning_once( |
|
|
"HithinkAudioModel is using HithinkAudioSdpaAttention, 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, |
|
|
past_key_value=past_key_value, |
|
|
attention_mask=attention_mask, |
|
|
layer_head_mask=layer_head_mask, |
|
|
output_attentions=output_attentions, |
|
|
cache_position=cache_position, |
|
|
) |
|
|
bsz, tgt_len, _ = hidden_states.size() |
|
|
|
|
|
|
|
|
query_states = self._shape(self.q_proj(hidden_states), tgt_len, bsz) |
|
|
key_states = self._shape(self.k_proj(hidden_states), -1, bsz) |
|
|
value_states = self._shape(self.v_proj(hidden_states), -1, bsz) |
|
|
if past_key_value is not None: |
|
|
|
|
|
key_states, value_states = past_key_value.update( |
|
|
key_states, value_states, self.layer_idx, {"cache_position": cache_position} |
|
|
) |
|
|
|
|
|
causal_mask = attention_mask |
|
|
if attention_mask is not None: |
|
|
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
is_causal = True if self.is_causal and causal_mask is None and tgt_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.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) |
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
HITHINKAUDIO_ATTENTION_CLASSES = { |
|
|
"eager": HithinkAudioAttention, |
|
|
"flash_attention_2": HithinkAudioFlashAttention2, |
|
|
"sdpa": HithinkAudioSdpaAttention, |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
class HithinkAudioEncoderLayer(nn.Module): |
|
|
def __init__(self, config: HithinkAudioEncoderConfig, layer_idx: int): |
|
|
super().__init__() |
|
|
self.embed_dim = config.d_model |
|
|
|
|
|
self.self_attn = HITHINKAUDIO_ATTENTION_CLASSES[config._attn_implementation]( |
|
|
embed_dim=self.embed_dim, |
|
|
num_heads=config.encoder_attention_heads, |
|
|
dropout=config.attention_dropout, |
|
|
config=config, |
|
|
layer_idx=layer_idx, |
|
|
is_causal=True |
|
|
) |
|
|
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.Tensor, |
|
|
attention_mask: torch.Tensor, |
|
|
layer_head_mask: torch.Tensor, |
|
|
past_key_value: Optional[Cache], |
|
|
output_attentions: bool = False, |
|
|
use_cache: bool = False, |
|
|
) -> torch.Tensor: |
|
|
""" |
|
|
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 = self.self_attn_layer_norm(hidden_states) |
|
|
hidden_states, attn_weights, present_key_value = self.self_attn( |
|
|
hidden_states=hidden_states, |
|
|
attention_mask=attention_mask, |
|
|
layer_head_mask=layer_head_mask, |
|
|
past_key_value=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 |
|
|
|
|
|
residual = hidden_states |
|
|
hidden_states = self.final_layer_norm(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 |
|
|
|
|
|
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,) |
|
|
|
|
|
if use_cache: |
|
|
outputs += (present_key_value,) |
|
|
|
|
|
return outputs |
|
|
|
|
|
|
|
|
HITHINKAUDIO_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 ([`HithinkOmniConfig`]): |
|
|
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 HithinkAudio Model outputting raw hidden-states without any specific head on top.", |
|
|
HITHINKAUDIO_START_DOCSTRING, |
|
|
) |
|
|
class HithinkAudioPreTrainedModel(PreTrainedModel): |
|
|
config_class = HithinkOmniConfig |
|
|
base_model_prefix = "model" |
|
|
supports_gradient_checkpointing = True |
|
|
_no_split_modules = ["HithinkAudioAttention"] |
|
|
_skip_keys_device_placement = "past_key_values" |
|
|
_supports_flash_attn_2 = True |
|
|
|
|
|
def _init_weights(self, module): |
|
|
|
|
|
|
|
|
std = self.config.init_std if hasattr(self.config, "init_std") else self.config.audio_config.init_std |
|
|
|
|
|
if isinstance(module, (nn.Linear, nn.Conv1d)): |
|
|
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_() |
|
|
|
|
|
@property |
|
|
def _supports_sdpa(self): |
|
|
""" |
|
|
Retrieve language_model's attribute to check whether the model supports |
|
|
SDPA or not. |
|
|
""" |
|
|
return self.language_model._supports_sdpa |
|
|
|
|
|
|
|
|
HITHINKAUDIOENCODER_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 ([`HithinkAudioEncoderConfig`]): |
|
|
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 audio model from HithinkAudio without any head or projection on top.""", |
|
|
HITHINKAUDIOENCODER_START_DOCSTRING, |
|
|
) |
|
|
|
|
|
class HithinkAudioEncoder(HithinkAudioPreTrainedModel): |
|
|
""" |
|
|
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a |
|
|
[`HithinkAudioEncoderLayer`]. |
|
|
|
|
|
Args: |
|
|
config: HithinkAudioEncoderConfig |
|
|
""" |
|
|
|
|
|
|
|
|
config_class = HithinkAudioEncoderConfig |
|
|
main_input_name = "input_features" |
|
|
_no_split_modules = ["HithinkAudioEncoderLayer"] |
|
|
|
|
|
def __init__(self, config: HithinkAudioEncoderConfig): |
|
|
super().__init__(config) |
|
|
self.dropout = config.dropout |
|
|
self.layerdrop = config.encoder_layerdrop |
|
|
|
|
|
embed_dim = config.d_model |
|
|
self.num_mel_bins = config.num_mel_bins |
|
|
self.padding_idx = config.pad_token_id |
|
|
self.max_source_positions = config.max_source_positions |
|
|
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0 |
|
|
|
|
|
self.conv1 = CausalConv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1) |
|
|
self.conv2 = CausalConv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1) |
|
|
|
|
|
self.embed_positions = nn.Embedding(self.max_source_positions, embed_dim) |
|
|
self.embed_positions.requires_grad_(False) |
|
|
|
|
|
self.layers = nn.ModuleList([ |
|
|
HithinkAudioEncoderLayer(config, layer_idx) for layer_idx in range(config.encoder_layers) |
|
|
]) |
|
|
self.layer_norm = nn.LayerNorm(config.d_model) |
|
|
|
|
|
self.avg_pooler = nn.AvgPool1d(2, stride=2) |
|
|
|
|
|
self.gradient_checkpointing = False |
|
|
|
|
|
self.post_init() |
|
|
|
|
|
def _freeze_parameters(self): |
|
|
for param in self.parameters(): |
|
|
param.requires_grad = False |
|
|
self._requires_grad = False |
|
|
|
|
|
def get_input_embeddings(self) -> nn.Module: |
|
|
return self.conv1 |
|
|
|
|
|
def set_input_embeddings(self, value: nn.Module): |
|
|
self.conv1 = value |
|
|
|
|
|
def forward( |
|
|
self, |
|
|
input_features, |
|
|
attention_mask=None, |
|
|
head_mask=None, |
|
|
past_key_values=None, |
|
|
output_attentions=None, |
|
|
output_hidden_states=None, |
|
|
return_dict=None, |
|
|
use_cache=False, |
|
|
): |
|
|
r""" |
|
|
Args: |
|
|
input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`): |
|
|
Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be |
|
|
obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a |
|
|
`numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into |
|
|
`input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding |
|
|
and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] |
|
|
attention_mask (`torch.Tensor`)`, *optional*): |
|
|
HithinkAudio does not support masking of the `input_features`, this argument is preserved for compatibility, |
|
|
but it is not used. By default the silence in the input log mel spectrogram are ignored. |
|
|
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**. |
|
|
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 |
|
|
|
|
|
|
|
|
if use_cache and past_key_values is None and not torch.jit.is_tracing(): |
|
|
past_key_values = DynamicCache() |
|
|
|
|
|
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 |
|
|
|
|
|
|
|
|
input_features = input_features.to(dtype=self.conv1.weight.dtype, device=self.conv1.weight.device) |
|
|
|
|
|
inputs_embeds = nn.functional.gelu(self.conv1(input_features)) |
|
|
inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds)) |
|
|
|
|
|
inputs_embeds = inputs_embeds.permute(0, 2, 1) |
|
|
if past_seen_tokens > 0: |
|
|
inputs_embeds = inputs_embeds[:, 2:] |
|
|
embed_pos = self.embed_positions.weight[past_seen_tokens: past_seen_tokens + inputs_embeds.shape[1]] |
|
|
|
|
|
hidden_states = inputs_embeds + embed_pos |
|
|
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) |
|
|
|
|
|
encoder_states = () if output_hidden_states else None |
|
|
all_attentions = () if output_attentions else None |
|
|
next_cache = None |
|
|
|
|
|
attention_mask = self._prepare_attention_mask(input_features, attention_mask, past_seen_tokens) |
|
|
|
|
|
|
|
|
if head_mask is not None: |
|
|
assert head_mask.size()[0] == ( |
|
|
len(self.layers) |
|
|
), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." |
|
|
|
|
|
for idx, encoder_layer in enumerate(self.layers): |
|
|
if output_hidden_states: |
|
|
encoder_states = encoder_states + (hidden_states,) |
|
|
|
|
|
to_drop = False |
|
|
if self.training: |
|
|
dropout_probability = torch.rand([]) |
|
|
if dropout_probability < self.layerdrop: |
|
|
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), |
|
|
past_key_values, |
|
|
output_attentions, |
|
|
use_cache, |
|
|
) |
|
|
else: |
|
|
layer_outputs = encoder_layer( |
|
|
hidden_states, |
|
|
attention_mask, |
|
|
layer_head_mask=(head_mask[idx] if head_mask is not None else None), |
|
|
past_key_value=past_key_values, |
|
|
output_attentions=output_attentions, |
|
|
use_cache=use_cache, |
|
|
) |
|
|
|
|
|
hidden_states = layer_outputs[0] |
|
|
|
|
|
if use_cache: |
|
|
next_cache = layer_outputs[2 if output_attentions else 1] |
|
|
|
|
|
if output_attentions: |
|
|
all_attentions = all_attentions + (layer_outputs[1],) |
|
|
|
|
|
|
|
|
hidden_states = hidden_states.permute(0, 2, 1) |
|
|
hidden_states = self.avg_pooler(hidden_states) |
|
|
hidden_states = hidden_states.permute(0, 2, 1) |
|
|
|
|
|
hidden_states = self.layer_norm(hidden_states) |
|
|
if output_hidden_states: |
|
|
encoder_states = encoder_states + (hidden_states,) |
|
|
|
|
|
if not return_dict: |
|
|
return tuple(v for v in [hidden_states, next_cache, encoder_states, all_attentions] if v is not None) |
|
|
return BaseModelOutputWithPast( |
|
|
last_hidden_state=hidden_states, |
|
|
past_key_values=next_cache, |
|
|
hidden_states=encoder_states, |
|
|
attentions=all_attentions |
|
|
) |
|
|
|
|
|
|
|
|
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor): |
|
|
""" |
|
|
Computes the output length of the convolutional layers and the output length of the audio encoder |
|
|
""" |
|
|
input_lengths = (input_lengths - 1) // 2 + 1 |
|
|
output_lengths = (input_lengths - 2) // 2 + 1 |
|
|
return input_lengths, output_lengths |
|
|
|
|
|
def _prepare_attention_mask(self, input_features, feature_attention_mask, past_seen_tokens): |
|
|
feat_lengths, output_lengths = self._get_feat_extract_output_lengths( |
|
|
feature_attention_mask.sum(-1) |
|
|
) |
|
|
batch_size, _, max_mel_seq_len = input_features.shape |
|
|
max_seq_len = (max_mel_seq_len - 1) // 2 + 1 |
|
|
|
|
|
seq_range = ( |
|
|
torch.arange(0, max_seq_len, dtype=feat_lengths.dtype, device=feat_lengths.device) |
|
|
.unsqueeze(0) |
|
|
.expand(batch_size, max_seq_len) |
|
|
) |
|
|
lengths_expand = feat_lengths.unsqueeze(1).expand(batch_size, max_seq_len) |
|
|
|
|
|
padding_mask = seq_range >= lengths_expand |
|
|
if self.config._attn_implementation == "flash_attention_2": |
|
|
attention_mask = ~padding_mask |
|
|
if past_seen_tokens > 0: |
|
|
attention_mask = attention_mask[:, 2:] |
|
|
past_mask = torch.ones( |
|
|
(batch_size, past_seen_tokens,), |
|
|
dtype=attention_mask.dtype, |
|
|
device=attention_mask.device |
|
|
) |
|
|
attention_mask = torch.cat([past_mask, attention_mask], dim=1) |
|
|
else: |
|
|
position_ids = torch.arange(max_seq_len, device=padding_mask.device) |
|
|
causal_mask = position_ids > position_ids.reshape(-1, 1) |
|
|
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) |
|
|
attention_mask_ = padding_mask.view(batch_size, 1, 1, max_seq_len).expand( |
|
|
batch_size, 1, max_seq_len, max_seq_len |
|
|
) |
|
|
attention_mask_ = attention_mask_.clone() | causal_mask |
|
|
attention_mask = attention_mask_.to( |
|
|
dtype=input_features.dtype, device=input_features.device |
|
|
) |
|
|
attention_mask[attention_mask_] = float("-inf") |
|
|
if past_seen_tokens > 0: |
|
|
attention_mask = attention_mask[:, :, 2:, 2:] |
|
|
past_mask = torch.zeros( |
|
|
attention_mask.shape[:3] + (past_seen_tokens,), |
|
|
dtype=attention_mask.dtype, |
|
|
device=attention_mask.device |
|
|
) |
|
|
attention_mask = torch.cat([past_mask, attention_mask], dim=-1) |
|
|
return attention_mask |
|
|
|
|
|
|
|
|
class HithinkAudioMultiModalProjector(nn.Module): |
|
|
def __init__(self, config: HithinkOmniConfig): |
|
|
super().__init__() |
|
|
self.linear = nn.Linear(config.audio_config.d_model, config.hidden_size, bias=True) |
|
|
|
|
|
def forward(self, audio_features): |
|
|
hidden_states = self.linear(audio_features) |
|
|
return hidden_states |
|
|
|
|
|
|
|
|
class HithinkOmniRotaryEmbedding(nn.Module): |
|
|
def __init__(self, config: HithinkOmniConfig, device=None): |
|
|
super().__init__() |
|
|
|
|
|
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")) |
|
|
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 |
|
|
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] |
|
|
|
|
|
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: |
|
|
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) |
|
|
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, :, None].float().expand(3, position_ids.shape[1], -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(2, 3) |
|
|
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) |
|
|
|
|
|
|
|
|
class HithinkOmniMLP(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)) |
|
|
|
|
|
|
|
|
|
|
|
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 seperately. |
|
|
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 |
|
|
) |
|
|
|
|
|
if q.is_cuda: |
|
|
if apply_rotary_emb_func is not None: |
|
|
rot_dim = cos.shape[-1] // 2 |
|
|
bs, qheads, seqlen, headdim = q.size() |
|
|
kheads = k.size(1) |
|
|
cos = cos[:, 0, :, :rot_dim].view(bs * seqlen, rot_dim) |
|
|
sin = sin[:, 0, :, :rot_dim].view(bs * seqlen, rot_dim) |
|
|
q = q.transpose(1, 2).view(1, bs * seqlen, qheads, headdim) |
|
|
k = k.transpose(1, 2).view(1, bs * seqlen, kheads, headdim) |
|
|
q_embed = apply_rotary_emb_func(q, cos, sin, False, False) |
|
|
k_embed = apply_rotary_emb_func(k, cos, sin, False, False) |
|
|
q_embed = q_embed.view(bs, seqlen, qheads, headdim).transpose(1, 2) |
|
|
k_embed = k_embed.view(bs, seqlen, kheads, headdim).transpose(1, 2) |
|
|
return q_embed, k_embed |
|
|
else: |
|
|
logger.warning_once("rotary_emb is not installed. If you want to accelerate training please install: " |
|
|
"https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary") |
|
|
|
|
|
q_embed = (q * cos) + (rotate_half(q) * sin) |
|
|
k_embed = (k * cos) + (rotate_half(k) * sin) |
|
|
return q_embed, k_embed |
|
|
|
|
|
|
|
|
def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor: |
|
|
orig_dtype = tensor.dtype |
|
|
tensor = tensor.float() |
|
|
cos = freqs.cos().float() |
|
|
sin = freqs.sin().float() |
|
|
if tensor.is_cuda: |
|
|
if apply_rotary_emb_func is not None: |
|
|
output = apply_rotary_emb_func(tensor, cos, sin, False, False) |
|
|
return output.to(orig_dtype) |
|
|
else: |
|
|
logger.warning_once("rotary_emb is not installed. If you want to accelerate training please install: " |
|
|
"https://github.com/Dao-AILab/flash-attention/tree/main/csrc/rotary") |
|
|
|
|
|
cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() |
|
|
sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() |
|
|
output = (tensor * cos) + (rotate_half(tensor) * sin) |
|
|
output = output.to(orig_dtype) |
|
|
return output |
|
|
|
|
|
|
|
|
class 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 PatchEmbed(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 PatchMerger(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 = HithinkRMSNorm(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 |
|
|
|
|
|
|
|
|
class VisionAttention(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, rotary_pos_emb: torch.Tensor = 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) |
|
|
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0) |
|
|
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0) |
|
|
|
|
|
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 VisionFlashAttention2(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, |
|
|
rotary_pos_emb: torch.Tensor = 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) |
|
|
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0) |
|
|
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0) |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
class VisionSdpaAttention(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, rotary_pos_emb: torch.Tensor = 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) |
|
|
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0) |
|
|
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0) |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
VISION_ATTENTION_CLASSES = { |
|
|
"eager": VisionAttention, |
|
|
"flash_attention_2": VisionFlashAttention2, |
|
|
"sdpa": VisionSdpaAttention, |
|
|
} |
|
|
|
|
|
|
|
|
class HithinkOmniVisionBlock(nn.Module): |
|
|
def __init__(self, config, attn_implementation: str = "sdpa") -> None: |
|
|
super().__init__() |
|
|
self.norm1 = HithinkRMSNorm(config.hidden_size, eps=1e-6) |
|
|
self.norm2 = HithinkRMSNorm(config.hidden_size, eps=1e-6) |
|
|
self.attn = VISION_ATTENTION_CLASSES[attn_implementation]( |
|
|
config.hidden_size, num_heads=config.num_heads |
|
|
) |
|
|
self.mlp = HithinkOmniMLP(config, bias=True) |
|
|
|
|
|
def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> torch.Tensor: |
|
|
hidden_states = hidden_states + self.attn( |
|
|
self.norm1(hidden_states), |
|
|
cu_seqlens=cu_seqlens, |
|
|
rotary_pos_emb=rotary_pos_emb, |
|
|
) |
|
|
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) |
|
|
return hidden_states |
|
|
|
|
|
|
|
|
class HithinkRMSNorm(nn.Module): |
|
|
def __init__(self, hidden_size, eps=1e-6): |
|
|
""" |
|
|
HithinkRMSNorm is equivalent to T5LayerNorm |
|
|
""" |
|
|
super().__init__() |
|
|
self.weight = nn.Parameter(torch.ones(hidden_size)) |
|
|
self.variance_epsilon = eps |
|
|
|
|
|
def forward(self, hidden_states, residual=None): |
|
|
if hidden_states.is_cuda: |
|
|
if dropout_add_rms_norm is not None: |
|
|
out, res = dropout_add_rms_norm( |
|
|
hidden_states, |
|
|
residual, |
|
|
self.weight, |
|
|
None, |
|
|
0., |
|
|
self.variance_epsilon, |
|
|
prenorm=True, |
|
|
residual_in_fp32=False, |
|
|
return_dropout_mask=False, |
|
|
) |
|
|
return out if residual is None else (out, res) |
|
|
else: |
|
|
logger.warning_once("dropout_add_rms_norm is not installed. If you want to accelerate training please install: " |
|
|
"https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm") |
|
|
|
|
|
if residual is not None: |
|
|
hidden_states = residual + hidden_states |
|
|
residual = 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) |
|
|
hidden_states = self.weight * hidden_states.to(input_dtype) |
|
|
return hidden_states if residual is None else (hidden_states, residual) |
|
|
|
|
|
def extra_repr(self): |
|
|
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" |
|
|
|
|
|
|
|
|
class HithinkMLP(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): |
|
|
if self.config.hidden_act == 'silu' and x.is_cuda: |
|
|
if swiglu is not None: |
|
|
down_proj = self.down_proj(swiglu(self.gate_proj(x), self.up_proj(x))) |
|
|
else: |
|
|
logger.warning_once("swiglu is not installed. If you want to accelerate training please install: " |
|
|
"https://github.com/Dao-AILab/flash-attention") |
|
|
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) |
|
|
return down_proj |
|
|
|
|
|
|
|
|
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 HithinkOmniAttention(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: HithinkOmniConfig, layer_idx: Optional[int] = 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 = HithinkOmniRotaryEmbedding(config=config) |
|
|
|
|
|
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) |
|
|
|
|
|
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} |
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
if query_states.dtype == torch.float16: |
|
|
attn_weights = torch.where(torch.isinf(attn_weights), torch.zeros_like(attn_weights), attn_weights) |
|
|
|
|
|
|
|
|
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 HithinkOmniFlashAttention2(HithinkOmniAttention): |
|
|
""" |
|
|
HithinkOmni flash attention module, following HithinkOmni attention module. This module inherits from `HithinkOmniAttention` |
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: 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, |
|
|
): |
|
|
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} |
|
|
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) |
|
|
dropout_rate = 0.0 if not self.training else self.attention_dropout |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
input_dtype = query_states.dtype |
|
|
if input_dtype == torch.float32: |
|
|
if torch.is_autocast_enabled(): |
|
|
target_dtype = torch.get_autocast_gpu_dtype() |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
query_states = query_states.transpose(1, 2) |
|
|
key_states = key_states.transpose(1, 2) |
|
|
value_states = value_states.transpose(1, 2) |
|
|
|
|
|
if ( |
|
|
self.config.use_sliding_window |
|
|
and getattr(self.config, "sliding_window", None) is not None |
|
|
and self.layer_idx >= self.config.max_window_layers |
|
|
): |
|
|
sliding_window = self.config.sliding_window |
|
|
else: |
|
|
sliding_window = None |
|
|
|
|
|
attn_output = _flash_attention_forward( |
|
|
query_states, |
|
|
key_states, |
|
|
value_states, |
|
|
attention_mask, |
|
|
q_len, |
|
|
dropout=dropout_rate, |
|
|
sliding_window=sliding_window, |
|
|
is_causal=self.is_causal, |
|
|
use_top_left_mask=self._flash_attn_uses_top_left_mask, |
|
|
) |
|
|
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 HithinkOmniSdpaAttention(HithinkOmniAttention): |
|
|
""" |
|
|
Hithink attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from |
|
|
`HithinkAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to |
|
|
SDPA API. |
|
|
""" |
|
|
|
|
|
|
|
|
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]]]: |
|
|
if output_attentions: |
|
|
|
|
|
logger.warning_once( |
|
|
"HithinkOmniModel is using HithinkOmniSdpaAttention, 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} |
|
|
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: |
|
|
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] |
|
|
|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
HITHINKOMNI_ATTENTION_CLASSES = { |
|
|
"eager": HithinkOmniAttention, |
|
|
"flash_attention_2": HithinkOmniFlashAttention2, |
|
|
"sdpa": HithinkOmniSdpaAttention, |
|
|
} |
|
|
|
|
|
|
|
|
class HithinkOmniDecoderLayer(nn.Module): |
|
|
def __init__(self, config: HithinkOmniConfig, 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 = HITHINKOMNI_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx) |
|
|
|
|
|
self.mlp = HithinkMLP(config) |
|
|
self.input_layernorm = HithinkRMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
|
|
self.post_attention_layernorm = HithinkRMSNorm(config.hidden_size, eps=config.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[Tuple[torch.Tensor]] = None, |
|
|
output_attentions: Optional[bool] = False, |
|
|
use_cache: Optional[bool] = False, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, |
|
|
**kwargs, |
|
|
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: |
|
|
""" |
|
|
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) |
|
|
|
|
|
|
|
|
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 = self.post_attention_layernorm(hidden_states, residual) |
|
|
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 |
|
|
|
|
|
|
|
|
HITHINKOMNI_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 ([`HithinkOmniConfig`]): |
|
|
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 HithinkOmni Model outputting raw hidden-states without any specific head on top.", |
|
|
HITHINKOMNI_START_DOCSTRING, |
|
|
) |
|
|
class HithinkOmniPreTrainedModel(PreTrainedModel): |
|
|
config_class = HithinkOmniConfig |
|
|
base_model_prefix = "model" |
|
|
supports_gradient_checkpointing = True |
|
|
_no_split_modules = ["HithinkOmniDecoderLayer", "HithinkOmniVisionBlock"] |
|
|
_skip_keys_device_placement = "past_key_values" |
|
|
_supports_flash_attn_2 = True |
|
|
_supports_sdpa = True |
|
|
_supports_cache_class = True |
|
|
_supports_static_cache = False |
|
|
|
|
|
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 HithinkVisionTransformerPretrainedModel(HithinkOmniPreTrainedModel): |
|
|
config_class = HithinkOmniVisionConfig |
|
|
_no_split_modules = ["HithinkOmniVisionBlock"] |
|
|
|
|
|
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 = PatchEmbed( |
|
|
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 = VisionRotaryEmbedding(head_dim // 2) |
|
|
|
|
|
self.blocks = nn.ModuleList( |
|
|
[HithinkOmniVisionBlock(config, config._attn_implementation) for _ in range(config.depth)] |
|
|
) |
|
|
self.merger = PatchMerger( |
|
|
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 `(batch_size, 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) |
|
|
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) |
|
|
|
|
|
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum( |
|
|
dim=0, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, |
|
|
) |
|
|
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) |
|
|
|
|
|
for layer_num, blk in enumerate(self.blocks): |
|
|
if layer_num in self.fullatt_block_indexes: |
|
|
cu_seqlens_now = cu_seqlens |
|
|
else: |
|
|
cu_seqlens_now = cu_window_seqlens |
|
|
if self.gradient_checkpointing and self.training: |
|
|
hidden_states = self._gradient_checkpointing_func( |
|
|
blk.__call__, hidden_states, cu_seqlens_now, rotary_pos_emb |
|
|
) |
|
|
else: |
|
|
hidden_states = blk( |
|
|
hidden_states, |
|
|
cu_seqlens=cu_seqlens_now, |
|
|
rotary_pos_emb=rotary_pos_emb, |
|
|
) |
|
|
|
|
|
hidden_states = self.merger(hidden_states) |
|
|
reverse_indices = torch.argsort(window_index) |
|
|
hidden_states = hidden_states[reverse_indices, :] |
|
|
|
|
|
return hidden_states |
|
|
|
|
|
|
|
|
@add_start_docstrings( |
|
|
"The bare HithinkOmni Model outputting raw hidden-states without any specific head on top.", |
|
|
HITHINKOMNI_START_DOCSTRING, |
|
|
) |
|
|
class HithinkOmniModel(HithinkOmniPreTrainedModel): |
|
|
def __init__(self, config: HithinkOmniConfig): |
|
|
super().__init__(config) |
|
|
self.padding_idx = config.pad_token_id |
|
|
self.vocab_size = config.vocab_size |
|
|
|
|
|
if config.vocab_size: |
|
|
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) |
|
|
else: |
|
|
self.embed_tokens = None |
|
|
|
|
|
if config.vocab_size_ext: |
|
|
self.embed_tokens_ext = nn.Embedding(config.vocab_size_ext, config.hidden_size) |
|
|
else: |
|
|
self.embed_tokens_ext = None |
|
|
|
|
|
self.layers = nn.ModuleList( |
|
|
[HithinkOmniDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] |
|
|
) |
|
|
self._attn_implementation = config._attn_implementation |
|
|
self.norm = HithinkRMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
|
|
self.rotary_emb = HithinkOmniRotaryEmbedding(config=config) |
|
|
|
|
|
self.gradient_checkpointing = False |
|
|
|
|
|
self.post_init() |
|
|
|
|
|
def get_input_embeddings(self): |
|
|
return self.embed_tokens |
|
|
|
|
|
def set_input_embeddings(self, value): |
|
|
self.embed_tokens = value |
|
|
|
|
|
def convert_token_ids_to_embedding(self, input_ids): |
|
|
if self.embed_tokens_ext is None: |
|
|
inputs_embeds = self.embed_tokens(input_ids) |
|
|
else: |
|
|
ext_mask = (input_ids >= self.vocab_size) |
|
|
input_ids_base = input_ids.clone() |
|
|
input_ids_base.masked_fill_(ext_mask, 0) |
|
|
inputs_embeds = self.embed_tokens(input_ids_base) |
|
|
inputs_embeds_ext = self.embed_tokens_ext(input_ids[ext_mask] - self.vocab_size) |
|
|
ext_embed_mask = ext_mask.unsqueeze(-1).expand_as(inputs_embeds) |
|
|
inputs_embeds.masked_scatter_(ext_embed_mask, inputs_embeds_ext) |
|
|
return inputs_embeds |
|
|
|
|
|
def forward( |
|
|
self, |
|
|
input_ids: torch.LongTensor = None, |
|
|
attention_mask: Optional[torch.Tensor] = None, |
|
|
position_ids: Optional[torch.LongTensor] = None, |
|
|
past_key_values: Optional[List[torch.FloatTensor]] = None, |
|
|
inputs_embeds: Optional[torch.FloatTensor] = None, |
|
|
use_cache: Optional[bool] = None, |
|
|
output_attentions: Optional[bool] = None, |
|
|
output_hidden_states: Optional[bool] = None, |
|
|
return_dict: Optional[bool] = None, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
) -> Union[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 |
|
|
|
|
|
|
|
|
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.convert_token_ids_to_embedding(input_ids) |
|
|
|
|
|
if ( |
|
|
use_cache and not isinstance(past_key_values, Cache) and not self.training |
|
|
): |
|
|
past_key_values = DynamicCache.from_legacy_cache(past_key_values) |
|
|
|
|
|
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.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 |
|
|
|
|
|
|
|
|
position_embeddings = self.rotary_emb(hidden_states, position_ids) |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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 0.0 in attention_mask: |
|
|
return attention_mask |
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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] |
|
|
|
|
|
if using_sliding_window_cache or using_static_cache: |
|
|
target_length = past_key_values.get_max_cache_shape() |
|
|
|
|
|
else: |
|
|
target_length = ( |
|
|
attention_mask.shape[-1] |
|
|
if isinstance(attention_mask, torch.Tensor) |
|
|
else past_seen_tokens + sequence_length + 1 |
|
|
) |
|
|
|
|
|
|
|
|
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 == "cuda" |
|
|
and not output_attentions |
|
|
): |
|
|
|
|
|
|
|
|
|
|
|
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: HithinkOmniConfig, |
|
|
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 plcae 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 (`HithinkOmniConfig`): |
|
|
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: |
|
|
|
|
|
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 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() |
|
|
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, :] |
|
|
padding_mask = padding_mask == 0 |
|
|
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( |
|
|
padding_mask, min_dtype |
|
|
) |
|
|
return causal_mask |
|
|
|
|
|
|
|
|
HITHINKOMNI_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 [`HithinkOmniImageProcessor.__call__`] for details. [`HithinkOmniProcessor`] uses |
|
|
[`HithinkOmniImageProcessor`] 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 [`HithinkOmniImageProcessor.__call__`] for details. [`HithinkOmniProcessor`] uses |
|
|
[`HithinkOmniImageProcessor`] for processing videos. |
|
|
input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, feature_sequence_length)`): |
|
|
Float values mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by |
|
|
loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via |
|
|
the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the |
|
|
[`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a |
|
|
tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] |
|
|
feature_attention_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`): |
|
|
Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`: |
|
|
|
|
|
- 1 for tokens that are **not masked**, |
|
|
- 0 for tokens that are **masked**. |
|
|
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 HithinkOmniForConditionalGeneration(HithinkOmniPreTrainedModel, GenerationMixin): |
|
|
_tied_weights_keys = ["lm_head.weight"] |
|
|
config_class = HithinkOmniConfig |
|
|
_no_split_modules = ["HithinkOmniDecoderLayer", "HithinkOmniVisionBlock"] |
|
|
|
|
|
def __init__(self, config: HithinkOmniConfig): |
|
|
super().__init__(config) |
|
|
self.visual = HithinkVisionTransformerPretrainedModel._from_config(config.vision_config) |
|
|
self.audio_tower = HithinkAudioEncoder._from_config(config.audio_config, attn_implementation=config._attn_implementation) |
|
|
self.multi_modal_projector = HithinkAudioMultiModalProjector(config) |
|
|
self.model = HithinkOmniModel(config) |
|
|
self.turn_taking_head = nn.Linear(config.hidden_size, 1, bias=False) |
|
|
self.vocab_size = config.vocab_size |
|
|
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) |
|
|
if config.vocab_size_ext: |
|
|
self.lm_head_ext = nn.Linear(config.hidden_size, config.vocab_size_ext, bias=False) |
|
|
else: |
|
|
self.lm_head_ext = None |
|
|
self.rope_deltas = None |
|
|
|
|
|
if config.audio_decoder_config is None: |
|
|
self.audio_decoder = None |
|
|
else: |
|
|
audio_decoder_config = copy.deepcopy(config) |
|
|
audio_decoder_config.vocab_size = None |
|
|
audio_decoder_config.vocab_size_ext = None |
|
|
audio_decoder_config.num_hidden_layers = config.audio_decoder_config.num_hidden_layers |
|
|
self.audio_decoder = HithinkOmniModel(audio_decoder_config) |
|
|
|
|
|
speech_vocab_size = config.audio_decoder_config.codebook_size + 3 |
|
|
num_codebooks = config.audio_decoder_config.num_codebooks |
|
|
self.codebook_embeddings = nn.ModuleList([ |
|
|
nn.Embedding(speech_vocab_size, config.hidden_size) for _ in range(num_codebooks) |
|
|
]) |
|
|
self.codebook_heads = nn.Linear(config.hidden_size, speech_vocab_size * num_codebooks) |
|
|
self.num_codebooks = num_codebooks |
|
|
|
|
|
|
|
|
self.post_init() |
|
|
|
|
|
if CrossEntropyLoss.__module__.startswith('flash_attn'): |
|
|
self.z_loss = 0.0 |
|
|
else: |
|
|
logger.warn("CrossEntropyLoss is not installed. If you want to accelerate training please install: " |
|
|
"https://github.com/Dao-AILab/flash-attention") |
|
|
|
|
|
def audio_first_chunk_size(self, output_length): |
|
|
"""流式推理时,输入音频第一个chunk的大小""" |
|
|
return 4 * output_length - 1 |
|
|
|
|
|
def audio_next_chunk_size(self, output_length): |
|
|
"""流式推理时,输入音频后续chunk的大小""" |
|
|
return 4 * output_length |
|
|
|
|
|
def audio_prev_chunk_overlap(self): |
|
|
"""流式推理时,输入音频后续chunk与之前chunk重合部分的大小""" |
|
|
return 3 |
|
|
|
|
|
def convert_audio_ids_to_embedding(self, audio_ids): |
|
|
audio_embedding = torch.stack([ |
|
|
self.codebook_embeddings[i](audio_ids[:, :, i]) for i in range(self.num_codebooks) |
|
|
]).sum(dim=0).to(self.model.embed_tokens.weight.dtype) |
|
|
audio_pad_token_id = self.config.audio_decoder_config.codebook_size + 2 |
|
|
audio_mask = audio_ids.ne(audio_pad_token_id).any(dim=-1) |
|
|
return audio_embedding, audio_mask |
|
|
|
|
|
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: Optional[torch.LongTensor] = None, |
|
|
image_grid_thw: Optional[torch.LongTensor] = None, |
|
|
video_grid_thw: Optional[torch.LongTensor] = None, |
|
|
second_per_grid_ts: Optional[torch.Tensor] = None, |
|
|
attention_mask: Optional[torch.Tensor] = 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 embeddin 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(HITHINKOMNI_INPUTS_DOCSTRING) |
|
|
@replace_return_docstrings(output_type=HithinkOmniCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) |
|
|
def forward( |
|
|
self, |
|
|
input_ids: torch.LongTensor = None, |
|
|
input_features: torch.FloatTensor = None, |
|
|
attention_mask: Optional[torch.Tensor] = None, |
|
|
feature_attention_mask: Optional[torch.Tensor] = None, |
|
|
position_ids: Optional[torch.LongTensor] = None, |
|
|
past_key_values: Optional[List[torch.FloatTensor]] = None, |
|
|
inputs_embeds: Optional[torch.FloatTensor] = None, |
|
|
labels: Optional[torch.LongTensor] = None, |
|
|
audio_past_key_values: Optional[Cache] = None, |
|
|
audio_use_cache: Optional[bool] = None, |
|
|
use_cache: Optional[bool] = None, |
|
|
output_attentions: Optional[bool] = None, |
|
|
output_hidden_states: Optional[bool] = None, |
|
|
output_logits: bool = True, |
|
|
return_dict: Optional[bool] = None, |
|
|
pixel_values: Optional[torch.Tensor] = None, |
|
|
pixel_values_videos: Optional[torch.FloatTensor] = None, |
|
|
image_grid_thw: Optional[torch.LongTensor] = None, |
|
|
video_grid_thw: Optional[torch.LongTensor] = None, |
|
|
rope_deltas: Optional[torch.LongTensor] = None, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
second_per_grid_ts: Optional[torch.Tensor] = None, |
|
|
audio_ids: Optional[torch.LongTensor] = None, |
|
|
add_image: Optional[bool] = None, |
|
|
add_video: Optional[bool] = None, |
|
|
add_audio: Optional[bool] = None, |
|
|
is_turn_taking: Optional[bool] = None, |
|
|
) -> Union[Tuple, HithinkOmniCausalLMOutputWithPast]: |
|
|
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, HithinkOmniForConditionalGeneration |
|
|
|
|
|
>>> model = HithinkOmniForConditionalGeneration.from_pretrained("hithink-omni-qw25-audio-vocab-split") |
|
|
>>> processor = AutoProcessor.from_pretrained("hithink-omni-qw25-audio-vocab-split") |
|
|
|
|
|
>>> 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 |
|
|
|
|
|
|
|
|
target_device = self.audio_tower.device |
|
|
if input_features is not None: |
|
|
|
|
|
input_features = input_features.to(target_device) |
|
|
feature_attention_mask = feature_attention_mask.to(target_device) |
|
|
|
|
|
if inputs_embeds is None: |
|
|
inputs_embeds = self.model.convert_token_ids_to_embedding(input_ids) |
|
|
|
|
|
|
|
|
visual_dtype = self.visual.dtype |
|
|
if pixel_values is not None: |
|
|
pixel_values = pixel_values.type(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) |
|
|
|
|
|
elif add_image: |
|
|
|
|
|
|
|
|
|
|
|
m = self.visual.patch_embed |
|
|
d = 3 * m.temporal_patch_size * m.patch_size * m.patch_size |
|
|
pixels = torch.ones((16, d), dtype=visual_dtype, device=inputs_embeds.device) |
|
|
grid_thw = torch.tensor([[1, 4, 4]], device=inputs_embeds.device) |
|
|
image_embeds = self.visual(pixels, grid_thw) |
|
|
inputs_embeds += image_embeds.mean() * 0. |
|
|
|
|
|
if pixel_values_videos is not None: |
|
|
pixel_values_videos = pixel_values_videos.type(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) |
|
|
|
|
|
elif add_video: |
|
|
|
|
|
|
|
|
|
|
|
m = self.visual.patch_embed |
|
|
d = 3 * m.temporal_patch_size * m.patch_size * m.patch_size |
|
|
pixels = torch.ones((16, d), dtype=visual_dtype, device=inputs_embeds.device) |
|
|
grid_thw = torch.tensor([[1, 4, 4]], device=inputs_embeds.device) |
|
|
image_embeds = self.visual(pixels, grid_thw) |
|
|
inputs_embeds += image_embeds.mean() * 0. |
|
|
|
|
|
|
|
|
if input_features is not None and (input_ids.shape[1] != 1 or audio_use_cache): |
|
|
audio_feat_lengths, audio_output_lengths = self.audio_tower._get_feat_extract_output_lengths( |
|
|
feature_attention_mask.sum(-1) |
|
|
) |
|
|
|
|
|
audio_outputs = self.audio_tower( |
|
|
input_features, |
|
|
attention_mask=feature_attention_mask, |
|
|
past_key_values=audio_past_key_values, |
|
|
use_cache=audio_use_cache, |
|
|
) |
|
|
selected_audio_feature = audio_outputs.last_hidden_state |
|
|
audio_features = self.multi_modal_projector(selected_audio_feature) |
|
|
|
|
|
num_audios, max_audio_tokens, embed_dim = audio_features.shape |
|
|
audio_features_mask = torch.arange(max_audio_tokens, device=audio_features.device) \ |
|
|
.expand(num_audios, max_audio_tokens) < audio_output_lengths.unsqueeze(1) |
|
|
audio_features = audio_features[audio_features_mask].view(-1, embed_dim) |
|
|
audio_features = audio_features.to(inputs_embeds.device, inputs_embeds.dtype) |
|
|
audio_token_mask = (input_ids == self.config.audio_token_index).unsqueeze(-1).expand_as(inputs_embeds) |
|
|
inputs_embeds = inputs_embeds.masked_scatter(audio_token_mask, audio_features) |
|
|
|
|
|
|
|
|
elif add_audio: |
|
|
m = self.audio_tower |
|
|
expected_seq_length = 3000 |
|
|
n_channels = 128 |
|
|
audio_outputs = m(torch.ones((1, n_channels, expected_seq_length), dtype=m.dtype, device=m.device)) |
|
|
audio_features = self.multi_modal_projector(audio_outputs.last_hidden_state) |
|
|
inputs_embeds += audio_features.mean() * 0. |
|
|
|
|
|
if attention_mask is not None: |
|
|
attention_mask = attention_mask.to(inputs_embeds.device) |
|
|
|
|
|
|
|
|
if position_ids is None and (attention_mask is None or attention_mask.ndim == 2): |
|
|
|
|
|
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 |
|
|
|
|
|
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: |
|
|
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] |
|
|
|
|
|
if is_turn_taking: |
|
|
logits = self.turn_taking_head(hidden_states) |
|
|
loss = None |
|
|
if labels is not None: |
|
|
loss_fct = BCEWithLogitsLoss() |
|
|
logits = logits.float() |
|
|
loss_mask = labels != -100 |
|
|
loss = loss_fct(logits[loss_mask].squeeze(-1), labels[loss_mask].to(logits.dtype)) |
|
|
|
|
|
elif self.training and labels is not None: |
|
|
is_train_flash = CrossEntropyLoss.__module__.startswith('flash_attn') |
|
|
if is_train_flash: |
|
|
loss_fct = CrossEntropyLoss(inplace_backward=True, lse_square_scale=self.z_loss) |
|
|
else: |
|
|
loss_fct = CrossEntropyLoss() |
|
|
|
|
|
if audio_ids is not None: |
|
|
assert self.audio_decoder.config._attn_implementation != 'flash_attention_2', \ |
|
|
'Audio decoder 训练不支持 FlashAttention-2,建议使用 attn_implementation="sdpa"' |
|
|
|
|
|
audio_embeds, audio_attention_mask = self.convert_audio_ids_to_embedding(audio_ids) |
|
|
output_start_idx = (labels != -100).int().argmax(dim=1).unsqueeze(1) |
|
|
bsz, a_len, _ = audio_embeds.shape |
|
|
ii = torch.arange(bsz).unsqueeze(1).expand(-1, a_len) |
|
|
jj = torch.arange(a_len, device=audio_embeds.device).unsqueeze(0).expand(bsz, -1) + output_start_idx |
|
|
jj.masked_fill_(~audio_attention_mask, 0) |
|
|
final_embeds = (hidden_states[ii, jj] + audio_embeds) / (1 + self.num_codebooks) |
|
|
|
|
|
audio_hidden_states = self.audio_decoder( |
|
|
inputs_embeds=final_embeds, |
|
|
attention_mask=audio_attention_mask |
|
|
)[0] |
|
|
logits = self.codebook_heads(audio_hidden_states) |
|
|
|
|
|
codebook_size = self.config.audio_decoder_config.codebook_size |
|
|
audio_bos_token_id = codebook_size |
|
|
audio_pad_token_id = codebook_size + 2 |
|
|
label_mask = (audio_ids == audio_bos_token_id) | (audio_ids == audio_pad_token_id) |
|
|
audio_labels = audio_ids.masked_fill(label_mask, loss_fct.ignore_index) |
|
|
logits = logits[:, :-1].reshape(-1, codebook_size + 3) |
|
|
labels = audio_labels[:, 1:].reshape(-1) |
|
|
|
|
|
else: |
|
|
hidden_states = hidden_states[..., :-1, :] |
|
|
labels = labels[..., 1:] |
|
|
loss_mask = labels != loss_fct.ignore_index |
|
|
hidden_states = hidden_states[loss_mask].contiguous() |
|
|
logits = self.lm_head(hidden_states) |
|
|
if self.lm_head_ext is not None: |
|
|
logits = torch.cat((logits, self.lm_head_ext(hidden_states)), dim=-1) |
|
|
if not is_train_flash: |
|
|
logits = logits.float() |
|
|
labels = labels[loss_mask].contiguous().to(logits.device) |
|
|
|
|
|
loss = loss_fct(logits, labels) |
|
|
logits = None |
|
|
|
|
|
elif output_logits: |
|
|
logits = self.lm_head(hidden_states) |
|
|
if self.lm_head_ext is not None: |
|
|
logits = torch.cat((logits, self.lm_head_ext(hidden_states)), dim=-1) |
|
|
|
|
|
loss = None |
|
|
if labels is not None: |
|
|
|
|
|
logits = logits.float() |
|
|
|
|
|
shift_logits = logits[..., :-1, :].contiguous() |
|
|
shift_labels = labels[..., 1:].contiguous() |
|
|
|
|
|
loss_fct = CrossEntropyLoss() |
|
|
shift_logits = shift_logits.view(-1, shift_logits.size(-1)) |
|
|
shift_labels = shift_labels.view(-1) |
|
|
|
|
|
shift_labels = shift_labels.to(shift_logits.device) |
|
|
loss = loss_fct(shift_logits, shift_labels) |
|
|
|
|
|
else: |
|
|
loss = None |
|
|
logits = None |
|
|
|
|
|
if not return_dict: |
|
|
output = (logits,) + outputs[1:] |
|
|
return (loss,) + output if loss is not None else output |
|
|
|
|
|
return HithinkOmniCausalLMOutputWithPast( |
|
|
loss=loss, |
|
|
logits=logits, |
|
|
past_key_values=outputs.past_key_values, |
|
|
audio_past_key_values=audio_outputs.past_key_values if audio_use_cache else None, |
|
|
hidden_states=outputs.hidden_states, |
|
|
attentions=outputs.attentions, |
|
|
rope_deltas=self.rope_deltas, |
|
|
) |
|
|
|
|
|
def prepare_inputs_for_generation( |
|
|
self, |
|
|
input_ids, |
|
|
input_features = None, |
|
|
feature_attention_mask = None, |
|
|
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, |
|
|
): |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if past_key_values is not None: |
|
|
if inputs_embeds is not None: |
|
|
input_ids = input_ids[:, -cache_position.shape[0] :] |
|
|
elif input_ids.shape[1] != cache_position.shape[0]: |
|
|
input_ids = input_ids[:, cache_position] |
|
|
|
|
|
if cache_position[0] != 0: |
|
|
pixel_values = None |
|
|
pixel_values_videos = None |
|
|
|
|
|
|
|
|
if inputs_embeds is not None and cache_position[0] == 0: |
|
|
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( |
|
|
{ |
|
|
"input_features": input_features, |
|
|
"feature_attention_mask": feature_attention_mask, |
|
|
"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 |
|
|
|
|
|
@torch.no_grad() |
|
|
def stream_inference( |
|
|
self, |
|
|
input_ids: torch.LongTensor = None, |
|
|
input_features: torch.FloatTensor = None, |
|
|
attention_mask: Optional[torch.Tensor] = None, |
|
|
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, |
|
|
position_ids: Optional[torch.Tensor] = None, |
|
|
feature_attention_mask: Optional[torch.Tensor] = None, |
|
|
pixel_values: Optional[torch.Tensor] = None, |
|
|
pixel_values_videos: Optional[torch.FloatTensor] = None, |
|
|
image_grid_thw: Optional[torch.LongTensor] = None, |
|
|
video_grid_thw: Optional[torch.LongTensor] = None, |
|
|
cache_position: Optional[torch.LongTensor] = None, |
|
|
output_txts: Optional[torch.LongTensor] = None, |
|
|
first_chunk_size: int = 25, |
|
|
chunk_size: int = 50, |
|
|
max_new_tokens: int = 512, |
|
|
top_k: int = 25, |
|
|
top_p: float = 0.95, |
|
|
temperature: float = 1.0, |
|
|
repeat_penalty: float = 1.0, |
|
|
length_penalty_params: Tuple[int, float] = (20, 1.01), |
|
|
**kwargs, |
|
|
): |
|
|
"""Streaming version of inference that yields partial results for batch_size=1""" |
|
|
assert input_ids.shape[0] == 1, "stream_inference only supports batch_size=1" |
|
|
|
|
|
|
|
|
outputs = self( |
|
|
input_ids=input_ids, |
|
|
input_features=input_features, |
|
|
attention_mask=attention_mask, |
|
|
feature_attention_mask=feature_attention_mask, |
|
|
position_ids=position_ids, |
|
|
past_key_values=past_key_values, |
|
|
use_cache=True, |
|
|
output_hidden_states=True, |
|
|
return_dict=True, |
|
|
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, |
|
|
) |
|
|
past_key_values = outputs.past_key_values |
|
|
last_hidden_state = outputs.hidden_states[-1][:, -1] |
|
|
|
|
|
|
|
|
a_last_hidden_state = None |
|
|
a_past_key_values = None |
|
|
audio_attention_mask = None |
|
|
|
|
|
codebook_size = self.config.audio_decoder_config.codebook_size |
|
|
audio_bos_token_id = codebook_size |
|
|
audio_eos_token_id = codebook_size + 1 |
|
|
audio_pad_token_id = codebook_size + 2 |
|
|
|
|
|
|
|
|
hyps = torch.ones((1, self.num_codebooks + 1, max_new_tokens), dtype=torch.long, device=self.device) * audio_pad_token_id |
|
|
hyps[:, 0] = self.config.pad_token_id |
|
|
|
|
|
|
|
|
if output_txts is not None: |
|
|
output_txts = output_txts.to(self.device) |
|
|
hyps[:, 0, :output_txts.shape[1]] = output_txts |
|
|
|
|
|
|
|
|
end_flag = torch.zeros((1, self.num_codebooks + 1), dtype=torch.bool, device=self.device) |
|
|
|
|
|
|
|
|
first_coden_idx = self.num_codebooks - 1 + 1 + first_chunk_size - 1 |
|
|
|
|
|
for i in range(max_new_tokens): |
|
|
|
|
|
if output_txts is None: |
|
|
text_logits = self.lm_head(last_hidden_state) |
|
|
if length_penalty_params[1] != 1.0: |
|
|
text_logits = length_penalty(hyps[:, 0, :i], text_logits, length_penalty_params, self.config.eos_token_id) |
|
|
|
|
|
text_token = sample(hyps[:, :1, :i], text_logits.unsqueeze(1), top_p=0.6, temperature=0.6).squeeze(1) |
|
|
text_token = text_token.masked_fill(end_flag[:, 0], self.config.pad_token_id) |
|
|
hyps[:, 0, i] = text_token |
|
|
|
|
|
|
|
|
if i == 0: |
|
|
hyps[:, 1:, i] = audio_bos_token_id |
|
|
else: |
|
|
audio_logits = self.codebook_heads(a_last_hidden_state.to(self.codebook_heads.weight.dtype)) |
|
|
audio_logits = audio_logits.view(1, self.num_codebooks, codebook_size + 3) |
|
|
audio_token = sample(hyps[:, 1:, :i], audio_logits, top_k=top_k, top_p=top_p, temperature=temperature, repeat_penalty=repeat_penalty) |
|
|
|
|
|
audio_token = audio_token.masked_fill(end_flag[:, 1:], audio_pad_token_id) |
|
|
delay_mask = torch.arange(self.num_codebooks).expand(1, -1).to(self.device) > (i-1) |
|
|
audio_token = audio_token.masked_fill(delay_mask, audio_pad_token_id) |
|
|
hyps[:, 1:, i] = audio_token |
|
|
|
|
|
|
|
|
end_flag[:, 0] = end_flag[:, 0] | (hyps[:, 0, i] == self.config.eos_token_id) |
|
|
end_flag[:, 1:] = end_flag[:, 1:] | (hyps[:, 1:, i] == audio_eos_token_id) |
|
|
|
|
|
|
|
|
if i == first_coden_idx or (i > first_coden_idx and (i - first_coden_idx) % chunk_size == 0) or i == max_new_tokens - 1 or end_flag.all(): |
|
|
if i <= first_coden_idx: |
|
|
buffer_size = i - self.num_codebooks + 1 |
|
|
elif (i - first_coden_idx) % chunk_size == 0: |
|
|
buffer_size = chunk_size |
|
|
else: |
|
|
buffer_size = (i - first_coden_idx) % chunk_size |
|
|
buffer = [] |
|
|
for j in range(self.num_codebooks + 1): |
|
|
st_idx = i - buffer_size + 1 - (self.num_codebooks - j) |
|
|
buffer.append(hyps[:, j, st_idx:st_idx+buffer_size]) |
|
|
buffer = torch.cat(buffer, dim=0) |
|
|
text_tokens = buffer[0].unsqueeze(0) |
|
|
audio_tokens = buffer[1:] |
|
|
audio_token_len = (audio_tokens[0].ne(audio_pad_token_id) & audio_tokens[0].ne(audio_eos_token_id)).sum().item() |
|
|
audio_tokens = audio_tokens[:, :audio_token_len] |
|
|
pad_token_mask = audio_tokens.eq(audio_pad_token_id) |
|
|
eos_token_mask = audio_tokens.eq(audio_eos_token_id) |
|
|
if pad_token_mask.sum().item() > 0: |
|
|
audio_tokens = audio_tokens.masked_fill(pad_token_mask, torch.randint(0, codebook_size, (1,)).item()) |
|
|
if eos_token_mask.sum().item() > 0: |
|
|
audio_tokens = audio_tokens.masked_fill(eos_token_mask, torch.randint(0, codebook_size, (1,)).item()) |
|
|
yield text_tokens, [audio_tokens.cpu().numpy()], past_key_values, attention_mask |
|
|
|
|
|
|
|
|
if end_flag.all(): |
|
|
break |
|
|
|
|
|
|
|
|
this_input_ids = hyps[:, :, i] |
|
|
this_input_ids = this_input_ids.unsqueeze(1) |
|
|
this_inputs_text_embeds = self.model.convert_token_ids_to_embedding(this_input_ids[:, :, 0]) |
|
|
this_inputs_audio_embeds, audio_att_mask = self.convert_audio_ids_to_embedding(this_input_ids[:, :, 1:]) |
|
|
attention_mask = torch.cat([attention_mask, this_input_ids[:, 0, 0].unsqueeze(-1).ne(self.config.pad_token_id)], dim=1) |
|
|
last_hidden_state, past_key_values = self.model( |
|
|
attention_mask=attention_mask, |
|
|
past_key_values=past_key_values, |
|
|
inputs_embeds=this_inputs_text_embeds, |
|
|
use_cache=True, |
|
|
return_dict=False, |
|
|
) |
|
|
last_hidden_state = last_hidden_state[:, -1] |
|
|
this_inputs_audio_embeds = (this_inputs_audio_embeds + last_hidden_state.unsqueeze(1)) / (1 + self.num_codebooks) |
|
|
if audio_attention_mask is None: |
|
|
audio_attention_mask = audio_att_mask |
|
|
else: |
|
|
audio_attention_mask = torch.cat([audio_attention_mask, audio_att_mask], dim=1) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
a_last_hidden_state, a_past_key_values = self.audio_decoder( |
|
|
inputs_embeds=this_inputs_audio_embeds, |
|
|
attention_mask=audio_attention_mask.to(torch.int64), |
|
|
past_key_values=a_past_key_values, |
|
|
use_cache=True, |
|
|
return_dict=False, |
|
|
) |
|
|
a_last_hidden_state = a_last_hidden_state[:, -1] |
|
|
|
|
|
|
|
|
def length_penalty(input_ids, scores, length_penalty_params=(20, 1.01), eos_token_id=None): |
|
|
""" |
|
|
Args: |
|
|
input_ids: torch.LongTensor of shape (batch_size, seq_len) |
|
|
scores: torch.FloatTensor of shape (batch_size, vocab_size) |
|
|
length_penalty_params: Tuple[int, float] |
|
|
eos_token_id: int |
|
|
""" |
|
|
processor = ExponentialDecayLengthPenalty(length_penalty_params, eos_token_id=eos_token_id, input_ids_seq_length=1) |
|
|
scores = processor(input_ids, scores) |
|
|
return scores |
|
|
|
|
|
|
|
|
def sample( |
|
|
input_ids: torch.LongTensor, |
|
|
scores: torch.Tensor, |
|
|
top_k: int = 50, |
|
|
top_p: float = 0.95, |
|
|
temperature: float = 1.0, |
|
|
repeat_penalty: float = 1.0, |
|
|
): |
|
|
""" |
|
|
Args: |
|
|
input_ids: torch.LongTensor of shape (batch_size, C, seq_len) |
|
|
scores: torch.FloatTensor of shape (batch_size, C, vocab_size) |
|
|
top_k: int |
|
|
top_p: float |
|
|
temperature: float |
|
|
repeat_penalty: float |
|
|
C is the number of channels |
|
|
""" |
|
|
repeat_logits_processor = RepetitionPenaltyLogitsProcessor(repeat_penalty) |
|
|
top_p_logits_processor = TopPLogitsWarper(top_p) |
|
|
top_k_logits_processor = TopKLogitsWarper(top_k) |
|
|
temperature_logits_processor = TemperatureLogitsWarper(temperature) |
|
|
|
|
|
assert len(input_ids.shape) == 3, f"input_ids shape is {input_ids.shape}" |
|
|
assert len(scores.shape) == 3, f"scores shape is {scores.shape}" |
|
|
assert input_ids.shape[1] == scores.shape[1], f"input_ids shape is {input_ids.shape}, scores shape is {scores.shape}" |
|
|
batch_size, c, seq_len = input_ids.shape |
|
|
for i in range(c): |
|
|
input_id = input_ids[:, i] |
|
|
score = scores[:, i] |
|
|
|
|
|
score = repeat_logits_processor(input_id, score) |
|
|
|
|
|
score = top_p_logits_processor(input_id, score) |
|
|
|
|
|
|
|
|
|
|
|
score = temperature_logits_processor(input_id, score) |
|
|
|
|
|
scores[:, i] = score |
|
|
|
|
|
|
|
|
probs = scores.softmax(dim=-1) |
|
|
q = torch.empty_like(probs).exponential_(1) |
|
|
return torch.argmax((probs / q), dim=-1) |
|
|
|