
    UhF                       d dl mZmZmZmZmZ d dlZd dlmc m	Z
 d dlmZ d dlmc mc mZ d dlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,  e*       rd dl-m.Z. d dl/m0Z0m1Z1 ndZ. e)       r	d dl2m3Z3m4Z4 nd\  Z4Z3 e&       rd dl5m6Z6 ddl7m8Z8  e'jr                  e:      Z;d Z<dKdZ=dej|                  de?dej|                  fdZ@	 dLdej                  dej|                  dej|                  d ej|                  d!eej|                     d"eBd#eBfd$ZC G d% d&ej                        ZD G d' d(ej                        ZEd)ej|                  d*e?fd+ZFd, ZGd- ZH eIe.e3e4f      ZJd. ZK G d/ d0ej                        ZL G d1 d2ej                  j                        ZM G d3 d4ej                        ZN G d5 d6ej                        ZO G d7 d8ej                        ZP G d9 d:ej                        ZQ G d; d<ej                        ZR G d= d>e      ZSe$ G d? d@e"             ZT G dA dBej                        ZUe$ G dC dDeT             ZV	 	 	 dMdEeej|                  eej|                     df   dFee?   d!eej|                     deej|                  e?f   fdGZW G dH dIeTe      ZXg dJZYy)N    )CallableListOptionalTupleUnionN)nn)ACT2FN   )Cache)GenerationMixin)AttentionMaskConverter)GradientCheckpointingLayer)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging)is_causal_conv1d_availableis_mamba_2_ssm_available   )GraniteMoeHybridConfig)selective_state_update)mamba_chunk_scan_combined mamba_split_conv1d_scan_combined)causal_conv1d_fncausal_conv1d_updateNN)	BlockMask)make_flex_block_causal_maskc                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..N   dim)shapetorchcat)xx1x2s      /var/www/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/granitemoehybrid/modeling_granitemoehybrid.pyrotate_halfr2   @   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''    c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer2   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r1   apply_rotary_pos_embr>   G   sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr3   hidden_statesn_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r+   expandreshape)r?   r@   batchnum_key_value_headsslenhead_dims         r1   	repeat_kvrI   b   so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr3   modulequerykeyvalueattention_maskscalingdropoutc                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr(   r
   r'   )r*   dtype)ptrainingr   )rI   num_key_value_groupsr,   matmul	transposer+   r   
functionalsoftmaxfloat32torS   rP   rU   
contiguous)rJ   rK   rL   rM   rN   rO   rP   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r1   eager_attention_forwardrd   n   s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1 ==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r3   c                   \    e Zd ZdZdedef fdZ	 	 	 	 	 	 ddej                  de	ej                     de	ej                     de	e   d	ed
e	ej                     de	eej                  ej                  f      deej                  e	ej                     e	eej                        f   fdZ xZS )GraniteMoeHybridAttentionz=Multi-headed attention from 'Attention Is All You Need' paperconfig	layer_idxc                    t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        d| _        |j                   | _        | j                  | j                  z  | j                  k7  r&t%        d| j                   d| j                   d      t'        j(                  | j                  | j                  | j                  z  |j*                        | _        t'        j(                  | j                  | j                  | j                  z  |j*                        | _        t'        j(                  | j                  | j                  | j                  z  |j*                        | _        t'        j(                  | j                  | j                  |j*                        | _        y )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).bias)super__init__rg   rh   loggerwarning_once	__class____name__attention_dropouthidden_sizenum_attention_heads	num_headsrH   rF   rV   	is_causalattention_multiplierrO   
ValueErrorr   Linearattention_biasq_projk_projv_projo_projselfrg   rh   rp   s      r1   rm   z"GraniteMoeHybridAttention.__init__   s   " !8!8 9 :, , "(!9!9!--33((DNN:#)#=#= $(NNd6N6N$N!22MMDNN*t/?/??QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii 0 0$2B2BI^I^_r3   r?   rN   r:   past_key_value	use_cachecache_positionposition_embeddingsrA   c                     |j                         \  }	}
}| j                  |      }| j                  |      }| j                  |      }|j	                  |	|
| j
                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }||nd\  }}|t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd      rt         j#                  d	       nt$        | j                  j                     } || ||||f| j&                  sd
n| j(                  | j*                  d|\  }}|j	                  |	|
d      }| j-                  |      }|||fS )Nr   r(   r#   )r9   r8   r   eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )rP   rO   r'   )sizer{   r|   r}   viewru   rH   rX   rF   r>   updaterh   rd   rg   _attn_implementationgetrn   ro   r   rU   rr   rO   r~   )r   r?   rN   r:   r   r   r   r   r^   bszq_len_query_statesr_   r`   r8   r9   cache_kwargsattention_interfacerc   ra   s                        r1   forwardz!GraniteMoeHybridAttention.forward   s
    &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm*=*I&|S*';L*VY[^'_$L*%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ "&&sE26kk+.L.88r3   )NNNFNN)rq   
__module____qualname____doc__r   intrm   r,   Tensorr   
LongTensorr   boolr   r   __classcell__rp   s   @r1   rf   rf      s    G`5 `# `F 2637*.59KO69||69 !.69 u//0	69
 !69 69 !!1!1269 &eELL%,,,F&GH69 
u||Xell3XeELL>Q5RR	S69r3   rf   c                   B     e Zd ZdZej
                  dfdef fdZ xZS ) HybridMambaAttentionDynamicCachea  
    A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
    (which has a constant shape regardless of seq_len).

    This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
    and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
    For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
    while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
    For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
    while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
    and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
    Nrg   c                 R   t         	|   ||||       |j                  | _        d| _        |j                  }|j
                  }g | _        g | _        g | _        t        |j                        D ]*  }| j                  |   dk(  r| xj                  t        j                  ||j                  |j                  z  d|j                  z  |z  z   |||      gz  c_        | xj                  t        j                  ||j                   |j"                  |||      gz  c_        | xj                  t        j$                  g g|z  |      gz  c_        | xj                  t        j$                  g g|z  |      gz  c_        | j                  j'                  |       - t        |j                        D cg c]  }t        j$                  g g|z  |       c}| _        t        |j                        D cg c]  }t        j$                  g g|z  |       c}| _        y c c}w c c}w )NFmambar(   devicerS   r   )rl   rm   layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statestransformer_layersrangenum_hidden_layersr,   zerosmamba_expandrs   mamba_n_groupsmamba_n_headsmamba_d_headtensorappend	key_cachevalue_cache)
r   rg   
batch_sizerS   r   conv_kernel_sizessm_state_sizeir   rp   s
            r1   rm   z)HybridMambaAttentionDynamicCache.__init__   s   UF;!'!9!9"'!..--"$v//0 	2A%%a(G3  KK",,v/A/AAAH]H]D]`nDnn(%#%   KK",,++&%#	$ 	   U\\2$2CF%S$TT ELL"
1B6$R#SS''..q11	24 SXX^XpXpRqrQ%,,tj'8HrTYZ`ZrZrTstqELL"
):6Jt sts   3"H4"H$)	rq   r   r   r   r,   float16r   rm   r   r   s   @r1   r   r      s+     JO_c %u5 %u %ur3   r   input_tensorpad_sizec                     t        | j                        dk(  r
ddddd|ddfnddd|ddf}t        j                  j                  j                  | |dd      S )z
    Padding x tensor with `pad_size` on the seq_len dim (dim=1)

    Assumes that we only have tensors of either size 4 or 3
       r   constant)moderM   )lenr+   r,   r   rY   pad)r   r   	pad_shapes      r1   pad_tensor_by_sizer   !  sf     47|7I7I3Ja3OAq!Q!Q/VWYZ\]_gijlmUnI88""<ST"UUr3   c                    t        | |      } t        | j                        dk(  r.| j                  | j                  d   d|| j                  d         S | j                  | j                  d   d|| j                  d   | j                  d         S )z
    Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
    simultaneously splitting it into chunk sequences.

    Assumes that we only have tensors of either size 4 or 3
    r
   r   r'   r(   )r   r   r+   rD   )r   r   
