
    UhS                     :   d dl mZmZmZmZmZ d dlZd dlmc m	Z
 d dlmZ ddlmZ ddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z'  e$       rd dl(m)Z) ddl*m+Z+  e%jX                  e-      Z.	 	 	 d9deej^                  eej^                     df   dee0   deej^                     deej^                  e0f   fdZ1 G d dejd                        Z3 e!jh                  e3        G d dejd                        Z5d Z6d:dZ7 G d dejd                        Z8 G d  d!ejd                        Z9 G d" d#ejd                        Z:d$ej^                  d%e0dej^                  fd&Z; G d' d(ejd                        Z<	 d;d)ejd                  d*ej^                  d+ej^                  d,ej^                  deej^                     d-e=d.e=fd/Z> G d0 d1e      Z?e# G d2 d3e             Z@e# G d4 d5e@             ZA G d6 d7e@e      ZBg d8ZCy)<    )CallableListOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)GradientCheckpointingLayer)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)ALL_LAYERNORM_LAYERS)auto_docstringis_torch_flex_attn_availablelogging   )GraniteMoeConfig)	BlockMask)make_flex_block_causal_maskgate_logitsnum_expertsattention_maskreturnc                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

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

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

    Returns:
        The auxiliary loss.
    Nr   dim)
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesum	unsqueeze)r   r    top_kr!   compute_device
layer_gateconcatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_losss                      /var/www/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/granitemoe/modeling_granitemoe.pyload_balancing_loss_funcrI   -   s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&
O[QRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1G1Q1QRS1TTUL+%%[ .ks   Ic                   ,     e Zd Zd fd	Zd Zd Z xZS )GraniteMoeRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z@
        GraniteMoeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr*   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      rH   rN   zGraniteMoeRMSNorm.__init__   s1     	ll5::k#:; #    c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   r&   T)keepdim)	dtyper,   r*   float32powr1   rsqrtrR   rQ   )rS   hidden_statesinput_dtypevariances       rH   forwardzGraniteMoeRMSNorm.forward   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::rW   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r(   rQ   r3   rR   rS   s    rH   
extra_reprzGraniteMoeRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrW   )gư>)__name__
__module____qualname__rN   rb   re   __classcell__rV   s   @rH   rK   rK      s    $;JrW   rK   c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )GraniteMoeRotaryEmbeddingconfigc                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)rM   rN   hasattrro   getrp   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrm   r   rope_init_fnattention_scalingregister_bufferrs   original_inv_freq)rS   rm   r)   rs   rV   s       rH   rN   z"GraniteMoeRotaryEmbedding.__init__   s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%rW   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r&   r   mpscpuF)device_typeenabledrY   r$   )r[   )rs   r2   r4   r3   r,   r)   r'   rq   strr*   autocast	transposer+   cosr{   sinr[   )
rS   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             rH   rb   z!GraniteMoeRotaryEmbedding.forward   sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.N)
rf   rg   rh   r   rN   r*   no_gradr   rb   ri   rj   s   @rH   rl   rl      s4    // /" U]]_<  <rW   rl   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..Nr&   rY   r$   )r3   r*   r+   )r   x1x2s      rH   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rW   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )r7   r   )qkr   r   r   unsqueeze_dimq_embedk_embeds           rH   apply_rotary_pos_embr      sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGrW   c                   6     e Zd Zdedededdf fdZd Z xZS )GraniteMoeParallelExpertsr    
input_sizeoutput_sizer"   Nc                     t         |           t        j                  t	        j
                  |||            | _        || _        || _        || _	        y)a  
        Initialize the GraniteMoeParallelExperts module.
        The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
        many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
        [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
        [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
        used in vllm.

        Args:
            num_experts (int):
                Number of experts.
            input_size (int):
                Size of the input.
            output_size (int):
                Size of the output.
        N)
rM   rN   r   rO   r*   emptyrQ   r    r   r   )rS   r    r   r   rV   s       rH   rN   z"GraniteMoeParallelExperts.__init__   sD    " 	ll5;;{K#TU&$&rW   c                     |j                  |d      }g }t        | j                        D ]7  }|j                  t	        j
                  ||   | j                  |                9 t        j                  |d      }|S )a  
        Forward pass of the GraniteMoeParallelExperts module.

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

        Returns:
            Tensor: Output tensor.
        r   r$   )	splitranger    appendFlinearrQ   r*   r+   )rS   inputsexpert_size
