
    i                     ^   d dl Z d dlmZ d dlmZmZ d dlZd dlmc m	Z
 d dlmZ ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZmZ ddlmZ ddl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% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5  e/       rd dl6m7Z7  ed       G d dejp                               Z9 G d dejp                        Z:d Z; ed      dFd       Z<dejz                  d e>d!ejz                  fd"Z?	 dGd#ejp                  d$ejz                  d%ejz                  d&ejz                  d'ejz                  dz  d(e@d)e@d*e*e,   fd+ZA	 	 dHd#ejp                  d$ejz                  d%ejz                  d&ejz                  d'eejz                  d,f   d(e@dz  d-e@dz  d!eBejz                  ejz                  f   fd.ZC e'       ZDeCeDd/<    G d0 d1ejp                        ZE G d2 d3ejp                        ZF G d4 d5ejp                        ZG G d6 d7e      ZHe- G d8 d9e(             ZIe- G d: d;eI             ZJ	 	 	 	 dId<ejz                  eBejz                     z  dz  d=e>dz  d>e>dz  d?e>d'ejz                  dz  d!ejz                  e>z  fd@ZKe- G dA dBeIe             ZL G dC dDeeI      ZMg dEZNy)J    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)OutputRecordercheck_model_inputsmaybe_autocast   )
DogeConfig)	BlockMaskRMSNormc                   ,     e Zd Zd fd	Zd Zd Z xZS )DogeRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z:
        DogeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      p/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/doge/modeling_doge.pyr*   zDogeRMSNorm.__init__6   s1     	ll5::k#:; #    c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor,   float32powmeanrsqrtr/   r.   )r0   hidden_statesinput_dtypevariances       r4   forwardzDogeRMSNorm.forward>   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r5   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler.   shaper/   )r0   s    r4   
extra_reprzDogeRMSNorm.extra_reprE   s*    ))*+6$2G2G1HIIr5   )gư>)__name__
__module____qualname__r*   rC   rG   __classcell__r3   s   @r4   r'   r'   4   s    $;Jr5   r'   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )DogeRotaryEmbeddinginv_freqNconfigc                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultrO   F)
persistentoriginal_inv_freq)r)   r*   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrP   rope_parametersrR   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r0   rP   devicerope_init_fnrO   r3   s        r4   r*   zDogeRotaryEmbedding.__init__L   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr5   r^   ztorch.deviceseq_lenreturnztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        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   r7   r:   r^   r:   )	rY   getattrr1   num_attention_headsr,   arangeint64r;   float)rP   r^   r`   basedimattention_factorrO   s          r4   rZ   z3DogeRotaryEmbedding.compute_default_rope_parameters\   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r5   c                 N   | 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        |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   r8   r"   mpscpuF)device_typeenabledr7   rn   rf   )rO   rl   expandrF   r;   r^   
isinstancetypestrr!   	transposer,   catcosr[   sinr:   )
r0   xposition_idsinv_freq_expandedposition_ids_expandedrs   freqsembr|   r}   s
             r4   rC   zDogeRotaryEmbedding.forwardz   sR    !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$NNNN)rH   rI   rJ   r,   Tensor__annotations__r#   r*   staticmethodr   intrE   rl   rZ   no_gradr   rC   rK   rL   s   @r4   rN   rN   I   s    llVz V  $(+/"*T!*(* t* 
~u$	%	* *: U]]_<  <r5   rN   c                     | 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..Nr8   r7   ru   )rF   r,   r{   )r~   x1x2s      r4   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r5   rotary_pos_embc                     |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.
        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          r4   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr5   r@   n_repra   c                     | 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)rF   rv   reshape)r@   r   batchnum_key_value_headsslenrd   s         r4   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr5   modulequerykeyvalueattention_maskscalingdropoutkwargsc                 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 )Nr7   r   r8   )rn   r:   ptrainingr"   )r   num_key_value_groupsr,   matmulrz   rF   r   
functionalsoftmaxr<   r;   r:   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r4   eager_attention_forwardr      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$$r5   r$   softcapc           
      .   d }d t        |t              r|}n|d d d d d d d |j                  d   f   fd}	t        ||||	|d|d      \  }
}|j	                  |j
                        }|
j                  dd      j                         }
|
|fS )Nr   c                 h    t        j                  | z        z  } | |   |   |   |   z   } | S r   )r,   tanh)score	batch_idxhead_idxq_idxkv_idxr   r   s        r4   	score_modz)flex_attention_forward.<locals>.score_mod   sI    ejj99E"K	28<UCFKKEr5   T)r   
block_mask
enable_gqascale
return_lser"   r7   )rw   r$   rF   r   r;   r:   rz   r   )r   r   r   r   r   r   r   r   r   r   r   attention_weightsr   s         `     @r4   flex_attention_forwardr      s     JK.),#
$!!Q?SYYr]?":; &E &"K" *,,U[[9''1-88:K)))r5   doge_flex_attentionc                       e Zd Zddededz  f fdZ	 	 	 ddej                  deej                  ej                  f   dej                  dz  de	dz  d	ej                  dz  d
eej                  ej                  dz  eej                     dz  f   fdZ	 	 ddej                  dej                  dedej                  dz  fdZ xZS )DogeAttentionNrP   	layer_idxc                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        |j                  | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j&                  t)        j*                  |j                              | _        t        j                  |j                  | j                  z  |j                  |j                        | _        t        j                  |j                  | j                  z  |j
                  |j                        | _        t3        | j                  |j4                        | _        t3        | j                  |j4                        | _        y )Nrd   g      ࿩biasr2   )r)   r*   rP   r   rh   r1   ri   rd   r   r   r   attention_dropoutkeep_window_sizer   Linearattention_biasq_projk_projv_projr+   r,   zerosAdt_projo_projr'   rms_norm_epsq_normk_normr0   rP   r   r3   s      r4   r*   z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r5   r@   position_embeddingsr   past_key_valuescache_positionra   c                    |j                   d d }g |d| j                  }| j                  | j                  |      j	                  |            j                  dd      }	| j                  | j                  |      j	                  |            j                  dd      }