chunk_sizes      r1   reshape_into_chunksr   ,  s     &lH=L
<!###L$6$6q$92z<K]K]^_K`aa ##q!2z<3E3Ea3H,J\J\]^J_
 	
r3   c                 "   | j                  d      } | d   j                  g | j                         | } t        j                  t        j                  ||| j
                  t        j                        d      }| j                  | d      } t        j                  | d      }t        j                  t        j                  ||| j
                  t        j                        d      }|j                  | t        j                         }|S )zo
    More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
    r'   .Nr   diagonalr   rR   r)   )
r   rC   r,   trilonesr   r   masked_fillcumsuminf)r   r   masktensor_segsums       r1   segment_sumr   @  s     ""2&J 2<	*11S<3D3D3FS
SL::ejjZ@S@S[`[e[efqstD++TE15LLL26M ::ejjZ@S@S[`[e[efqrsD!--teeiiZ@Mr3   c                     |N|j                   d   dkD  r<|j                   d   dkD  r*| j                  }| |dddddf   z  j                  |      } | S )zm
    Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
    Nr   r   )r+   rS   r\   )r?   rN   rS   s      r1   apply_mask_to_padding_statesr   W  sa     !n&:&:1&=&AnFZFZ[\F]`aFa##&1d
)CCGGNr3   c                       e Zd ZdZdedef fdZ	 	 	 	 ddej                  de	e
   de	ej                     de	ej                     d	e	ej                     f
d
Z	 	 	 dde	e
   de	ej                     de	ej                     fdZ	 	 	 	 dde	e
   de	ej                     de	ej                     d	e	ej                     fdZ xZS )GraniteMoeHybridMambaLayeruO  
    Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
    A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
    ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
    and is why Mamba is called **selective** state spaces)

    The are a few differences between this and Mamba2Mixer:
    - The variable use_precomputed_states is slightly different due to the HybridCache structure
    - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
    - Some extra variables that our layer doesn't need have been removed
    - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
    rg   rh   c           	         t         |           |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        |j                  | j                  z        | _        || _        |j                  | _        |j                  | _        t"        |j                     | _        |j&                  | _        |j*                  | _        |j.                  | _        |j2                  | _        |j6                  | _        dt;        d      f| _        d| _        d| _         | j                  d| j0                  z  | j                  z  z   | _!        tE        jF                  | jB                  | jB                  |j                  | j                  | jB                  | j                  dz
        | _$        | j                  | jB                  z   | j                  z   }tE        jJ                  | j                  || j(                        | _&        tE        jN                  tQ        jR                  | j                              | _*        tQ        jV                  d| j                  dz         }tE        jN                  tQ        jX                  |            | _-        d	| jZ                  _.        t_        | j                  | j,                  
      | _0        tE        jN                  tQ        jR                  | j                              | _1        d	| jb                  _.        tE        jJ                  | j                  | j                  | j(                        | _2        tf        sth        jk                  d       y th        jk                  d       y )Nr   r   gMbP?g?r(   r   )in_channelsout_channelsrk   kernel_sizegroupspaddingrj   Tepsa  The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)` is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1dzOThe fast path for GraniteMoeHybrid will be used when running the model on a GPU)6rl   rm   r   ru   rs   r   r   r   r   r   r   intermediate_sizerh   mamba_conv_biasuse_conv_bias
hidden_act
activationr	   actmamba_proj_biasuse_biasrms_norm_epslayer_norm_epsilonr   n_groupsr   rH   mamba_chunk_sizer   floattime_step_limittime_step_mintime_step_maxconv_dimr   Conv1dconv1dry   in_proj	Parameterr,   r   dt_biasarangelogA_log_no_weight_decayGraniteMoeHybridRMSNormGatednormDout_projis_fast_path_availablern   ro   )r   rg   rh   projection_sizeArp   s        r1   rm   z#GraniteMoeHybridMambaLayer.__init__q  s   --!--$22 & 3 3!$V%8%84;K;K%K!L"#33 ++&++,.."("5"5--++ 11 !$U5\2" ..T]]1BTEXEX1XXii''--==))A-
 004==@4>>Qyy
 ||EJJt~~$>? LLDNNQ./\\%))A,/
&*

#01G1GTMdMde	ejj89"&		$"8"8$:J:JQUQ^Q^_%>  qrr3   r?   cache_paramsr   rN   seq_idxc                 P   t        ||      }| j                  |      }|j                  \  }}}	| j                  | j                  z  }
|d uxr} |j
                  xro |dk(  xrh |j                  | j                     j                  d   |j                  | j                     j                  d   cxk(  xr |k(  nc xr |d uxr |d   dkD  }|r|j                  d      j                  | j                  | j                  | j                  gd      \  }}}t        ||j                  | j                     | j                  j                   j                  d      | j                  j"                  | j$                        }t'        j                  || j                  |