input_listoutput_listiresultss          rH   rb   z!GraniteMoeParallelExperts.forward   sq     \\+1\5
t''( 	HAqxx
1t{{1~FG	H))KQ/rW   rf   rg   rh   intrN   rb   ri   rj   s   @rH   r   r      s)    'C 'S 's 't '.rW   r   c                   2     e Zd Zdededef fdZd Z xZS )GraniteMoeTopKGatingr   r    r8   c                     t         |           || _        || _        || _        t        j                  ||d      | _        y)a  
        Initialize the top-k gating mechanism.
        Args:
            input_size (`int`):
                Size of the input.
            num_experts (`int`):
                Number of experts.
            top_k (`int`):
                Number of top experts to select.
        FbiasN)rM   rN   r    r   r8   r   Linearlayer)rS   r   r    r8   rV   s       rH   rN   zGraniteMoeTopKGating.__init__  s:     	&$
YYz;UC
rW   c                    | j                  |      j                         }|j                  | j                  d      \  }}t	        j
                  |d      j                  |      }t	        j                  |j                  d      | j                  g|j                  |j                        }|j                  d|d      }|j                         j                  d      }|j                         }|j!                         }	|	j#                  d      \  }
}|j%                  | j                  d      }|j!                         }||   }|||||fS )Nr   r$   r   r[   r)   trunc)rounding_mode)r   r2   r/   r8   r*   r.   type_aszerossizer    r[   r)   scatterlongr6   tolistflattensortdiv)rS   r_   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr   top_k_expertsr=   index_sorted_expertsbatch_indexbatch_gatess                 rH   rb   zGraniteMoeTopKGating.forward!  s.   M*002&,kk$**!k&D#mmmLa8@@O a $"2"23;;L;LU`UgUg
 a2jjl&&q) "((* &--/"/"4"4Q"7*..tzz.Q "))+!"67#[+{FRRrW   r   rj   s   @rH   r   r     s'    D3 DS D D&SrW   r   c                   .     e Zd ZdZdef fdZd Z xZS )GraniteMoeMoEz
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    rm   c                    t         t        |           |j                  | _        |j
                  | _        t        |j                     | _        t        |j                  | j                  | j                  dz        | _        t        |j                  | j                  | j                        | _        t        | j                  |j                  |j                        | _        y )NrY   )r   r    r8   )rM   r   rN   rT   r   intermediate_sizer
   
hidden_act
activationr   num_local_expertsinput_linearoutput_linearr   num_experts_per_tokrouterrS   rm   rV   s     rH   rN   zGraniteMoeMoE.__init__F  s    mT+- ,,!33 !2!235f6N6NPTP_P_aeaqaqtuauv6v7O7OQUQaQacgcrcrs*00,,
rW   c                    |j                         \  }}}|j                  d|      }| j                  |      \  }}}}}	||   }
| j                  |
|      }|j	                  dd      }| j                  |d         |d   z  }| j                  ||      }||dddf   z  }t        j                  ||z  | j                  f|j                  |j                        }|j                  d||      }|j                  ||| j                        }||	fS )a  
        Forward pass of the mixture of experts layer.

        Args:
            layer_input (Tensor):
                Input tensor.

        Returns:
            Tensor:
                Output tensor.
            Tensor:
                Router logits.
        r&   rY   r$   r   r   Nr   )r   r5   r   r   chunkr   r   r*   r   r   r[   r)   	index_addview)rS   layer_inputbszlengthemb_sizer=   r   r   r   router_logitsexpert_inputsr_   chunked_hidden_statesexpert_outputsr   layer_outputs                   rH   rb   zGraniteMoeMoE.forwardU  s    !, 0 0 2VX!))"h7BF++kBZ?;[-#K0))-E - 3 3A2 3 >(=a(@ADYZ[D\\++M;G'+ag*>>S6\4??;>CWCW`n`u`uvq+~F#((fdooF]**rW   )rf   rg   rh   __doc__r   rN   rb   ri   rj   s   @rH   r   r   =  s    
