
    ^jhu                     `   d dl mZ d dl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mZmZ ddl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& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1  ed       G d dejd                               Z3 G d dejd                        Z4 G d dejd                        Z5e G d dejd                               Z6 G d d ejd                        Z7d! Z8 ed"      d?d#       Z9d$ejt                  d%e;d&ejt                  fd'Z<	 d@d(ejd                  d)ejt                  d*ejt                  d+ejt                  d,ejt                  dz  d-e=d.e=d/e&e(   fd0Z> ee9       G d1 d2ejd                               Z? G d3 d4e      Z@e) G d5 d6e$             ZAe) G d7 d8eA             ZB	 	 	 dAd9ejt                  eCejt                     z  dz  d:e;dz  d,ejt                  dz  d&ejt                  e;z  fd;ZDe) G d< d=eAe             ZEg d>ZFy)B    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstring)can_return_tuplemaybe_autocastmerge_with_config_defaults)capture_outputs   )GraniteMoeConfigRMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	GraniteMoeRMSNormepsreturnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z@
        GraniteMoeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer$   	__class__s      }/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/granitemoe/modeling_granitemoe.pyr(   zGraniteMoeRMSNorm.__init__5   s1     	ll5::k#:; #    hidden_statesc                 "   |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,   )r.   r3   input_dtypevariances       r1   forwardzGraniteMoeRMSNorm.forward=   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r2   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler,   shaper-   )r.   s    r1   
extra_reprzGraniteMoeRMSNorm.extra_reprD   s*    ))*+6$2G2G1HIIr2   )gư>)
__name__
__module____qualname__floatr(   r*   Tensorr@   rD   __classcell__r0   s   @r1   r#   r#   3   s7    $ $$ $;U\\ ;ell ;Jr2   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 )GraniteMoeRotaryEmbedding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defaultrN   F)
persistentoriginal_inv_freq)r'   r(   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrO   rope_parametersrQ   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r.   rO   devicerope_init_fnrN   r0   s        r1   r(   z"GraniteMoeRotaryEmbedding.__init__K   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr2   r]   ztorch.deviceseq_lenr%   z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_dimNg      ?r   r5   r8   )r]   r8   )	rX   getattrr/   num_attention_headsr*   arangeint64r9   rH   )rO   r]   r_   basedimattention_factorrN   s          r1   rY   z9GraniteMoeRotaryEmbedding.compute_default_rope_parameters[   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r2   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   r6   r   mpscpuF)device_typeenabledr5   ri   rc   )rN   rH   expandrC   r9   r]   
isinstancetypestrr   	transposer*   catcosrZ   sinr8   )
r.   xposition_idsinv_freq_expandedposition_ids_expandedrn   freqsembrw   rx   s
             r1   r@   z!GraniteMoeRotaryEmbedding.forwardy   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)rE   rF   rG   r*   rI   __annotations__r    r(   staticmethodr   intrB   rH   rY   no_gradr   r@   rJ   rK   s   @r1   rM   rM   H   s    llV/ V  *.+/"* 4'*(* t* 
~u$	%	* *: U]]_<  <r2   rM   c                        e Zd ZdZdef fdZdej                  deej                  ej                  ej                  f   fdZ	 xZ
S )GraniteMoeTopKRoutera  Top-k gating that returns the routing decisions without grouping tokens by expert.

    Returns ``(top_k_index, top_k_weights, router_logits)``; the grouping/scattering used to live
    here (via ``expert_size.tolist()``, which broke fullgraph compile) and now happens inside the
    experts forward via ``use_experts_implementation`` so the default ``grouped_mm`` / ``batched_mm``
    paths can compile cleanly.
    rO   c                     t         |           |j                  | _        |j                  | _        t        j                  t        j                  | j                  |j                              | _        y r   )r'   r(   num_local_expertsnum_expertsnum_experts_per_toktop_kr   r)   r*   emptyr/   r,   r.   rO   r0   s     r1   r(   zGraniteMoeTopKRouter.__init__   sP    !33//
ll5;;t/?/?ASAS#TUr2   r3   r%   c                     t        j                  || j                        j                         }|j	                  | j
                  d      \  }}t        j                  |d      j                  |      }|||fS )Nr6   rp   )	Flinearr,   rH   topkr   r*   softmaxtype_as)r.   r3   router_logitstop_k_logitstop_k_indextop_k_weightss         r1   r@   zGraniteMoeTopKRouter.forward   se    <BBD$1$6$6tzzr$6$J!kl;CCMRM=88r2   )rE   rF   rG   __doc__r    r(   r*   rI   rB   r@   rJ   rK   s   @r1   r   r      sI    V/ V9U\\ 9eELL%,,X]XdXd<d6e 9r2   r   c                        e Zd ZdZdef fdZdej                  dej                  dej                  dej                  fdZ xZ	S )	GraniteMoeExpertsz2Collection of expert weights stored as 3D tensors.rO   c                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )Nr5   )r'   r(   r   r   r/   
hidden_dimintermediate_sizeintermediate_dimr   r)   r*   r   gate_up_proj	down_projr   
hidden_actact_fnr   s     r1   r(   zGraniteMoeExperts.__init__   s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r2   r3   r   r   r%   c                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesr5   r   r   )r6   rp   r6   )r*   
zeros_liker   r   
functionalone_hotr   permutegreatersumnonzerowherer   r   chunkr   r   
index_add_r9   r8   )r.   r3   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r1   r@   zGraniteMoeExperts.forward   s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0
rE   rF   rG   r   r    r(   r*   rI   r@   rJ   rK   s   @r1   r   r      sN    <0/ 0#||# \\# ||	#
 
#r2   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 )GraniteMoeMoEzISparsely-gated mixture-of-experts block: router decides, experts compute.rO   c                     t         |           |j                  | _        t	        |      | _        t        |      | _        y r   )r'   r(   r/   
input_sizer   routerr   expertsr   s     r1   r(   zGraniteMoeMoE.__init__   s3     ,,*62(0r2   layer_inputr%   c                     |j                         \  }}}|j                  d|      }| j                  |      \  }}}| j                  |||      }	|	j	                  ||| j
                        S )Nr6   )sizereshaper   r   viewr   )
r.   r   bszlengthemb_sizer3   r   r   _layer_outputs
             r1   r@   zGraniteMoeMoE.forward   si     + 0 0 2VX#++B9(,M(B%]A||M;N  fdoo>>r2   r   rK   s   @r1   r   r      s.    S1/ 1?5<< ?ELL ?r2   r   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..Nr6   r5   rp   )rC   r*   rv   )ry   x1x2s      r1   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r2   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krw   rx   unsqueeze_dimq_embedk_embeds          r1   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr2   r3   n_repr%   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)rC   rq   r   )r3   r   batchnum_key_value_headsslenrb   s         r1   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr2   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr5   r   r6   )ri   r8   )ptrainingr   )r   num_key_value_groupsr*   matmulru   r   r   r   r:   r9   r8   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r1   eager_attention_forwardr     s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r2   c                        e Zd ZdZdedef fdZ	 	 	 ddej                  de	ej                  ej                  f   dz  dej                  dz  d	e
dz  d
ee   de	ej                  ej                  f   fdZ xZS )GraniteMoeAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrO   	layer_idxc                 ^   t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        |j                  | _        |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                  z  |j
                  |j                         | _        y )Nrb   Tbias)r'   r(   rO   r   rd   r/   re   rb   r   r   attention_multiplierr   attention_dropout	is_causalr   Linearattention_biasq_projk_projv_projo_projr.   rO   r   r0   s      r1   r(   zGraniteMoeAttention.__init__"  sJ   "
F4F4F&JdJd4de$*$>$>&B\B\$\!22!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r2   Nr3   position_embeddingsr   past_key_valuesr   r%   c                 
   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
|\  }}t        ||	||      \  }}	| |j                  |	|
| j                        \  }	}
t        j                  | j                  j                  t              } || ||	|
|f| j                  sdn| j                   | j"                  d|\  }} |j$                  g |d j'                         }| j)                  |      }||fS )Nr6   r   r5           )r   r   )rC   rb   r   r   ru   r   r   r   updater   r   get_interfacerO   _attn_implementationr   r   r   r   r   r   r   )r.   r3   r  r   r  r   input_shapehidden_shapequery_statesr   r   rw   rx   attention_interfacer   r   s                   r1   r@   zGraniteMoeAttention.forward9  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j&'6'='=j,X\XfXf'g$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r2   r   )rE   rF   rG   r   r    r   r(   r*   rI   rB   r	   r   r   r@   rJ   rK   s   @r1   r   r     s    G
/ 
C 
4 IM.2(,&)||&) #5<<#=>E&) t+	&)
 &) +,&) 
u||U\\)	*&)r2   r   c                        e Zd Zdedef fdZ	 	 	 ddej                  dej                  dz  dedz  de	ej                  ej                  f   dz  d	ej                  f
d
Z
 xZS )GraniteMoeDecoderLayerrO   r   c                 B   t         |           |j                  | _        t        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |      | _
        |j                  | _        y )N)rO   r   r$   )r'   r(   r/   r   	self_attnr#   rms_norm_epsinput_layernormpost_attention_layernormr   block_sparse_moeresidual_multiplierr   s      r1   r(   zGraniteMoeDecoderLayer.__init__c  s|    !--,FiP01C1CI\I\](9&:L:LRXReRe(f% -f 5#)#=#= r2   Nr3   r   r  r  r%   c                     |}| j                  |      } | j                  d||||d|\  }}||| j                  z  z   }|}| j                  |      }| j	                  |      }||| j                  z  z   }|S )N)r3   r   r  r   )r  r  r  r  r  )r.   r3   r   r  r  r   residualr   s           r1   r@   zGraniteMoeDecoderLayer.forwardl  s     !,,];)4>> 
')+ 3	

 
q !=43K3K#KK 55mD--m< =43K3K#KKr2   r   )rE   rF   rG   r    r   r(   r*   rI   r	   rB   r@   rJ   rK   s   @r1   r  r  b  s    >/ >C > /3(,HL|| t+ 	
 #5<<#=>E 
r2   r  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Z ej$                          fd       Z xZS )GraniteMoePreTrainedModelrO   modelTr  r  )r3   
attentionsc                    t         |   |       t        |t              rmt	        j
                  |j                  d| j                  j                         t	        j
                  |j                  d| j                  j                         y t        |t              r7t	        j
                  |j                  d| j                  j                         y y )Nr  )r<   std)r'   _init_weightsrr   r   initnormal_r   rO   initializer_ranger   r   r,   )r.   r   r0   s     r1   r  z'GraniteMoePreTrainedModel._init_weights  s    f%f/0LL,,3DKK<Y<YZLL))9V9VW 45LLSdkk6S6ST 6r2   )rE   rF   rG   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   _can_record_outputsr*   r   r  rJ   rK   s   @r1   r  r    sp    &*#12#4"5N!"&/)
 U]]_U Ur2   r  c                        e Zd Zdef fdZe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e   defd                     Z xZS )GraniteMoeModelrO   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(                  | _        | j+                          y c c}w )Nr  rO   F)r'   r(   pad_token_idpadding_idx
vocab_sizer   	Embeddingr/   embed_tokens
ModuleListrangenum_hidden_layersr  layersr#   r  normrM   
rotary_embgradient_checkpointingembedding_multiplier	post_initr   s      r1   r(   zGraniteMoeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammHMfNfNfHgh9#FI6h
 &f&8&8f>Q>QR	36B&+#$*$?$?! 	 is   DN	input_idsr   rz   r  inputs_embeds	use_cacher   r%   c           
      X   |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|V||j	                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        | j                  ||||      }	|| j                  z  }|}
| j                  |
|      }| j                  d | j                  j                   D ]  } ||
f||	|||d|}
 | j                  |
      }
t!        |
|      S )	Nz:You must specify exactly one of input_ids or inputs_embedsr0  r   r   )r]   )rO   r@  r   r  rz   )r  r   rz   r  rA  )last_hidden_stater  )
ValueErrorr
   rO   r5  get_seq_lengthr*   rf   rC   r]   r   r   r=  r;  r9  r8  r:  r   )r.   r?  r   rz   r  r@  rA  r   past_seen_tokenscausal_maskr3   r  decoder_layers                r1   r@   zGraniteMoeModel.forward  s\    -t";<YZZ0*$++>O  --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L(;;')+%
 &(A(AA% #oom\J![[)H4;;+H+HI 		M)$7*) /# M		 		-0%++
 	
r2   )NNNNNN)rE   rF   rG   r    r(   r   r   r   r*   
LongTensorrI   r	   FloatTensorboolr   r   r   r@   rJ   rK   s   @r1   r.  r.    s    / "   .2.204(,26!%5
##d*5
 t+5
 &&-	5

 5
 ((4/5
 $;5
 +,5
 
 5
    5
r2   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://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 `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   rp   r6   )rr   rB   r]   r*   rv   r9   r   r   r   r   r   r<   rH   rC   rq   r   r   r   )rL  r   r   r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr   selected_expertsr   tokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthr8  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r1   load_balancing_loss_funcrZ    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                   D    e Zd ZddiZddiZddgdgfi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
j                  d	z  ded	z  dee
j                  z  deez  fd              Z xZS )GraniteMoeForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr3   logitsrO   c                 p   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        |j                  | _        | j                          y )NFr   )r'   r(   r.  r  r3  r   r   r/   r]  router_aux_loss_coefr   r   r   logits_scalingr>  r   s     r1   r(   zGraniteMoeForCausalLM.__init__F  s     $V,
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#= $33 	r2   Nr?  r   rz   r  r@  labelsoutput_router_logitslogits_to_keepr%   c	           	         ||n| j                   j                  } | j                  d|||||d|	}
|
j                  }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }|| j                   j                  z  }d}|* | j                  ||fd| j                   j                  i|	}d}|rYt        |
j                  | j                  | j                  |      }|+|| j                  |j!                  |j"                        z  z  }t%        ||||
j&                  |
j(                  |
j*                  |
j                        S )al  
        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, GraniteMoeForCausalLM

        >>> model = GraniteMoeForCausalLM.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?  r   rz   r  r@  r3  )lossaux_lossr_  r  r3   r  r   r  )rO   rd  r  rC  rr   r   slicer]  rb  loss_functionr3  rZ  r   r   r   ra  r9   r]   r   r  r3   r  )r.   r?  r   rz   r  r@  rc  rd  re  r   outputsr3   slice_indicesr_  rg  rh  s                   r1   r@   zGraniteMoeForCausalLM.forwardS  s|   J %9$D $++JjJj 	 $** 
)%+'
 
  118B>SV8W~ot4]kmA}a,?@A$++444%4%%  ;;11 	D /%%  ((	H !11HKK4LLL(#33!//))!//
 	
r2   )NNNNNNNr   )rE   rF   rG   _tied_weights_keys_tp_plan_pp_planr    r(   r   r   r*   rI  rI   r	   rJ  rK  r   rB   r   r@   rJ   rK   s   @r1   r\  r\  @  s    *,GH23H_-z:;H/   .2.204(,26*.,0-.Q
##d*Q
 t+Q
 &&-	Q

 Q
 ((4/Q
   4'Q
 #TkQ
 ell*Q
 
*	*Q
  Q
r2   r\  )r\  r.  r  )r   )r  )Nr5   N)Gcollections.abcr   typingr   r*   torch.nn.functionalr   r   r    r   r   activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   r   r   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.genericr   r   r   utils.output_capturingr   configuration_granitemoer    Moduler#   rM   r   r   r   r   r   rI   r   r   rH   r   r   r  r  r.  rB   rZ  r\  __all__r  r2   r1   <module>r     s  , %      & ! . )  0 9 Q K F & 7 Y Y 5 6 Y'J		 J (J(><		 ><B9299 9, $#		 $# $#N?BII ?"( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*@)")) @) +@)F 7  F U U U4 J
/ J
 J
^ #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d e
5 e
 e
P Tr2   