| j                  |      j	                  |      j                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}| j                  |j                  dd      j                  |j                   d   |j                   d   d            }t        j                  | j                   t#        j$                  |      z        j                  dd      }| j'                  ||| j(                  |      }t+        || j,                        }t.        j1                  | j2                  j4                  t6              } || |	|
|f|| j8                  sdn| j:                  | j<                  d	|\  }} |j                  g |d j?                         }| jA                  |      }||fS )
Nr8   r"   r7   )r}   r|   r   r   r   )r@   	dt_statesr   r           )r   r   r   )!rF   rd   r   r   viewrz   r   r   r   r   updater   r   r   r,   expr   Fsoftplusprepare_dynamic_maskr   r   r   ALL_ATTENTION_FUNCTIONSget_interfacerP   _attn_implementationr   r   r   r   r   r   )r0   r@   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r|   r}   cache_kwargsr   	attn_maskattention_interfacer   r   s                       r4   rC   z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&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$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	%
 	%
!\ *k));;;;FFHkk+.L((r5   r   r   c           	         t        j                  |j                        j                  }|j                  }|dddddddf   j	                  dd|j
                  d   d      }|t        |t              s|j                  t         j                  k(  rC|j                  }t        j                  |t        j                  d|j                  |      |      }|j                  |ddddddd|j
                  d   f   dk7  |      }|j
                  d   |kD  rnt        j                  |||j                        }t        j                  ||ddd	
      j                  }	|j!                  d|	d      }|j                  |dk(  |      }|S )a8  
        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)`.
        Nr8   r"   r   rg   r   r:   r^   TF)rn   largestsortedre   )r,   finfor:   minrv   rF   rw   r$   boolwheretensorr^   masked_fill
zeros_liketopkindicesscatter)
r0   r@   r   r   r   	min_dtyper:   r   active_masktopk_indicess
             r4   r   z"DogeAttention.prepare_dynamic_maskZ  sg   $ KK 3 3488	##aD!m,33M''*B
	 %j.S##uzz1%++!&"ELL^=R=RZ_$`bk" "--nQ1F[	XZH[F[=[.\`a.aclmI??2!11**9E)JZJZ[K ::i1ArSW`efnnL%--b,DK!--kS.@)LIr5   r   r   )i   N)rH   rI   rJ   r#   r   r*   r,   r   rE   r
   
LongTensorrC   r   rK   rL   s   @r4   r   r     s   Jz JcDj JD /3(,266)||6) #5<<#=>6) t+	6)
 6) ((4/6) 
u||U\\D0%2E2LL	M6)x !%.2#||# <<# 	#
 t+#r5   r   c                   $     e Zd Z fdZd Z xZS )DogeMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        |j                     | _        y )Nr   )r)   r*   rP   r1   intermediate_sizer   r   mlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnr0   rP   r3   s     r4   r*   zDogeMLP.__init__  s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r5   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r   )r  r  r
  r  )r0   r~   r  s      r4   rC   zDogeMLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r5   )rH   rI   rJ   r*   rC   rK   rL   s   @r4   r  r    s    0r5   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )	DogeCDMoErP   c                    t         |           |j                  | _        |j                  | _        t        |j
                     | _        |j                  | _        t        j                  t        j                  | j                              | _        |j                  | _        |j                  | _        t        j                   | j                  | j                  |j"                        | _        t        j                   | j                  | j                  |j"                        | _        t        j                   | j                  | j                  |j"                        | _        t        j                   | j                  | j                  dz  d      | _        t        j,                  | j                  | j                        | _        t        j,                  | j                  | j                        | _        y )Nr   r7   F)r)   r*   r1   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     r4   r*   z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r5   r@   ra   c                    |j                   \  }}}| j                  |      j                  d||z  d      }|j                  | j                  d      \  \  }}\  }	}