/ 
+rW   r   r_   n_repc                     | 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)r3   r4   r5   )r_   r   batchnum_key_value_headsslenhead_dims         rH   	repeat_kvr   v  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTrW   c                   d    e Zd ZdZddedee   f fdZ	 	 	 	 	 	 ddej                  deej                     deej                     dee   d	ed
eej                     deeej                  ej                  f      deej                  eej                     eeej                        f   fdZ xZS )GraniteMoeAttentionz=Multi-headed attention from 'Attention Is All You Need' paperrm   	layer_idxc                    t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        d| _        |j                   | _        | j                  | j                  z  | j                  k7  r&t%        d| j                   d| j                   d      t'        j(                  | j                  | j                  | j                  z  |j*                        | _        t'        j(                  | j                  | j                  | j                  z  |j*                        | _        t'        j(                  | j                  | j                  | j                  z  |j*                        | _        t'        j(                  | j                  | j                  |j*                        | _        y )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   )rM   rN   rm   r   loggerwarning_oncerV   rf   attention_dropoutrT   num_attention_heads	num_headsr   r   num_key_value_groups	is_causalattention_multiplierscaling
ValueErrorr   r   attention_biasq_projk_projv_projo_projrS   rm   r   rV   s      rH   rN   zGraniteMoeAttention.__init__  s   " !8!8 9 :, , "(!9!9!--33((DNN:#)#=#= $(NNd6N6N$N!22MMDNN*t/?/??QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii 0 0$2B2BI^I^_rW   r_   r!   r   past_key_value	use_cachecache_positionposition_embeddingsr"   c                     |j                         \  }	}
}| j                  |      }| j                  |      }| j                  |      }|j	                  |	|
| j
                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }||nd\  }}|t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd      rt         j#                  d	       nt$        | j                  j                     } || ||||f| j&                  sd
n| j(                  | j*                  d|\  }}|j	                  |	|
d      }| j-                  |      }|||fS )Nr   rY   )NN)r   r   r  eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )dropoutr   r&   )r   r   r   r   r   r   r   r   r   r   updater   eager_attention_forwardrm   _attn_implementationrv   r   r   r   trainingr   r   r   )rS   r_   r!   r   r  r  r  r  kwargsr   q_lenr=   query_states
key_statesvalue_statesr   r   cache_kwargsattention_interfaceattn_outputattn_weightss                        rH   rb   zGraniteMoeAttention.forward  s
    &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm*=*I&|S*';L*VY[^'_$L*%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ "&&sE26kk+.L.88rW   r   )NNNFNN)rf   rg   rh   r   r   r   r   rN   r*   Tensor
