class_docstr: Custom multipack implementation w flash attention 2
class_docstr_tok: ["Custom","multipack","implementation","w","flash","attention","2"]
code: def forward(
      self,
      hidden_states: torch.Tensor,
      attention_mask: Optional[torch.Tensor] = None,
      position_ids: Optional[torch.LongTensor] = None,
      past_key_value: Optional[Cache] = None,
      output_attentions: bool = False,
      use_cache: bool = False,
      cu_seqlens: Optional[torch.Tensor] = None,
      max_seqlen: Optional[torch.Tensor] = None,
      **kwargs,
  ) -> Tuple[
      torch.Tensor,
      Optional[torch.Tensor],
      Optional[Tuple[torch.Tensor]],
  ]:
      if "padding_mask" in kwargs:
          warnings.warn(
              "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
          )
      bsz, q_len, _ = hidden_states.size()
  
      query_states = self.q_proj(hidden_states)
      key_states = self.k_proj(hidden_states)
      value_states = self.v_proj(hidden_states)
  
      query_states = query_states.view(
          bsz, q_len, self.num_heads, self.head_dim
      ).transpose(1, 2)
      key_states = key_states.view(
          bsz, q_len, self.num_key_value_heads, self.head_dim
      ).transpose(1, 2)
      value_states = value_states.view(
          bsz, q_len, self.num_key_value_heads, self.head_dim
      ).transpose(1, 2)
  
      kv_seq_len = key_states.shape[-2]
      if past_key_value is not None:
          if self.layer_idx is None:
              raise ValueError(
                  f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
                  "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
                  "with a layer index."
              )
          kv_seq_len += past_key_value.get_usable_length(
              kv_seq_len, self.layer_idx
          )
      cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
      query_states, key_states = apply_rotary_pos_emb(
          query_states, key_states, cos, sin, position_ids
      )
  
      if past_key_value is not None:
          cache_kwargs = {
              "sin": sin,
              "cos": cos,
          }  # Specific to RoPE models
          key_states, value_states = past_key_value.update(
              key_states, value_states, self.layer_idx, cache_kwargs
          )
  
      # repeat k/v heads if n_kv_heads < n_heads
      key_states = repeat_kv(key_states, self.num_key_value_groups)
      value_states = repeat_kv(value_states, self.num_key_value_groups)
  
      if (
          cu_seqlens is not None
          and max_seqlen is not None
          and cu_seqlens.dim() == 1
      ):
          # special handling using sample packing
          qkv = torch.stack(
              [query_states, key_states, value_states], dim=2
          )  # [bsz, nh, 3, q_len, hd]
          qkv = qkv.transpose(1, 3)  # [bsz, q_len, 3, nh, hd]
          qkv = rearrange(qkv, "b s ... -> (b s) ...")
  
          attn_output = flash_attn_varlen_qkvpacked_func(
              qkv,
              cu_seqlens,
              max_seqlen,
              dropout_p=self.attention_dropout,
              softmax_scale=None,
              causal=True,
          )
          attn_output = rearrange(
              attn_output, "(b s) ... -> b s ...", b=bsz
          )
  
      attn_output = attn_output.reshape(
          bsz, q_len, self.hidden_size
      ).contiguous()
      attn_output = self.o_proj(attn_output)
  
      if not output_attentions:
          attn_weights = None
  
      return attn_output, attn_weights, past_key_value
  
file_path: axolotl/src/axolotl/monkeypatch/mixtral/modeling_mixtral.py
imports: import logging
  import warnings
  from typing import List, Optional, Tuple, Union
  import torch
  from einops import rearrange
  from flash_attn import flash_attn_varlen_qkvpacked_func
  from transformers import Cache, DynamicCache
  from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
  from transformers.modeling_outputs import MoeModelOutputWithPast
  from transformers.models.mixtral.modeling_mixtral import MixtralFlashAttention2, apply_rotary_pos_emb, repeat_kv
  from axolotl.monkeypatch.utils import get_cu_seqlens_from_pos_ids
label_desc: Use image node_id 2 for calling the MixtralMultipackFlashAttention2 obj's underlying member method code with example usage: obj.forward(hidden_states, attention_mask, position_ids, past_key_value, output_attentions, use_cache, cu_seqlens, max_seqlen) and returns: attn_output,  attn_weights,  past_key_value