|j                  d      |j                  d      z   }|	j                  d      | j                  z  |
j                  d      z   } |j                  g |j                   d d d } |j                  g |j                   d d d }|j                  | j                  d      \  }}|j                  d|      }t        j                  |d      }| j                  r||j                  dd      z  }| j                  |      }| j                  |      }t        j                  ||j                  ||z  dd            j                  ||z  d      }| j!                  |      |z  }t        j                  |j                  ||z  dd      |      j                  ||d      }| j#                  | j!                  | j%                  |            | j'                  |      z        }||z   }||fS )Nr7   r8   ru   r   T)rn   r9   r"   )rF   r  r   r   r  r   r  gatherr   r   r  sumr  r  r,   r   r  r  r
  r  )r0   r@   r   bszr`   _router_logitsscores_xscores_y	indices_x	indices_y
all_scoresall_indicesscoresposition_indicesr   routing_weightsr  r  experts_weightsexperts_statess                        r4   rC   zDogeCDMoE.forward  sF   
 (--Wa ((7<<QgrR 8E7I7I$--]_7I7`484y)''+h.@.@.DD
))"-=	@S@STV@WW$Z__@j&6&6s&;@R@
&k&&C(9(9#2(>CC#-??4::2?#F  $$R)9:))F322r42HHO __W-
==),,z=3E3EcGmUWYZ3[\aabehoboqst++o6Ho&:&:3=!R&PRZ[``adfmoqrt{{4>>-3P'QTXT`T`anTo'op%6m++r5   )	rH   rI   rJ   r#   r*   r,   r   rC   rK   rL   s   @r4   r  r    s0    Iz I.,||, 
	,r5   r  c                   l    e Zd Zddededz  f fdZ	 	 	 	 	 	 ddej                  deej                  ej                  f   dz  dej                  dz  dej                  dz  d	e
dz  d
edz  dej                  dz  dee   deej                  eej                  ej                  f   dz  f   fdZ xZS )DogeDecoderLayerNrP   r   c                 *   t         |           |j                  | _        t        |j                  |j
                        | _        t        ||      | _        t        j                  t        j                  |j                              | _        t        |j                  |j
                        | _        |j                  st!        |      n
t#        |      | _        t        j                  t        j                  |j                              | _        y )Nr   )rP   r   )r)   r*   hidden_dropoutr'   r1   r   input_layernormr   	self_attnr   r+   r,   r-   input_residualpost_attention_layernormis_moer  r  mlppost_attention_residualr   s      r4   r*   zDogeDecoderLayer.__init__  s    $33*6+=+=6CVCVW&f	J ll5::f6H6H+IJ(3F4F4FFL_L_(`%*0--76?Yv=N')||EJJv?Q?Q4R'S$r5   r@   r   r   r   r   	use_cacher   r   ra   c                    |}	| j                  |      } | j                  d|||||||d|\  }}
t        j                  || j                  | j
                        }| j                  |	z  |z   }|}	| j                  |      }| j                  |      }t        j                  || j                  | j
                        }| j                  |	z  |z   }|S )N)r@   r   r   r   r   r<  r   r    )
r5  r6  r   r   r4  r   r7  r8  r:  r;  )r0   r@   r   r   r   r   r<  r   r   residualself_attn_weightss              r4   rC   zDogeDecoderLayer.forward  s     !,,];+94>> 	,
' 3)%+)	,
 	,
(( 		-43F3FQUQ^Q^_++h6F !55mD/		-43F3FQUQ^Q^_44x?-Or5   r   )NNNNFN)rH   rI   rJ   r#   r   r*   r,   r   rE   r  r
   r   r   r   FloatTensorrC   rK   rL   s   @r4   r2  r2    s   