|
gd      \  }}}t'        j(                  | j*                  j-                                }|d d d df   d d d d d f   j/                  d| j0                  | j                        j3                  t&        j4                        }|d d d d d f   j/                  dd| j0                        }| j6                  d d d df   j/                  d| j0                        }| j8                  d d d df   j/                  d| j0                        }|j;                  || j                  |j                  d   | j                  z        }|j;                  || j                  |j                  d   | j                  z        }|j;                  || j                  | j0                        }t=        |j                  | j                     ||||||d |d
      }|j;                  || j                  | j0                  z        }| j?                  ||      }| jA                  |      d d d df   }|S t'        j(                  | j*                  j-                                }| jB                  d	t-        d
      fk(  ri nd| jB                  i}| jD                  r|tG        || j                  j                   j                  d      | j                  j"                  | j6                  |f| j8                  | jH                  || j$                  | j>                  j                   | j>                  jJ                  | j@                  j                   | j@                  j"                  | j0                  | j                  ddd|}|S |j                  | j                  | j                  | j                  gd      \  }}}|v|jM                  dd      }tN        jP                  jS                  || jT                  |j                  d   z
  df      }|j                  | j                     jW                  |       | j$                  dvrH| jY                  | j                  |jM                  dd            dd |f   jM                  dd            }nqt[        |jM                  dd      | j                  j                   j                  d      | j                  j"                  | j$                  |      jM                  dd      }t        ||      }t'        j                  || j                  |
|
gd      \  }}}t]        |j;                  ||d| j0                        |||j;                  ||| j                  d      |j;                  ||| j                  d      f| jH                  | j8                  d |d| j6                  dd|\  }}|*|(|j                  | j                     jW                  |       |j;                  ||d      }| j?                  ||      }| jA                  |      }|S )Nr   r   r'   r)   .rS   T)zr   dt_softplusr   r   dt_limitF)r   r   r  r   rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesr(   )siluswish)r.   weightrk   r   r  )r   r   r  r  r  r   r  )/r   r   r+   r   r   r   r   rh   r   squeezesplitr   r   ru   r"   r   r  rk   r   r,   expr   r   rC   rH   r\   r[   r   r   r   r   r   r   r   rU   r    r   variance_epsilonrX   r   rY   r   r   copy_r   r!   r   )r   r?   r  r   rN   r  projected_statesr   seq_lenr   groups_time_state_sizeuse_precomputed_statesgatehidden_states_B_CdtBCr  r   r   hidden_states_reshapedoutdt_limit_kwargshidden_states_B_C_transposedr   scan_output	ssm_states                              r1   cuda_kernels_forwardz/GraniteMoeHybridMambaLayer.cuda_kernels_forward  s    5]NS<<6 "/!4!4
GQ!%1D1D!D $ &//&1& ((8>>qA&&t~~6<<Q?& d*& q!A% 	 "*:*B*B1*E*K*K''GR +L +'D#R
 !5!((8""**1-  ! #(++!'')?AWX#M1a 4::++-..A!T3,1d
+222t}}dFYFYZ]]didqdq]rAAq$J&&r2t}}=Bll1dC<077DMMJGq$|$++B>Az4==!''!*2MNAz4==!''!*2MNA%2%7%7
DNNTXTaTa%b"2''7& M *..z4>>DMM;YZM IImT:M --.q$|<C| 
w 4::++-..A$($8$8S%,<O$ObV`bfbvbvUwO }}!56$KK&&..q1KK$$LL ff####'99#3#3 $		 : :#'==#7#7!%!3!3 MM MM%*(-#$ &%l 
A /?.D.D++T]]DNNKQS /E /+'  + 4E3N3NqRS3T0"$--"3"34..1M1S1STV1WWYZ[#K !,,T^^<BB;O??*;;(,$5$?$?1$EFsHWH}U__`acde)% )9+55a;#{{1199!<![[--#'?? ')  i1o & %AARTb$c!&+kk%++-CE[\'#q! *C!&&z7BNFF:wrBFF:wrB*  $ff#(, LL $* &*&Y" (\-E ++DNN;AA)L)..z7BG"iiT: mmK0
r3   c                 *   |j                   \  }}}|j                  }t        ||      }| j                  |      }	|	j	                  | j
                  | j                  | j                  gd      \  }
}}|d uxr} |j                  xro |dk(  xrh |j                  | j                     j                   d   |j                  | j                     j                   d   cxk(  xr |k(  nc xr |d uxr |d   dkD  }|rY|j                  | j                     j                  dd      |j                  | j                  <   |d d dd d f   j                  |j                  | j                     j                        |j                  | j                     d d d d df<   |j                  | j                     j                  | j                  j                   j                        }t#        j$                  || j                  j                   j'                  d      z  d      }| j(                  r|| j                  j*                  z   }| j-                  |      }n|v|j/                  dd      }t0        j2                  j5                  || j6                  |j                   d   z
  df      }|j                  | j                     j9                  |       | j-                  | j                  |j/                  dd            dd |f   j/                  dd            }t        ||      }t#        j                  || j
                  | j:                  | j<                  z  | j:                  | j<                  z  gd      \  }}}t#        j>                  | j@                  jC                                }|r|j                  | j                     j                  }|d d dd d f   d d d df   }|j/                  dd      jE                  ||j                   d   | jF                        }| jH                  d	   jE                  | jH                  j                   d   | jF                        }t"        j0                  j2                  jK                  ||j                  |j                        z         }t#        jL                  || jN                  d   | jN                  d         }|d
   jE                  | j                  | jF                  | j<                        j                  t"        jP                        }t#        j>                  |d	   |z        j                  |      }|jS                  || j:                  d      dd d d f   }|jE                  || j:                  | j                  | j:                  z  |j                   d         jU                         }|jS                  |d|j                   d         }|d	   |dd d d f   z  }|jS                  |d| jF                        }||d	   z  j                  |      }|j                  | j                     j9                  |j                  | j                     |z  |z          |jS                  || j:                  d      dd d d f   }|jE                  || j:                  | j                  | j:                  z  |j                   d         jU                         }|jS                  |d|j                   d         }|j                  | j                     j                  |j                  |j                        }|jW                  || j                  z  | jF                  | j<                        }|jW                  || j                  z  | j<                  d      }t#        jX                  ||      }|jW                  || j                  | jF                        }| jZ                  d	   jE                  | jZ                  j                   d   | jF                        }|||z  z   j                  |j                        }|jS                  |d      d d d df   }n
