kz919 commited on
Commit
8eaa725
1 Parent(s): 5138b9d

Update modeling_sliding_llama.py

Browse files
Files changed (1) hide show
  1. modeling_sliding_llama.py +29 -303
modeling_sliding_llama.py CHANGED
@@ -29,7 +29,6 @@ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
  from transformers.activations import ACT2FN
30
  from transformers.cache_utils import Cache, DynamicCache, StaticCache
31
  from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
- from transformers.modeling_flash_attention_utils import _flash_attention_forward
33
  from transformers.modeling_outputs import (
34
  BaseModelOutputWithPast,
35
  CausalLMOutputWithPast,
@@ -47,13 +46,25 @@ from transformers.utils import (
47
  logging,
48
  replace_return_docstrings,
49
  )
 
50
  from configuration_sliding_llama import LlamaConfig
51
-
52
 
53
  logger = logging.get_logger(__name__)
54
 
55
  _CONFIG_FOR_DOC = "LlamaConfig"
56
 
 
 
 
 
 
 
 
 
 
 
 
57
  class LlamaRMSNorm(nn.Module):
58
  def __init__(self, hidden_size, eps=1e-6):
59
  """
@@ -267,43 +278,11 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
267
  return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
268
 
269
 
270
- class LlamaAttention(nn.Module):
271
  """Multi-headed attention from 'Attention Is All You Need' paper"""
272
 
273
- def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
274
- super().__init__()
275
- self.config = config
276
- self.layer_idx = layer_idx
277
- if layer_idx is None:
278
- logger.warning_once(
279
- f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
280
- "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
281
- "when creating this class."
282
- )
283
-
284
- self.attention_dropout = config.attention_dropout
285
- self.hidden_size = config.hidden_size
286
- self.num_heads = config.num_attention_heads
287
- self.head_dim = self.hidden_size // self.num_heads
288
- self.num_key_value_heads = config.num_key_value_heads
289
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
290
- self.max_position_embeddings = config.max_position_embeddings
291
- self.rope_theta = config.rope_theta
292
- self.is_causal = True
293
-
294
- if (self.head_dim * self.num_heads) != self.hidden_size:
295
- raise ValueError(
296
- f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
297
- f" and `num_heads`: {self.num_heads})."
298
- )
299
-
300
- self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
301
- self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
302
- self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
303
- self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
304
-
305
- # TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the decoder layers)
306
- self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
307
 
308
  def forward(
309
  self,
@@ -365,16 +344,18 @@ class LlamaAttention(nn.Module):
365
  key_states = repeat_kv(key_states, self.num_key_value_groups)
366
  value_states = repeat_kv(value_states, self.num_key_value_groups)
367
 
368
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
369
-
370
- if attention_mask is not None: # no matter the length, we just slice it
371
- causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
372
- attn_weights = attn_weights + causal_mask
373
-
374
- # upcast attention to fp32
375
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
376
- attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
377
- attn_output = torch.matmul(attn_weights, value_states)
 
 
378
 
379
  if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
380
  raise ValueError(
@@ -398,263 +379,8 @@ class LlamaAttention(nn.Module):
398
 
399
  return attn_output, attn_weights, past_key_value
400
 
401
-
402
- class LlamaFlashAttention2(LlamaAttention):
403
- """
404
- Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
405
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
406
- flash attention and deal with padding tokens in case the input contains any of them.
407
- """
408
-
409
- def __init__(self, *args, **kwargs):
410
- super().__init__(*args, **kwargs)
411
-
412
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
413
- # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
414
- # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
415
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
416
-
417
- def forward(
418
- self,
419
- hidden_states: torch.Tensor,
420
- attention_mask: Optional[torch.LongTensor] = None,
421
- position_ids: Optional[torch.LongTensor] = None,
422
- past_key_value: Optional[Cache] = None,
423
- output_attentions: bool = False,
424
- use_cache: bool = False,
425
- cache_position: Optional[torch.LongTensor] = None,
426
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
427
- **kwargs,
428
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
429
- if isinstance(past_key_value, StaticCache):
430
- raise ValueError(
431
- "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
432
- "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
433
- )
434
-
435
- output_attentions = False
436
-
437
- bsz, q_len, _ = hidden_states.size()
438
-
439
- query_states = self.q_proj(hidden_states)
440
- key_states = self.k_proj(hidden_states)
441
- value_states = self.v_proj(hidden_states)
442
-
443
- # Flash attention requires the input to have the shape
444
- # batch_size x seq_length x head_dim x hidden_dim
445
- # therefore we just need to keep the original shape
446
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
447
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
448
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
449
-
450
- if position_embeddings is None:
451
- logger.warning_once(
452
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
453
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
454
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
455
- "removed and `position_embeddings` will be mandatory."
456
- )
457
- cos, sin = self.rotary_emb(value_states, position_ids)
458
- else:
459
- cos, sin = position_embeddings
460
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
461
-
462
- use_sliding_windows = (
463
- getattr(self.config, "sliding_windows", None) is not None
464
- and self.config.sliding_windows[self.layer_idx] > 0
465
- )
466
-
467
- if past_key_value is not None:
468
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
469
- cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
470
- if (
471
- getattr(self.config, "sliding_windows", None) is not None
472
- and cache_has_contents
473
- and self.config.sliding_windows[self.layer_idx] > 0
474
- ):
475
- slicing_tokens = 1 - self.config.sliding_windows[self.layer_idx]
476
-
477
- past_key = past_key_value.key_cache[self.layer_idx]
478
- past_value = past_key_value.value_cache[self.layer_idx]
479
-
480
- past_key = past_key[:, :, slicing_tokens:, :].contiguous()
481
- past_value = past_value[:, :, slicing_tokens:, :].contiguous()
482
-
483
- if past_key.shape[-2] != self.config.sliding_windows[self.layer_idx] - 1:
484
- raise ValueError(
485
- f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_windows[self.layer_idx]-1, head_dim`), got"
486
- f" {past_key.shape}"
487
- )
488
-
489
- if attention_mask is not None:
490
- attention_mask = attention_mask[:, slicing_tokens:]
491
- attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
492
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
493
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
494
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
495
-
496
- # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
497
- # to be able to avoid many of these transpose/reshape/view.
498
- query_states = query_states.transpose(1, 2)
499
- key_states = key_states.transpose(1, 2)
500
- value_states = value_states.transpose(1, 2)
501
-
502
- dropout_rate = self.attention_dropout if self.training else 0.0
503
-
504
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
505
- # therefore the input hidden states gets silently casted in float32. Hence, we need
506
- # cast them back in the correct dtype just to be sure everything works as expected.
507
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
508
- # in fp32. (LlamaRMSNorm handles it correctly)
509
-
510
- input_dtype = query_states.dtype
511
- if input_dtype == torch.float32:
512
- if torch.is_autocast_enabled():
513
- target_dtype = torch.get_autocast_gpu_dtype()
514
- # Handle the case where the model is quantized
515
- elif hasattr(self.config, "_pre_quantization_dtype"):
516
- target_dtype = self.config._pre_quantization_dtype
517
- else:
518
- target_dtype = self.q_proj.weight.dtype
519
-
520
- logger.warning_once(
521
- f"The input hidden states seems to be silently casted in float32, this might be related to"
522
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
523
- f" {target_dtype}."
524
- )
525
-
526
- query_states = query_states.to(target_dtype)
527
- key_states = key_states.to(target_dtype)
528
- value_states = value_states.to(target_dtype)
529
-
530
- sliding_window = self.config.sliding_windows[self.layer_idx]
531
- if sliding_window == 0:
532
- sliding_window = None
533
-
534
- attn_output = _flash_attention_forward(
535
- query_states,
536
- key_states,
537
- value_states,
538
- attention_mask,
539
- q_len,
540
- position_ids=position_ids,
541
- dropout=dropout_rate,
542
- sliding_window=sliding_window,
543
- use_top_left_mask=self._flash_attn_uses_top_left_mask,
544
- is_causal=self.is_causal,
545
- )
546
-
547
- attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
548
- attn_output = self.o_proj(attn_output)
549
-
550
- if not output_attentions:
551
- attn_weights = None
552
-
553
- return attn_output, attn_weights, past_key_value
554
-
555
-
556
- class LlamaSdpaAttention(LlamaAttention):
557
- """
558
- Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
559
- `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
560
- SDPA API.
561
- """
562
-
563
- # Adapted from LlamaAttention.forward
564
- def forward(
565
- self,
566
- hidden_states: torch.Tensor,
567
- attention_mask: Optional[torch.Tensor] = None,
568
- position_ids: Optional[torch.LongTensor] = None,
569
- past_key_value: Optional[Cache] = None,
570
- output_attentions: bool = False,
571
- use_cache: bool = False,
572
- cache_position: Optional[torch.LongTensor] = None,
573
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
574
- **kwargs
575
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
576
- if output_attentions:
577
- # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
578
- logger.warning_once(
579
- "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
580
- '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.'
581
- )
582
- return super().forward(
583
- hidden_states=hidden_states,
584
- attention_mask=attention_mask,
585
- position_ids=position_ids,
586
- past_key_value=past_key_value,
587
- output_attentions=output_attentions,
588
- use_cache=use_cache,
589
- cache_position=cache_position,
590
- )
591
-
592
- bsz, q_len, _ = hidden_states.size()
593
-
594
- query_states = self.q_proj(hidden_states)
595
- key_states = self.k_proj(hidden_states)
596
- value_states = self.v_proj(hidden_states)
597
-
598
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
599
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
600
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
601
-
602
- if position_embeddings is None:
603
- logger.warning_once(
604
- "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
605
- "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
606
- "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
607
- "removed and `position_embeddings` will be mandatory."
608
- )
609
- cos, sin = self.rotary_emb(value_states, position_ids)
610
- else:
611
- cos, sin = position_embeddings
612
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
613
-
614
- if past_key_value is not None:
615
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
616
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
617
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
618
-
619
- key_states = repeat_kv(key_states, self.num_key_value_groups)
620
- value_states = repeat_kv(value_states, self.num_key_value_groups)
621
-
622
- causal_mask = attention_mask
623
- if attention_mask is not None:
624
- causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
625
-
626
- # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
627
- # Reference: https://github.com/pytorch/pytorch/issues/112577.
628
- if query_states.device.type == "cuda" and causal_mask is not None:
629
- query_states = query_states.contiguous()
630
- key_states = key_states.contiguous()
631
- value_states = value_states.contiguous()
632
-
633
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
634
- # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
635
- is_causal = True if causal_mask is None and q_len > 1 else False
636
-
637
- attn_output = torch.nn.functional.scaled_dot_product_attention(
638
- query_states,
639
- key_states,
640
- value_states,
641
- attn_mask=causal_mask,
642
- dropout_p=self.attention_dropout if self.training else 0.0,
643
- is_causal=is_causal,
644
- )
645
-
646
- attn_output = attn_output.transpose(1, 2).contiguous()
647
- attn_output = attn_output.view(bsz, q_len, self.hidden_size)
648
-
649
- attn_output = self.o_proj(attn_output)
650
-
651
- return attn_output, None, past_key_value
652
-
653
-
654
  LLAMA_ATTENTION_CLASSES = {
655
- "eager": LlamaAttention,
656
- "flash_attention_2": LlamaFlashAttention2,
657
- "sdpa": LlamaSdpaAttention,
658
  }
659
 
660
 
 
29
  from transformers.activations import ACT2FN
30
  from transformers.cache_utils import Cache, DynamicCache, StaticCache
31
  from transformers.modeling_attn_mask_utils import AttentionMaskConverter
 
32
  from transformers.modeling_outputs import (
33
  BaseModelOutputWithPast,
34
  CausalLMOutputWithPast,
 
46
  logging,
47
  replace_return_docstrings,
48
  )
49
+ from transformers.models.llama.modeling_llama import LlamaAttention
50
  from configuration_sliding_llama import LlamaConfig
51
+ from torch.nn.attention.flex_attention import flex_attention, create_block_mask
52
 
53
  logger = logging.get_logger(__name__)
54
 
55
  _CONFIG_FOR_DOC = "LlamaConfig"
56
 
57
+ def attn_causal(b, h, q_idx, kv_idx):
58
+ causal_mask = q_idx >= kv_idx
59
+ return causal_mask
60
+
61
+ def stream_attn_causal(b, h, q_idx, kv_idx, attn_sink_size, sliding_window):
62
+ causal_mask = q_idx >= kv_idx
63
+ window_mask = q_idx - kv_idx <= sliding_window
64
+ sink_mask = kv_idx < attn_sink_size
65
+ return causal_mask & (window_mask | sink_mask)
66
+
67
+
68
  class LlamaRMSNorm(nn.Module):
69
  def __init__(self, hidden_size, eps=1e-6):
70
  """
 
278
  return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
279
 
280
 
281
+ class LlamaStreamingFlexAttention(LlamaAttention):
282
  """Multi-headed attention from 'Attention Is All You Need' paper"""
283
 
284
+ def __init__(self, *args, **kwargs):
285
+ super().__init__(*args, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
  def forward(
288
  self,
 
344
  key_states = repeat_kv(key_states, self.num_key_value_groups)
345
  value_states = repeat_kv(value_states, self.num_key_value_groups)
346
 
347
+ sliding_window_size = self.config.sliding_windows[self.layer_idx]
348
+ if sliding_window_size > 0:
349
+ block_mask = create_block_mask(
350
+ lambda b, h, q_idx, kv_idx: stream_attn_causal(b, h, q_idx, kv_idx, 4, sliding_window_size),
351
+ B=None, H=None, Q_LEN=query_states.shape[1], KV_LEN=key_states.shape[1]
352
+ )
353
+ else:
354
+ block_mask = create_block_mask(
355
+ lambda b, h, q_idx, kv_idx: attn_causal(b, h, q_idx, kv_idx),
356
+ B=None, H=None, Q_LEN=query_states.shape[1], KV_LEN=key_states.shape[1]
357
+ )
358
+ attn_output = flex_attention(query_states, key_states, value_states, block_mask=block_mask)
359
 
360
  if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
361
  raise ValueError(
 
379
 
380
  return attn_output, attn_weights, past_key_value
381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  LLAMA_ATTENTION_CLASSES = {
383
+ "eager": LlamaStreamingFlexAttention
 
 
384
  }
385
 
386