AliceAI-T5-35B-A0.6B / modeling_aliceai_t5.py
toxabuk's picture
Upload folder using huggingface_hub
4062845 verified
Raw
History Blame Contribute Delete
50.2 kB
from collections.abc import Callable
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.cache_utils import Cache, DynamicCache, EncoderDecoderCache, StaticCache
from transformers.configuration_utils import PretrainedConfig
from transformers.generation.utils import GenerationMixin
from transformers.masking_utils import (
create_bidirectional_mask,
create_bidirectional_sliding_window_mask,
create_causal_mask,
create_sliding_window_causal_mask,
)
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
Seq2SeqLMOutput,
Seq2SeqModelOutput,
)
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils import logging
from transformers.utils.generic import can_return_tuple
from .configuration_aliceai_t5 import AliceAIT5Config, AliceAIT5ModuleConfig
logger = logging.get_logger(__name__)
class AliceAIT5RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def forward(self, x):
return F.rms_norm(x.to(self.weight.dtype), x.shape[-1:], self.weight, self.eps)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.eps}"
class AliceAIT5RotaryEmbedding(nn.Module):
def __init__(self, config, device=None):
super().__init__()
rope_type = config.rope_parameters.get("rope_type", "default")
if "dynamic" in rope_type or rope_type == "longrope":
raise ValueError(f"{rope_type} requires dynamic RoPE updates; this model uses fixed rotary tables.")
self.config = config
self._rope_initialized = False
self.rope_init_fn = self.compute_default_rope_parameters
if rope_type != "default":
self.rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
inv_freq, attention_scaling = self.rope_init_fn(self.config, device)
self._build_cos_sin(inv_freq, attention_scaling)
if device is not None and str(device) != "meta":
self._rope_initialized = True
def _build_cos_sin(self, inv_freq: torch.Tensor, attention_scaling: float):
positions = torch.arange(
self.config.max_position_embeddings,
dtype=torch.float32,
device=inv_freq.device,
)
angles = torch.outer(positions, inv_freq.float())
cos = angles.cos() * attention_scaling
sin = angles.sin() * attention_scaling
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
@staticmethod
def compute_default_rope_parameters(
config: PretrainedConfig | None = None,
device: Optional["torch.device"] = None,
seq_len: int | None = None,
) -> tuple["torch.Tensor", float]:
"""Return default RoPE inverse frequencies; ``seq_len`` is unused."""
base = config.rope_parameters["rope_theta"]
partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
dim = int(head_dim * partial_rotary_factor)
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, 1.0
@torch.no_grad()
def forward(self, x, position_ids):
if self.cos.device.type == "meta" or not self._rope_initialized:
inv_freq, attention_scaling = self.rope_init_fn(self.config, x.device)
self._build_cos_sin(inv_freq, attention_scaling)
self._rope_initialized = True
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):
return self.cos[position_ids].to(x.dtype), self.sin[position_ids].to(x.dtype)
def rotate_half_torch(x):
x1, x2 = x.chunk(2, dim=-1)
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_emb_torch(x, cos, sin):
"""
x: (batch_size, seqlen, nheads, headdim)
cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2)
"""
ro_dim = cos.shape[-1] * 2
assert ro_dim <= x.shape[-1]
cos = torch.cat((cos, cos), dim=-1)
sin = torch.cat((sin, sin), dim=-1)
cos = cos.unsqueeze(-2)
sin = sin.unsqueeze(-2)
return torch.cat(
[x[..., :ro_dim] * cos + rotate_half_torch(x[..., :ro_dim]) * sin, x[..., ro_dim:]],
dim=-1,
)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""Repeat key/value heads to match the number of query heads."""
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: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: torch.Tensor | None,
dropout: float = 0.0,
scaling: float | None = None,
softcap: float | None = None,
**kwargs,
) -> tuple[torch.Tensor, torch.Tensor]:
if scaling is None:
scaling = module.head_dim**-0.5
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 softcap is not None:
attn_weights = attn_weights / softcap
attn_weights = torch.tanh(attn_weights)
attn_weights = attn_weights * softcap
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = F.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
class AliceAIT5SelfAttention(nn.Module):
"""Self-attention with rotary position embeddings and grouped key/value heads."""
def __init__(self, config: AliceAIT5ModuleConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
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 = config.query_pre_attn_scalar**-0.5
self.attention_dropout = self.config.attention_dropout
# FlashAttention reads causality from the module.
self.is_causal = config.is_decoder
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.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
)
self.attn_logit_softcapping = self.config.attn_logit_softcapping
self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None,
past_key_value: Cache | None = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, torch.Tensor | None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 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)
cos, sin = position_embeddings
query_states = apply_rotary_emb_torch(query_states.transpose(1, 2), cos, sin).transpose(1, 2)
key_states = apply_rotary_emb_torch(key_states.transpose(1, 2), cos, sin).transpose(1, 2)
if past_key_value is not None:
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=self.attention_dropout if self.training else 0.0,
scaling=self.scaling,
sliding_window=self.sliding_window,
softcap=self.attn_logit_softcapping,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
class AliceAIT5CrossAttention(nn.Module):
"""Non-causal decoder attention over cached encoder keys and values."""
def __init__(self, config: AliceAIT5ModuleConfig, layer_idx: int):
super().__init__()
if config.cross_attention_hidden_size is None:
raise ValueError("Cross-attention needs cross_attention_hidden_size to be specified.")
self.config = config
self.layer_idx = layer_idx
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 = config.query_pre_attn_scalar**-0.5
self.attention_dropout = self.config.attention_dropout
self.is_causal = False
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.cross_attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.cross_attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
)
self.attn_logit_softcapping = self.config.attn_logit_softcapping
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor | None,
encoder_hidden_states: torch.Tensor | None,
past_key_value: EncoderDecoderCache | None = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, torch.Tensor | None]:
if encoder_hidden_states is None:
raise ValueError("Encoder hidden state is required for cross attention.")
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
if past_key_value is not None:
is_updated = past_key_value.is_updated.get(self.layer_idx)
curr_past_key_value = past_key_value.cross_attention_cache
if past_key_value is None or not is_updated:
encoder_input_shape = encoder_hidden_states.shape[:-1]
encoder_hidden_shape = (*encoder_input_shape, -1, self.head_dim)
key_states = self.k_proj(encoder_hidden_states).view(encoder_hidden_shape).transpose(1, 2)
value_states = self.v_proj(encoder_hidden_states).view(encoder_hidden_shape).transpose(1, 2)
if past_key_value is not None:
key_states, value_states = curr_past_key_value.update(key_states, value_states, self.layer_idx)
past_key_value.is_updated[self.layer_idx] = True
else:
key_states = curr_past_key_value.layers[self.layer_idx].keys
value_states = curr_past_key_value.layers[self.layer_idx].values
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
# Pack valid encoder keys/values separately from decoder queries so
# right padding cannot mask out decoder positions.
extra_attention_kwargs = {}
if (
self.config._attn_implementation.startswith("flash_attention")
and attention_mask is not None
and attention_mask.ndim == 2
):
batch_size, query_length = hidden_states.shape[:2]
key_mask = attention_mask.to(device=key_states.device, dtype=torch.bool)
key_states = key_states.transpose(1, 2)[key_mask].transpose(0, 1).unsqueeze(0)
value_states = value_states.transpose(1, 2)[key_mask].transpose(0, 1).unsqueeze(0)
query_states = (
query_states.transpose(1, 2)
.reshape(1, batch_size * query_length, self.config.num_attention_heads, self.head_dim)
.transpose(1, 2)
)
key_lengths = key_mask.sum(dim=-1, dtype=torch.int32)
cu_seq_lens_k = F.pad(key_lengths.cumsum(dim=0, dtype=torch.int32), (1, 0))
cu_seq_lens_q = torch.arange(
0,
(batch_size + 1) * query_length,
query_length,
dtype=torch.int32,
device=hidden_states.device,
)
extra_attention_kwargs = {
"cu_seq_lens_q": cu_seq_lens_q,
"cu_seq_lens_k": cu_seq_lens_k,
"max_length_q": query_length,
"max_length_k": int(key_lengths.max().item()),
}
attention_mask = None
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=self.attention_dropout if self.training else 0.0,
scaling=self.scaling,
sliding_window=None,
softcap=self.attn_logit_softcapping,
**extra_attention_kwargs,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
class AliceAIT5EncoderLayer(GradientCheckpointingLayer):
"""Encoder sub-layer."""
def __init__(self, config, layer_idx: int, *, mlp: nn.Module):
super().__init__()
self.config = config
self.attention_type = config.layer_types[layer_idx]
self.pre_self_attn_layernorm = AliceAIT5RMSNorm(config.hidden_size, eps=config.norm_eps)
self.self_attn = AliceAIT5SelfAttention(config=config, layer_idx=layer_idx)
self.post_self_attn_layernorm = AliceAIT5RMSNorm(config.hidden_size, eps=config.norm_eps)
self.mlp = mlp
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
output_attentions: bool | None = False,
**kwargs,
) -> tuple[
torch.FloatTensor,
tuple[torch.FloatTensor, torch.FloatTensor] | None,
]:
mlp_attn_dtype = self.self_attn.q_proj.weight.dtype
residual = hidden_states
hidden_states = self.pre_self_attn_layernorm(hidden_states)
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states.to(mlp_attn_dtype),
position_embeddings=position_embeddings,
attention_mask=attention_mask,
position_ids=position_ids,
output_attentions=output_attentions,
use_cache=False,
past_key_value=None,
**kwargs,
)
if self.config.fp32_residual:
hidden_states = residual.float() + hidden_states.float()
else:
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_self_attn_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states.to(mlp_attn_dtype))
if self.config.fp32_residual:
hidden_states = residual.float() + hidden_states.float()
else:
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
class AliceAIT5DecoderLayer(AliceAIT5EncoderLayer):
"""Decoder sub-layer: an extra cross-attention layer."""
def __init__(self, config, layer_idx: int, *, mlp: nn.Module):
super().__init__(config, layer_idx, mlp=mlp)
self.cross_attn = AliceAIT5CrossAttention(config=config, layer_idx=layer_idx)
self.post_cross_attn_layernorm = AliceAIT5RMSNorm(config.hidden_size, eps=config.norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_value: EncoderDecoderCache | None = None,
output_attentions: bool | None = False,
use_cache: bool | None = False,
encoder_hidden_states: torch.Tensor | None = None,
encoder_attention_mask: torch.Tensor | None = None,
**kwargs,
) -> tuple[
torch.FloatTensor,
tuple[torch.FloatTensor, torch.FloatTensor] | None,
tuple[torch.FloatTensor, torch.FloatTensor] | None,
]:
mlp_attn_dtype = self.self_attn.q_proj.weight.dtype
residual = hidden_states
hidden_states = self.pre_self_attn_layernorm(hidden_states)
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states.to(mlp_attn_dtype),
position_embeddings=position_embeddings,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value.self_attention_cache if past_key_value is not None else None,
output_attentions=output_attentions,
use_cache=use_cache,
**kwargs,
)
if self.config.fp32_residual:
hidden_states = residual.float() + hidden_states.float()
else:
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_self_attn_layernorm(hidden_states)
hidden_states, cross_attn_weights = self.cross_attn(
hidden_states=hidden_states.to(mlp_attn_dtype),
encoder_hidden_states=encoder_hidden_states.to(mlp_attn_dtype),
attention_mask=encoder_attention_mask,
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
**kwargs,
)
if self.config.fp32_residual:
hidden_states = residual.float() + hidden_states.float()
else:
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_cross_attn_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states.to(mlp_attn_dtype))
if self.config.fp32_residual:
hidden_states = residual.float() + hidden_states.float()
else:
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights, cross_attn_weights)
return outputs
class AliceAIT5LMHead(nn.Module):
"""Head for language modeling (generation) tasks."""
def __init__(self, hidden_size: int, vocab_size: int, bias: bool = False, dtype: torch.dtype = torch.float):
super().__init__()
self.out_proj = nn.Linear(hidden_size, vocab_size, bias=bias, dtype=dtype)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# Accumulate low-precision CUDA products into FP32 without copying tied weights.
output_dtype = torch.float32 if hidden_states.dtype in (torch.float16, torch.bfloat16) else hidden_states.dtype
flat_states = hidden_states.reshape(-1, hidden_states.shape[-1])
weight = self.out_proj.weight
if (
not torch.is_grad_enabled()
and flat_states.device.type == "cuda"
and flat_states.dtype in (torch.float16, torch.bfloat16)
and weight.dtype == flat_states.dtype
):
logits = torch.mm(flat_states, weight.t(), out_dtype=output_dtype)
else:
logits = F.linear(
flat_states.to(output_dtype),
weight.to(output_dtype),
)
if self.out_proj.bias is not None:
logits = logits + self.out_proj.bias.to(output_dtype)
return logits.view(*hidden_states.shape[:-1], weight.shape[0])
class AliceAIT5PreTrainedModel(PreTrainedModel):
config_class = AliceAIT5Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = []
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_attention_backend = True
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
from .moe_layers import _checkpoint_contexts
options = dict(gradient_checkpointing_kwargs or {})
if options.get("use_reentrant", False):
raise ValueError("AliceAIT5 gradient checkpointing requires use_reentrant=False.")
if "context_fn" in options:
raise ValueError(
"Custom checkpointing context_fn is not supported; router statistics need recompute control."
)
if options.get("debug", False):
raise ValueError("Checkpointing debug=True is incompatible with router recomputation contexts.")
options["use_reentrant"] = False
options["context_fn"] = _checkpoint_contexts
return super().gradient_checkpointing_enable(gradient_checkpointing_kwargs=options)
@classmethod
def from_pretrained(cls, *args, **kwargs):
if any(kwargs.get(name) is not None for name in ("tp_plan", "tp_size", "device_mesh", "distributed_config")):
raise ValueError("Tensor/expert parallelism is not implemented for AliceAIT5; omit TP arguments.")
return super().from_pretrained(*args, **kwargs)
def resize_token_embeddings(
self,
new_num_tokens: int | None = None,
pad_to_multiple_of: int | None = None,
mean_resizing: bool = True,
) -> nn.Embedding:
model_embeds = super().resize_token_embeddings(
new_num_tokens=new_num_tokens,
pad_to_multiple_of=pad_to_multiple_of,
mean_resizing=mean_resizing,
)
vocab_size = model_embeds.weight.shape[0]
self.config.vocab_size = vocab_size
for subconfig_name in ("encoder", "decoder"):
subconfig = getattr(self.config, subconfig_name, None)
if subconfig is not None:
subconfig.vocab_size = vocab_size
if not getattr(self.config, "shared_embeddings", True) and (
new_num_tokens is not None or pad_to_multiple_of is not None
):
decoder = self.get_decoder()
if decoder is not self:
decoder.resize_token_embeddings(
vocab_size,
mean_resizing=mean_resizing,
)
self.tie_weights()
return model_embeds
def _init_weights(self, module):
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, AliceAIT5RMSNorm):
module.weight.data.fill_(1.0)
elif isinstance(module, AliceAIT5LMHead):
if not self.config.tie_word_embeddings:
scale = module.out_proj.weight.shape[0] ** -0.5
module.out_proj.weight.data.normal_(mean=0.0, std=std * scale)
def _shift_right(self, input_ids):
"""Prepend decoder BOS and replace ignored labels with the padding token."""
decoder_start_token_id = self.config.decoder.bos_token_id
pad_token_id = self.config.decoder.pad_token_id
if decoder_start_token_id is None:
raise ValueError("self.model.config.decoder.bos_token_id has to be defined. ")
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
shifted_input_ids[..., 0] = decoder_start_token_id
if pad_token_id is None:
raise ValueError("self.model.config.decoder.pad_token_id has to be defined.")
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
return shifted_input_ids
def make_default_2d_attention_mask(
token_ids: torch.LongTensor | None,
hidden_states: torch.Tensor,
pad_token_id: int | None,
) -> torch.Tensor:
"""Construct the default attention mask."""
if token_ids is not None:
if pad_token_id is None:
raise ValueError("`pad_token_id` is required for padding information.")
attention_mask = (token_ids != pad_token_id).to(hidden_states.device, torch.long)
else:
attention_mask = torch.ones(
(hidden_states.shape[0], hidden_states.shape[1]), device=hidden_states.device, dtype=torch.long
)
return attention_mask
def validate_encoder_attention_mask(attention_mask: torch.Tensor | dict | None):
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim == 2:
if attention_mask.shape[-1] == 0 or not attention_mask.bool().any(dim=-1).all():
raise ValueError("Each encoder sequence must contain at least one unmasked token.")
class AliceAIT5Encoder(AliceAIT5PreTrainedModel):
_no_split_modules = [AliceAIT5EncoderLayer.__name__]
def __init__(self, config):
super().__init__(config)
self._init_components(config)
self.post_init()
def _init_components(self, config):
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.has_embeddings = config.has_embeddings
if not config.is_decoder and not config.has_embeddings:
raise ValueError("Encoder must have embeddings, but got has_embeddings=False with is_decoder=False")
if config.has_embeddings:
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.norm = AliceAIT5RMSNorm(config.hidden_size, eps=config.norm_eps)
self.rotary_emb = AliceAIT5RotaryEmbedding(config=config)
self.gradient_checkpointing = False
if config.is_decoder:
self.dropout = nn.Dropout(config.dropout_rate)
self._build_layers(config)
def _build_layers(self, config):
raise NotImplementedError("Use AliceAIT5MoEEncoder to construct encoder layers.")
def get_input_embeddings(self):
if not self.has_embeddings:
raise NotImplementedError("Module has no `embed_tokens` due to config")
return self.embed_tokens
def set_input_embeddings(self, value):
if not self.has_embeddings:
raise NotImplementedError("Module can't have `embed_tokens` due to config")
self.embed_tokens = value
@can_return_tuple
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.FloatTensor | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
) -> BaseModelOutput:
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 None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
if attention_mask is None:
attention_mask = make_default_2d_attention_mask(input_ids, inputs_embeds, self.config.pad_token_id)
validate_encoder_attention_mask(attention_mask)
if not isinstance(self_attn_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"inputs_embeds": inputs_embeds,
"attention_mask": attention_mask,
}
self_attn_mask_mapping = {
"full_attention": create_bidirectional_mask(**mask_kwargs),
}
if self.config.sliding_window is not None:
self_attn_mask_mapping["sliding_attention"] = create_bidirectional_sliding_window_mask(**mask_kwargs)
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
for layer_module in self.layers[: self.config.num_hidden_layers]:
if output_hidden_states:
all_hidden_states += (hidden_states,)
layer_outputs = layer_module(
hidden_states,
position_embeddings,
self_attn_mask_mapping[layer_module.attention_type],
position_ids,
output_attentions,
**flash_attn_kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attns += (layer_outputs[1],)
if self.norm is not None:
hidden_states = self.norm(hidden_states)
if output_hidden_states:
all_hidden_states += (hidden_states,)
return BaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=all_hidden_states,
attentions=all_self_attns,
)
class AliceAIT5Decoder(AliceAIT5Encoder):
_no_split_modules = [AliceAIT5DecoderLayer.__name__]
def _build_layers(self, config):
raise NotImplementedError("Use AliceAIT5MoEDecoder to construct decoder layers.")
@can_return_tuple
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: EncoderDecoderCache | None = None,
inputs_embeds: torch.FloatTensor | None = None,
use_cache: bool | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
encoder_hidden_states: torch.Tensor | None = None,
encoder_attention_mask: torch.Tensor | None = None,
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
) -> BaseModelOutputWithPastAndCrossAttentions:
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
if input_ids is not None and not self.has_embeddings:
raise ValueError(
"Cannot process input_ids with has_embeddings=False (decoder has no embeddings when shared_embeddings=True)"
)
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:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
)
use_cache = False
if encoder_hidden_states is None:
raise ValueError("`encoder_hidden_states` must be given in decoder")
if (
past_key_values is not None
and isinstance(past_key_values.self_attention_cache, StaticCache)
and self.config._attn_implementation.startswith("flash_attention")
):
raise ValueError(
"FlashAttention with StaticCache is not supported because unwritten cache capacity cannot be masked safely."
)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# Build an implicit padding mask before creating a cache. In the
# shared-embedding path the outer model supplies this mask explicitly.
if attention_mask is None and past_key_values is None:
attention_mask = make_default_2d_attention_mask(input_ids, inputs_embeds, self.config.pad_token_id)
if not self.training and use_cache and past_key_values is None:
past_key_values = EncoderDecoderCache(
DynamicCache(config=self.config),
DynamicCache(),
)
if position_ids is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
position_ids = (
torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
).unsqueeze(0)
if not isinstance(self_attn_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"inputs_embeds": inputs_embeds,
"attention_mask": attention_mask,
"past_key_values": past_key_values.self_attention_cache if past_key_values is not None else None,
"position_ids": position_ids,
}
self_attn_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
}
if self.config.sliding_window is not None:
self_attn_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
if not isinstance(cross_attn_mask_mapping := encoder_attention_mask, dict):
cross_attn_mask_mapping = {
"full_attention": create_bidirectional_mask(
config=self.config,
inputs_embeds=inputs_embeds,
attention_mask=encoder_attention_mask,
encoder_hidden_states=encoder_hidden_states,
),
}
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
all_cross_attns = () if output_attentions else None
hidden_states = self.dropout(hidden_states)
for layer_module in self.layers[: self.config.num_hidden_layers]:
if output_hidden_states:
all_hidden_states += (hidden_states,)
layer_outputs = layer_module(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
attention_mask=self_attn_mask_mapping[layer_module.attention_type],
position_ids=position_ids,
past_key_value=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=cross_attn_mask_mapping["full_attention"],
**flash_attn_kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attns += (layer_outputs[1],)
all_cross_attns += (layer_outputs[2],)
hidden_states = self.norm(hidden_states)
if output_hidden_states:
all_hidden_states += (hidden_states,)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
hidden_states=all_hidden_states,
attentions=all_self_attns,
cross_attentions=all_cross_attns,
)
class AliceAIT5Model(AliceAIT5PreTrainedModel):
_no_split_modules = [AliceAIT5EncoderLayer.__name__, AliceAIT5DecoderLayer.__name__]
def __init__(self, config: AliceAIT5Config):
super().__init__(config)
if not config.is_encoder_decoder:
raise ValueError(
"AliceAIT5Model only support encoder-decoder modeling. Use `AliceAIT5EncoderModel` instead."
)
self.encoder = AliceAIT5Encoder(config.encoder)
self.decoder = AliceAIT5Decoder(config.decoder)
self.post_init()
def get_encoder(self):
return self.encoder
def get_decoder(self):
return self.decoder
def get_input_embeddings(self):
return self.encoder.get_input_embeddings()
def set_input_embeddings(self, new_embeddings):
return self.encoder.set_input_embeddings(new_embeddings)
@can_return_tuple
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.FloatTensor | None = None,
position_ids: torch.LongTensor | None = None,
decoder_input_ids: torch.LongTensor | None = None,
decoder_attention_mask: torch.BoolTensor | None = None,
decoder_position_ids: torch.LongTensor | None = None,
encoder_outputs: BaseModelOutput | None = None,
past_key_values: EncoderDecoderCache | None = None,
inputs_embeds: torch.Tensor | None = None,
decoder_inputs_embeds: torch.Tensor | None = None,
use_cache: bool | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
) -> Seq2SeqModelOutput:
"""Encode the input and decode the target, optionally reusing cached states."""
use_cache = use_cache if use_cache is not None else self.config.use_cache
# Canonicalize implicit masks while token IDs are still available.
# The same encoder mask is used for encoder self-attention and decoder
# cross-attention.
if attention_mask is None:
if input_ids is not None:
if self.config.encoder.pad_token_id is None:
raise ValueError("`pad_token_id` is required for padding information.")
attention_mask = input_ids.ne(self.config.encoder.pad_token_id).long()
elif encoder_outputs is None and inputs_embeds is not None:
attention_mask = torch.ones(
inputs_embeds.shape[:2],
dtype=torch.long,
device=inputs_embeds.device,
)
if decoder_attention_mask is None and past_key_values is None:
if decoder_input_ids is not None:
if self.config.decoder.pad_token_id is None:
raise ValueError("`pad_token_id` is required for padding information.")
decoder_attention_mask = decoder_input_ids.ne(self.config.decoder.pad_token_id).long()
elif decoder_inputs_embeds is not None:
decoder_attention_mask = torch.ones(
decoder_inputs_embeds.shape[:2],
dtype=torch.long,
device=decoder_inputs_embeds.device,
)
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
**flash_attn_kwargs,
)
else:
validate_encoder_attention_mask(attention_mask)
encoder_hidden_states = encoder_outputs.last_hidden_state
if encoder_hidden_states.shape[1] == 0:
raise ValueError("Each encoder sequence must contain at least one unmasked token.")
if (decoder_inputs_embeds is None) and self.config.shared_embeddings:
decoder_inputs_embeds = self.get_input_embeddings()(decoder_input_ids)
decoder_outputs = self.decoder(
input_ids=decoder_input_ids if not self.config.shared_embeddings else None,
attention_mask=decoder_attention_mask,
position_ids=decoder_position_ids,
inputs_embeds=decoder_inputs_embeds,
past_key_values=past_key_values,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
**flash_attn_kwargs,
)
return Seq2SeqModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
)
class AliceAIT5EncoderModel(AliceAIT5PreTrainedModel):
def __init__(self, config: AliceAIT5Config):
super().__init__(config)
if config.is_encoder_decoder:
raise ValueError("AliceAIT5EncoderModel only supports encoder-only model. Use `AliceAIT5Model` instead.")
self.encoder = self._build_encoder(config)
self.post_init()
def _build_encoder(self, config):
return AliceAIT5Encoder(config.encoder)
def get_input_embeddings(self):
return self.encoder.get_input_embeddings()
def set_input_embeddings(self, new_embeddings):
return self.encoder.set_input_embeddings(new_embeddings)
@can_return_tuple
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.FloatTensor | None = None,
position_ids: torch.LongTensor | None = None,
inputs_embeds: torch.Tensor | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
**flash_attn_kwargs: Unpack[FlashAttentionKwargs],
) -> BaseModelOutput:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
**flash_attn_kwargs,
)
return encoder_outputs
class AliceAIT5ForConditionalGeneration(AliceAIT5PreTrainedModel, GenerationMixin):
_no_split_modules = [AliceAIT5EncoderLayer.__name__, AliceAIT5DecoderLayer.__name__]
def __init__(self, config: AliceAIT5Config):
config.is_encoder_decoder = True
self._tied_weights_keys = {
"lm_head.out_proj.weight": (
"model.encoder.embed_tokens.weight"
if config.shared_embeddings
else "model.decoder.embed_tokens.weight"
)
}
super().__init__(config)
self.model = self._build_model(config)
self.vocab_size = config.encoder.vocab_size
self.lm_head = AliceAIT5LMHead(config.decoder.hidden_size, self.vocab_size, dtype=self.dtype)
self.loss_type = "ForMaskedLM"
self.post_init()
def _build_model(self, config):
return AliceAIT5Model(config)
def set_output_embeddings(self, new_embeddings):
self.lm_head.out_proj = new_embeddings
def get_output_embeddings(self):
return self.lm_head.out_proj
def get_encoder(self):
return self.model.encoder
def get_decoder(self):
return self.model.decoder
@can_return_tuple
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.FloatTensor | None = None,
position_ids: torch.LongTensor | None = None,
decoder_input_ids: torch.LongTensor | None = None,
decoder_attention_mask: torch.BoolTensor | None = None,
decoder_position_ids: torch.LongTensor | None = None,
encoder_outputs: BaseModelOutput | None = None,
past_key_values: EncoderDecoderCache | None = None,
inputs_embeds: torch.FloatTensor | None = None,
decoder_inputs_embeds: torch.FloatTensor | None = None,
labels: torch.LongTensor | None = None,
use_cache: bool | None = None,
output_attentions: bool | None = None,
output_hidden_states: bool | None = None,
logits_to_keep: int | torch.Tensor = 0,
**loss_kwargs,
) -> tuple[torch.FloatTensor] | Seq2SeqLMOutput:
"""Return decoder logits and optional cross-entropy loss.
Labels have shape ``[batch_size, target_length]``; ``-100`` is ignored.
When labels are supplied, all target logits are computed and decoder
inputs default to the labels shifted right by one position.
"""
if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = self._shift_right(labels)
decoder_outputs: Seq2SeqModelOutput = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
decoder_position_ids=decoder_position_ids,
encoder_outputs=encoder_outputs,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
**loss_kwargs,
)
hidden_states = decoder_outputs.last_hidden_state
# Loss needs every target position; generation may request only a suffix.
if labels is not None:
slice_indices = slice(None)
elif isinstance(logits_to_keep, int):
slice_indices = slice(-logits_to_keep, None)
else:
slice_indices = logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
decoder_config = self.get_decoder().config
if decoder_config.final_logit_softcapping is not None:
logits = logits / decoder_config.final_logit_softcapping
logits = torch.tanh(logits)
logits = logits * decoder_config.final_logit_softcapping
loss = None
if labels is not None:
# Decoder inputs are already shifted; labels stay aligned with logits.
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
return Seq2SeqLMOutput(
loss=loss,
logits=logits,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.decoder_hidden_states,
decoder_attentions=decoder_outputs.decoder_attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=decoder_outputs.encoder_last_hidden_state,
encoder_hidden_states=decoder_outputs.encoder_hidden_states,
encoder_attentions=decoder_outputs.encoder_attentions,
)
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
return self._shift_right(labels)
__all__ = [
"AliceAIT5Config",
"AliceAIT5ModuleConfig",
"AliceAIT5ForConditionalGeneration",
"AliceAIT5Model",
"AliceAIT5EncoderModel",
"AliceAIT5PreTrainedModel",
]