t0        j2                  jK                  || jH                  z         }t#        jL                  || jN                  d   | jN                  d         }|jS                  ||d| jF                        jC                         }|jS                  ||d| j<                        jC                         }|jS                  ||d| j<                        jC                         }|j]                  | j                  | j:                  z  d| j                        }|j]                  | j                  | j:                  z  d| j                        }| j^                  || j^                  z  z
  | j^                  z  }| jZ                  d	   ta        ||      z  }||d	   z  }|j                  |j                        |z  }||||fD  cg c]  } tc        | || j^                         c} \  }}}}|je                  dddd      }t#        jf                  |d      }!t#        j>                  ti        |            }"|d d d d d d d d d d d f   |d d d d d d d d d d d f   z  }#|#j%                  d      }$|$d	   |"je                  ddddd      d	   z  }%|%j%                  d      }&|&d	   |d d d d d f   z  j%                  d      }'t#        j>                  |!d d d d d d dd f   |!z
        }(||(je                  dddd      d	   z  })|)dd d d f   |d	   z  j%                  d      }*|r<|j                  | j                     d d d df   j                  |*j                        }+nt#        jj                  |*d d d df         }+t#        jl                  |+|*gd      }*t#        j>                  ti        t0        j2                  j5                  |!d d d d d d df   d                  },|,j/                  dd      },|,d
   |*d d d d d df   z  j%                  d      }-|-d d d df   |-d d df   }.}*t#        j>                  |!      }/|dd d d f   |*d d d d d df   z  }0|/je                  dddd      }1|0j%                  d      |1d	   z  }2|'|2z   }|jS                  |d| j                  | jF                        }||z   }|dkD  r|d d d |d d d d f   }|jS                  ||d      }|.1|/|j                  | j                     j9                  |.       d|_        | jo                  ||
      }3| jq                  |3j                  |            }4|4S c c} w )Nr'   r)   r   r   )shiftsdimsr   r(   .r   ).NNr  r   )r*   output_sizer
   r   rR   )r   r   T)9r+   rS   r   r   r  r   r   ru   r   r   rh   r   rollr\   r   r   r  r,   sumr  r   rk   r   rX   r   rY   r   r   r  r   r   r  r   r   rC   rH   r   softplusclampr   r[   rD   r]   r   bmmr   repeat_interleaver   r   r   permuter   r   
zeros_liker-   r   r   )5r   input_statesr  r   rN   r   r  r   rS   r  r  r  r   r  r   r&  r?   r!  r"  r  cache_devicer   dAdBdBxr   ssm_states_reshaped
C_reshapedyr   r   
D_residualtA_cumsumLG_intermediateGM_intermediateMY_diagdecay_statesB_decaystatesprevious_statesdecay_chunk
new_statesr(  state_decay_outC_times_statesstate_decay_out_permutedY_offr'  contextualized_statess5                                                        r1   torch_forwardz(GraniteMoeHybridMambaLayer.torch_forward^  s]    ".!3!3
GQ"" 4L.Q<<5&6&<&<''GR '= '
#
 $ &//&1& ((8>>qA&&t~~6<<Q?& d*& q!A% 	 "7C7O7OPTP^P^7_7d7dlnuw7d7xL$$T^^4ARSTVWYZSZA[A^A^_k_w_wx|  yG  yG  `H  `O  `O  BPL$$T^^4Q2X> '224>>BEET[[M_M_MfMfEgK %		dkk0088;;! !!$58H8H$H! $): ; '/@/J/J1a/P, mm//043H3HKgKmKmnpKq3qst2u ((8>>{K $5F5P5PQRTU5V)WX[]e^e]eXe)f)p)pqrtu)v w89JN[#kk##T]]T5H5H%H$--Z^ZmZmJmn
q! YYtzz'')**!'224>>BIIL Aq!GQc\*Ba#**:rxx|T]]SBll9-44T\\5G5G5JDMMZG$$--b7::bhh3G.GHBR!5!5a!8$:N:Nq:QRB/"))$..$--I\I\]``glgtgt`uA))ByMA-.22,2GB
 		*dmmR8dAFAT]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6AI3a<0B *11*b$--PMi0044L4IC ##DNN399''7"<sB 		*dmmR8dAFAT]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6A &00@CC188[\[b[bCcJ",//*t~~2Mt}}^b^q^q"r
T^^ ;T=P=PRSTJ		-z:Az4>>4==AA y!((a$--HA]Q&&**1773A 		*b)!T3,7A ''T\\(9:BR!5!5a!8$:N:Nq:QRB)11*gr4==Y__aM		*gr43F3FGMMOA		*gr43F3FGMMOA##DNNdmm$CX\XfXf#gA##DNNdmm$CX\XfXf#gA'DOO*CCtVH	*-?x-XXJ *ByM9M](()B.A cpqrtuwxay%z\]&9!Xt&W%z"M1a 		!Q1%A||A2.H 		+a.)A q!Qa23a1dAq!8K6LLN""r"*A y\AIIaAq!,DY,OON""r"*A 	l]1a:%>>CCCJF !99hq!Q|&<x&GIL,..q"b!<YGGGc4l+mI.FFKKPQKRF &"."9"9$.."I!TSV,"W"Z"Zbhbobo"Z"p"'"2"26!RaR%="AYY8a@F))K0A0A(1aQRTV;BWY_0`$abK%//15K%o61dC9PPUUZ[U\J *1crc6 2Jq"u4EIF $ii1OT1oq!T30GGN'6'>'>q!Q'J$#''+.Fy.QQE A		*b$..$--HAJA!|a'1a'(		*gr2A $)A''7==iH26/ii4(
 !%knnU.C D$$I &{s   vc                 r   t         rAd| j                  j                  j                  j                  v r| j                  |||||      S |t        d      |j                  }|B|j                  d   dkD  r0|j                  d   dkD  r||d d d d d f   z  j                  |      }| j                  ||||      S )Ncudaz\`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`r   r   )r   r   r  r   typer)  NotImplementedErrorrS   r+   r\   rR  )r   r?   r  r   rN   r  r^   rS   s           r1   r   z"GraniteMoeHybridMambaLayer.forward.  s     "f0C0C0J0J0O0O&O,,]L.Zhjqrr%n  ##%.*>*>q*AA*E.J^J^_`JadeJe*^Aq$J-GGKKERM!!-~~^^r3   )NNNN)NNN)rq   r   r   r   r   r   rm   r,   r   r   r   r   	IntTensorr)  rR  r   r   r   s   @r1   r   r   c  sJ   As5 As# AsL DH5915-1g||g ?@g !!1!12	g
 !.g %//*gZ DH5915M% ?@M% !!1!12	M%
 !.M%f DH5915-1_ ?@_ !!1!12	_
 !._ %//*_r3   r   c                   (     e Zd Zd fd	ZddZ xZS )r   c                     t         |           t        j                  t	        j
                  |            | _        || _        y Nrl   rm   r   r   r,   r   r  r  r   rs   r   rp   s      r1   rm   z%GraniteMoeHybridRMSNormGated.__init__F  s/    ll5::k#:; #r3   c                    |j                   }|j                  t        j                        }|?|t        j
                  j                  |j                  t        j                              z  }|j                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S Nr(   r'   T)keepdim)rS   r\   r,   r[   r   rY   r  powmeanrsqrtr  r  )r   r?   r  input_dtypevariances        r1   r   z$GraniteMoeHybridRMSNormGated.forwardK  s    #))%((7)BMM,>,>twwu}}?U,VVM $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   gư>rZ  )rq   r   r   rm   r   r   r   s   @r1   r   r   E  s    $
	;r3   r   c                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )GraniteMoeHybridMLPz~
    MLP layer for shared experts

    Args:
        config:
            Configuration object with model hyperparameters.
    rg   c                 h   t         t        |           |j                  | _        |j
                  | _        t        |j                     | _        t        j                  | j                  | j                  dz  d      | _        t        j                  | j                  | j                  d      | _        y )Nr(   Frj   )rl   rg  rm   rs   
