
    Z j]                        S SK r S SKJr  S SKJrJr  S SKrS SKJs  J	r
  S SKJr  SSKJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJr  SSKJr  SSKJrJr  SSKJrJr  SSK J!r!J"r"  SSK#J$r$J%r%  SSK&J'r'J(r(  SSK)J*r*  SSK+J,r,J-r-J.r.J/r/  SSK0J1r1J2r2  SSK3J4r4J5r5  SSK6J7r7  \/" 5       (       a  S SK8J9r9  \" S5       " S S\Rt                  5      5       r; " S S\Rt                  5      r<S r=\" S5      SGS j5       r>S \R~                  S!\@S"\R~                  4S# jrA SHS$\Rt                  S%\R~                  S&\R~                  S'\R~                  S(\R~                  S-  S)\BS*\BS+\*\,   4S, jjrC  SIS$\Rt                  S%\R~                  S&\R~                  S'\R~                  S(\\R~                  S-4   S)\BS-  S.\BS-  S"\D\R~                  \R~                  4   4S/ jjrE\'" 5       rF\E\FS0'    " S1 S2\Rt                  5      rG " S3 S4\Rt                  5      rH " S5 S6\Rt                  5      rI " S7 S8\5      rJ\- " S9 S:\(5      5       rK\- " S; S<\K5      5       rL    SJS=\R~                  \D\R~                     -  S-  S>\@S-  S?\@S-  S@\@S(\R~                  S-  S"\R~                  \@-  4SA jjrM\- " SB SC\K\5      5       rN " SD SE\\K5      rO/ SFQrPg)K    N)Callable)OptionalUnion)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hubuse_kernel_func_from_hub)compile_friendly_flex_attention)create_causal_mask!create_sliding_window_causal_mask) GenericForSequenceClassificationGradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)AttentionInterfacePreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torch_flex_attn_available)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )
DogeConfig)	BlockMaskRMSNormc                   x   ^  \ rS rSrS
S\SS4U 4S jjjrS\R                  S\R                  4S jrS r	S	r
U =r$ )DogeRMSNorm5   epsreturnNc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z*
DogeRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer*   	__class__s      w/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/doge/modeling_doge.pyr.   DogeRMSNorm.__init__7   s/     	ll5::k#:; #    hidden_statesc                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )N   T)keepdim)	dtypetor0   float32powmeanrsqrtr3   r2   )r4   r:   input_dtypevariances       r7   forwardDogeRMSNorm.forward?   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r9   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler2   shaper3   )r4   s    r7   
extra_reprDogeRMSNorm.extra_reprF   s*    ))*+6$2G2G1HIIr9   )r3   r2   )gư>)__name__
__module____qualname____firstlineno__floatr.   r0   TensorrG   rL   __static_attributes____classcell__r6   s   @r7   r(   r(   5   sB    $ $$ $ $;U\\ ;ell ;J Jr9   r(   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )DogeRotaryEmbeddingJ   inv_freqNconfigc                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultrZ   F)
persistentoriginal_inv_freq)r-   r.   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr[   rope_parametersr]   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r4   r[   devicerope_init_fnrZ   r6   s        r7   r.   DogeRotaryEmbedding.__init__M   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuUr9   ri   ztorch.deviceseq_lenr+   ztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetahead_dimN      ?r   r<   r?   ri   r?   )	rd   getattrr5   num_attention_headsr0   arangeint64r@   rR   )r[   ri   rl   basedimattention_factorrZ   s          r7   re   3DogeRotaryEmbedding.compute_default_rope_parameters]   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r9   c                 L   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r=   r#   mpscpuF)device_typeenabledr<   rx   rq   )rZ   rR   expandrK   r@   ri   
isinstancetypestrr   	transposer0   catcosrf   sinr?   )
r4   xposition_idsinv_freq_expandedposition_ids_expandedr~   freqsembr   r   s
             r7   rG   DogeRotaryEmbedding.forward{   sN    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F#)rf   r[   rb   rc   r]   N)NNN)rN   rO   rP   rQ   r0   rS   __annotations__r$   r.   staticmethodr   intrJ   rR   re   no_gradr   rG   rT   rU   rV   s   @r7   rX   rX   J   s    llVz V V  $(+/"*T!*(* t* 
~u$	%	* *: ]]_<  <r9   rX   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nr=   r<   r   )rK   r0   r   )r   x1x2s      r7   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r9   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  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.
    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.
)	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r7   apply_rotary_pos_embr      sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0Gr9   r:   n_repr+   c                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )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)rK   r   reshape)r:   r   batchnum_key_value_headsslenro   s         r7   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr9   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub  X-   n
[
        R                  R                  U
S[        R                  S9R                  UR                  5      n
[
        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )Nr<   r   r=   )rx   r?   ptrainingr#   )r   num_key_value_groupsr0   matmulr   r   
functionalsoftmaxrA   r@   r?   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r7   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r9   r%   softcapc                 2  ^^ S nS m[        U[        5      (       a  UnOUmTb  TS S 2S S 2S S 2S UR                  S   24   mUU4S jn	[        UUUU	USUSS9u  pUR	                  UR
                  5      nU
R                  SS5      R                  5       n
X4$ )Nc                 n   > Tb  T[         R                  " U T-  5      -  n Tb  U TU   U   U   U   -   n U $ r   )r0   tanh)score	batch_idxhead_idxq_idxkv_idxcausal_maskr   s        r7   	score_mod)flex_attention_forward.<locals>.score_mod   sI    ejj99E"K	28<UCFKKEr9   T)r   
block_mask
enable_gqascale
return_lser#   r<   )r   r%   rK   r   r@   r?   r   r   )r   r   r   r   r   r   r   r   r   r   r   attention_weightsr   s         `     @r7   flex_attention_forwardr      s     JK.),,#
$!!Q?SYYr]?":; &E &"K *,,U[[9''1-88:K))r9   doge_flex_attentionc                     ^  \ rS rSrSS\S\S-  4U 4S jjjr  SS\R                  S\	\R                  \R                  4   S\R                  S-  S	\
S-  S
\	\R                  \R                  S-  \	\R                     S-  4   4
S jjr  SS\R                  S\R                  S\S\R                  S-  4S jjrSrU =r$ )DogeAttentioni  Nr[   	layer_idxc                   > [         TU ]  5         Xl        X l        [	        USUR
                  UR                  -  5      U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        UR                  U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R&                  " [(        R*                  " UR                  5      5      U l        [        R                  " UR                  U R                  -  UR                  UR                  S9U l        [        R                  " UR                  U R                  -  UR
                  UR                  S9U l        [3        U R                  UR4                  S9U l        [3        U R                  UR4                  S9U l        g )Nro   g      ࿩biasr*   )r-   r.   r[   r   rs   r5   rt   ro   r   r   r   attention_dropoutkeep_window_sizer   Linearattention_biasq_projk_projv_projr/   r0   zerosAdt_projo_projr(   rms_norm_epsq_normk_normr4   r[   r   r6   s      r7   r.   DogeAttention.__init__  s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9 & 7 7ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ekk&*D*DEFyy&&68R8RY_YnYn
 ii&&68J8JQWQfQf
 "$--V5H5HI!$--V5H5HIr9   r:   position_embeddingsr   past_key_valuesr+   c                    UR                   S S n/ UQSPU R                  P7nU R                  U R                  U5      R	                  U5      5      R                  SS5      nU R                  U R                  U5      R	                  U5      5      R                  SS5      n	U R                  U5      R	                  U5      R                  SS5      n
Uu  p[        XX5      u  pUb  UR                  XU R                  5      u  pU R                  U
R                  SS5      R                  U
R                   S   U
R                   S   S5      5      n[        R                  " U R                   ["        R$                  " U5      -  5      R                  SS5      nU R'                  UUU R(                  US9n[+        XR,                  5      n[.        R1                  U R2                  R4                  [6        5      nU" U UU	U
4UU R8                  (       d  SOU R:                  U R<                  S.UD6u  nnUR                  " / UQSP76 R?                  5       nU RA                  U5      nUU4$ )	Nr=   r#   r<   r   r   )r:   	dt_statesr   r           )r   r   r   )!rK   ro   r   r   viewr   r   r   r   r   updater   r   r   r0   expr   Fsoftplusprepare_dynamic_maskr   r   r   ALL_ATTENTION_FUNCTIONSget_interfacer[   _attn_implementationr   r   r   r   r   r   )r4   r:   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   r   	attn_maskattention_interfacer   r   s                     r7   rG   DogeAttention.forward"  sE    $))#2.88b8$--8{{4;;}#=#B#B<#PQ[[\]_`a[[]!;!@!@!NOYYZ[]^_
{{=166|DNNqRST&#7RU#[ &'6'='=jX\XfXf'g$J LL""1a(001C1CA1FHZHZ[]H^`bc
	 IIdffqzz)'<<=GGBO	--'!22)	 . 
	 i)B)BC	(?(M(MKK,,.E)
 %8		%

 %#}}C$2H2HLL	%
 	%
!\ "));;;;FFHkk+.L((r9   r   r   c           	         [         R                  " UR                  5      R                  nUR                  nUSS2SS2SSS24   R	                  SSUR
                  S   S5      nUb  [        U[        5      (       d  UR                  [         R                  :X  aB  UR                  n[         R                  " U[         R                  " SUR                  US9U5      nUR                  USS2SS2SS2SUR
                  S   24   S:g  U5      nUR
                  S   U:  ah  [         R                  " XvUR                  S9n[         R                  " XsSSS	S
9R                  n	UR!                  SU	S5      nUR                  US:H  U5      nU$ )a  
The core idea of DMA is to calculate the dynamic attention mask to mask the tokens that should be masked, so as to form sparse attention.

Combine `dt_states` with `attention_mask` to generate the final `attn_mask`.

Args:
    hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision.
    dt_states (`torch.Tensor`): dt_states of shape `(batch_size, num_heads, key_sequence_length)`.
    keep_window_size (`int`): The window size of tokens that are not dynamically masked, and dynamic masking is only performed when the sequence length exceeds this value.
    attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`.
Nr=   r#   r   rr   r   r?   ri   TF)rx   largestsortedrp   )r0   finfor?   minr   rK   r   r%   boolwheretensorri   masked_fill
zeros_liketopkindicesscatter)
r4   r:   r   r   r   	min_dtyper?   r   active_masktopk_indicess
             r7   r   "DogeAttention.prepare_dynamic_maskW  se   $ KK 3 3488	##aD!m,33M''*B
	 %j.S.S##uzz1%++!&"ELL^=R=RZ_$`bk" "--nQ1F[	XZH[F[=[.\`a.aclmI??2!11**9)JZJZ[K ::irSW`efnnL%--b,DK!--kS.@)LIr9   )r   r   r[   r   ro   r   r   r   r   r   r   r   r   r   r   r   NN)i   N)rN   rO   rP   rQ   r$   r   r.   r0   rS   rJ   r
   rG   r   rT   rU   rV   s   @r7   r   r     s    Jz JcDj J JD /3(,3)||3) #5<<#=>3) t+	3)
 3) 
u||U\\D0%2E2LL	M3)r !%.2#||# <<# 	#
 t+# #r9   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )DogeMLPi}  c                   > [         TU ]  5         Xl        UR                  U l        UR                  U l        [
        R                  " U R                  U R                  UR                  S9U l        [
        R                  " U R                  U R                  UR                  S9U l	        [
        R                  " U R                  U R                  UR                  S9U l
        [        UR                     U l        g )Nr   )r-   r.   r[   r5   intermediate_sizer   r   mlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnr4   r[   r6   s     r7   r.   DogeMLP.__init__~  s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r9   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ r   )r  r  r  r  )r4   r   r  s      r7   rG   DogeMLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r9   )r  r[   r  r  r5   r  r  )rN   rO   rP   rQ   r.   rG   rT   rU   rV   s   @r7   r  r  }  s    0 r9   r  c                   j   ^  \ rS rSrS\4U 4S jjrS\R                  S\R                  4S jrSr	U =r
$ )	DogeCDMoEi  r[   c                   > [         TU ]  5         UR                  U l        UR                  U l        [        UR
                     U l        UR                  U l        [        R                  " [        R                  " U R                  5      5      U l        UR                  U l        UR                  U l        [        R                   " U R                  U R                  UR"                  S9U l        [        R                   " U R                  U R                  UR"                  S9U l        [        R                   " U R                  U R                  UR"                  S9U l        [        R                   " U R                  U R                  S-  SS9U l        [        R,                  " U R                  U R                  5      U l        [        R,                  " U R                  U R                  5      U l        g )Nr   r<   F)r-   r.   r5   r  r	   r  r  num_expertsmathfloorsqrtnum_keysnum_experts_per_toktop_knorm_topk_probr   r   r  r  r  r  router_gate	Embedding
down_embedup_embedr  s     r7   r.   DogeCDMoE.__init__  s_   !--!'!9!9V../!--

499T-=-=#>?//
$33 4#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRab 99T%5%5t}}q7HuU ,,t'7'79I9IJT%5%5t7G7GHr9   r:   r+   c                    UR                   u  p4nU R                  U5      R                  SX4-  S5      nUR                  U R                  SS9u  u  pxu  pUR                  S5      UR                  S5      -   nU	R                  S5      U R                  -  U
R                  S5      -   nUR                  " / UR                   S S QSP76 nUR                  " / UR                   S S QSP76 nUR                  U R                  SS9u  pUR                  SU5      n[        R                  " USS9nU R                  (       a  UUR                  SSS9-  nU R                  U5      nU R                  U5      n[        R                  " UUR                  X4-  SS5      5      R                  X4-  S5      nU R!                  U5      U-  n[        R                  " UR                  X4-  SS5      U5      R                  X4S5      nU R#                  U R!                  U R%                  U5      5      U R'                  U5      -  5      nUU-   nX4$ )Nr<   r=   r   r   T)rx   r>   r#   )rK   r*  r   r	  r&  r   r(  gatherr   r   r)  sumr,  r-  r0   r   r  r  r  r  )r4   r:   r   bszrl   _router_logitsscores_xscores_y	indices_x	indices_y
all_scoresall_indicesscoresposition_indicesr
  routing_weightsr,  r-  experts_weightsexperts_statess                        r7   rG   DogeCDMoE.forward  s+   
 (--a ((7<<QrR 8E7I7I$--]_7I7`44y''+h.@.@.DD
))"-=	@S@STV@WW__@j&6&6s&;@R@
!&&C(9(9#2(>CC#-??4::2?#F $$R)9:))F322r42HHO __W-
==),,z=3E3EcmUWYZ3[\aabeboqst++o6Ho&:&:3=!R&PRZ[``adoqrt{{4>>-3P'QTXT`T`anTo'op%6++r9   )r  r,  r  r  r5   r  r)  r"  r&  r*  r(  r-  r  )rN   rO   rP   rQ   r$   r.   r0   rS   rG   rT   rU   rV   s   @r7   r   r     s5    Iz I.,||, 
	, ,r9   r   c                   ^  ^  \ rS rSrSS\S\S-  4U 4S jjjr     SS\R                  S\	\R                  \R                  4   S-  S\R                  S-  S	\R                  S-  S
\S-  S\S-  S\\   S\	\R                  \	\R                  \R                  4   S-  4   4S jjrSrU =r$ )DogeDecoderLayeri  Nr[   r   c                 (  > [         TU ]  5         UR                  U l        [        UR                  UR
                  S9U l        [        XS9U l        [        R                  " [        R                  " UR                  5      5      U l        [        UR                  UR
                  S9U l        UR                  (       d  [!        U5      O
[#        U5      U l        [        R                  " [        R                  " UR                  5      5      U l        g )Nr   )r[   r   )r-   r.   hidden_dropoutr(   r5   r   input_layernormr   	self_attnr   r/   r0   r1   input_residualpost_attention_layernormis_moer  r   mlppost_attention_residualr   s      r7   r.   DogeDecoderLayer.__init__  s    $33*6+=+=6CVCVW&fJ ll5::f6H6H+IJ(3F4F4FFL_L_(`%*0--76?Yv=N')||EJJv?Q?Q4R'S$r9   r:   r   r   r   r   	use_cacher   r+   c           
         UnU R                  U5      nU R                  " SUUUUUUS.UD6u  p[        R                  " XR                  U R
                  S9nU R                  U-  U-   nUnU R                  U5      nU R                  U5      n[        R                  " XR                  U R
                  S9nU R                  U-  U-   nU$ )N)r:   r   r   r   r   rM  r    )
rE  rF  r   r   rD  r   rG  rH  rJ  rK  )
r4   r:   r   r   r   r   rM  r   residualself_attn_weightss
             r7   rG   DogeDecoderLayer.forward  s     !,,];+/>> ,
' 3)%+,
 ,
( 		-3F3FQUQ^Q^_++h6F !55mD/		-3F3FQUQ^Q^_44x?-Or9   )rD  rE  rG  rJ  rH  rK  rF  r   )NNNNF)rN   rO   rP   rQ   r$   r   r.   r0   rS   rJ   
LongTensorr
   r  r   r   FloatTensorrG   rT   rU   rV   s   @r7   rB  rB    s    
Tz 
TcDj 
T 
T IM.204(,!& ||  #5<<#=>E  t+	 
 &&-    $;  +,  
u  %(9(95;L;L(L"MPT"TT	U   r9   rB  c                      ^  \ rS rSr% \\S'   SrSrS/rS/r	Sr
SrSrSrSr\" \SS	9\\S
.r\R*                  " 5       U 4S j5       rSrU =r$ )DogePreTrainedModeli  r[   modelTrB  r   Fr#   )index)r4  r:   
attentionsc                   > [         TU ]  U5        [        U[        5      (       a3  [	        US5      (       a!  [
        R                  " UR                  5        gg[        U[        5      (       ad  [	        US5      (       a   [
        R                  " UR                  5        [	        US5      (       a!  [
        R                  " UR                  5        ggg)zInitialize the weightsr   rG  rK  N)r-   _init_weightsr   r   hasattrinitzeros_r   rB  ones_rG  rK  )r4   r   r6   s     r7   r[  !DogePreTrainedModel._init_weights  s     	f%fm,,vs##FHH% $ 011v/00

6001v899

699: : 2r9   rO  )rN   rO   rP   rQ   r$   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr!   r   rB  r   _can_record_outputsr0   r   r[  rT   rU   rV   s   @r7   rV  rV    sv    &*#+,#4"5 N""&'	;)# ]]_
; 
;r9   rV  c                     ^  \ rS rSrS\4U 4S jjr\\\      SS\	R                  S-  S\	R                  S-  S\	R                  S-  S\S-  S	\	R                  S-  S
\S-  S\\   S\4S jj5       5       5       rSrU =r$ )	DogeModeli  r[   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [
        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        [#        US9U l        SU l        U R)                  5         g s  snf )Nr   r[   F)r-   r.   pad_token_idpadding_idx
vocab_sizer   r+  r5   embed_tokens
ModuleListrangenum_hidden_layersrB  layersr(   r   normrX   
rotary_embgradient_checkpointing	post_initr   s      r7   r.   DogeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammBGH`H`BabBaYf0Bab
   2 28K8KL	-V<&+# 	 cs   C?N	input_idsr   r   r   inputs_embedsrM  r   r+   c           
      ~   US L US L-  (       a  [        S5      eU(       a  Uc  [        U R                  S9nUc  U R                  U5      nUcU  Ub  UR	                  5       OSn[
        R                  " UR                  S   UR                  S9U-   nUR                  S5      nU R                  R                  c  [        O[        n	U	" U R                  UUUUS9n
UnU R                  XS9nU R                  S U R                  R                    H  nU" U4U
UUUUS.UD6nM     U R!                  U5      n[#        UUS	9$ )
Nz:You must specify exactly one of input_ids or inputs_embedsrn  r   r#   )ri   )r[   r}  r   r   r   )r   )r   r   r   rM  r   )last_hidden_stater   )
ValueErrorr   r[   rr  get_seq_lengthr0   ru   rK   ri   r   sliding_windowr   r   rx  rv  ru  rw  r   )r4   r|  r   r   r   r}  rM  r   past_seen_tokensmask_functionr   r:   r   decoder_layers                 r7   rG   DogeModel.forward(  s^    -t";<YZZ0*$++>O  --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L.2kk.H.H.P*Vw#;;')+%
 &"oomoW![[)H4;;+H+HIM)*) /#$7 M J 		-0%++
 	
r9   )rr  ry  rv  rw  rp  rx  rq  )NNNNNN)rN   rO   rP   rQ   r$   r.   r    r"   r   r0   rS  rS   r
   rT  r  r   r   r   rG   rT   rU   rV   s   @r7   rl  rl    s    z     .2.204(,26!%4
##d*4
 t+4
 &&-	4

 4
 ((4/4
 $;4
 +,4
 
 4
    4
r9   rl  gate_logitsr"  r&  r(  c                    U b  [        U [        5      (       d  gU S   R                  nU S   R                  n/ n/ nU  GH  n	U	R	                  U5      n	U	R                  USS9u  u  pu  pU
R                  S5      UR                  S5      -   nUR                  S5      U-  UR                  S5      -   nUR                  " / UR                  SS QSP76 nUR                  " / UR                  SS QSP76 nUR                  USS9u  nnUR                  SU5      n[        R                  " USS9nUR                  U5        UR                  U5        GM     [        R                  " USS9n[        R                  " USS9nUcu  UR                  S5      n[        R                  " XUS9n[        R                   " XuUS9nUR#                  SUU5      UR                  S   -  n[        R$                  " USS9nGO;UR                  u  nn['        U 5      nUSSS2SS2S4   R)                  UUUU45      R+                  S5      R	                  U5      nUR                  S5      UR-                  5          n[        R                  " XUS9n[        R                   " XuUS9nUR#                  SUU5      [        R.                  " U5      -  nUSSS2SS2S4   R)                  UUUU45      R+                  SU5      R	                  U5      n[        R.                  " UU-  SS9[        R.                  " USS9-  n[        R.                  " UU-  5      nUU-  $ )a  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

See Switch Transformer (https://huggingface.co/papers/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 `router_gate`, should be a tuple of model.config.num_hidden_layers tensors of
        shape [2, batch_size * sequence_length, num_keys].
    num_experts:
        Number of experts
    num_keys:
        Number of keys
    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   r   )r   rJ   r?   ri   r@   r	  r   r   rK   r0  r   r   appendr0   r   r   	ones_likescatter_add_rC   lenr   r   r  r1  )r  r"  r&  r(  r   compute_dtypecompute_deviceall_expert_indicesall_routing_weightslayer_gate_logitsr5  r6  r7  r8  r9  r:  r3  r<  expert_indicesr=  tokens_per_expertpadrouter_prob_per_expert
batch_sizesequence_lengthru  expert_attention_mask router_per_expert_attention_maskoverall_losss                                r7   load_balancing_loss_funcr  b  si   @ *[%"@"@N((M ^**N(-00@7H7M7Mh\^7M7_44y''+h.@.@.DD
))"-89;N;Nr;RR__@j&6&6s&;@R@
!&&C(9(9#2(>CC(ooeo<$++B0@A))JB7!!.1""?3! )" #51=))$7Q?/44R8!KKQ_`oo0n]-::1>PRUVYkYqYqrsYtt "',?Q!G&4&:&:#
O, 4At+,V&
OUKLWR[R	 	 044R89N9S9S9UV "KKQ_`oo0n]-::1>PRUVY^YbYb!Z
 
 4At+,V&
O[QRWR%R	 	) "'+>Aa+agh!ilqlulu,!m
 "
 99.1GGHL+%%r9   c                   \  ^  \ rS rSrSS0rSS0rSS/S/40rU 4S jr\\	         SS
\
R                  S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\\
R                  -  S\S	-  S\\   S\4S jj5       5       rSrU =r$ )DogeForCausalLMi  zlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr:   logitsc                 J  > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  U l	        UR                  U l
        UR                  U l        U R                  5         g )NFr   )r-   r.   rl  rW  rq  r   r   r5   r  router_aux_loss_coefr"  r'  rz  r  s     r7   r.   DogeForCausalLM.__init__  s     v&
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	r9   Nr|  r   r   r   r}  labelsrM  logits_to_keepoutput_router_logitsr   r+   c
           
         U	b  U	OU R                   R                  n	U R                  " SUUUUUUS.U
D6nUR                  n[	        U[
        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      nSnUb  U R                  " XU R                  40 U
D6nSnU	(       a  [        UR                  U R                  [        R                  " [        R                  " U R                  5      5      U R                   U5      nUb*  XR"                  UR%                  UR&                  5      -  -  n[)        UUUUR*                  UR,                  UR.                  UR                  S9$ )a  
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, DogeForCausalLM

>>> model = DogeForCausalLM.from_pretrained("SmallDoge/Doge-320M")
>>> tokenizer = AutoTokenizer.from_pretrained("SmallDoge/Doge-320M")

>>> 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|  r   r   r   r}  rM  )lossaux_lossr  r   r:   rY  r4  rO  )r[   r  rW  r  r   r   slicer  loss_functionrq  r  r4  r"  r#  r$  r%  r'  r  r@   ri   r   r   r:   rY  )r4   r|  r   r   r   r}  r  rM  r  r  r   outputsr:   slice_indicesr  r  r  s                    r7   rG   DogeForCausalLM.forward  sh   L %9$D $++JjJj 	
 +/** +
)%+'+
 +
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD/%%  

499T%5%567((H !11HKK4LLL(#33!//))!//
 	
r9   )r  rW  r"  r'  r  rq  )	NNNNNNNr   N)rN   rO   rP   rQ   _tied_weights_keys_tp_plan_pp_planr.   r   r   r0   rS  rS   r
   rT  r  r   r   r   r   rG   rT   rU   rV   s   @r7   r  r    s5   *,GH23H_-z:;H
  .2.204(,26*.!%-.,0O
##d*O
 t+O
 &&-	O

 O
 ((4/O
   4'O
 $;O
 ell*O
 #TkO
 +,O
 
#O
  O
r9   r  c                       \ rS rSrSrg)DogeForSequenceClassificationi2  rO  N)rN   rO   rP   rQ   rT   rO  r9   r7   r  r  2  s    r9   r  )r  rl  rV  r  )r#   )r   r  )NNr<   N)Qr#  collections.abcr   typingr   r   r0   torch.nn.functionalr   r   r    r   r]  activationsr	   cache_utilsr
   r   
generationr   integrationsr   r   integrations.flex_attentionr   masking_utilsr   r   modeling_layersr   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r    utils.output_capturingr!   r"   configuration_doger$   !torch.nn.attention.flex_attentionr%   Moduler(   rX   r   r   rS   r   r   rR   r   rJ   r   r   r   r  r   rB  rV  rl  r  r  r  __all__rO  r9   r7   <module>r     s3  .  $ "     & ! . ) Q J R [ Q K A & g g G E *  !!; Y'J")) J (J(><")) ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%> ! +*II+*<<+* 
+* <<	+*
 %,,34+* T\+* T\+* 5<<%&+*\ -. 1G - .wBII wtbii  6,		 6,r-1 -` ;/ ; ;> H
# H
 H
Z #*.g&ell 33d:g&tg& Djg& 	g&
 LL4'g& \\Cg&T b
)? b
 b
J	$DFY 	 cr9   