reyllama/DiffLlamav0_early
0
1from typing import Callable, List, Optional, Tuple, Union2import math3 4import torch5import torch.nn as nn6from transformers.models.llama import LlamaForCausalLM, LlamaConfig7from transformers.models.diffllama import DiffLlamaForCausalLM, DiffLlamaConfig8 9from transformers.utils import logging10from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS11 12logger = logging.get_logger(__name__)13 14class DiffLlamaForCausalLMv0(DiffLlamaForCausalLM):15 16 def __init__(self, config: LlamaConfig):17 super().__init__(config)18 19 for layer_i, layer in enumerate(self.model.layers):20 21 hidden_dim = config.hidden_size22 n_heads = config.num_attention_heads23 depth = layer_i # or pass 024 25 layer.self_attn = DiffLlamaSdpaAttention(26 config, layer_idx=layer_i27 )28 29 print("# Initializing GroupNorm-free DiffLlama")30 31def lambda_init_fn(layer_idx):32 return 0.8 - 0.6 * math.exp(-0.3 * layer_idx)33 34class DiffLlamaAttention(nn.Module):35 """Multi-headed attention from 'Attention Is All You Need' paper"""36 37 def __init__(self, config: DiffLlamaConfig, layer_idx: Optional[int] = None):38 super().__init__()39 self.config = config40 self.layer_idx = layer_idx41 if layer_idx is None:42 logger.warning_once(43 f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "44 "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "45 "when creating this class."46 )47 48 self.attention_dropout = config.attention_dropout49 self.hidden_size = config.hidden_size50 self.num_heads = config.num_attention_heads51 self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)52 self.num_key_value_heads = config.num_key_value_heads53 self.num_key_value_groups = self.num_heads // self.num_key_value_heads54 # under this are not used55 self.max_position_embeddings = config.max_position_embeddings56 self.rope_theta = config.rope_theta57 self.is_causal = True58 59 self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)60 self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)61 self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)62 self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)63 64 self.lambda_init = lambda_init_fn(layer_idx)65 self.lambda_q1 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))66 self.lambda_k1 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))67 self.lambda_q2 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))68 self.lambda_k2 = nn.Parameter(torch.normal(0, config.lambda_std_dev, size=(self.head_dim,)))69 self.groupnorm = nn.RMSNorm(2 * self.head_dim, eps=config.rms_norm_eps, elementwise_affine=False)70 71 # self.collected_attn_logits = None72 73 def _store_attn_logits(self, attn_logits):74 top_vals, _ = torch.topk(attn_logits.reshape(-1), k=5)75 self.collected_attn_logits = top_vals.detach().cpu().tolist()76 77 def forward(78 self,79 hidden_states,80 position_embeddings,81 attention_mask,82 position_ids,83 past_key_value,84 output_attentions = False,85 use_cache = False,86 cache_position = None,87 **kwargs,88 ):89 bsz, target_len, _ = hidden_states.size()90 q_len = target_len91 92 query_states = self.q_proj(hidden_states)93 key_states = self.k_proj(hidden_states)94 value_states = self.v_proj(hidden_states)95 96 query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)97 key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)98 value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)99 100 cos, sin = position_embeddings101 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)102 103 if past_key_value is not None:104 # sin and cos are specific to RoPE models; cache_position needed for the static cache105 cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}106 key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)107 108 key_states = repeat_kv(key_states, self.num_key_value_groups)109 value_states = repeat_kv(value_states, self.num_key_value_groups)110 value_states = torch.cat(torch.chunk(value_states, 2, dim=1), dim=-1)111 value_states = value_states.repeat(1, 2, 1, 1)112 113 attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)114 115 if attention_mask is not None: # no matter the length, we just slice it116 causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]117 attn_weights = attn_weights + causal_mask118 119 # upcast attention to fp32120 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)121 attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)122 lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(123 query_states.dtype124 )125 lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(126 query_states.dtype127 )128 lambda_full = lambda_1 - lambda_2 + self.lambda_init129 130 attn_output = torch.matmul(attn_weights, value_states)131 attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=1)132 133 attn_output = attn_output1 - lambda_full * attn_output2134 attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output)135 attn_output = attn_output.transpose(1, 2).contiguous()136 attn_output = attn_output.reshape(bsz, q_len, -1)137 138 attn_output = self.o_proj(attn_output)139 140 if not output_attentions:141 attn_weights = None142 143 return attn_output, attn_weights144 145class DiffLlamaSdpaAttention(DiffLlamaAttention):146 """147 DiffLlama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from148 `DiffLlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to149 SDPA API.150 """151 # Adapted from DiffLlamaAttention.forward152 def forward(153 self,154 hidden_states: torch.Tensor,155 position_embeddings: Tuple[torch.Tensor, torch.Tensor],156 attention_mask: Optional[torch.Tensor] = None,157 position_ids: Optional[torch.LongTensor] = None,158 past_key_value = None,159 output_attentions: bool = False,160 use_cache: bool = False,161 cache_position: Optional[torch.LongTensor] = None,162 **kwargs,163 ):164 if output_attentions:165 # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.166 logger.warning_once(167 "DiffLlamaModel is using DiffLlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "168 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'169 )170 return super().forward(171 hidden_states=hidden_states,172 attention_mask=attention_mask,173 position_ids=position_ids,174 past_key_value=past_key_value,175 output_attentions=output_attentions,176 use_cache=use_cache,177 cache_position=cache_position,178 position_embeddings=position_embeddings,179 )180 181 bsz, q_len, _ = hidden_states.size()182 183 query_states = self.q_proj(hidden_states)184 key_states = self.k_proj(hidden_states)185 value_states = self.v_proj(hidden_states)186 187 query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)188 key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)189 value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)190 191 cos, sin = position_embeddings192 query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)193 194 if past_key_value is not None:195 # sin and cos are specific to RoPE models; cache_position needed for the static cache196 cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}197 key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)198 199 key_states = repeat_kv(key_states, self.num_key_value_groups)200 value_states = repeat_kv(value_states, self.num_key_value_groups)201 value_states = torch.cat(torch.chunk(value_states, 2, dim=1), dim=-1)202 value_states = value_states.repeat(1, 2, 1, 1)203 204 causal_mask = attention_mask205 if attention_mask is not None:206 causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]207 208 # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,209 # Reference: https://github.com/pytorch/pytorch/issues/112577.210 if query_states.device.type == "cuda" and causal_mask is not None:211 query_states = query_states.contiguous()212 key_states = key_states.contiguous()213 value_states = value_states.contiguous()214 215 # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment216 # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.217 is_causal = True if causal_mask is None and q_len > 1 else False218 219 attn_output = torch.nn.functional.scaled_dot_product_attention(220 query_states,221 key_states,222 value_states,223 attn_mask=causal_mask,224 dropout_p=self.attention_dropout if self.training else 0.0,225 is_causal=is_causal,226 )227 228 attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=1)229 230 lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to(231 query_states.dtype232 )233 lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to(234 query_states.dtype235 )236 lambda_full = lambda_1 - lambda_2 + self.lambda_init237 238 attn_output = attn_output1 - lambda_full * attn_output2239 # attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output) # FIXME!!240 attn_output = attn_output.transpose(1, 2).contiguous()241 attn_output = attn_output.view(bsz, q_len, -1)242 attn_output = self.o_proj(attn_output)243 244 return attn_output, None245 246def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:247 """248 This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,249 num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)250 """251 batch, num_key_value_heads, slen, head_dim = hidden_states.shape252 if n_rep == 1:253 return hidden_states254 hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)255 return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)256 257 258def eager_attention_forward(259 module: nn.Module,260 query: torch.Tensor,261 key: torch.Tensor,262 value: torch.Tensor,263 attention_mask: Optional[torch.Tensor],264 scaling: float,265 dropout: float = 0.0,266 **kwargs,267):268 key_states = repeat_kv(key, module.num_key_value_groups)269 value_states = repeat_kv(value, module.num_key_value_groups)270 271 temperature = kwargs.get("temperature", 1.0)272 273 attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling / temperature274 if attention_mask is not None:275 causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]276 attn_weights = attn_weights + causal_mask277 278 attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)279 attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)280 attn_output = torch.matmul(attn_weights, value_states)281 attn_output = attn_output.transpose(1, 2).contiguous()282 283 return attn_output, attn_weights284 285class LlamaRMSNorm(nn.Module):286 def __init__(self, hidden_size, eps=1e-6):287 """288 LlamaRMSNorm is equivalent to T5LayerNorm289 """290 super().__init__()291 self.weight = nn.Parameter(torch.ones(hidden_size))292 self.variance_epsilon = eps293 294 def forward(self, hidden_states):295 input_dtype = hidden_states.dtype296 hidden_states = hidden_states.to(torch.float32)297 variance = hidden_states.pow(2).mean(-1, keepdim=True)298 hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)299 return self.weight * hidden_states.to(input_dtype)300 301 def extra_repr(self):302 return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"303 304 305 306class LlamaRotaryEmbedding(nn.Module):307 def __init__(self, config: LlamaConfig, device=None):308 super().__init__()309 # BC: "rope_type" was originally "type"310 if hasattr(config, "rope_scaling") and config.rope_scaling is not None:311 self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))312 else:313 self.rope_type = "default"314 self.max_seq_len_cached = config.max_position_embeddings315 self.original_max_seq_len = config.max_position_embeddings316 317 self.config = config318 self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]319 320 inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)321 self.register_buffer("inv_freq", inv_freq, persistent=False)322 self.original_inv_freq = self.inv_freq323 324 def _dynamic_frequency_update(self, position_ids, device):325 """326 dynamic RoPE layers should recompute `inv_freq` in the following situations:327 1 - growing beyond the cached sequence length (allow scaling)328 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)329 """330 seq_len = torch.max(position_ids) + 1331 if seq_len > self.max_seq_len_cached: # growth332 inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)333 self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation334 self.max_seq_len_cached = seq_len335 336 if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset337 # This .to() is needed if the model has been moved to a device after being initialized (because338 # the buffer is automatically moved, but not the original copy)339 self.original_inv_freq = self.original_inv_freq.to(device)340 self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)341 self.max_seq_len_cached = self.original_max_seq_len342 343 @torch.no_grad()344 def forward(self, x, position_ids):345 if "dynamic" in self.rope_type:346 self._dynamic_frequency_update(position_ids, device=x.device)347 348 # Core RoPE block349 inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)350 position_ids_expanded = position_ids[:, None, :].float()351 # Force float32 (see https://github.com/huggingface/transformers/pull/29285)352 device_type = x.device.type353 device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"354 with torch.autocast(device_type=device_type, enabled=False):355 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)356 emb = torch.cat((freqs, freqs), dim=-1)357 cos = emb.cos()358 sin = emb.sin()359 360 # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention361 cos = cos * self.attention_scaling362 sin = sin * self.attention_scaling363 364 return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)365 366 367def rotate_half(x):368 """Rotates half the hidden dims of the input."""369 x1 = x[..., : x.shape[-1] // 2]370 x2 = x[..., x.shape[-1] // 2 :]371 return torch.cat((-x2, x1), dim=-1)372 373 374def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):375 """Applies Rotary Position Embedding to the query and key tensors.376 377 Args:378 q (`torch.Tensor`): The query tensor.379 k (`torch.Tensor`): The key tensor.380 cos (`torch.Tensor`): The cosine part of the rotary embedding.381 sin (`torch.Tensor`): The sine part of the rotary embedding.382 position_ids (`torch.Tensor`, *optional*):383 Deprecated and unused.384 unsqueeze_dim (`int`, *optional*, defaults to 1):385 The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and386 sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note387 that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and388 k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes389 cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have390 the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.391 Returns:392 `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.393 """394 cos = cos.unsqueeze(unsqueeze_dim)395 sin = sin.unsqueeze(unsqueeze_dim)396 q_embed = (q * cos) + (rotate_half(q) * sin)397 k_embed = (k * cos) + (rotate_half(k) * sin)398 return q_embed, k_embed399 400 401class LlamaMLP(nn.Module):402 def __init__(self, config):403 super().__init__()404 self.config = config405 self.hidden_size = config.hidden_size406 self.intermediate_size = config.intermediate_size407 self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)408 self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)409 self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)410 self.act_fn = ACT2FN[config.hidden_act]411 412 def forward(self, x):413 down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))414 return down_proj