input_sizeshared_intermediate_sizer	   r   r   r   ry   input_linearoutput_linearr   rg   rp   s     r1   rm   zGraniteMoeHybridMLP.__init__`  s    !413 ,,!:: !2!23IIdoot7G7G!7KRWXYYt'7'7uUr3   r?   rA   c                     | j                  |      }|j                  dd      }| j                  |d         |d   z  }| j                  |      }|S )Nr(   r'   r)   r   r   )rk  chunkr   rl  )r   r?   chunked_hidden_statess      r1   r   zGraniteMoeHybridMLP.forwardi  s^    ))-8 - 3 3A2 3 >(=a(@ADYZ[D\\**=9r3   )
rq   r   r   r   r   rm   r,   r   r   r   r   s   @r1   rg  rg  W  s2    V5 VU\\ ell r3   rg  c                   ,     e Zd Zd fd	Zd Zd Z xZS )GraniteMoeHybridRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)zF
        GraniteMoeHybridRMSNorm is equivalent to T5LayerNorm
        Nr[  r\  s      r1   rm   z GraniteMoeHybridRMSNorm.__init__r  s1     	ll5::k#:; #r3   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S r^  )	rS   r\   r,   r[   r`  ra  rb  r  r  )r   r?   rc  rd  s       r1   r   zGraniteMoeHybridRMSNorm.forwardz  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler  r+   r  r   s    r1   
extra_reprz"GraniteMoeHybridRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr3   re  )rq   r   r   rm   r   rx  r   r   s   @r1   rr  rr  q  s    $;Jr3   rr  c                   6     e Zd Zdedededdf fdZd Z xZS )GraniteMoeHybridParallelExpertsnum_expertsri  r-  rA   Nc                     t         |           t        j                  t	        j
                  |||            | _        || _        || _        || _	        y)a  
        Initialize the GraniteMoeHybridParallelExperts module.
        The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
        many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
        [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
        [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
        used in vllm.

        Args:
            num_experts (int):
                Number of experts.
            input_size (int):
                Size of the input.
            output_size (int):
                Size of the output.
        N)
rl   rm   r   r   r,   emptyr  r{  ri  r-  )r   r{  ri  r-  rp   s       r1   rm   z(GraniteMoeHybridParallelExperts.__init__  sD    " 	ll5;;{K#TU&$&r3   c                     |j                  |d      }g }t        | j                        D ]7  }|j                  t	        j
                  ||   | j                  |                9 t        j                  |d      }|S )a  
        Forward pass of the GraniteMoeHybridParallelExperts module.

        Args:
            inputs (Tensor):
                Input tensor.
            expert_size:
                Expert size information.

        Returns:
            Tensor: Output tensor.
        r   r)   )	r  r   r{  r   Flinearr  r,   r-   )r   inputsexpert_size
input_listoutput_listr   resultss          r1   r   z'GraniteMoeHybridParallelExperts.forward  sq     \\+1\5
t''( 	HAqxx
1t{{1~FG	H))KQ/r3   rq   r   r   r   rm   r   r   r   s   @r1   rz  rz    s)    'C 'S 's 't '.r3   rz  c                   2     e Zd Zdededef fdZd Z xZS )GraniteMoeHybridTopKGatingri  r{  top_kc                     t         |           || _        || _        || _        t        j                  ||d      | _        y)a  
        Initialize the top-k gating mechanism.
        Args:
            input_size (`int`):
                Size of the input.
            num_experts (`int`):
                Number of experts.
            top_k (`int`):
                Number of top experts to select.
        Frj   N)rl   rm   r{  ri  r  r   ry   layer)r   ri  r{  r  rp   s       r1   rm   z#GraniteMoeHybridTopKGating.__init__  s:     	&$
YYz;UC
r3   c                    | j                  |      j                         }|j                  | j                  d      \  }}t	        j
                  |d      j                  |      }t	        j                  |j                  d      | j                  g|j                  |j                        }|j                  d|d      }|j                         j                  d      }|j                         }|j!                         }	|	j#                  d      \  }
}|j%                  | j                  d      }|j!                         }||   }|||||fS )Nr   r)   r   rS   r   trunc)rounding_mode)r  r   topkr  r,   rZ   type_asr   r   r{  rS   r   scatterlongr/  tolistflattensortdiv)r   r?   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr  top_k_expertsr   index_sorted_expertsbatch_indexbatch_gatess                 r1   r   z"GraniteMoeHybridTopKGating.forward  s.   M*002&,kk$**!k&D#mmmLa8@@O a $"2"23;;L;LU`UgUg
 a2jjl&&q) "((* &--/"/"4"4Q"7*..tzz.Q "))+!"67#[+{FRRr3   r  r   s   @r1   r  r    s'    D3 DS D D&Sr3   r  c                   .     e Zd ZdZdef fdZd Z xZS )GraniteMoeHybridMoEz
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    rg   c                    t         t        |           |j                  | _        |j
                  | _        t        |j                     | _        t        |j                  | j                  | j                  dz        | _        t        |j                  | j                  | j                        | _        t        | j                  |j                  |j                        | _        y )Nr(   )ri  r{  r  )rl   r  rm   rs   ri  r   r	   r   r   rz  num_local_expertsrk  rl  r  num_experts_per_tokrouterrm  s     r1   rm   zGraniteMoeHybridMoE.__init__  s    !413 ,,!33 !2!23;$$doot7G7G!7K
 =$$d&6&6
 100,,
