Opt.Gear-1B / modeling_gear.py
kyw96's picture
Update modeling_gear.py
9a4c308 verified
Raw
History Blame Contribute Delete
44.9 kB
from collections.abc import Callable
from typing import Optional, Union, Any
import math
import copy
import torch
import torch.nn.functional as F
from torch import nn
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.generation import GenerationMixin
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
from transformers.modeling_layers import (
GenericForQuestionAnswering,
GenericForSequenceClassification,
GenericForTokenClassification,
GradientCheckpointingLayer,
)
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
from transformers.utils.generic import check_model_inputs
from transformers.utils.import_utils import is_causal_conv1d_available
from .configuration_gear import GearConfig
if is_causal_conv1d_available():
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
else:
causal_conv1d_fn, causal_conv1d_update = None, None
kernel_modules = (causal_conv1d_fn, causal_conv1d_update)
is_fast_path_available = all(kernel_modules)
class GearHybridKVConvCache:
"""
Attention and conv cache for Gear.
It stores the Key and Value states as a list of tensors, one for each layer.
Attention layer cache shape: `[batch_size, num_heads, seq_len, head_dim]`.
Key-Value Conv layer cache shape: `[batch_size, hidden_size, L_cache-1]`.
"""
# Override @property existing in Cache
max_batch_size = None
is_compileable = False
key_cache = None
value_cache = None
def __init__(
self,
config: GearConfig,
max_batch_size: int,
dtype: torch.dtype = torch.float32,
device: Union[torch.device, str, None] = None,
):
self.key_cache = []
self.value_cache = []
self.max_batch_size = max_batch_size
self.layer_types = config.layer_types
self.first_attention_layer = self.layer_types.index("full_attention")
self.conv_L_cache = config.conv_L_cache
self._dtype = dtype
self.key_conv_cache: list[torch.Tensor] = []
self.value_conv_cache: list[torch.Tensor] = []
device = torch.device(device) if device is not None else None
for _ in range(config.num_hidden_layers):
key_conv_state = torch.zeros(
self.max_batch_size,
config.num_key_value_heads * config.head_dim,
self.conv_L_cache,
dtype=self._dtype,
device=device,
)
value_conv_state = torch.zeros_like(key_conv_state)
torch._dynamo.mark_static_address(key_conv_state)
torch._dynamo.mark_static_address(value_conv_state)
self.key_conv_cache.append(key_conv_state)
self.value_conv_cache.append(value_conv_state)
def update(
self,
key_states: torch.Tensor,
value_states: torch.Tensor,
layer_idx: int,
cache_kwargs: Optional[dict[str, Any]] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Updates the cache with the new `key_states` and `value_states` for the layer `layer_idx`.
Parameters:
key_states (`torch.Tensor`):
The new key states to cache.
value_states (`torch.Tensor`):
The new value states to cache.
layer_idx (`int`):
The index of the layer to cache the states for.
cache_kwargs (`Dict[str, Any]`, `optional`):
Additional arguments for the cache subclass. No additional arguments are used in `DynamicCache`.
Return:
A tuple containing the updated key and value states.
"""
# Update the cache
if key_states is not None:
if len(self.key_cache) <= layer_idx:
# There may be skipped layers, fill them with empty lists
for _ in range(len(self.key_cache), layer_idx):
self.key_cache.append(torch.tensor([]))
self.value_cache.append(torch.tensor([]))
self.key_cache.append(key_states)
self.value_cache.append(value_states)
elif (
not self.key_cache[layer_idx].numel() # prefers not t.numel() to len(t) == 0 to export the model
): # fills previously skipped layers; checking for tensor causes errors
self.key_cache[layer_idx] = key_states
self.value_cache[layer_idx] = value_states
else:
self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
return self.key_cache[layer_idx], self.value_cache[layer_idx]
def reorder_cache(self, beam_idx: torch.LongTensor):
"""Reorders the cache for beam search, given the selected beam indices."""
for layer_idx in range(len(self.key_cache)):
device = self.key_cache[layer_idx].device
self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
device = self.value_cache[layer_idx].device
self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
device = self.key_conv_cache[layer_idx].device
self.key_conv_cache[layer_idx] = self.key_conv_cache[layer_idx].index_select(0, beam_idx.to(device))
device = self.value_conv_cache[layer_idx].device
self.value_conv_cache[layer_idx] = self.value_conv_cache[layer_idx].index_select(0, beam_idx.to(device))
def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
# take any layer that contains cache and not empty tensor
layer_idx = self.first_attention_layer if self.layer_types[layer_idx] != "full_attention" else layer_idx
if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
return 0
return self.key_cache[layer_idx].shape[-2]
def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
"""
Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
the given layer at `layer_idx`.
The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns (i.e. sliding_window, chunk_size),
for each layer.
"""
full_mask_kv_offset = 0
query_length = cache_position.shape[0]
past_seen_tokens = self.get_seq_length()
kv_length = query_length + past_seen_tokens
return kv_length, full_mask_kv_offset
def crop(self, max_length: int):
"""Crop the cache to the given length"""
if max_length < 0:
max_length = self.get_seq_length() - abs(max_length)
if self.get_seq_length() <= max_length:
return
for idx in range(len(self.key_cache)):
if self.key_cache[idx].numel():
self.key_cache[idx] = self.key_cache[idx][..., :max_length, :]
self.value_cache[idx] = self.value_cache[idx][..., :max_length, :]
def __len__(self) -> int:
return len(self.key_cache)
def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
return self.key_cache[layer_idx], self.value_cache[layer_idx]
def reset(self):
for layer_idx in range(len(self.key_conv_cache)):
self.key_conv_cache[layer_idx].zero_()
self.value_conv_cache[layer_idx].zero_()
class GearTextScaledWordEmbedding(nn.Embedding):
"""
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: float = 1.0):
super().__init__(num_embeddings, embedding_dim, padding_idx)
self.register_buffer("embed_scale", torch.tensor(embed_scale), persistent=False)
def forward(self, input_ids: torch.Tensor):
return super().forward(input_ids) * self.embed_scale.to(self.weight.dtype)
class GearRMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
output = output * (1.0 + self.weight.float())
return output.type_as(x)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.eps}"
class GearRMSNormGated(nn.Module):
def __init__(self, config, hidden_size, eps=1e-6, **kwargs):
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.eps = eps
self.act_fn = ACT2FN[config.hidden_activation]
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x, gate=None):
# Norm before gate
output = self._norm(x.float())
output = output * (1.0 + self.weight.float())
output = output * self.act_fn(gate.float())
return output.type_as(x)
class GearMLP(nn.Module):
def __init__(self, config: GearConfig):
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_activation]
def forward(self, x):
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
class GearRotaryEmbedding(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: GearConfig, device=None):
super().__init__()
# BC: "rope_type" was originally "type"
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
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
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
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)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
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: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
dropout: float = 0.0,
scaling: Optional[float] = None,
softcap: Optional[float] = 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: # no matter the length, we just slice it
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
# upcast attention to fp32
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
class GearAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: GearConfig, layer_idx: int):
super().__init__()
self.is_sliding = config.layer_types[layer_idx] == "sliding_attention"
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 = not self.config.use_bidirectional_attention
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 self.is_sliding else None
self.q_norm = GearRMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
self.k_norm = GearRMSNorm(dim=config.head_dim, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: torch.Tensor,
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
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)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_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)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
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,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
class GearConvKVGatedMixer(nn.Module):
"""Convolutional Key-Value Gated Mixer is using Key-Value Convolution State and Sigmoid Gating"""
def __init__(
self,
config: GearConfig,
layer_idx: int,
):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.hidden_size = config.hidden_size
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.L_cache = config.conv_L_cache
self.bias = config.attention_bias
# self.adaptive_scaling = nn.Parameter(torch.tensor(1.0))
self.key_conv = nn.Conv1d(
in_channels=config.num_key_value_heads * self.head_dim,
out_channels=config.num_key_value_heads * self.head_dim,
kernel_size=self.L_cache,
groups=config.num_key_value_heads * self.head_dim,
bias=self.bias,
padding=self.L_cache - 1,
)
self.value_conv = nn.Conv1d(
in_channels=config.num_key_value_heads * self.head_dim,
out_channels=config.num_key_value_heads * self.head_dim,
kernel_size=self.L_cache,
groups=config.num_key_value_heads * self.head_dim,
bias=self.bias,
padding=self.L_cache - 1,
)
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=self.bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=self.bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=self.bias
)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=self.bias)
self.q_norm = GearRMSNorm(dim=self.head_dim, eps=config.rms_norm_eps)
self.k_norm = GearRMSNorm(dim=self.head_dim, eps=config.rms_norm_eps)
def apply_mask_to_padding_states(self, hidden_states, attention_mask):
"""
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
"""
# NOTE: attention mask is a 2D boolean tensor
if hidden_states.shape[1] == 1:
return hidden_states
if attention_mask is not None and attention_mask.dim() == 2 and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
dtype = hidden_states.dtype
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
return hidden_states
def expand_kv(self, kv_states):
# kv_states: [B, S, kv_heads * head_dim]
B, S, _ = kv_states.shape
kv_states = kv_states.view(B, S, self.config.num_key_value_heads, self.head_dim)
kv_states = kv_states[:, :, :, None, :].expand(
B,
S,
self.config.num_key_value_heads,
self.num_key_value_groups,
self.head_dim,
)
return kv_states.reshape(B, S, self.config.num_attention_heads * self.head_dim)
def cuda_kernels_forward(
self,
hidden_states: torch.Tensor,
past_key_values: GearHybridKVConvCache | None = None,
cache_position: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
hidden_states = self.apply_mask_to_padding_states(hidden_states, attention_mask)
query = self.q_proj(hidden_states).view(hidden_shape)
key = self.k_proj(hidden_states).view(hidden_shape)
value = self.v_proj(hidden_states).transpose(-1, -2)
query = self.q_norm(query).reshape(*input_shape, -1)
key = self.k_norm(key).reshape(*input_shape, -1).transpose(-1, -2)
key_conv_weights = self.key_conv.weight.view(self.key_conv.weight.size(0), self.key_conv.weight.size(2))
value_conv_weights = self.value_conv.weight.view(self.value_conv.weight.size(0), self.value_conv.weight.size(2))
if past_key_values is not None and cache_position[0] > 0:
key = causal_conv1d_update(
key.squeeze(-1),
past_key_values.key_conv_cache[self.layer_idx],
key_conv_weights,
self.key_conv.bias,
None,
)
value = causal_conv1d_update(
value.squeeze(-1),
past_key_values.value_conv_cache[self.layer_idx],
value_conv_weights,
self.value_conv.bias,
None,
)
key, value = key.unsqueeze(-1), value.unsqueeze(-1)
else:
if past_key_values is not None:
key_conv_state = nn.functional.pad(key, (self.L_cache - key.shape[-1], 0))
past_key_values.key_conv_cache[self.layer_idx].copy_(key_conv_state)
value_conv_state = nn.functional.pad(value, (self.L_cache - value.shape[-1], 0))
past_key_values.value_conv_cache[self.layer_idx].copy_(value_conv_state)
key = causal_conv1d_fn(key, key_conv_weights, self.key_conv.bias, activation=None)
value = causal_conv1d_fn(value, value_conv_weights, self.value_conv.bias, activation=None)
key = self.expand_kv(key.transpose(-1, -2))
value = self.expand_kv(value.transpose(-1, -2))
mixer_weights = torch.sigmoid(query * key)
core_mixer_out = mixer_weights * value
core_mixer_out = self.o_proj(core_mixer_out)
return core_mixer_out
def torch_native_forward(
self,
hidden_states: torch.Tensor,
past_key_values: GearHybridKVConvCache | None = None,
cache_position: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
):
seqlen = hidden_states.shape[1]
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
hidden_states = self.apply_mask_to_padding_states(hidden_states, attention_mask)
query = self.q_proj(hidden_states).view(hidden_shape)
key = self.k_proj(hidden_states).view(hidden_shape)
value = self.v_proj(hidden_states).transpose(-1, -2)
query = self.q_norm(query).reshape(*input_shape, -1)
key = self.k_norm(key).reshape(*input_shape, -1).transpose(-1, -2)
# NOTE: This native path is kept numerically close to the
# causal_conv1d fast path:
# - the new token always goes to the *last* cache slot (matching
# causal_conv1d_update semantics) instead of the previous
# clamped-cache_position behavior that misplaced the first
# decode steps.
# - depthwise reductions are accumulated in fp32 then cast back,
# matching the CUDA kernel which also accumulates in fp32.
if past_key_values is not None and cache_position[0] > 0:
key_conv_state = past_key_values.key_conv_cache[self.layer_idx]
key_conv_state = key_conv_state.roll(shifts=-1, dims=-1)
key_conv_state[:, :, -1] = key.squeeze(-1).to(
device=key_conv_state.device, dtype=key_conv_state.dtype
)
past_key_values.key_conv_cache[self.layer_idx].copy_(key_conv_state)
key_fp32 = (
key_conv_state.to(key.device, dtype=torch.float32)
* self.key_conv.weight[:, 0, :].to(torch.float32)
).sum(dim=-1)
key = key_fp32.to(self.k_proj.weight.dtype)
value_conv_state = past_key_values.value_conv_cache[self.layer_idx]
value_conv_state = value_conv_state.roll(shifts=-1, dims=-1)
value_conv_state[:, :, -1] = value.squeeze(-1).to(
device=value_conv_state.device, dtype=value_conv_state.dtype
)
past_key_values.value_conv_cache[self.layer_idx].copy_(value_conv_state)
value_fp32 = (
value_conv_state.to(value.device, dtype=torch.float32)
* self.value_conv.weight[:, 0, :].to(torch.float32)
).sum(dim=-1)
value = value_fp32.to(self.v_proj.weight.dtype)
if self.bias and self.key_conv.bias is not None:
key = key + self.key_conv.bias
if self.bias and self.value_conv.bias is not None:
value = value + self.value_conv.bias
key, value = key.unsqueeze(-1), value.unsqueeze(-1)
else:
if past_key_values is not None:
key_conv_state = nn.functional.pad(key, (self.L_cache - key.shape[-1], 0))
past_key_values.key_conv_cache[self.layer_idx].copy_(key_conv_state)
value_conv_state = nn.functional.pad(value, (self.L_cache - value.shape[-1], 0))
past_key_values.value_conv_cache[self.layer_idx].copy_(value_conv_state)
# Run conv in fp32 to match the CUDA kernel's accumulation
# precision; cast result back to the parameter dtype.
orig_dtype = self.k_proj.weight.dtype
key_fp = nn.functional.conv1d(
key.to(torch.float32),
self.key_conv.weight.to(torch.float32),
bias=(self.key_conv.bias.to(torch.float32)
if self.key_conv.bias is not None else None),
stride=self.key_conv.stride,
padding=self.key_conv.padding,
dilation=self.key_conv.dilation,
groups=self.key_conv.groups,
)
value_fp = nn.functional.conv1d(
value.to(torch.float32),
self.value_conv.weight.to(torch.float32),
bias=(self.value_conv.bias.to(torch.float32)
if self.value_conv.bias is not None else None),
stride=self.value_conv.stride,
padding=self.value_conv.padding,
dilation=self.value_conv.dilation,
groups=self.value_conv.groups,
)
key = key_fp[..., :seqlen].to(orig_dtype)
value = value_fp[..., :seqlen].to(orig_dtype)
key = self.expand_kv(key.transpose(-1, -2))
value = self.expand_kv(value.transpose(-1, -2))
mixer_weights = torch.sigmoid(query * key)
core_mixer_out = mixer_weights * value
core_mixer_out = self.o_proj(core_mixer_out)
return core_mixer_out
def forward(
self,
hidden_states: torch.Tensor,
past_key_values: Cache | None = None,
cache_position: torch.LongTensor = None,
attention_mask: torch.Tensor | None = None,
):
if is_fast_path_available:
return self.cuda_kernels_forward(hidden_states, past_key_values, cache_position, attention_mask)
return self.torch_native_forward(hidden_states, past_key_values, cache_position, attention_mask)
class GearDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: GearConfig, layer_idx: int):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.layer_idx = layer_idx
self.attention_type = config.layer_types[layer_idx]
if self.attention_type == "conv_mixer":
self.local_mixer = GearConvKVGatedMixer(config=config, layer_idx=layer_idx)
else:
self.self_attn = GearAttention(config=config, layer_idx=layer_idx)
self.mlp = GearMLP(config)
self.input_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
self.pre_feedforward_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
self.post_feedforward_layernorm = GearRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings_global: torch.Tensor,
position_embeddings_local: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
**kwargs,
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
if self.attention_type == "conv_mixer":
hidden_states = self.local_mixer(
hidden_states=hidden_states,
past_key_values=past_key_values,
cache_position=cache_position,
attention_mask=attention_mask,
)
else:
# apply global RoPE to non-sliding layer only
if self.self_attn.is_sliding:
position_embeddings = position_embeddings_local
else:
position_embeddings = position_embeddings_global
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
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,
**kwargs,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.pre_feedforward_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_feedforward_layernorm(hidden_states)
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
@auto_docstring
class GearPreTrainedModel(PreTrainedModel):
config: GearConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["GearDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": GearDecoderLayer,
"attentions": GearAttention,
"conv_mixer": GearConvKVGatedMixer,
}
@auto_docstring
class GearModel(GearPreTrainedModel):
config: GearConfig
def __init__(self, config: GearConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = GearTextScaledWordEmbedding(
config.vocab_size, config.hidden_size, self.padding_idx, embed_scale=self.config.hidden_size**0.5
)
self.layers = nn.ModuleList(
[GearDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = GearRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = GearRotaryEmbedding(config=config)
self.gradient_checkpointing = False
config = copy.deepcopy(config)
config.rope_theta = config.rope_local_base_freq
config.rope_scaling = {"rope_type": "default"}
self.rotary_emb_local = GearRotaryEmbedding(config=config)
# Initialize weights and apply final processing
self.post_init()
# @check_model_inputs()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> 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
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 inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# if use_cache and past_key_values is None and not self.training:
# batch_size = inputs_embeds.shape[0]
# past_key_values = GearHybridKVConvCache(config=self.config, max_batch_size=batch_size, dtype=self.dtype, device=self.device)
if use_cache and not self.training:
if past_key_values is None or type(past_key_values).__name__ == "DynamicCache":
batch_size = inputs_embeds.shape[0]
past_key_values = GearHybridKVConvCache(
config=self.config,
max_batch_size=batch_size,
dtype=self.dtype,
device=self.device
)
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.unsqueeze(0)
# It may already have been prepared by e.g. `generate`
if not isinstance(causal_mask_mapping := attention_mask, dict):
# Prepare mask arguments
mask_kwargs = {
"config": self.config,
"input_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
sliding_mask_kwargs = mask_kwargs.copy()
if self.config.use_bidirectional_attention:
mask_kwargs["or_mask_function"] = lambda *args: torch.tensor(True, dtype=torch.bool)
sliding_mask_kwargs["or_mask_function"] = _bidirectional_window_overlay(self.config.sliding_window)
# Create the masks
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**sliding_mask_kwargs),
"conv_mixer": attention_mask if inputs_embeds.shape[-1] != 1 else None,
}
# embed positions
hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers
position_embeddings_global = self.rotary_emb(hidden_states, position_ids)
position_embeddings_local = self.rotary_emb_local(hidden_states, position_ids)
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
if output_hidden_states:
all_hidden_states += (hidden_states,)
layer_outputs = decoder_layer(
hidden_states,
position_embeddings_global=position_embeddings_global,
position_embeddings_local=position_embeddings_local,
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
position_ids=position_ids,
past_key_values=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attns += (layer_outputs[1],)
hidden_states = self.norm(hidden_states)
if output_hidden_states:
all_hidden_states += (hidden_states,)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
hidden_states=all_hidden_states,
attentions=all_self_attns,
)
@auto_docstring
class GearForCausalLM(GearPreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
config: GearConfig
def __init__(self, config: GearConfig):
super().__init__(config)
self.model = GearModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs,
) -> CausalLMOutputWithPast:
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
)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# 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, :])
# if self.config.final_logit_softcapping is not None:
# logits = logits / self.config.final_logit_softcapping
# logits = torch.tanh(logits)
# logits = logits * self.config.final_logit_softcapping
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class GearForSequenceClassification(GenericForSequenceClassification, GearPreTrainedModel):
pass
class GearForTokenClassification(GenericForTokenClassification, GearPreTrainedModel):
pass
class GearForQuestionAnswering(GenericForQuestionAnswering, GearPreTrainedModel):
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
__all__ = [
"GearForCausalLM",
"GearForQuestionAnswering",
"GearPreTrainedModel",
"GearModel",
"GearForSequenceClassification",
"GearForTokenClassification",
]