modified MLP
Browse files- modeling_edgellm.py +6 -936
modeling_edgellm.py
CHANGED
@@ -366,8 +366,6 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
|
366 |
return q_embed, k_embed
|
367 |
|
368 |
|
369 |
-
|
370 |
-
# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Edgellm
|
371 |
class EdgellmMLP(nn.Module):
|
372 |
def __init__(self, config):
|
373 |
super().__init__()
|
@@ -375,15 +373,14 @@ class EdgellmMLP(nn.Module):
|
|
375 |
self.intermediate_size = config.intermediate_size
|
376 |
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
377 |
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
378 |
-
|
379 |
-
return torch.pow(F.relu(x), 2)
|
380 |
-
self.act_fn = squared_relu
|
381 |
|
382 |
def forward(self, hidden_state):
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
|
|
387 |
|
388 |
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
389 |
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
@@ -398,418 +395,6 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
|
398 |
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
399 |
|
400 |
|
401 |
-
# class EdgellmAttention(nn.Module):
|
402 |
-
# """
|
403 |
-
# Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
404 |
-
# and "Generating Long Sequences with Sparse Transformers".
|
405 |
-
# """
|
406 |
-
|
407 |
-
# def __init__(self, config: EdgellmConfig, layer_idx: Optional[int] = None):
|
408 |
-
# super().__init__()
|
409 |
-
# self.config = config
|
410 |
-
# self.layer_idx = layer_idx
|
411 |
-
# if layer_idx is None:
|
412 |
-
# logger.warning_once(
|
413 |
-
# f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
414 |
-
# "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
415 |
-
# "when creating this class."
|
416 |
-
# )
|
417 |
-
|
418 |
-
# self.hidden_size = config.hidden_size
|
419 |
-
# self.num_heads = config.num_attention_heads
|
420 |
-
# self.head_dim = self.hidden_size // self.num_heads
|
421 |
-
# self.num_key_value_heads = config.num_key_value_heads
|
422 |
-
# self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
423 |
-
# self.max_position_embeddings = config.max_position_embeddings
|
424 |
-
# self.rope_theta = config.rope_theta
|
425 |
-
# self.is_causal = True
|
426 |
-
# self.attention_dropout = config.attention_dropout
|
427 |
-
|
428 |
-
# if (self.head_dim * self.num_heads) != self.hidden_size:
|
429 |
-
# raise ValueError(
|
430 |
-
# f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
431 |
-
# f" and `num_heads`: {self.num_heads})."
|
432 |
-
# )
|
433 |
-
# self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
434 |
-
# self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
435 |
-
# self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
436 |
-
# self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
437 |
-
|
438 |
-
# self.rotary_emb = EdgellmRotaryEmbedding(
|
439 |
-
# self.head_dim,
|
440 |
-
# max_position_embeddings=self.max_position_embeddings,
|
441 |
-
# base=self.rope_theta,
|
442 |
-
# )
|
443 |
-
|
444 |
-
# def forward(
|
445 |
-
# self,
|
446 |
-
# hidden_states: torch.Tensor,
|
447 |
-
# attention_mask: Optional[torch.Tensor] = None,
|
448 |
-
# position_ids: Optional[torch.LongTensor] = None,
|
449 |
-
# past_key_value: Optional[Cache] = None,
|
450 |
-
# output_attentions: bool = False,
|
451 |
-
# use_cache: bool = False,
|
452 |
-
# cache_position: Optional[torch.LongTensor] = None,
|
453 |
-
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
454 |
-
# bsz, q_len, _ = hidden_states.size()
|
455 |
-
|
456 |
-
# query_states = self.q_proj(hidden_states)
|
457 |
-
# key_states = self.k_proj(hidden_states)
|
458 |
-
# value_states = self.v_proj(hidden_states)
|
459 |
-
|
460 |
-
# query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
461 |
-
# key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
462 |
-
# value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
463 |
-
|
464 |
-
# kv_seq_len = key_states.shape[-2]
|
465 |
-
# if past_key_value is not None:
|
466 |
-
# if self.layer_idx is None:
|
467 |
-
# raise ValueError(
|
468 |
-
# f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
469 |
-
# "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
470 |
-
# "with a layer index."
|
471 |
-
# )
|
472 |
-
# kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
473 |
-
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
474 |
-
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
475 |
-
|
476 |
-
# if past_key_value is not None:
|
477 |
-
# cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
478 |
-
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
479 |
-
|
480 |
-
# # repeat k/v heads if n_kv_heads < n_heads
|
481 |
-
# key_states = repeat_kv(key_states, self.num_key_value_groups)
|
482 |
-
# value_states = repeat_kv(value_states, self.num_key_value_groups)
|
483 |
-
|
484 |
-
# attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
485 |
-
|
486 |
-
# if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
487 |
-
# raise ValueError(
|
488 |
-
# f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
489 |
-
# f" {attn_weights.size()}"
|
490 |
-
# )
|
491 |
-
|
492 |
-
# if attention_mask is not None: # no matter the length, we just slice it
|
493 |
-
# causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
494 |
-
# attn_weights = attn_weights + causal_mask
|
495 |
-
|
496 |
-
# # upcast attention to fp32
|
497 |
-
# attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
498 |
-
# attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
499 |
-
# attn_output = torch.matmul(attn_weights, value_states)
|
500 |
-
|
501 |
-
# if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
502 |
-
# raise ValueError(
|
503 |
-
# f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
504 |
-
# f" {attn_output.size()}"
|
505 |
-
# )
|
506 |
-
|
507 |
-
# attn_output = attn_output.transpose(1, 2).contiguous()
|
508 |
-
# attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
509 |
-
|
510 |
-
# attn_output = self.o_proj(attn_output)
|
511 |
-
|
512 |
-
# if not output_attentions:
|
513 |
-
# attn_weights = None
|
514 |
-
|
515 |
-
# return attn_output, attn_weights, past_key_value
|
516 |
-
|
517 |
-
|
518 |
-
# class EdgellmFlashAttention2(EdgellmAttention):
|
519 |
-
# """
|
520 |
-
# Edgellm flash attention module, following Edgellm attention module. This module inherits from `EdgellmAttention`
|
521 |
-
# as the weights of the module stays untouched. The only required change would be on the forward pass
|
522 |
-
# where it needs to correctly call the public API of flash attention and deal with padding tokens
|
523 |
-
# in case the input contains any of them. Additionally, for sliding window attention, we apply SWA only to the bottom
|
524 |
-
# config.max_window_layers layers.
|
525 |
-
# """
|
526 |
-
|
527 |
-
# # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
|
528 |
-
# def __init__(self, *args, **kwargs):
|
529 |
-
# super().__init__(*args, **kwargs)
|
530 |
-
|
531 |
-
# # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
532 |
-
# # 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.
|
533 |
-
# # 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).
|
534 |
-
# self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
535 |
-
|
536 |
-
# def forward(
|
537 |
-
# self,
|
538 |
-
# hidden_states: torch.Tensor,
|
539 |
-
# attention_mask: Optional[torch.Tensor] = None,
|
540 |
-
# position_ids: Optional[torch.LongTensor] = None,
|
541 |
-
# past_key_value: Optional[Cache] = None,
|
542 |
-
# output_attentions: bool = False,
|
543 |
-
# use_cache: bool = False,
|
544 |
-
# cache_position: Optional[torch.LongTensor] = None,
|
545 |
-
# ):
|
546 |
-
# bsz, q_len, _ = hidden_states.size()
|
547 |
-
|
548 |
-
# query_states = self.q_proj(hidden_states)
|
549 |
-
# key_states = self.k_proj(hidden_states)
|
550 |
-
# value_states = self.v_proj(hidden_states)
|
551 |
-
|
552 |
-
# query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
553 |
-
# key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
554 |
-
# value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
555 |
-
|
556 |
-
# kv_seq_len = key_states.shape[-2]
|
557 |
-
# if past_key_value is not None:
|
558 |
-
# if self.layer_idx is None:
|
559 |
-
# raise ValueError(
|
560 |
-
# f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
561 |
-
# "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
562 |
-
# "with a layer index."
|
563 |
-
# )
|
564 |
-
# kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
565 |
-
|
566 |
-
# # Because the input can be padded, the absolute sequence length depends on the max position id.
|
567 |
-
# rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
|
568 |
-
# cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
|
569 |
-
|
570 |
-
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
571 |
-
|
572 |
-
# use_sliding_windows = (
|
573 |
-
# _flash_supports_window_size
|
574 |
-
# and getattr(self.config, "sliding_window", None) is not None
|
575 |
-
# and kv_seq_len > self.config.sliding_window
|
576 |
-
# and self.config.use_sliding_window
|
577 |
-
# )
|
578 |
-
|
579 |
-
# if not _flash_supports_window_size:
|
580 |
-
# logger.warning_once(
|
581 |
-
# "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
|
582 |
-
# " make sure to upgrade flash-attn library."
|
583 |
-
# )
|
584 |
-
|
585 |
-
# if past_key_value is not None:
|
586 |
-
# # Activate slicing cache only if the config has a value `sliding_windows` attribute
|
587 |
-
# cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
|
588 |
-
# if (
|
589 |
-
# getattr(self.config, "sliding_window", None) is not None
|
590 |
-
# and kv_seq_len > self.config.sliding_window
|
591 |
-
# and cache_has_contents
|
592 |
-
# ):
|
593 |
-
# slicing_tokens = 1 - self.config.sliding_window
|
594 |
-
|
595 |
-
# past_key = past_key_value[self.layer_idx][0]
|
596 |
-
# past_value = past_key_value[self.layer_idx][1]
|
597 |
-
|
598 |
-
# past_key = past_key[:, :, slicing_tokens:, :].contiguous()
|
599 |
-
# past_value = past_value[:, :, slicing_tokens:, :].contiguous()
|
600 |
-
|
601 |
-
# if past_key.shape[-2] != self.config.sliding_window - 1:
|
602 |
-
# raise ValueError(
|
603 |
-
# f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
|
604 |
-
# f" {past_key.shape}"
|
605 |
-
# )
|
606 |
-
|
607 |
-
# if attention_mask is not None:
|
608 |
-
# attention_mask = attention_mask[:, slicing_tokens:]
|
609 |
-
# attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
|
610 |
-
|
611 |
-
# cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
612 |
-
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
613 |
-
|
614 |
-
# # repeat k/v heads if n_kv_heads < n_heads
|
615 |
-
# key_states = repeat_kv(key_states, self.num_key_value_groups)
|
616 |
-
# value_states = repeat_kv(value_states, self.num_key_value_groups)
|
617 |
-
# dropout_rate = 0.0 if not self.training else self.attention_dropout
|
618 |
-
|
619 |
-
# # In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
620 |
-
# # therefore the input hidden states gets silently casted in float32. Hence, we need
|
621 |
-
# # cast them back in float16 just to be sure everything works as expected.
|
622 |
-
# input_dtype = query_states.dtype
|
623 |
-
# if input_dtype == torch.float32:
|
624 |
-
# if torch.is_autocast_enabled():
|
625 |
-
# target_dtype = torch.get_autocast_gpu_dtype()
|
626 |
-
# # Handle the case where the model is quantized
|
627 |
-
# elif hasattr(self.config, "_pre_quantization_dtype"):
|
628 |
-
# target_dtype = self.config._pre_quantization_dtype
|
629 |
-
# else:
|
630 |
-
# target_dtype = self.q_proj.weight.dtype
|
631 |
-
|
632 |
-
# logger.warning_once(
|
633 |
-
# f"The input hidden states seems to be silently casted in float32, this might be related to"
|
634 |
-
# f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
635 |
-
# f" {target_dtype}."
|
636 |
-
# )
|
637 |
-
|
638 |
-
# query_states = query_states.to(target_dtype)
|
639 |
-
# key_states = key_states.to(target_dtype)
|
640 |
-
# value_states = value_states.to(target_dtype)
|
641 |
-
|
642 |
-
# # Reashape to the expected shape for Flash Attention
|
643 |
-
# query_states = query_states.transpose(1, 2)
|
644 |
-
# key_states = key_states.transpose(1, 2)
|
645 |
-
# value_states = value_states.transpose(1, 2)
|
646 |
-
|
647 |
-
# attn_output = self._flash_attention_forward(
|
648 |
-
# query_states,
|
649 |
-
# key_states,
|
650 |
-
# value_states,
|
651 |
-
# attention_mask,
|
652 |
-
# q_len,
|
653 |
-
# dropout=dropout_rate,
|
654 |
-
# use_sliding_windows=use_sliding_windows,
|
655 |
-
# )
|
656 |
-
|
657 |
-
# attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
658 |
-
# attn_output = self.o_proj(attn_output)
|
659 |
-
|
660 |
-
# if not output_attentions:
|
661 |
-
# attn_weights = None
|
662 |
-
|
663 |
-
# return attn_output, attn_weights, past_key_value
|
664 |
-
|
665 |
-
# def _flash_attention_forward(
|
666 |
-
# self,
|
667 |
-
# query_states,
|
668 |
-
# key_states,
|
669 |
-
# value_states,
|
670 |
-
# attention_mask,
|
671 |
-
# query_length,
|
672 |
-
# dropout=0.0,
|
673 |
-
# softmax_scale=None,
|
674 |
-
# use_sliding_windows=False,
|
675 |
-
# ):
|
676 |
-
# """
|
677 |
-
# Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
678 |
-
# first unpad the input, then computes the attention scores and pad the final attention scores.
|
679 |
-
|
680 |
-
# Args:
|
681 |
-
# query_states (`torch.Tensor`):
|
682 |
-
# Input query states to be passed to Flash Attention API
|
683 |
-
# key_states (`torch.Tensor`):
|
684 |
-
# Input key states to be passed to Flash Attention API
|
685 |
-
# value_states (`torch.Tensor`):
|
686 |
-
# Input value states to be passed to Flash Attention API
|
687 |
-
# attention_mask (`torch.Tensor`):
|
688 |
-
# The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
689 |
-
# position of padding tokens and 1 for the position of non-padding tokens.
|
690 |
-
# dropout (`float`):
|
691 |
-
# Attention dropout
|
692 |
-
# softmax_scale (`float`, *optional*):
|
693 |
-
# The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
694 |
-
# use_sliding_windows (`bool`, *optional*):
|
695 |
-
# Whether to activate sliding window attention.
|
696 |
-
# """
|
697 |
-
# if not self._flash_attn_uses_top_left_mask:
|
698 |
-
# causal = self.is_causal
|
699 |
-
# else:
|
700 |
-
# # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
701 |
-
# causal = self.is_causal and query_length != 1
|
702 |
-
|
703 |
-
# # Decide whether to use SWA or not by layer index.
|
704 |
-
# if use_sliding_windows and self.layer_idx >= self.config.max_window_layers:
|
705 |
-
# use_sliding_windows = False
|
706 |
-
|
707 |
-
# # Contains at least one padding token in the sequence
|
708 |
-
# if attention_mask is not None:
|
709 |
-
# batch_size = query_states.shape[0]
|
710 |
-
# query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
711 |
-
# query_states, key_states, value_states, attention_mask, query_length
|
712 |
-
# )
|
713 |
-
|
714 |
-
# cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
715 |
-
# max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
716 |
-
|
717 |
-
# if not use_sliding_windows:
|
718 |
-
# attn_output_unpad = flash_attn_varlen_func(
|
719 |
-
# query_states,
|
720 |
-
# key_states,
|
721 |
-
# value_states,
|
722 |
-
# cu_seqlens_q=cu_seqlens_q,
|
723 |
-
# cu_seqlens_k=cu_seqlens_k,
|
724 |
-
# max_seqlen_q=max_seqlen_in_batch_q,
|
725 |
-
# max_seqlen_k=max_seqlen_in_batch_k,
|
726 |
-
# dropout_p=dropout,
|
727 |
-
# softmax_scale=softmax_scale,
|
728 |
-
# causal=causal,
|
729 |
-
# )
|
730 |
-
# else:
|
731 |
-
# attn_output_unpad = flash_attn_varlen_func(
|
732 |
-
# query_states,
|
733 |
-
# key_states,
|
734 |
-
# value_states,
|
735 |
-
# cu_seqlens_q=cu_seqlens_q,
|
736 |
-
# cu_seqlens_k=cu_seqlens_k,
|
737 |
-
# max_seqlen_q=max_seqlen_in_batch_q,
|
738 |
-
# max_seqlen_k=max_seqlen_in_batch_k,
|
739 |
-
# dropout_p=dropout,
|
740 |
-
# softmax_scale=softmax_scale,
|
741 |
-
# causal=causal,
|
742 |
-
# window_size=(self.config.sliding_window, self.config.sliding_window),
|
743 |
-
# )
|
744 |
-
|
745 |
-
# attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
746 |
-
# else:
|
747 |
-
# if not use_sliding_windows:
|
748 |
-
# attn_output = flash_attn_func(
|
749 |
-
# query_states,
|
750 |
-
# key_states,
|
751 |
-
# value_states,
|
752 |
-
# dropout,
|
753 |
-
# softmax_scale=softmax_scale,
|
754 |
-
# causal=causal,
|
755 |
-
# )
|
756 |
-
# else:
|
757 |
-
# attn_output = flash_attn_func(
|
758 |
-
# query_states,
|
759 |
-
# key_states,
|
760 |
-
# value_states,
|
761 |
-
# dropout,
|
762 |
-
# softmax_scale=softmax_scale,
|
763 |
-
# causal=causal,
|
764 |
-
# window_size=(self.config.sliding_window, self.config.sliding_window),
|
765 |
-
# )
|
766 |
-
|
767 |
-
# return attn_output
|
768 |
-
|
769 |
-
# # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
|
770 |
-
# def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
771 |
-
# batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
|
772 |
-
|
773 |
-
# # On the first iteration we need to properly re-create the padding mask
|
774 |
-
# # by slicing it on the proper place
|
775 |
-
# if kv_seq_len != attention_mask.shape[-1]:
|
776 |
-
# attention_mask_num_tokens = attention_mask.shape[-1]
|
777 |
-
# attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
|
778 |
-
|
779 |
-
# indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
780 |
-
|
781 |
-
# key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
782 |
-
# value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
|
783 |
-
|
784 |
-
# if query_length == kv_seq_len:
|
785 |
-
# query_layer = index_first_axis(
|
786 |
-
# query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
|
787 |
-
# )
|
788 |
-
# cu_seqlens_q = cu_seqlens_k
|
789 |
-
# max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
790 |
-
# indices_q = indices_k
|
791 |
-
# elif query_length == 1:
|
792 |
-
# max_seqlen_in_batch_q = 1
|
793 |
-
# cu_seqlens_q = torch.arange(
|
794 |
-
# batch_size + 1, dtype=torch.int32, device=query_layer.device
|
795 |
-
# ) # There is a memcpy here, that is very bad.
|
796 |
-
# indices_q = cu_seqlens_q[:-1]
|
797 |
-
# query_layer = query_layer.squeeze(1)
|
798 |
-
# else:
|
799 |
-
# # The -q_len: slice assumes left padding.
|
800 |
-
# attention_mask = attention_mask[:, -query_length:]
|
801 |
-
# query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
802 |
-
|
803 |
-
# return (
|
804 |
-
# query_layer,
|
805 |
-
# key_layer,
|
806 |
-
# value_layer,
|
807 |
-
# indices_q,
|
808 |
-
# (cu_seqlens_q, cu_seqlens_k),
|
809 |
-
# (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
810 |
-
# )
|
811 |
-
|
812 |
-
|
813 |
# Copied from https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite/blob/main/modeling_deepseek.py
|
814 |
# DeepseekV2Attention with DeepseekV2->Edgellm
|
815 |
|
@@ -1036,522 +621,7 @@ class EdgellmAttention(nn.Module):
|
|
1036 |
attn_weights = None
|
1037 |
|
1038 |
return attn_output, attn_weights, past_key_value
|
1039 |
-
# class EdgellmAttention(nn.Module):
|
1040 |
-
# """Multi-headed attention from 'Attention Is All You Need' paper"""
|
1041 |
-
|
1042 |
-
# def __init__(self, config: EdgellmConfig, layer_idx: Optional[int] = None):
|
1043 |
-
# super().__init__()
|
1044 |
-
# self.config = config
|
1045 |
-
# self.layer_idx = layer_idx
|
1046 |
-
# if layer_idx is None:
|
1047 |
-
# logger.warning_once(
|
1048 |
-
# f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
1049 |
-
# "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
1050 |
-
# "when creating this class."
|
1051 |
-
# )
|
1052 |
-
|
1053 |
-
# self.attention_dropout = config.attention_dropout
|
1054 |
-
# self.hidden_size = config.hidden_size
|
1055 |
-
# self.num_heads = config.num_attention_heads
|
1056 |
-
|
1057 |
-
# self.max_position_embeddings = config.max_position_embeddings
|
1058 |
-
# self.rope_theta = config.rope_theta
|
1059 |
-
# self.q_lora_rank = config.q_lora_rank
|
1060 |
-
# self.qk_rope_head_dim = config.qk_rope_head_dim
|
1061 |
-
# self.kv_lora_rank = config.kv_lora_rank
|
1062 |
-
# self.v_head_dim = config.v_head_dim
|
1063 |
-
# self.qk_nope_head_dim = config.qk_nope_head_dim
|
1064 |
-
# self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
|
1065 |
-
|
1066 |
-
# self.is_causal = True
|
1067 |
-
|
1068 |
-
# if self.q_lora_rank is None:
|
1069 |
-
# self.q_proj = nn.Linear(
|
1070 |
-
# self.hidden_size, self.num_heads * self.q_head_dim, bias=False
|
1071 |
-
# )
|
1072 |
-
# else:
|
1073 |
-
# self.q_a_proj = nn.Linear(
|
1074 |
-
# self.hidden_size, config.q_lora_rank, bias=config.attention_bias
|
1075 |
-
# )
|
1076 |
-
# self.q_a_layernorm = EdgellmRMSNorm(config.q_lora_rank)
|
1077 |
-
# self.q_b_proj = nn.Linear(
|
1078 |
-
# config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
|
1079 |
-
# )
|
1080 |
-
|
1081 |
-
# self.kv_a_proj_with_mqa = nn.Linear(
|
1082 |
-
# self.hidden_size,
|
1083 |
-
# config.kv_lora_rank + config.qk_rope_head_dim,
|
1084 |
-
# bias=config.attention_bias,
|
1085 |
-
# )
|
1086 |
-
# self.kv_a_layernorm = EdgellmRMSNorm(config.kv_lora_rank)
|
1087 |
-
# self.kv_b_proj = nn.Linear(
|
1088 |
-
# config.kv_lora_rank,
|
1089 |
-
# self.num_heads
|
1090 |
-
# * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
|
1091 |
-
# bias=False,
|
1092 |
-
# )
|
1093 |
-
|
1094 |
-
# self.o_proj = nn.Linear(
|
1095 |
-
# self.num_heads * self.v_head_dim,
|
1096 |
-
# self.hidden_size,
|
1097 |
-
# bias=config.attention_bias,
|
1098 |
-
# )
|
1099 |
-
# self._init_rope()
|
1100 |
-
|
1101 |
-
# self.softmax_scale = self.q_head_dim ** (-0.5)
|
1102 |
-
# if self.config.rope_scaling is not None:
|
1103 |
-
# mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
|
1104 |
-
# scaling_factor = self.config.rope_scaling["factor"]
|
1105 |
-
# if mscale_all_dim:
|
1106 |
-
# mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
1107 |
-
# self.softmax_scale = self.softmax_scale * mscale * mscale
|
1108 |
-
|
1109 |
-
# def _init_rope(self):
|
1110 |
-
# if self.config.rope_scaling is None:
|
1111 |
-
# self.rotary_emb = EdgellmRotaryEmbedding(
|
1112 |
-
# self.qk_rope_head_dim,
|
1113 |
-
# max_position_embeddings=self.max_position_embeddings,
|
1114 |
-
# base=self.rope_theta,
|
1115 |
-
# )
|
1116 |
-
# else:
|
1117 |
-
# scaling_type = self.config.rope_scaling["type"]
|
1118 |
-
# scaling_factor = self.config.rope_scaling["factor"]
|
1119 |
-
# if scaling_type == "linear":
|
1120 |
-
# self.rotary_emb = EdgellmLinearScalingRotaryEmbedding(
|
1121 |
-
# self.qk_rope_head_dim,
|
1122 |
-
# max_position_embeddings=self.max_position_embeddings,
|
1123 |
-
# scaling_factor=scaling_factor,
|
1124 |
-
# base=self.rope_theta,
|
1125 |
-
# )
|
1126 |
-
# elif scaling_type == "dynamic":
|
1127 |
-
# self.rotary_emb = EdgellmDynamicNTKScalingRotaryEmbedding(
|
1128 |
-
# self.qk_rope_head_dim,
|
1129 |
-
# max_position_embeddings=self.max_position_embeddings,
|
1130 |
-
# scaling_factor=scaling_factor,
|
1131 |
-
# base=self.rope_theta,
|
1132 |
-
# )
|
1133 |
-
# elif scaling_type == "yarn":
|
1134 |
-
# kwargs = {
|
1135 |
-
# key: self.config.rope_scaling[key]
|
1136 |
-
# for key in [
|
1137 |
-
# "original_max_position_embeddings",
|
1138 |
-
# "beta_fast",
|
1139 |
-
# "beta_slow",
|
1140 |
-
# "mscale",
|
1141 |
-
# "mscale_all_dim",
|
1142 |
-
# ]
|
1143 |
-
# if key in self.config.rope_scaling
|
1144 |
-
# }
|
1145 |
-
# self.rotary_emb = EdgellmYarnRotaryEmbedding(
|
1146 |
-
# self.qk_rope_head_dim,
|
1147 |
-
# max_position_embeddings=self.max_position_embeddings,
|
1148 |
-
# scaling_factor=scaling_factor,
|
1149 |
-
# base=self.rope_theta,
|
1150 |
-
# **kwargs,
|
1151 |
-
# )
|
1152 |
-
# else:
|
1153 |
-
# raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
1154 |
-
|
1155 |
-
# def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
1156 |
-
# return (
|
1157 |
-
# tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
|
1158 |
-
# .transpose(1, 2)
|
1159 |
-
# .contiguous()
|
1160 |
-
# )
|
1161 |
-
|
1162 |
-
# def forward(
|
1163 |
-
# self,
|
1164 |
-
# hidden_states: torch.Tensor,
|
1165 |
-
# attention_mask: Optional[torch.Tensor] = None,
|
1166 |
-
# position_ids: Optional[torch.LongTensor] = None,
|
1167 |
-
# past_key_value: Optional[Cache] = None,
|
1168 |
-
# output_attentions: bool = False,
|
1169 |
-
# use_cache: bool = False,
|
1170 |
-
# **kwargs,
|
1171 |
-
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
1172 |
-
# if "padding_mask" in kwargs:
|
1173 |
-
# warnings.warn(
|
1174 |
-
# "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
1175 |
-
# )
|
1176 |
-
# torch.save(hidden_states, "hf-hidden_states.pt")
|
1177 |
-
# bsz, q_len, _ = hidden_states.size()
|
1178 |
-
|
1179 |
-
# if self.q_lora_rank is None:
|
1180 |
-
# q = self.q_proj(hidden_states)
|
1181 |
-
# else:
|
1182 |
-
# q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
1183 |
-
# q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
|
1184 |
-
# q_nope, q_pe = torch.split(
|
1185 |
-
# q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
|
1186 |
-
# )
|
1187 |
-
|
1188 |
-
# compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
1189 |
-
# compressed_kv, k_pe = torch.split(
|
1190 |
-
# compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
|
1191 |
-
# )
|
1192 |
-
# k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
|
1193 |
-
# kv = (
|
1194 |
-
# self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
|
1195 |
-
# .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
|
1196 |
-
# .transpose(1, 2)
|
1197 |
-
# )
|
1198 |
-
|
1199 |
-
# k_nope, value_states = torch.split(
|
1200 |
-
# kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
|
1201 |
-
# )
|
1202 |
-
# kv_seq_len = value_states.shape[-2]
|
1203 |
-
# if past_key_value is not None:
|
1204 |
-
# if self.layer_idx is None:
|
1205 |
-
# raise ValueError(
|
1206 |
-
# f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
1207 |
-
# "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
1208 |
-
# "with a layer index."
|
1209 |
-
# )
|
1210 |
-
# kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
1211 |
-
|
1212 |
-
# # torch.save(value_states, "./hf_value_states_rope.pt")
|
1213 |
-
# # print(kv_seq_len)
|
1214 |
-
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
1215 |
-
# # torch.save(q_pe, "./hf_q_pe_1.pt")
|
1216 |
-
# # torch.save(cos, "./hf-cos.pt")
|
1217 |
-
# # torch.save(cos, "./hf-sin.pt")
|
1218 |
-
# q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
|
1219 |
-
# # torch.save(q_pe, "./hf_q_pe_2.pt")
|
1220 |
-
# query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1221 |
-
# query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
|
1222 |
-
# query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
|
1223 |
-
|
1224 |
-
# key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1225 |
-
# key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
|
1226 |
-
# key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
|
1227 |
-
# if past_key_value is not None:
|
1228 |
-
# cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
1229 |
-
# key_states, value_states = past_key_value.update(
|
1230 |
-
# key_states, value_states, self.layer_idx, cache_kwargs
|
1231 |
-
# )
|
1232 |
-
# # torch.save(query_states, "./hf-q.pt")
|
1233 |
-
# # torch.save(key_states, "./hf-k.pt")
|
1234 |
-
# # torch.save(value_states, "./hf-v.pt")
|
1235 |
-
# # breakpoint()
|
1236 |
-
# attn_weights = (
|
1237 |
-
# torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
|
1238 |
-
# )
|
1239 |
-
|
1240 |
-
# if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
1241 |
-
# raise ValueError(
|
1242 |
-
# f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
1243 |
-
# f" {attn_weights.size()}"
|
1244 |
-
# )
|
1245 |
-
# assert attention_mask is not None
|
1246 |
-
# if attention_mask is not None:
|
1247 |
-
# if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
1248 |
-
# raise ValueError(
|
1249 |
-
# f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
1250 |
-
# )
|
1251 |
-
# attn_weights = attn_weights + attention_mask
|
1252 |
-
|
1253 |
-
# # upcast attention to fp32
|
1254 |
-
# attn_weights = nn.functional.softmax(
|
1255 |
-
# attn_weights, dim=-1, dtype=torch.float32
|
1256 |
-
# ).to(query_states.dtype)
|
1257 |
-
# attn_weights = nn.functional.dropout(
|
1258 |
-
# attn_weights, p=self.attention_dropout, training=self.training
|
1259 |
-
# )
|
1260 |
-
# attn_output = torch.matmul(attn_weights, value_states)
|
1261 |
-
|
1262 |
-
# if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
|
1263 |
-
# raise ValueError(
|
1264 |
-
# f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
|
1265 |
-
# f" {attn_output.size()}"
|
1266 |
-
# )
|
1267 |
-
|
1268 |
-
# attn_output = attn_output.transpose(1, 2).contiguous()
|
1269 |
-
|
1270 |
-
# attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
|
1271 |
-
|
1272 |
-
# attn_output = self.o_proj(attn_output)
|
1273 |
-
|
1274 |
-
# if not output_attentions:
|
1275 |
-
# attn_weights = None
|
1276 |
-
|
1277 |
-
# return attn_output, attn_weights, past_key_value
|
1278 |
-
|
1279 |
|
1280 |
-
# Copied from https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite/blob/main/modeling_deepseek.py
|
1281 |
-
# DeepseekV2Attention with DeepseekV2->Edgellm
|
1282 |
-
# class EdgellmFlashAttention2(EdgellmAttention):
|
1283 |
-
# """
|
1284 |
-
# Edgellm flash attention module. This module inherits from `EdgellmAttention` as the weights of the module stays
|
1285 |
-
# untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
1286 |
-
# flash attention and deal with padding tokens in case the input contains any of them.
|
1287 |
-
# """
|
1288 |
-
|
1289 |
-
# def __init__(self, *args, **kwargs):
|
1290 |
-
# super().__init__(*args, **kwargs)
|
1291 |
-
|
1292 |
-
# # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
1293 |
-
# # 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.
|
1294 |
-
# # 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).
|
1295 |
-
# self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
1296 |
-
|
1297 |
-
# def forward(
|
1298 |
-
# self,
|
1299 |
-
# hidden_states: torch.Tensor,
|
1300 |
-
# attention_mask: Optional[torch.LongTensor] = None,
|
1301 |
-
# position_ids: Optional[torch.LongTensor] = None,
|
1302 |
-
# past_key_value: Optional[Cache] = None,
|
1303 |
-
# output_attentions: bool = False,
|
1304 |
-
# use_cache: bool = False,
|
1305 |
-
# **kwargs,
|
1306 |
-
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
1307 |
-
# # EdgellmFlashAttention2 attention does not support output_attentions
|
1308 |
-
# if "padding_mask" in kwargs:
|
1309 |
-
# warnings.warn(
|
1310 |
-
# "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
1311 |
-
# )
|
1312 |
-
|
1313 |
-
# # overwrite attention_mask with padding_mask
|
1314 |
-
# attention_mask = kwargs.pop("padding_mask")
|
1315 |
-
|
1316 |
-
# output_attentions = False
|
1317 |
-
|
1318 |
-
# bsz, q_len, _ = hidden_states.size()
|
1319 |
-
|
1320 |
-
# if self.q_lora_rank is None:
|
1321 |
-
# q = self.q_proj(hidden_states)
|
1322 |
-
# else:
|
1323 |
-
# q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
|
1324 |
-
# q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
|
1325 |
-
# q_nope, q_pe = torch.split(
|
1326 |
-
# q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
|
1327 |
-
# )
|
1328 |
-
|
1329 |
-
# # Flash attention requires the input to have the shape
|
1330 |
-
# # batch_size x seq_length x head_dim x hidden_dim
|
1331 |
-
# # therefore we just need to keep the original shape
|
1332 |
-
# compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
1333 |
-
# compressed_kv, k_pe = torch.split(
|
1334 |
-
# compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
|
1335 |
-
# )
|
1336 |
-
# k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
|
1337 |
-
# kv = (
|
1338 |
-
# self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
|
1339 |
-
# .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
|
1340 |
-
# .transpose(1, 2)
|
1341 |
-
# )
|
1342 |
-
|
1343 |
-
# k_nope, value_states = torch.split(
|
1344 |
-
# kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
|
1345 |
-
# )
|
1346 |
-
# kv_seq_len = value_states.shape[-2]
|
1347 |
-
|
1348 |
-
# kv_seq_len = value_states.shape[-2]
|
1349 |
-
# if past_key_value is not None:
|
1350 |
-
# kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
1351 |
-
|
1352 |
-
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
1353 |
-
# q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
|
1354 |
-
|
1355 |
-
# query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1356 |
-
# query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
|
1357 |
-
# query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
|
1358 |
-
|
1359 |
-
# key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
|
1360 |
-
# key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
|
1361 |
-
# key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
|
1362 |
-
|
1363 |
-
# if self.q_head_dim != self.v_head_dim:
|
1364 |
-
# value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
|
1365 |
-
|
1366 |
-
# if past_key_value is not None:
|
1367 |
-
# cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
1368 |
-
# key_states, value_states = past_key_value.update(
|
1369 |
-
# key_states, value_states, self.layer_idx, cache_kwargs
|
1370 |
-
# )
|
1371 |
-
|
1372 |
-
# # 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
|
1373 |
-
# # to be able to avoid many of these transpose/reshape/view.
|
1374 |
-
# query_states = query_states.transpose(1, 2)
|
1375 |
-
# key_states = key_states.transpose(1, 2)
|
1376 |
-
# value_states = value_states.transpose(1, 2)
|
1377 |
-
|
1378 |
-
# dropout_rate = self.attention_dropout if self.training else 0.0
|
1379 |
-
|
1380 |
-
# # In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
1381 |
-
# # therefore the input hidden states gets silently casted in float32. Hence, we need
|
1382 |
-
# # cast them back in the correct dtype just to be sure everything works as expected.
|
1383 |
-
# # This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
1384 |
-
# # in fp32. (EdgellmRMSNorm handles it correctly)
|
1385 |
-
|
1386 |
-
# input_dtype = query_states.dtype
|
1387 |
-
# if input_dtype == torch.float32:
|
1388 |
-
# # Handle the case where the model is quantized
|
1389 |
-
# if hasattr(self.config, "_pre_quantization_dtype"):
|
1390 |
-
# target_dtype = self.config._pre_quantization_dtype
|
1391 |
-
# elif torch.is_autocast_enabled():
|
1392 |
-
# target_dtype = torch.get_autocast_gpu_dtype()
|
1393 |
-
# else:
|
1394 |
-
# target_dtype = (
|
1395 |
-
# self.q_proj.weight.dtype
|
1396 |
-
# if self.q_lora_rank is None
|
1397 |
-
# else self.q_a_proj.weight.dtype
|
1398 |
-
# )
|
1399 |
-
|
1400 |
-
# logger.warning_once(
|
1401 |
-
# f"The input hidden states seems to be silently casted in float32, this might be related to"
|
1402 |
-
# f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
1403 |
-
# f" {target_dtype}."
|
1404 |
-
# )
|
1405 |
-
|
1406 |
-
# query_states = query_states.to(target_dtype)
|
1407 |
-
# key_states = key_states.to(target_dtype)
|
1408 |
-
# value_states = value_states.to(target_dtype)
|
1409 |
-
|
1410 |
-
# attn_output = self._flash_attention_forward(
|
1411 |
-
# query_states,
|
1412 |
-
# key_states,
|
1413 |
-
# value_states,
|
1414 |
-
# attention_mask,
|
1415 |
-
# q_len,
|
1416 |
-
# dropout=dropout_rate,
|
1417 |
-
# softmax_scale=self.softmax_scale,
|
1418 |
-
# )
|
1419 |
-
# if self.q_head_dim != self.v_head_dim:
|
1420 |
-
# attn_output = attn_output[:, :, :, : self.v_head_dim]
|
1421 |
-
|
1422 |
-
# attn_output = attn_output.reshape(
|
1423 |
-
# bsz, q_len, self.num_heads * self.v_head_dim
|
1424 |
-
# ).contiguous()
|
1425 |
-
# attn_output = self.o_proj(attn_output)
|
1426 |
-
|
1427 |
-
# if not output_attentions:
|
1428 |
-
# attn_weights = None
|
1429 |
-
|
1430 |
-
# return attn_output, attn_weights, past_key_value
|
1431 |
-
|
1432 |
-
# def _flash_attention_forward(
|
1433 |
-
# self,
|
1434 |
-
# query_states,
|
1435 |
-
# key_states,
|
1436 |
-
# value_states,
|
1437 |
-
# attention_mask,
|
1438 |
-
# query_length,
|
1439 |
-
# dropout=0.0,
|
1440 |
-
# softmax_scale=None,
|
1441 |
-
# ):
|
1442 |
-
# """
|
1443 |
-
# Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
1444 |
-
# first unpad the input, then computes the attention scores and pad the final attention scores.
|
1445 |
-
# Args:
|
1446 |
-
# query_states (`torch.Tensor`):
|
1447 |
-
# Input query states to be passed to Flash Attention API
|
1448 |
-
# key_states (`torch.Tensor`):
|
1449 |
-
# Input key states to be passed to Flash Attention API
|
1450 |
-
# value_states (`torch.Tensor`):
|
1451 |
-
# Input value states to be passed to Flash Attention API
|
1452 |
-
# attention_mask (`torch.Tensor`):
|
1453 |
-
# The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
1454 |
-
# position of padding tokens and 1 for the position of non-padding tokens.
|
1455 |
-
# dropout (`int`, *optional*):
|
1456 |
-
# Attention dropout
|
1457 |
-
# softmax_scale (`float`, *optional*):
|
1458 |
-
# The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
1459 |
-
# """
|
1460 |
-
# if not self._flash_attn_uses_top_left_mask:
|
1461 |
-
# causal = self.is_causal
|
1462 |
-
# else:
|
1463 |
-
# # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in EdgellmFlashAttention2 __init__.
|
1464 |
-
# causal = self.is_causal and query_length != 1
|
1465 |
-
|
1466 |
-
# # Contains at least one padding token in the sequence
|
1467 |
-
# if attention_mask is not None:
|
1468 |
-
# batch_size = query_states.shape[0]
|
1469 |
-
# (
|
1470 |
-
# query_states,
|
1471 |
-
# key_states,
|
1472 |
-
# value_states,
|
1473 |
-
# indices_q,
|
1474 |
-
# cu_seq_lens,
|
1475 |
-
# max_seq_lens,
|
1476 |
-
# ) = self._upad_input(
|
1477 |
-
# query_states, key_states, value_states, attention_mask, query_length
|
1478 |
-
# )
|
1479 |
-
|
1480 |
-
# cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
1481 |
-
# max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
1482 |
-
|
1483 |
-
# attn_output_unpad = flash_attn_varlen_func(
|
1484 |
-
# query_states,
|
1485 |
-
# key_states,
|
1486 |
-
# value_states,
|
1487 |
-
# cu_seqlens_q=cu_seqlens_q,
|
1488 |
-
# cu_seqlens_k=cu_seqlens_k,
|
1489 |
-
# max_seqlen_q=max_seqlen_in_batch_q,
|
1490 |
-
# max_seqlen_k=max_seqlen_in_batch_k,
|
1491 |
-
# dropout_p=dropout,
|
1492 |
-
# softmax_scale=softmax_scale,
|
1493 |
-
# causal=causal,
|
1494 |
-
# )
|
1495 |
-
|
1496 |
-
# attn_output = pad_input(
|
1497 |
-
# attn_output_unpad, indices_q, batch_size, query_length
|
1498 |
-
# )
|
1499 |
-
# else:
|
1500 |
-
# attn_output = flash_attn_func(
|
1501 |
-
# query_states,
|
1502 |
-
# key_states,
|
1503 |
-
# value_states,
|
1504 |
-
# dropout,
|
1505 |
-
# softmax_scale=softmax_scale,
|
1506 |
-
# causal=causal,
|
1507 |
-
# )
|
1508 |
-
|
1509 |
-
# return attn_output
|
1510 |
-
|
1511 |
-
# def _upad_input(
|
1512 |
-
# self, query_layer, key_layer, value_layer, attention_mask, query_length
|
1513 |
-
# ):
|
1514 |
-
# indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
1515 |
-
# batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
1516 |
-
|
1517 |
-
# key_layer = index_first_axis(
|
1518 |
-
# key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
1519 |
-
# indices_k,
|
1520 |
-
# )
|
1521 |
-
# value_layer = index_first_axis(
|
1522 |
-
# value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
|
1523 |
-
# indices_k,
|
1524 |
-
# )
|
1525 |
-
# if query_length == kv_seq_len:
|
1526 |
-
# query_layer = index_first_axis(
|
1527 |
-
# query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
|
1528 |
-
# indices_k,
|
1529 |
-
# )
|
1530 |
-
# cu_seqlens_q = cu_seqlens_k
|
1531 |
-
# max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
1532 |
-
# indices_q = indices_k
|
1533 |
-
# elif query_length == 1:
|
1534 |
-
# max_seqlen_in_batch_q = 1
|
1535 |
-
# cu_seqlens_q = torch.arange(
|
1536 |
-
# batch_size + 1, dtype=torch.int32, device=query_layer.device
|
1537 |
-
# ) # There is a memcpy here, that is very bad.
|
1538 |
-
# indices_q = cu_seqlens_q[:-1]
|
1539 |
-
# query_layer = query_layer.squeeze(1)
|
1540 |
-
# else:
|
1541 |
-
# # The -q_len: slice assumes left padding.
|
1542 |
-
# attention_mask = attention_mask[:, -query_length:]
|
1543 |
-
# query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
|
1544 |
-
# query_layer, attention_mask
|
1545 |
-
# )
|
1546 |
-
|
1547 |
-
# return (
|
1548 |
-
# query_layer,
|
1549 |
-
# key_layer,
|
1550 |
-
# value_layer,
|
1551 |
-
# indices_q,
|
1552 |
-
# (cu_seqlens_q, cu_seqlens_k),
|
1553 |
-
# (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
1554 |
-
# )
|
1555 |
|
1556 |
class EdgellmFlashAttention2(EdgellmAttention):
|
1557 |
"""
|
|
|
366 |
return q_embed, k_embed
|
367 |
|
368 |
|
|
|
|
|
369 |
class EdgellmMLP(nn.Module):
|
370 |
def __init__(self, config):
|
371 |
super().__init__()
|
|
|
373 |
self.intermediate_size = config.intermediate_size
|
374 |
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
375 |
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
376 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
|
|
|
|
377 |
|
378 |
def forward(self, hidden_state):
|
379 |
+
h = self.up_proj(hidden_state)
|
380 |
+
h = self.act_fn(h)
|
381 |
+
h = self.down_proj(h)
|
382 |
+
return h
|
383 |
+
|
384 |
|
385 |
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
386 |
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
|
|
395 |
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
396 |
|
397 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
398 |
# Copied from https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite/blob/main/modeling_deepseek.py
|
399 |
# DeepseekV2Attention with DeepseekV2->Edgellm
|
400 |
|
|
|
621 |
attn_weights = None
|
622 |
|
623 |
return attn_output, attn_weights, past_key_value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
624 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
625 |
|
626 |
class EdgellmFlashAttention2(EdgellmAttention):
|
627 |
"""
|