r3   c                    |j                         \  }}}|j                  d|      }| j                  |      \  }}}}}	||   }
| j                  |
|      }|j	                  dd      }| j                  |d         |d   z  }| j                  ||      }||dddf   z  }t        j                  ||z  | j                  f|j                  |j                        }|j                  d||      }|j                  ||| j                        }||	fS )a  
        Forward pass of the mixture of experts layer.

        Args:
            layer_input (Tensor):
                Input tensor.

        Returns:
            Tensor:
                Output tensor.
            Tensor:
                Router logits.
        r'   r(   r)   r   r   Nr  )r   rD   r  rk  ro  r   rl  r,   r   ri  rS   r   	index_addr   )r   layer_inputr   lengthemb_sizer   r  r  r  router_logitsexpert_inputsr?   rp  expert_outputsr   layer_outputs                   r1   r   zGraniteMoeHybridMoE.forward  s    !, 0 0 2VX!))"h7BF++kBZ?;[-#K0))-E - 3 3A2 3 >(=a(@ADYZ[D\\++M;G'+ag*>>S6\4??;>CWCW`n`u`uvq+~F#((fdooF]**r3   )rq   r   r   r   r   rm   r   r   r   s   @r1   r  r    s    
5 
&+r3   r  c                   R    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  deej                     dee	   dee
   dee
   d	eej                     d
ee
   deeej                  ej                  f      deej                  eeej                  ej                  f      f   fdZ xZS )GraniteMoeHybridDecoderLayerrg   rh   c                    t         |           |j                  | _        d | _        t	        |      | _        t        |j                  |j                        | _        t        |j                  |j                        | _	        |j                  | _
        t        |      | _        d | _        |j                  |   dk(  rt        ||      | _        nt!        ||      | _        |j                  |   | _        y )Nr   r   )rl   rm   rs   	self_attnr  block_sparse_moerr  r   input_layernormpost_attention_layernormresidual_multiplierrg  
shared_mlpr   r   r   rf   
layer_typer   s      r1   rm   z%GraniteMoeHybridDecoderLayer.__init__  s    !-- 3F ;6v7I7IvObObc(?@R@RX^XkXk(l%#)#=#= -f5
##I.'93FIFDJ6vyIDN 229=r3   r?   rN   r   r   r   r   output_router_logitsr   rA   c	                    |}
| j                  |      }| j                  | j                  ||||      }d}n | j                  d|||||||d|	\  }}}|
|| j                  z  z   }|}
| j	                  |      }| j                  |      \  }}|| j                  |      z   }|
|| j                  z  z   }|f}|r||fz  }|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
                should not be returned during inference.
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        N)r?   r   r  rN   )r?   rN   r   r   r   r   r    )r  r   r  r  r  r  r  )r   r?   rN   r   r   r   r   r  r   r^   residualself_attn_weightsr   moe_hidden_statesr  outputss                   r1   r   z$GraniteMoeHybridDecoderLayer.forward2  s1   J !,,];::! JJ+-+-	 ' M !%2@$.. 	3+--"3#-$7	3 	3/M,a !=43K3K#KK !55mD+/+@+@+O(=)DOOM,JJ =43K3K#KK ")++G((G''Gr3   )NNFFNFN)rq   r   r   r   r   rm   r,   r   r   r   r   r   r   FloatTensorr   r   r   s   @r1   r  r    s    >5 ># >, 26*.,1$)59/4KOR||R !.R !	R
 $D>R D>R !!1!12R 'tnR &eELL%,,,F&GHR 
u  (51B1BEDUDU1U+V"WW	XRr3   r  c                   B    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZd Zy)GraniteMoeHybridPreTrainedModelmodelTr  past_key_valuesFc                    t        |t        j                        rn|j                  j                  j                  d| j                  j                         |j                  :|j                  j                  j                          nt        |t        j                        ry|j                  j                  j                  d| j                  j                         |j                  |j                  j                  |j                     j                          nt        |t              r&|j                  j                  j                  d       nKt        |t              r;|j                  j                  j                  d| j                  j                         t        |t        j                        rm|j                  j                  j                  d| j                  j                         |j                  %|j                  j                  j                          y y t        |t               r|j"                  j                  j                  d       t%        j&                  t%        j(                  d|j*                  dz               |j,                  _        |j.                  j                  j                  d       y t        |t0              r&|j                  j                  j                  d       y y )Nr   )ra  stdg      ?r   )
isinstancer   ry   r  datanormal_rg   initializer_rangerk   zero_	Embeddingpadding_idxrr  fill_rz  r   r   r   r,   r   r   ru   r   r   r   )r   rJ   s     r1   _init_weightsz-GraniteMoeHybridPreTrainedModel._init_weights  s   fbii(MM&&CT[[5R5R&S{{&  &&(-MM&&CT[[5R5R&S!!-""6#5#56<<> 78MM$$S) ?@MM&&CT[[5R5R&Sfryy*MM&&CT[[5R5R&S{{&  &&( ' :;NN%%c* %		%,,q&:J:JQ:N*O PFLLHHMM$ <=MM$$S) >r3   N)rq   r   r   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cache_is_statefulr  r  r3   r1   r  r    sL    )L&*#78#4"5!N  $"L*r3   r  c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )GraniteMoeHybridRotaryEmbeddingrg   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typerU  defaultinv_freqF)
persistent)rl   rm   hasattrr  r   r  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrg   r   rope_init_fnattention_scalingregister_bufferr  original_inv_freq)r   rg   r   r  rp   s       r1   rm   z(GraniteMoeHybridRotaryEmbedding.__init__  s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r3   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r'   r   mpscpuF)device_typeenabledr(   r)   r  )r  r   rC   r+   r\   r   r  rU  strr,   autocastrX   r-   r8   r  r9   rS   )
r   r.   r:   inv_freq_expandedposition_ids_expandedr  freqsembr8   r9   s
             r1   r   z'GraniteMoeHybridRotaryEmbedding.forward  sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.rZ  )
rq   r   r   r   rm   r,   no_gradr   r   r   r   s   @r1   r  r    s4    /5 /" U]]_<  <r3   r  c                   4    e Zd Zdef fdZd Zd Zee	 	 	 	 	 	 	 	 	 	 	 dde	j                  dee	j                     dee	j                     deeeee	j                      f      d	ee	j                      d
ee   dee   dee   dee   dee   dee	j                     deeef   fd              Z	 ddee	j                  df   de	j                  de	j                  dedef
dZede	j                  dedede	j0                  de	j                  defd       Zd Z xZS )GraniteMoeHybridModelrg   c           	      4   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        d| _        |j$                  | _        |j                  | _        |j&                  | _        | j                  | j(                  z  | _        |j,                  | _        |j.                  | _        |j0                  | _        | j0                  dk(  rt3        |      nd | _        | j7                          y c c}w )Nr   Frope)rl   rm   pad_token_idr  
vocab_sizer   r  rs   embed_tokens
ModuleListr   r   r  layersrr  r   r   gradient_checkpointingembedding_multiplierrt   ru   rH   r  
rope_thetaposition_embedding_typer  
rotary_emb	post_initr   s      r1   rm   zGraniteMoeHybridModel.__init__  sA    !.. ++LL):):F<N<NPTP`P`ammNSTZTlTlNmn)&)<n
 ,F,>,>FDWDWX	&+#$*$?$?!!--33((DNN:'-'E'E$ ++'-'E'E$EIEaEaekEk9&Aqu 	! os   Fc                     | j                   S rZ  r  rw  s    r1   get_input_embeddingsz*GraniteMoeHybridModel.get_input_embeddings  s       r3   c                     || _         y rZ  r  r   rM   s     r1   set_input_embeddingsz*GraniteMoeHybridModel.set_input_embeddings  s
    !r3   	input_idsrN   r:   r  inputs_embedsr   r   output_hidden_statesr  return_dictr   rA   c                 |   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|
|
n| j                   j                  }
|d u |d uz  rt        d      | j                  r%| j                  r|rt        j                  d       d}|| j                  |      }|| j                  z  }|r|t        j                  d       |F||j                         nd}t        j                  |||j                  d   z   |j                         }||j#                  d      }| j%                  |||||      }| j'                  ||      }|}d }| j(                  | j)                  ||      }|rdnd }|rdnd }|	rdnd }d }| j*                  D ]_  }|j,                  d	k(  r|n|}|r||fz  } ||||||||	|
      }|d   }|r	||rdnd   }|r|d   	||d   fz  }|	sQ|d   W||d   fz  }a | j/                  |      }|r||fz  }|r|nd }t1        |||||      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzGraniteMoeHybrid requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. Because one was not provided, no cache will be returned.r   r   r   r  r   )rN   r   r   r   r   r  r   r(   r'   )last_hidden_stater  r?   
attentionsr  )rg   r   r  r   use_return_dictrx   r  rU   rn   ro   r  r  get_seq_lengthr,   r   r+   r   r5   _update_causal_mask_update_mamba_maskr  r   r  r   r   )r   r  rN   r:   r  r  r   r   r  r  r  r   past_seen_tokensrb   
mamba_maskr?   r   all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layer
layer_masklayer_outputs
next_caches                            r1   r   zGraniteMoeHybridModel.forward  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M%(A(AA 0K
 !CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 ,,^^L
 &"??&"&//-"N #7BD0d"6BD!![[ 	>M'4'?'?7'JP[J#!m%55!))."3#-%9$7	M *!,M%28I1q%Q"  #/"}Q'7&99N# $0%-*;)==%?	>B 		-0  -!11+4'$
%+&+%+
 	
r3   r$   r   c           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  }|j                  d   }	|r|j                         }
n1t        |t        j
                        r|j                  d	   n||	z   dz   }
| j                  ||	|
|||j                  d   
      }| j                   j                  dk(  rQ|O|j                   j"                  dv r7|s5t	        j$                  |      j&                  }t        j(                  ||      }|S )Nflash_attention_2r   flex_attentionr   Fr   )r  past_key_values_lengthis_trainingr   r'   )sequence_lengthtarget_lengthrS   r   r   )rT  xpunpu)rg   r   anyr  r,   r   r%   r  is_compileabler   _ignore_causal_mask_sdparU   rS   r+   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   rU  finfomin_unmask_unattended)r   rN   r   r   r  r   r  using_compilable_cacherS   r'  r(  rb   	min_dtypes                r1   r  z)GraniteMoeHybridModel._update_causal_maskj  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCKQZ[Kr3   r'  r(  rS   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |ddddddd|	f<   |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )
fill_valuerS   r   r   r   r   r'   r   )r*   r,   r0  r1  fullr   triur   rD   rC   cloner+   r\   r   )rN   r'  r(  rS   r   r   r^   rb   r4  mask_lengthpadding_masks              r1   r/  zKGraniteMoeHybridModel._prepare_4d_causal_attention_mask_with_cache_position  s   < %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r3   c                 R    |}|d   dkD  s|t        j                  |dk(        rd}|S )zv
        No need for zeroing states when
            1. Cached forward
            2. Attending to all inputs
        r   Nr   )r,   all)r   rN   r   r  s       r1   r  z(GraniteMoeHybridModel._update_mamba_mask  s7     $
!q ^%?EIIn`aNaDbJr3   )NNNNNNNNNNN)F)rq   r   r   r   rm   r	  r  r   r   r,   r   r   r   r   r   r   r  r   r   r   r   r  staticmethodr   rS   r/  r  r   r   s   @r1   r  r    s   5 2!"  '+1537KO59$(,0/3/3&*59t
##t
 !.t
 u//0	t

 "%tE4E4E/F(F"GHt
   1 12t
 D>t
 $D>t
 'tnt
 'tnt
 d^t
 !!1!12t
 