Tz 
TcDj 
T IM.204(,!&26"||" #5<<#=>E" t+	"
 &&-" " $;" ((4/" +," 
u  %(9(95;L;L(L"MPT"TT	U"r5   r2  c                        e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZ eed      eed	Z ej(                          fd
       Z xZS )DogePreTrainedModelrP   modelTr2  r   Fr"   )index)r%  r@   
attentionsc                 n   t         |   |       t        |t              r-t	        |d      r t        j                  |j                         yyt        |t              rXt	        |d      rt        j                  |j                         t	        |d      r t        j                  |j                         yyy)zInitialize the weightsr   r7  r;  N)r)   _init_weightsrw   r   hasattrinitzeros_r   r2  ones_r7  r;  )r0   r   r3   s     r4   rH  z!DogePreTrainedModel._init_weights  s     	f%fm,vs#FHH% $ 01v/0

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

699: : 2r5   )rH   rI   rJ   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  r2  r   _can_record_outputsr,   r   rH  rK   rL   s   @r4   rC  rC    sx    &*#+,#4"5 N""&'	;)# U]]_
; 
;r5   rC  c                       e Zd Zdef fdZee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  de
dz  dej                  dz  d	edz  d
ej                  dz  dee   defd              Z xZS )	DogeModelrP   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   rP   F)r)   r*   pad_token_idpadding_idx
vocab_sizer   r  r1   embed_tokens
ModuleListrangenum_hidden_layersr2  layersr'   r   normrN   
rotary_embgradient_checkpointing	post_initr   s      r4   r*   zDogeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammBGH`H`BabYfi0b
   2 28K8KL	-V<&+# 	 cs   DN	input_idsr   r   r   inputs_embedsr<  r   r   ra   c                    |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|F||j	                         nd}	t        j                  |	|	|j                  d   z   |j                        }||j                  d      }| j                  j                  t        nt        }
 |
| j                  |||||      }|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f||||||d|} | j!                  |      }t#        ||	      S )
Nz:You must specify exactly one of input_ids or inputs_embedsrZ  r   r"   )r^   )rP   input_embedsr   r   r   r   )r   )r   r   r   r<  r   r   )last_hidden_stater   )
ValueErrorr   rP   r^  get_seq_lengthr,   rj   rF   r^   r   sliding_windowr   r   rd  rb  ra  rc  r   )r0   rg  r   r   r   rh  r<  r   r   past_seen_tokensmask_functionr   r@   r   decoder_layers                  r4   rC   zDogeModel.forward-  sx    -t";<YZZ0*$++>O  --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L.2kk.H.H.P*Vw#;;&))+%
 &"oom,oW![[)H4;;+H+HI 
	M)	*) /#-$7	 	M
	 		-0%++
 	