LongTensorr   boolr   rb   ri   rj   s   @rH   r   r     s    G`/ `HSM `F 2637*.59KO69||69 !.69 u//0	69
 !69 69 !!1!1269 &eELL%,,,F&GH69 
u||Xell3XeELL>Q5RR	S69rW   r   modulequerykeyvaluer   r
  c                 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 )NrY   r	   r&   )r%   r[   )pr  r   )r   r   r*   matmulr   r3   r   r-   r.   r\   r,   r[   r
  r  
contiguous)r  r  r  r  r!   r   r
  r  r  r  r  causal_maskr  s                rH   r  r    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$$rW   c                   r    e Zd Zdedef fdZ	 	 	 	 	 	 	 	 ddej                  deej                     deej                     dee
   dee   d	ee   d
eej                     dee   deeej                  ej                  f      deej                  eeej                  ej                  f      f   fdZ xZS )GraniteMoeDecoderLayerrm   r   c                 B   t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        |j                  | _        y )N)rm   r   rU   )rM   rN   rT   r   	self_attnr   block_sparse_moerK   rms_norm_epsinput_layernormpost_attention_layernormresidual_multiplierr   s      rH   rN   zGraniteMoeDecoderLayer.__init__  s|    !--,FiP -f 501C1CI\I\](9&:L:LRXReRe(f%#)#=#= rW   r_   r!   r   r  r  r  r  output_router_logitsr  r"   c
                 6   |}| j                  |      } | j                  d||||||||	d|
\  }}}||| j                  z  z   }|}| j                  |      }| j	                  |      \  }}||| j                  z  z   }|f}|r||fz  }|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
                should not be returned during inference.
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        )r_   r!   r   r  r  r  r  r   )r,  r)  r.  r-  r*  )rS   r_   r!   r   r  r  r  r  r/  r  r  residualself_attn_weightspresent_key_valuer   outputss                   rH   rb   zGraniteMoeDecoderLayer.forward  s    L !,,]; ?Mdnn 
?
')%)/) 3
?
 
?
;(*; !=43K3K#KK !55mD'+'<'<]'K$} =43K3K#KK ")++G)++G''GrW   )NNNFFNFN)rf   rg   rh   r   r   rN   r*   r  r   r  r   r  r   FloatTensorrb   ri   rj   s   @rH   r&  r&    s   	>/ 	>C 	> 2637*.,1$)59/4KOK||K !.K u//0	K
 !K $D>K D>K !!1!12K 'tnK &eELL%,,,F&GHK 
u  (51B1BEDUDU1U+V"WW	XKrW   r&  c                   >    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZd Zy)GraniteMoePreTrainedModelmodelTr&  past_key_valuesFc                 >   t        |t        j                        rm|j                  j                  j                  d| j                  j                         |j                  %|j                  j                  j                          y y t        |t        j                        rz|j                  j                  j                  d| j                  j                         |j                  2|j                  j                  |j                     j                          y y t        |t              r&|j                  j                  j                  d       y t        |t              r<|j                  j                  j                  d| j                  j                         y y )Nr	  )r1   stdg      ?)r'   r   r   rQ   datanormal_rm   initializer_ranger   zero_	Embeddingpadding_idxrK   fill_r   )rS   r  s     rH   _init_weightsz'GraniteMoePreTrainedModel._init_weightsb  s   fbii(MM&&CT[[5R5R&S{{&  &&( '-MM&&CT[[5R5R&S!!-""6#5#56<<> . 12MM$$S) 9:MM&&CT[[5R5R&S ;rW   N)rf   rg   rh   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacherD  r1  rW   rH   r8  r8  U  sH    #L&*#12#4"5!N  $"TrW   r8  c                   *    e Zd Zdef fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 ddee	j                     dee	j                     dee	j                     deeeee	j                     f      d	ee	j                     d
ee   dee   dee   dee   dee   dee	j                     deeef   fd       Z	 ddee	j                  df   de	j                  de	j                  dedef
dZede	j                  dedede	j.                  de	j                  defd       Z xZS )GraniteMoeModelrm   c           	      4   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        d| _        |j$                  | _        |j                  | _        |j&                  | _        | j                  | j(                  z  | _        |j,                  | _        |j.                  | _        |j0                  | _        | j0                  dk(  rt3        |      nd | _        | j7                          y c c}w )Nr(  Frope)rM   rN   pad_token_idrB  
vocab_sizer   rA  rT   embed_tokens
ModuleListr   rD   r&  layersrK   r+  normgradient_checkpointingembedding_multiplierr   r   r   rw   
rope_thetaposition_embedding_typerl   
rotary_emb	post_initr   s      rH   rN   zGraniteMoeModel.__init__s  s@    !.. ++LL):):F<N<NPTP`P`ammHMfNfNfHgh9#FI6h
 &f&8&8f>Q>QR	&+#$*$?$?!!--33((DNN:'-'E'E$ ++'-'E'E$?C?[?[_e?e3F;ko 	! is   Fc                     | j                   S r   rU  rd   s    rH   get_input_embeddingsz$GraniteMoeModel.get_input_embeddings  s       rW   c                     || _         y r   r`  rS   r  s     rH   set_input_embeddingsz$GraniteMoeModel.set_input_embeddings  s
    !rW   	input_idsr!   r   r:  inputs_embedsr  r  output_hidden_statesr/  return_dictr  r"   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|
|
n| j                   j                  }
|d u |d uz  rt        d      | j                  r%| j                  r|rt        j                  d       d}|| j                  |      }|| j                  z  }d}|r<t        |t              s,d}t        j                  |      }t        j                  d       |F||j!                         nd}t#        j$                  |||j&                  d   z   |j(                        }||j+                  d      }| j-                  |||||      }|}d }| j.                  | j/                  ||      }|rd	nd }|rd	nd }|	rd	nd }d }| j0                  D ]B  }|r||fz  } |||||||||	|
	      }|d   }|r	||rdnd   }|r	||d   fz  }|	s:||d   fz  }D | j3                  |      }|r||fz  }|r|nd }|r|j5                         }|