u--	.t
  t
x #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4l	r3   r  gate_logitsr{  c                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
    function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
    experts is too unbalanced.

    Args:
        gate_logits:
            Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts].
        num_experts:
            Number of experts
        top_k:
            The number of experts to route per-token, can be also interpreted as the `top-k` routing
            parameter.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.

    Returns:
        The auxiliary loss.
    Nr   r)   r'   )r  rv  r   r,   r-   r\   r   rY   rZ   r  one_hotra  r   r+   rC   rD   r/  r5   )r?  r{  r  rN   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr   selected_expertsexpert_masktokens_per_expertrouter_prob_per_expertr   r'  r   expert_attention_mask router_per_expert_attention_maskoverall_losss                      r1   load_balancing_loss_funcrM    s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&
O[QRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1G1Q1QRS1TTUL+%%[ .ks   Ic                        e Zd ZdgZdef fdZd Zd Zd Zd Z	d Z
d	 Ze	 	 	 	 	 	 	 	 	 	 	 	 	 dd
eej                     deej                      deej                     deeeeej(                     f      deej(                     deej                     dee   dee   dee   dee   dee   deej                     deeej                   f   deeef   fd       Zed        Z	 	 	 	 	 	 ddZdefdZ xZS )GraniteMoeHybridForCausalLMzlm_head.weightrg   c                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        | j                          y )NFrj   )rl   rm   r  r  r  r   ry   rs   lm_headrouter_aux_loss_coefr  r{  r  r  rm  s     r1   rm   z$GraniteMoeHybridForCausalLM.__init__F  s     *62
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r3   c                 .    | j                   j                  S rZ  r  r  rw  s    r1   r	  z0GraniteMoeHybridForCausalLM.get_input_embeddingsS  s    zz&&&r3   c                 &    || j                   _        y rZ  rT  r  s     r1   r  z0GraniteMoeHybridForCausalLM.set_input_embeddingsV  s    "'

r3   c                     | j                   S rZ  rQ  rw  s    r1   get_output_embeddingsz1GraniteMoeHybridForCausalLM.get_output_embeddingsY  s    ||r3   c                     || _         y rZ  rW  )r   new_embeddingss     r1   set_output_embeddingsz1GraniteMoeHybridForCausalLM.set_output_embeddings\  s	    %r3   c                     || _         y rZ  r  )r   decoders     r1   set_decoderz'GraniteMoeHybridForCausalLM.set_decoder_  s	    
r3   c                     | j                   S rZ  r]  rw  s    r1   get_decoderz'GraniteMoeHybridForCausalLM.get_decoderb  s    zzr3   r  rN   r:   r  r  labelsr   r   r  r  r  r   logits_to_keeprA   c                    ||n| j                   j                  }|
|
n| j                   j                  }
|	|	n| j                   j                  }	||n| j                   j                  }| j                  ||||||||	|
||      }|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }|| j                   j                  z  }d}|:|j                         } | j                  ||fd| j                   j                  i|}d}|
r`t        |r|j                  n|d   | j                   | j"                  |      }|+|| j$                  |j'                  |j(                        z  z  }|s|f|dd z   }|
r|f|z   }||f|z   S |S t+        ||||j,                  |j.                  |j0                  |j                        S )ax  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, GraniteMoeHybridForCausalLM

        >>> model = GraniteMoeHybridForCausalLM.from_pretrained("ibm/PowerMoE-3b")
        >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)r  rN   r:   r  r  r   r   r  r  r  r   r   r  r'   r   )lossaux_lossr  r  r?   r  r  )rg   r   r  r  r  r  r  r   slicerQ  logits_scalingr   loss_functionr  rM  r  r{  r  rR  r\   r   r   r  r?   r  )r   r  rN   r:   r  r  rb  r   r   r  r  r  r   rc  r^   r  r?   slice_indicesr  re  rf  outputs                         r1   r   z#GraniteMoeHybridForCausalLM.forwarde  s   P 2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 &1%<k$++B]B] **)%+'/!5!5#)  
  
8B>SV8W~ot4]kmA}a,?@A$++444\\^F%4%%  ;;11 	D /)4%%'"+  ((	H !11HKK4LLLY,F#"v-'+'7D7V#CVC(#33!//))!//
 	
r3   c                 J    d}| D ]  }|t        fd|D              fz  } |S )Nr  c              3   t   K   | ]/  }|j                  d j                  |j                               1 yw)r   N)index_selectr\   r   ).0
past_statebeam_idxs     r1   	<genexpr>z=GraniteMoeHybridForCausalLM._reorder_cache.<locals>.<genexpr>  s.     nU_j--aZ=N=N1OPns   58)rv  )r  rq  reordered_past
layer_pasts    `  r1   _reorder_cachez*GraniteMoeHybridForCausalLM._reorder_cache  s=    ) 	Jncmnn N	 r3   c                 J   |d u }	|	sZ||d   |j                   d   k\  r|d d |j                   d    d f   }nc|j                   d   |j                   d   k7  rD|d d |f   }n:t        | j                  |j                   d   | j                  | j                        }|T|R|j                         j                  d      dz
  }|j                  |dk(  d       |	s|d d |j                   d    d f   }||	rd|i}