r5   )NNNNNNN)rH   rI   rJ   r#   r*   r    r   r,   r  r   r
   rA  r   r   r   r   rC   rK   rL   s   @r4   rX  rX    s    z    .2.204(,26!%26:
##d*:
 t+:
 &&-	:

 :
 ((4/:
 $;:
 ((4/:
 +,:
 
 :
  :
r5   rX  gate_logitsr  r  r  c                    | t        | t              sy| d   j                  }| d   j                  }g }g }| D ]  }	|	j	                  |      }	|	j                  |d      \  \  }
}\  }}|
j                  d      |j                  d      z   }|j                  d      |z  |j                  d      z   } |j                  g |j                  dd d } |j                  g |j                  dd d }|j                  |d      \  }}|j                  d|      }t        j                  |d      }|j                  |       |j                  |        t        j                  |d      }t        j                  |d      }|}|j                  d      }t        j                  |||      }t        j                   |||      }|j#                  d||      |j                  d   z  }t        j$                  |d      }nD|j                  \  }}t'        |       }|ddddddf   j)                  ||||f      j+                  d      j	                  |      }|j                  d      |j-                            }t        j                  |||      }t        j                   |||      }|j#                  d||      t        j.                  |      z  }|ddddddf   j)                  ||||f      j+                  d|      j	                  |      }t        j.                  ||z  d      t        j.                  |d      z  }t        j.                  ||z        }||z  S )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   r8   ru   r   r   )rw   rE   r:   r^   r;   r   r   r   rF   r!  r   r   appendr,   r{   r   	ones_likescatter_add_r>   lenrv   r   r   r"  )rr  r  r  r  r   compute_dtypecompute_deviceall_expert_indicesall_routing_weightslayer_gate_logitsr&  r'  r(  r)  r*  r+  r$  r-  expert_indicesr.  tokens_per_expertpadrouter_prob_per_expert
batch_sizesequence_lengthra  expert_attention_mask router_per_expert_attention_maskoverall_losss                                r4   load_balancing_loss_funcr  l  s{   @ *[%"@N((M ^**N( 4-00@7H7M7Mh\^7M7_484y)''+h.@.@.DD
))"-89;N;Nr;RR$Z__@j&6&6s&;@R@
&k&&C(9(9#2(>CC(ooeo<$++B0@A))JB7!!.1""?3!4" #51=))$7Q?/44R8!KK=Q_`oo0n]-::1>PRUVYkYqYqrsYtt "',?Q!G&4&:&:#
O, 4At+,V&
OUKLWR[R	 	 044R89N9S9S9UV "KK=Q_`oo0n]-::1>PRUVY^YbYb!Z
 
 4At+,V&
O[QRWR%R	 	) "'+>Aa+agh!ilqlulu,!m
 "
 99.1GGHL+%%r5   c                   n    e Zd ZddiZddiZddgdgfiZ fdZee	 	 	 	 	 	 	 	 	 	 dd	e	j                  dz  d
e	j                  dz  de	j                  dz  dedz  de	j                  dz  de	j                  dz  dedz  de	j                  dz  dee	j                  z  dedz  dee   defd              Z xZS )DogeForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr@   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _
        |j                  | _        | j                          y )NFr   )r)   r*   rX  rD  r]  r   r   r1   r  router_aux_loss_coefr  r  rf  r  s     r4   r*   zDogeForCausalLM.__init__  s     v&
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	r5   Nrg  r   r   r   rh  labelsr<  r   logits_to_keepoutput_router_logitsr   ra   c                    |
|
n| j                   j                  }
 | j                  d|||||||d|}|j                  }t	        |	t
              rt        |	 d      n|	}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |}d}|
rt        |j                  | j                  t        j                  t        j                  | j                              | j                   |      }|+|| j"                  |j%                  |j&                        z  z  }t)        ||||j*                  |j,                  |j.                  |j                        S )ah  
        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)rg  r   r   r   rh  r<  r   )lossaux_lossr  r   r@   rF  r%  r>  )rP   r  rD  rk  rw   r   slicer  loss_functionr]  r  r%  r  r  r  r  r  r  r;   r^   r   r   r@   rF  )r0   rg  r   r   r   rh  r  r<  r   r  r  r   outputsr@   slice_indicesr  r  r  s                     r4   rC   zDogeForCausalLM.forward  sp   N %9$D $++JjJj 	
 +5$** 	+
)%+')	+
 	+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD/%%  

499T%5%567((H !11HKK4LLL(#33!//))!//
 	
r5   )
NNNNNNNNr   N)rH   rI   rJ   _tied_weights_keys_tp_plan_pp_planr*   r   r   r,   r  r   r
   rA  r   r   r   r   r   rC   rK   rL   s   @r4   r  r    sN   *,GH23H_-z:;H
  .2.204(,26*.!%26-.,0Q
##d*Q
 t+Q
 &&-	Q

 Q
 ((4/Q
   4'Q
 $;Q
 ((4/Q
 ell*Q
 #TkQ
 +,Q
 
#Q
  Q
r5   r  c                       e Zd Zy)DogeForSequenceClassificationN)rH   rI   rJ   r>  r5   r4   r  r  >  s    r5   r  )r  rX  rC  r  )r"   )r   )NN)NNr7   N)Or  collections.abcr   typingr   r   r,   torch.nn.functionalr   r   r    r   rJ  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    r!   configuration_doger#   !torch.nn.attention.flex_attentionr$   Moduler'   rN   r   r   r   r   r   rl   r   rE   r   r   r   r  r  r2  rC  rX  r  r  r  __all__r>  r5   r4   <module>r     s1  .  $ "     & ! . ) Q J R [ Q K A & g g O O *  !; Y'J")) J (J(><")) ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%@ ! +*II+*<<+* 
+* <<	+*
 %,,34+* T\+* T\+* 5<<%&+*\ -. 1G - .zBII zzbii  6,		 6,r/1 /d ;/ ; ;> M
# M
 M
d #*.g&ell 33d:g&tg& Djg& 	g&
 LL4'g& \\Cg&T d
)? d
 d
N	$DFY 	 cr5   