st7        d ||||fD              S t9        |||||      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FTzWe detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)r   r   r)   r1  )r!   r   r  r  r  r  r/  r  rY   r&   c              3   &   K   | ]	  }||  y wr   r1  ).0vs     rH   	<genexpr>z*GraniteMoeModel.forward.<locals>.<genexpr>  s     tqfgfsts   )last_hidden_stater:  r_   
attentionsr   )rm   r  rg  r  use_return_dictr   rY  r  r   r   rU  rZ  r'   r   r   from_legacy_cacheget_seq_lengthr*   aranger3   r)   r7   _update_causal_maskr]  rW  rX  to_legacy_cacher(   r   )rS   re  r!   r   r:  rf  r  r  rg  r/  rh  r  return_legacy_cachepast_seen_tokensr$  r_   r  all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                           rH   rb   zGraniteMoeModel.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M%(A(AA#Z?"&*<<_MO]
 !CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]

 &"??&"&//-"N #7BD0d"6BD!![[ 	:M#!m%55!)*)."3#-%9$7
M *!,M%28I1q%Q" =#3"55#!mB&7%99!3	:6 		-0  -!11+4'$
#335Jt]J@QSa$bttt%+&+%+
 	
rW   r   input_tensorc           	         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r't        |t        j
                        rt        |      }|S ||j                         nd}||j                  nd}| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  }|j                  d   }	|r|j                         }
n1t        |t        j
                        r|j                  d	   n||	z   dz   }
| j                  ||	|
|||j                  d   
      }| j                   j                  dk(  rQ|O|j                   j"                  dv r7|s5t	        j$                  |      j&                  }t        j(                  ||      }|S )Nflash_attention_2r	  flex_attentionr   Fr  )rf  past_key_values_lengthis_trainingr   r&   )rC   target_lengthr[   r  rB   )cudaxpunpu)rm   r  anyr'   r*   r  r   rs  is_compileabler   _ignore_causal_mask_sdpar  r[   r3   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr)   rq   finfomin_unmask_unattended)rS   r!   r  r  r:  r  rx  using_compilable_cacher[   rC   r  r$  	min_dtypes                rH   ru  z#GraniteMoeModel._update_causal_mask	  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCKQZ[KrW   rC   r  r[   rB   c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||j
                        |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }	|ddddddd|	f   | ddddddf   j                  |j
                        z   }
|
dk(  }
|ddddddd|	f   j                  |
|      |ddddddd|	f<   |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer[   r)   r   )diagonalrj  r&   r   )r%   r*   r  r  fullr)   triurt  r5   r4   cloner3   r,   masked_fill)r!   rC   r  r[   r  rB   r  r$  r  mask_lengthpadding_masks              rH   r  zEGraniteMoeModel._prepare_4d_causal_attention_mask_with_cache_positionM  s   > %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 rW   )NNNNNNNNNNN)F)rf   rg   rh   r   rN   ra  rd  r   r   r*   r  r  r   r   r   r6  r  r   r   rb   ru  staticmethodr   r[   r  ri   rj   s   @rH   rP  rP  q  s   / 2!"  151537KO59$(,0/3/3&*59s
E,,-s
 !.s
 u//0	s

 "%tE4E4E/F(F"GHs
   1 12s
 D>s
 $D>s
 'tns
 'tns
 d^s
 !!1!12s
 
u--	.s
 s
x #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4rW   rP  c                        e Zd ZdgZdef fdZd Zd Zd Zd Z	d Z
d	 Ze	 	 	 	 	 	 	 	 	 	 	 	 	 dd
eej                     deej                      deej                     deeeeej(                     f      deej(                     deej                     dee   dee   dee   dee   dee   deej                     deeej                   f   deeef   fd       Zed        Z xZS )GraniteMoeForCausalLMzlm_head.weightrm   c                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        | j                          y )NFr   )rM   rN   rP  r9  rT  r   r   rT   lm_headrouter_aux_loss_coefr   r    r   r^  r   s     rH   rN   zGraniteMoeForCausalLM.__init__  s     $V,
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	rW   c                 .    | j                   j                  S r   r9  rU  rd   s    rH   ra  z*GraniteMoeForCausalLM.get_input_embeddings  s    zz&&&rW   c                 &    || j                   _        y r   r  rc  s     rH   rd  z*GraniteMoeForCausalLM.set_input_embeddings  s    "'