nd|j                         i}
|
j                  |||||d       |
S )Nr'   r   r   r   r  r  )r:   r  r   rN   r   )
r+   r   rg   rS   r   r  r   masked_fill_r]   r   )r   r  r  rN   r  r   r:   r   r^   empty_past_kvmodel_inputss              r1   prepare_inputs_for_generationz9GraniteMoeHybridForCausalLM.prepare_inputs_for_generation  sT    (4/ )!"%);;%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	>Y__Q/DKKO %,*>)..077;a?L%%n&91= +A	0B/B/D,DE $+];L')=)=)?@L ,#2&"0"0	
 r3   c                      y)aG  
        Function overwritten as this class uses its own `HybridMambaAttentionDynamicCache`
        and do not need to initialize the Cache in advance in order to save memory
        (because no back and forth `to_legacy_cache` and `from_legacy_cache` will be performed
        for `HybridMambaAttentionDynamicCache`).
        Fr  rw  s    r1   _supports_default_dynamic_cachez;GraniteMoeHybridForCausalLM._supports_default_dynamic_cache  s     r3   )NNNNNNNNNNNNr   )NNNNNT)rq   r   r   _tied_weights_keysr   rm   r	  r  rX  r[  r_  ra  r   r   r,   r   r   r   r   r   r  r   r   r   r   r   r>  ru  rz  r|  r   r   s   @r1   rO  rO  C  s   *+5 '(&  151537KO59-1$(,0/3/3&*5934j
E,,-j
 !.j
 u//0	j

 "%tE4E4E/F(F"GHj
   1 12j
 ))*j
 D>j
 $D>j
 'tnj
 'tnj
 d^j
 !!1!12j
 c5<</0j
  
u//	0!j
 j
X   7r r3   rO  )rO  r  r  )Nr   )r   )Nr(   N)Ztypingr   r   r   r   r   r,   torch.nn.functionalr   rY   r  (transformers.models.jamba.modeling_jambamodelsjambamodeling_jambatransformers.activationsr	   cache_utilsr   
generationr   modeling_attn_mask_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   utilsr   r   r   r   utils.import_utilsr   r   configuration_granitemoehybridr   +mamba_ssm.ops.triton.selective_state_updater   !mamba_ssm.ops.triton.ssd_combinedr   r    causal_conv1dr!   r"   !torch.nn.attention.flex_attentionr$   integrations.flex_attentionr%   
get_loggerrq   rn   r2   r>   r   r   rI   Moduler   rd   rf   r   r   r   r   r=  r   r   r   r   rg  rr  rz  r  r  r  r  r  r  rM  rO  __all__r  r3   r1   <module>r     s  , : 9     A A +   ) > 9 j j K F \ \ V B Rmm!DD-7**  !;J 
		H	%(6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %:Y9		 Y9z3u~'V'V 3urVU\\ VS V
(( 46FH\]^ __ __D;588?? ;$")) 4Jbii J(*bii *Z-S -S`9+")) 9+xf#= fR $*o $* $*N<bii <D \; \ \B	 "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&dX"A? Xv fr3   