# Derived from PFN PLaMo; see docs/LICENSING.md. import enum import math import warnings from typing import Any, Dict, List, Literal, NamedTuple, Optional, Tuple, Union import torch from torch import nn from torch.nn import functional as F from transformers import GenerationMixin, PretrainedConfig, PreTrainedModel from transformers.cache_utils import DynamicCache from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from architecture.config import LuxferConfig, is_full_attn from layers.normalization import LuxferRMSNorm from embeddings.rotary import RotaryEmbedding, _rotary_pos_emb from embeddings.token import LuxferEmbedding from layers.mlp import MLP def _make_causal_mask( input_ids_shape: Tuple[int, int], dtype: torch.dtype, device: torch.device, seq_len: int, cache_position: torch.Tensor, ) -> torch.Tensor: """ Make a causal attention mask. Follows the logic in `LlamaModel._prepare_4d_causal_attention_mask_with_cache_position` https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L664 NOTE: seq_len (sequence_length) and tgt_len(target_length) are swapped in the original code. Our implementation: - seq_len: the length of the sequences which is being processed as well as which have been processed - tgt_len: the length of the sequences which is being processed Original (Llama) implementation: - sequence_length: "The sequence length being processed" - 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." """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, seq_len), float("-inf"), device=device) if tgt_len != 1: # TODO: is this necessary? mask = torch.triu(mask, diagonal=1) mask = torch.where(torch.arange(seq_len, device=device) > cache_position.reshape(-1, 1), mask, 0.0) mask = mask.to(dtype) return mask[None, None, :, :].expand(bsz, 1, tgt_len, seq_len) def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None) -> torch.Tensor: """ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. """ bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), float("-inf")) def swa_mask(q_len: int, kv_len: int, device: torch.device, window_size: int) -> torch.Tensor: max_len = max(q_len, kv_len) query_positions = torch.arange(max_len - q_len, max_len, device=device) key_positions = torch.arange(max_len - kv_len, max_len, device=device) mask = key_positions[None, :] > query_positions[:, None] - window_size mask &= key_positions[None, :] < query_positions[:, None] + window_size return mask class Attention(torch.nn.Module): def __init__(self, config: LuxferConfig, layer_idx: int) -> None: super().__init__() self.config = config self.layer_idx = layer_idx self.hidden_size = config.hidden_size head_dim = config.head_dim self.max_position_embeddings = config.max_position_embeddings self.q_num_heads = config.num_attention_heads self.qk_dim = self.v_dim = head_dim self.k_num_heads = self.v_num_heads = config.num_key_value_heads assert self.q_num_heads % self.k_num_heads == 0 self.n_group = self.q_num_heads // self.k_num_heads self.q_proj_dim = self.q_num_heads * self.qk_dim self.k_proj_dim = self.k_num_heads * self.qk_dim self.v_proj_dim = self.v_num_heads * self.v_dim self.qkv_proj = nn.Linear(self.hidden_size, self.q_proj_dim + self.k_proj_dim + self.v_proj_dim, bias=False) self.o_proj = nn.Linear(self.q_num_heads * self.v_dim, self.hidden_size, bias=False) self.q_norm = LuxferRMSNorm(self.qk_dim, eps=self.config.rms_norm_eps, offset=1.0) self.k_norm = LuxferRMSNorm(self.qk_dim, eps=self.config.rms_norm_eps, offset=1.0) self.full_attn = config.layer_types[layer_idx] == "full_attention" parameter = self.config.rope_parameters[config.layer_types[layer_idx]] self.rotary_emb = RotaryEmbedding( self.qk_dim, max_position_embeddings=self.config.max_position_embeddings, parameter=parameter ) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_states: Optional[DynamicCache] = None, output_attentions: bool = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[DynamicCache]]: bsz, q_len, _ = hidden_states.size() qkv = self.qkv_proj(hidden_states) query_states, key_states, value_states = torch.split( qkv, [self.q_proj_dim, self.k_proj_dim, self.v_proj_dim], dim=-1 ) query_states = query_states.view(bsz, q_len, self.q_num_heads, self.qk_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.k_num_heads, self.qk_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.v_num_heads, self.v_dim).transpose(1, 2) attn_dtype = query_states.dtype query_states = self.q_norm(query_states) key_states = self.k_norm(key_states) if past_states is not None: key_states, value_states = past_states.update(key_states, value_states, self.layer_idx) # NICT inference path: each cached key keeps its own position; the query # occupies the tail of the same local coordinate system after SWA cropping. kv_seq_len = key_states.shape[-2] key_position_ids = torch.arange(kv_seq_len, dtype=torch.long, device=hidden_states.device)[None] q_position_ids = key_position_ids[:, -query_states.shape[2] :] cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) query_states = _rotary_pos_emb(query_states, cos, sin, q_position_ids) key_states = _rotary_pos_emb(key_states, cos, sin, key_position_ids) # [bsz, nh, t, hd] query_states = query_states.to(attn_dtype) key_states = key_states.to(attn_dtype) value_states = value_states.to(attn_dtype) if attention_mask is not None and attention_mask.dtype != torch.bool: attention_mask = attention_mask.to(attn_dtype) if attention_mask is None: assert self.full_attn or key_states.shape[2] <= self.config.window_size + 1 attn_output = F.scaled_dot_product_attention( query_states, key_states, value_states, is_causal=True, enable_gqa=True ) else: if attention_mask.dtype == torch.bool: attention_mask = torch.where(attention_mask, torch.tensor(0.0, dtype=torch.float), float("-inf")) if len(attention_mask.shape) == 2: attention_mask = attention_mask[None, None] assert len(attention_mask.shape) == 4 if not self.full_attn: m_swa = swa_mask( query_states.shape[2], key_states.shape[2], query_states.device, self.config.window_size ) # `generate` function creates attention mask that does not consider sliding window m_swa = m_swa[None, None] attention_mask = attention_mask[:, :, -query_states.shape[2] :, -key_states.shape[2] :] attention_mask = torch.where(m_swa, attention_mask, float("-inf")) # like AttentionMaskConverter._unmask_unattended in huggingface.transfoermers, # we need to attend to all tokens in masked rows for `scaled_dot_product_attention` bool_mask = torch.logical_not(torch.isneginf(attention_mask)) valid_tokens = torch.any(bool_mask, dim=-1) # (..., q_len) attention_mask = torch.where(valid_tokens[..., None], attention_mask, float(0.0)) attn_output = F.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=attention_mask, enable_gqa=True, ) attn_output = attn_output.transpose(1, 2) attn_output = attn_output.reshape(bsz, q_len, self.q_num_heads * self.v_dim) attn_output = self.o_proj(attn_output) return attn_output, None, past_states