rW   c                     | j                   S r   r  rd   s    rH   get_output_embeddingsz+GraniteMoeForCausalLM.get_output_embeddings  s    ||rW   c                     || _         y r   r  )rS   new_embeddingss     rH   set_output_embeddingsz+GraniteMoeForCausalLM.set_output_embeddings  s	    %rW   c                     || _         y r   r9  )rS   decoders     rH   set_decoderz!GraniteMoeForCausalLM.set_decoder  s	    
rW   c                     | j                   S r   r  rd   s    rH   get_decoderz!GraniteMoeForCausalLM.get_decoder  s    zzrW   re  r!   r   r:  rf  labelsr  r  rg  r/  rh  r  logits_to_keepr"   c                    ||n| j                   j                  }|
|
n| j                   j                  }
|	|	n| j                   j                  }	||n| j                   j                  }| j                  ||||||||	|
||      }|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }|| j                   j                  z  }d}|:|j                         } | j                  ||fd| j                   j                  i|}d}|
r`t        |r|j                  n|d   | j                   | j"                  |      }|+|| j$                  |j'                  |j(                        z  z  }|s|f|dd z   }|
r|f|z   }||f|z   S |S t+        ||||j,                  |j.                  |j0                  |j                        S )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)re  r!   r   r:  rf  r  r  rg  r/  rh  r  r   rT  r&   r   )lossaux_lossr   r:  r_   rp  r   )rm   r  r/  rg  rq  r9  r'   r   slicer  logits_scalingr2   loss_functionrT  rI   r   r    r   r  r,   r)   r   r:  r_   rp  )rS   re  r!   r   r:  rf  r  r  r  rg  r/  rh  r  r  r  r5  r_   slice_indicesr   r  r  outputs                         rH   rb   zGraniteMoeForCausalLM.forward  s   P 2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 &1%<k$++B]B] **)%+'/!5!5#)  
  
8B>SV8W~ot4]kmA}a,?@A$++444\\^F%4%%  ;;11 	D /)4%%'"+  ((	H !11HKK4LLLY,F#"v-'+'7D7V#CVC(#33!//))!//
 	
rW   c                 J    d}| D ]  }|t        fd|D              fz  } |S )Nr1  c              3   t   K   | ]/  }|j                  d j                  |j                               1 yw)r   N)index_selectr,   r)   )rl  
past_statebeam_idxs     rH   rn  z7GraniteMoeForCausalLM._reorder_cache.<locals>.<genexpr>  s.     nU_j--aZ=N=N1OPns   58)r(   )r:  r  reordered_past
layer_pasts    `  rH   _reorder_cachez$GraniteMoeForCausalLM._reorder_cache  s=    ) 	Jncmnn N	 rW   )NNNNNNNNNNNNr   )rf   rg   rh   _tied_weights_keysr   rN   ra  rd  r  r  r  r  r   r   r*   r  r  r   r   r   r6  r  r   r   r   rb   r  r  ri   rj   s   @rH   r  r    s   *+/ '(&  151537KO59-1$(,0/3/3&*5934j
E,,-j
 !.j
 u//0	j

 "%tE4E4E/F(F"GHj
   1 12j
 ))*j
 D>j
 $D>j
 'tnj
 'tnj
 d^j
 !!1!12j
 c5<</0j
  
u//	0!j
 j
X  rW   r  )r  rP  r8  )NrY   N)Nr   )r	  )Dtypingr   r   r   r   r   r*   torch.nn.functionalr   r-   r   activationsr
   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   pytorch_utilsr   utilsr   r   r   configuration_granitemoer   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerrf   r   r  r   rI   ModulerK   r   rl   r   r   r   r   r   r   r   r2   r  r&  r8  rP  r  __all__r1  rW   rH   <module>r     sL    : 9     ! . ) > 9 j j K F 1 J J 6  !;J 
		H	% "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&fJ		 J(    - .<		 <F(8*		 *\-S299 -S`5+BII 5+r	UU\\ 	U# 	U%,, 	UY9")) Y9F %II%<<% 
% <<	%
 U\\*% % %6W7 Wt T T T6 Q/ Q QhV5 Vr TrW   