Image-Text-to-Text
Transformers
Safetensors
English
Helium1_VL_2B
custom_code
Helium1-VL-2B / language_helium1_casa.py
ameroyer's picture
Super-squash branch 'main' using huggingface_hub
1126ea7 verified
# ADAPTED FROM https://github.com/huggingface/transformers/blob/main/src/transformers/models/helium/modeling_helium.py
# GIT HASH 1b222903c3e1cfd9492d75e4b2548aa8bd458674
import logging
import math
from dataclasses import dataclass
from functools import partial
from typing import Any, Callable, Literal, Optional
from typing import cast as type_cast
import torch
from torch import nn
from transformers import (
ROPE_INIT_FUNCTIONS, # pyright: ignore[reportPrivateImportUsage]
dynamic_rope_update, # pyright: ignore[reportPrivateImportUsage]
)
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.configuration_utils import PretrainedConfig
from transformers.generation.utils import GenerationMixin
from transformers.loss.loss_utils import ForCausalLMLoss
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils.generic import LossKwargs, can_return_tuple
from transformers.utils.import_utils import is_torch_flex_attn_available
from .casa_attention import CASAAttention, CASAAttentionHandler, insert_image_tokens
from .configuration_helium1_casa import Helium1CASAConfig
logger = logging.getLogger(__name__)
if is_torch_flex_attn_available():
from transformers.integrations.flex_attention import make_flex_block_causal_mask
def remove_image_tokens(
inputs_embeds: torch.Tensor,
image_tokens_mask: torch.Tensor,
) -> torch.Tensor:
"""Remove the image tokens from inputs_embeds as indicated by image_tokens_mask
:param inputs_embeds: Tokens of shape (Batch, Seqlen, Dims) containing image tokens
:param image_tokens_mask: 1-0 mask indicating where image tokens are; (Batch, Seqlen)
:return: Tokens tensor of shape (Batch, S' < Seqlen, Dims)
"""
image_seq_lengths = torch.sum(image_tokens_mask, dim=1)[:, 0]
image_seq_length = int(image_seq_lengths[0].item())
assert torch.all(image_seq_lengths == image_seq_length)
new_shape = (
inputs_embeds.shape[0],
inputs_embeds.shape[1] - image_seq_length,
inputs_embeds.shape[-1],
)
tokens = torch.masked_select(
inputs_embeds,
torch.logical_not(image_tokens_mask).expand((-1, -1, inputs_embeds.shape[-1])),
)
return tokens.reshape(new_shape)
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)
def eager_attention_forward(
module: "HeliumAttention",
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: None | torch.Tensor,
scaling: float,
dropout: float = 0.0,
**kwargs: Any,
):
del kwargs # unused
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
# Different Attention Classes
class HeliumAttention(torch.nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Helium1CASAConfig, layer_idx: None | int = None):
super().__init__()
self.config = config
assert layer_idx is not None
self.layer_idx: int = layer_idx
self.apply_rotary_fn = ApplyRotaryPosEmbHelium1()
self.head_dim = getattr(
config, "head_dim", config.hidden_size // config.num_attention_heads
)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = 1 / math.sqrt(self.head_dim)
self.attention_dropout = config.attention_dropout
self.is_causal = True
self.q_proj = nn.Linear(
config.hidden_size,
config.num_attention_heads * self.head_dim,
bias=config.attention_bias,
)
self.k_proj = nn.Linear(
config.hidden_size,
config.num_key_value_heads * self.head_dim,
bias=config.attention_bias,
)
self.v_proj = nn.Linear(
config.hidden_size,
config.num_key_value_heads * self.head_dim,
bias=config.attention_bias,
)
self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: None | torch.Tensor,
past_key_values: None | Cache = None,
cache_position: None | torch.LongTensor = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, torch.Tensor | None]:
# del (cache_position, past_key_value) # we use our own generate/caching
bs, seq_len, _ = hidden_states.shape
# Get QKV
hidden_shape = (bs, seq_len, -1, self.head_dim)
# Embed Queries
# Shape: (batch_size, num_heads, seq_len, head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
num_queries = query_states.shape[2]
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
# Applies rotation
cos, sin = position_embeddings
query_states, key_states = self.apply_rotary_fn(
query_states, key_states, cos, sin, num_queries=num_queries
)
assert key_states is not None and query_states is not None
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
if self.config._attn_implementation == "sdpa" and kwargs.get(
"output_attentions", False
):
print(
"`torch.nn.functional.scaled_dot_product_attention` does not support"
" `output_attentions=True`. Falling back to "
'eager attention. This warning can be removed using the argument"\
" `attn_implementation="eager"` when loading the model.'
)
else:
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(
key_states, value_states, self.layer_idx, cache_kwargs
)
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(bs, num_queries, -1).contiguous()
attn_output = self.o_proj(attn_output)
assert isinstance(attn_output, torch.Tensor)
return attn_output, attn_weights
class ApplyRotaryPosEmbHelium1:
@staticmethod
def rotate_half(x: torch.Tensor) -> torch.Tensor:
"""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)
@staticmethod
def __call__(
q: torch.Tensor,
k: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
position_ids: torch.Tensor | None = None,
unsqueeze_dim: int = 1,
num_queries: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
del position_ids
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
if num_queries is None:
offset = 0
else:
offset = -num_queries
q_embed = (q * cos[:, :, offset:]) + (
ApplyRotaryPosEmbHelium1.rotate_half(q) * sin[:, :, offset:]
)
k_embed = (k * cos) + (ApplyRotaryPosEmbHelium1.rotate_half(k) * sin)
return q_embed, k_embed
class HeliumRotaryEmbedding(nn.Module):
def __init__(self, config: Helium1CASAConfig, device: None | torch.device | str = 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
assert self.rope_type in ROPE_INIT_FUNCTIONS, (
f"Invalid rope type {self.rope_type}. Supported types are: {list(ROPE_INIT_FUNCTIONS.keys())}"
)
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(config, device=device)
self.inv_freq: torch.Tensor # only defined for typing
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = self.inv_freq
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(
self, x: torch.Tensor, position_ids: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
inv_freq_expanded = (
self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
)
position_ids_expanded = position_ids[:, None, :].float()
device_type = (
x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
)
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
class Helium1CASAAttention(CASAAttention):
"""A CASA Attention layer compatible with Qwen"""
def __init__(
self,
config: Helium1CASAConfig,
layer_idx: int | None,
self_attn: torch.nn.Module | None = None,
input_layernorm_fn: Callable[[torch.Tensor], torch.Tensor] | None = None,
):
# Only adding this init for typing purposes for the config
super().__init__(config, layer_idx, self_attn, input_layernorm_fn) # pyright: ignore[reportArgumentType]
@staticmethod
def rotate_half(x: torch.Tensor) -> torch.Tensor:
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_position_embeddings(
self,
key: Literal["q", "kv"],
x: torch.Tensor, # (batch, seq_len, num_heads, head_dim)
casa_handler: CASAAttentionHandler | None,
num_queries: int = 0,
unsqueeze_dim: int = 1,
) -> torch.Tensor: # (batch, seq_len, num_heads, head_dim)
"""Apply position embeddings to query and key states"""
if casa_handler is not None:
posemb = casa_handler.get_position_embedding(key, num_queries=num_queries)
if posemb is not None:
x = x.transpose(1, 2).to(torch.float32)
x = (x * posemb[0].unsqueeze(dim=unsqueeze_dim)) + (
self.rotate_half(x) * posemb[1].unsqueeze(dim=unsqueeze_dim)
)
return x.transpose(1, 2)
return x
def init_from_config_proj(
self, key: Literal["q", "o", "k", "v"], config: PretrainedConfig
) -> torch.nn.Linear:
"""Initialize the Linear proj in this module"""
num_heads = config.num_key_value_heads if key in {"k", "v"} else config.num_attention_heads
return torch.nn.Linear(
config.hidden_size,
num_heads * config.head_dim,
bias=config.attention_bias if key != "o" else False,
)
# NORMALISATION LAYER
def __rms_norm_forward__(
hidden_states: torch.Tensor, weight: torch.Tensor, variance_epsilon: float = 1e-6
) -> torch.Tensor:
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 + variance_epsilon)
return weight * hidden_states.to(input_dtype)
class Helium1RMSNorm(nn.Module):
def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
"""
Helium1RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return __rms_norm_forward__(hidden_states, self.weight, self.variance_epsilon)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
def delta_w_factory_rms_norm(
org_lin: Helium1RMSNorm, new_lin: Helium1RMSNorm
) -> Callable[[torch.Tensor], torch.Tensor]:
"""Factory for building rms norm where the weights are the sum of two layers' weights"""
def _delta_w_fwd(input: torch.Tensor) -> torch.Tensor:
nonlocal org_lin, new_lin
return __rms_norm_forward__(
input, org_lin.weight + new_lin.weight, new_lin.variance_epsilon
)
return _delta_w_fwd
# FULL CONNECTED LAYER
class HeliumMLP(nn.Module):
def __init__(self, config: Helium1CASAConfig) -> None:
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=config.mlp_bias)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x: torch.Tensor) -> torch.Tensor:
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
class HeliumDecoderLayer(nn.Module):
def __init__(self, config: Helium1CASAConfig, layer_idx: None | int = None):
super().__init__()
self.hidden_size = config.hidden_size
self.config = config
self.mlp = HeliumMLP(config)
self.input_layernorm = Helium1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Helium1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# Self-attention
self.self_attn = HeliumAttention(config=config, layer_idx=layer_idx)
# Setup norm for fusion mechanisms; Note that this norm is on the text tokens
is_xa_layer = layer_idx is None or not config.xa_layers or layer_idx in config.xa_layers
self.norm_cross: None | Helium1RMSNorm = None
self.override_norm_cross: Callable[[torch.Tensor], torch.Tensor] | None = None
if is_xa_layer and config.casa_attention:
# Custom normalization layer for the extra fusion module
if self.config.xa_custom_norm:
self.norm_cross = Helium1RMSNorm(config.hidden_size)
if config.casa_delta_w:
self.override_norm_cross = delta_w_factory_rms_norm(
self.input_layernorm, self.norm_cross
)
with torch.no_grad():
torch.nn.init.ones_(self.norm_cross.weight)
# Setup additional norm for images tokens which is set in each individual mechansims
norm_on_images_fn = (
None
if not self.config.xa_norm_on_images
else self.override_norm_cross
if self.override_norm_cross is not None
else self.norm_cross.forward
if self.norm_cross is not None
else self.input_layernorm.forward
)
# CASA
self.casa_attn: Helium1CASAAttention | None = None
if config.casa_attention and is_xa_layer:
self.casa_attn = Helium1CASAAttention(
config, layer_idx, self_attn=self.self_attn, input_layernorm_fn=norm_on_images_fn
)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: None | torch.Tensor = None,
position_ids: None | torch.LongTensor = None,
past_key_values: None | Cache = None,
output_attentions: None | bool = False,
use_cache: None | bool = False,
cache_position: None | torch.LongTensor = None,
position_embeddings: None
| tuple[torch.Tensor, torch.Tensor] = None, # necessary, but kept here for BC
# CASA
casa_handler: CASAAttentionHandler | None = None,
cu_seqlens: torch.Tensor | None = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor]:
# Image fusion mechanisms
apply_ca = self.casa_attn is not None
ca_update: torch.Tensor | None = None
if (
self.config.xa_order
in {
"parallel",
"ca_first",
"instead",
}
and apply_ca
):
# Apply layer norm
assert self.norm_cross is not None
ca_input = (
self.override_norm_cross
if self.override_norm_cross is not None
else self.norm_cross
)(hidden_states)
# CASA
if self.casa_attn is not None:
ca_update = self.casa_attn(ca_input, casa_handler=casa_handler)
# If we're here, it's because we had proper inputs (no text-only samples)
# so the output better be not None !
if ca_update is not None:
# `instead`: directly return the output of the CA module as residual
if self.config.xa_order == "instead":
outputs = (hidden_states + ca_update,)
if output_attentions:
outputs += (
torch.zeros((), device=ca_update.device, dtype=ca_update.dtype),
)
return outputs
# `ca_first`: update then continue with normal self-attention
if self.config.xa_order == "ca_first":
hidden_states = hidden_states + ca_update
ca_update = None
# Self Attention with initial input layer norm
residual = hidden_states
hidden_states, self_attn_weights = self.self_attn(
hidden_states=self.input_layernorm(hidden_states),
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
**kwargs,
)
hidden_states = residual + hidden_states
# parallel - residual update
if self.config.xa_order == "parallel" and apply_ca and ca_update is not None:
hidden_states = hidden_states + ca_update
# Fully Connected layer
residual = hidden_states
# MLP updates for image embeddings
if (
self.config.xa_update_image_embeds
and self.casa_attn is not None
and casa_handler is not None
and casa_handler.image_embeds is not None
):
# Text flattening
hs = self.post_attention_layernorm(hidden_states).reshape(-1, hidden_states.shape[-1])
# Image flattening
img_seq_lengths = [_x.shape[0] for _x in casa_handler.image_embeds]
img_residual = torch.cat(list(casa_handler.image_embeds), dim=0)
update = self.mlp(torch.cat([hs, self.post_attention_layernorm(img_residual)], dim=0))
# update text
hidden_states = hidden_states + update[: hs.shape[0]].reshape(hidden_states.shape)
casa_handler.image_embeds = list(
torch.split(img_residual + update[hs.shape[0] :], img_seq_lengths)
)
else:
hidden_states = self.mlp(self.post_attention_layernorm(hidden_states))
hidden_states = residual + hidden_states
# Outputs
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
# FULL HELIUM MODEL
@dataclass
class CausalHeliumOutput(CausalLMOutputWithPast):
attention_mask: Optional[torch.Tensor] = None
num_image_tokens_log: Optional[torch.Tensor] = None
num_text_tokens_log: Optional[torch.Tensor] = None
class Helium1PreTrainedModel(PreTrainedModel):
config_class = Helium1CASAConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["HeliumDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn_2 = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_cache_class = True
_supports_quantized_cache = True
_supports_static_cache = True
_supports_attention_backend = True
def _init_weights(self, module: torch.nn.Module) -> None:
std = self.config.initializer_range
if isinstance(module, nn.Linear):
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_()
elif isinstance(module, Helium1RMSNorm):
module.weight.data.fill_(1.0)
class Helium1Model(Helium1PreTrainedModel):
"""
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
Args:
config: Helium1CASAConfig
"""
def __init__(self, config: Helium1CASAConfig):
Helium1PreTrainedModel.__init__(self, config)
self.training: bool
self._gradient_checkpointing_func: Callable
self.config = config
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = Helium1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = HeliumRotaryEmbedding(config=config)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value: nn.Module) -> None:
self.embed_tokens = value
@can_return_tuple
def forward(
self,
input_ids: None | torch.LongTensor = None,
attention_mask: None | torch.Tensor = None,
position_ids: None | torch.Tensor = None,
past_key_values: None | DynamicCache = None,
inputs_embeds: None | torch.Tensor = None,
use_cache: None | bool = None,
output_attentions: None | bool = None,
output_hidden_states: None | bool = None,
cache_position: None | torch.Tensor = None,
# Insertion
image_tokens_mask: torch.Tensor | None = None,
# CASA
casa_handler: CASAAttentionHandler | None = None,
cu_seqlens: torch.Tensor | None = None,
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
) -> 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 = not self.training and (
use_cache if use_cache is not None else self.config.use_cache
)
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 and use_cache:
print(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
)
use_cache = False
# TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
if not isinstance(past_key_values, (type(None), Cache)):
raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
assert inputs_embeds is not None
if use_cache and past_key_values is None:
past_key_values = DynamicCache()
if cache_position is None:
past_seen_tokens = 0 if past_key_values is None else past_key_values._seen_tokens
assert inputs_embeds is not None
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + inputs_embeds.shape[1],
device=inputs_embeds.device,
)
assert cache_position is not None
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
# Get attention mask
causal_mask: None | torch.Tensor = self._update_causal_mask(
attention_mask,
inputs_embeds,
cache_position,
past_key_values,
output_attentions,
force_mask=False,
)
# create position embeddings to be shared across the decoder layers
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
for decoder_layer_idx, decoder_layer in enumerate(
self.layers[: self.config.num_hidden_layers]
):
is_xa_layer = not self.config.xa_layers or decoder_layer_idx in self.config.xa_layers
if output_hidden_states is not None:
if all_hidden_states is None:
all_hidden_states = ()
all_hidden_states += (hidden_states,)
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
partial(decoder_layer.__call__, **flash_attn_kwargs),
hidden_states,
causal_mask,
position_ids,
past_key_values,
output_attentions,
use_cache,
cache_position,
position_embeddings,
casa_handler if is_xa_layer else None,
cu_seqlens,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=causal_mask,
position_ids=position_ids,
past_key_values=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
casa_handler=casa_handler if is_xa_layer else None,
cu_seqlens=cu_seqlens,
**flash_attn_kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
if all_self_attns is None:
all_self_attns = ()
all_self_attns += (layer_outputs[1],)
hidden_states = self.norm(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
if all_hidden_states is None:
all_hidden_states = ()
all_hidden_states += (hidden_states,)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values if use_cache else None, # pyright: ignore[reportArgumentType]
hidden_states=all_hidden_states, # pyright: ignore[reportArgumentType]
attentions=all_self_attns,
)
def _update_causal_mask(
self,
attention_mask: torch.Tensor | None,
input_tensor: torch.Tensor,
cache_position: torch.Tensor,
past_key_values: None | DynamicCache | Cache,
output_attentions: bool = False,
force_mask: bool = False,
) -> torch.Tensor | None:
if self.config._attn_implementation == "flex_attention":
if isinstance(attention_mask, torch.Tensor):
attention_mask = make_flex_block_causal_mask(attention_mask) # type: ignore
return attention_mask
assert attention_mask is None or isinstance(attention_mask, torch.Tensor)
if self.config._attn_implementation == "flash_attention_2":
if attention_mask is not None and (force_mask or (attention_mask == 0.0).any()):
return attention_mask
return None
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
# to infer the attention mask.
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
using_compilable_cache = (
past_key_values.is_compileable if past_key_values is not None else False
)
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
if (
self.config._attn_implementation == "sdpa"
and not using_compilable_cache
and not output_attentions
):
if not force_mask and AttentionMaskConverter._ignore_causal_mask_sdpa(
attention_mask,
inputs_embeds=input_tensor,
past_key_values_length=past_seen_tokens,
is_training=self.training,
):
return None
dtype = input_tensor.dtype
sequence_length = input_tensor.shape[1]
if using_compilable_cache and past_key_values is not None:
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
)
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
assert target_length is not None
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
attention_mask,
sequence_length=sequence_length,
target_length=target_length,
dtype=dtype,
cache_position=cache_position,
batch_size=input_tensor.shape[0],
)
if (
self.config._attn_implementation == "sdpa"
and attention_mask is not None
and attention_mask.device.type in ["cuda", "xpu", "npu"]
and not output_attentions
):
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
# Details: https://github.com/pytorch/pytorch/issues/110213
min_dtype = torch.finfo(dtype).min
causal_mask = AttentionMaskConverter._unmask_unattended(
type_cast(torch.FloatTensor, causal_mask), min_dtype
)
return causal_mask
@staticmethod
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor | None,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
cache_position: torch.Tensor,
batch_size: int,
**kwargs: Any,
):
"""
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.
cache_position (`torch.Tensor`):
Indices depicting the position of the input sequence tokens in the sequence.
batch_size (`torch.Tensor`):
Batch size.
"""
del kwargs
if attention_mask is not None and attention_mask.dim() == 4:
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
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=cache_position.device,
)
if sequence_length != 1:
causal_mask = torch.triu(causal_mask, diagonal=1)
causal_mask *= torch.arange(
target_length, device=cache_position.device
) > cache_position.reshape(-1, 1)
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
if attention_mask is not None:
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
mask_length = attention_mask.shape[-1]
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[
:, None, None, :
].to(causal_mask.device)
padding_mask = padding_mask == 0
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
padding_mask, min_dtype
)
return causal_mask
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
class Helium1ForCausalLM(Helium1PreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config: Helium1CASAConfig, **kwargs: Any) -> None:
del kwargs
super().__init__(config)
self.model: Helium1Model
self.model = Helium1Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self._loss_function = ForCausalLMLoss
def get_input_embeddings(self) -> nn.Module:
return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Module) -> None:
self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Module:
return self.lm_head
def set_output_embeddings(self, new_embeddings: nn.Module) -> None:
self.lm_head = new_embeddings
def set_decoder(self, decoder: Helium1Model) -> None:
self.model = decoder
def get_decoder(self) -> Helium1Model:
return self.model
@can_return_tuple
def forward(
self,
input_ids: None | torch.LongTensor = None,
attention_mask: None | torch.Tensor = None,
position_ids: None | torch.LongTensor = None,
past_key_values: None | Cache = None,
inputs_embeds: None | torch.Tensor = None,
image_embeds: None | torch.Tensor | list[torch.Tensor] = None,
image_embeds_insertion_points: None | list[torch.Tensor] = None,
labels: None | torch.LongTensor = None,
use_cache: None | bool = None,
output_attentions: None | bool = None,
output_hidden_states: None | bool = None,
cache_position: None | torch.LongTensor = None,
logits_to_keep: int | torch.Tensor = 0,
# CASA
casa_windows_info: None | dict = None,
**kwargs: Unpack[KwargsForCausalLM],
) -> CausalHeliumOutput:
r"""
Helium1 augmented with CASA layers
"""
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
)
if input_ids is not None:
assert inputs_embeds is None, (
"Need to provide only one of `input_ids` or `inputs_embeds`."
)
inputs_embeds = self.model.embed_tokens(input_ids)
assert inputs_embeds is not None
# Setup image + text token fusion
bs, og_seq_len, _ = inputs_embeds.shape
image_tokens_mask: torch.Tensor | None = None
casa_handler: CASAAttentionHandler | None = None
num_image_tokens = -1
if image_embeds is not None:
num_image_tokens = sum(_x.shape[0] for _x in image_embeds)
assert image_embeds_insertion_points is not None, (
"Missing image embeddings insertion points"
)
# B1. CASA layers: We need to init the shared Handler
if self.model.config.casa_attention:
casa_handler = CASAAttentionHandler(
# for text tokens, we don't need the actual values
inputs_embeds=torch.zeros_like(inputs_embeds),
# for image embeddings, we put real inputs as this will be fixed
image_embeds=image_embeds,
image_embeds_insertion_points=image_embeds_insertion_points,
# attention mask is only needed at inference / left padding
attention_mask=None if self.training else attention_mask,
rope_fn=self.model.rotary_emb,
windows=self.model.config.casa_windows,
use_asymetric_q_kv=self.model.config.casa_use_asymetric_qkv,
# further params are fed to the funtion computing attention
casa_windows_info=casa_windows_info,
)
# B2. Direct image insertion
else:
inputs_embeds, _, attention_mask, image_tokens_mask = insert_image_tokens(
inputs_embeds=inputs_embeds,
image_embeds=image_embeds,
image_embeds_insertion_points=image_embeds_insertion_points,
attention_mask=attention_mask,
padding_side="right" if self.training else "left",
recover_batch_dim=True,
)
del image_embeds
del input_ids
outputs: BaseModelOutputWithPast = self.model(
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
cache_position=cache_position,
image_tokens_mask=image_tokens_mask,
casa_handler=casa_handler,
**kwargs,
)
hidden_states = outputs.last_hidden_state
assert hidden_states is not None
if image_tokens_mask is not None:
hidden_states = remove_image_tokens(hidden_states, image_tokens_mask)
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = (
slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
)
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(
logits=logits,
labels=labels,
vocab_size=self.config.vocab_size,
**kwargs,
)
out = CausalHeliumOutput(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
num_image_tokens_log=torch.tensor(num_image_tokens).to(logits.device).to(torch.float),
num_text_tokens_log=torch.tensor(og_seq_len).to(logits.device).to(torch.float),
)
return out