
    g                        d dl mZmZmZmZ d dlZd dlmc mZ	 d dl
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 dd	lmZ dd
lmZ ddlmZ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&m'Z'm(Z( ddl)m*Z*  e'j+        e,          Z-dZ.	 	 	 d:d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j2                  Z3 e"j4        e3            G d dej2                  Z5d Z6d;dZ7 G d d ej2                  Z8 G d! d"ej2                  Z9 G d# d$ej2                  Z:d%ej/        d&e0dej/        fd'Z; G d( d)ej2                  Z< G d* d+e<          Z= G d, d-e<          Z>e<e=e>d.Z? G d/ d0ej2                  Z@d1ZA e$d2eA           G d3 d4e                       ZBd5ZC e$d2eA           G d6 d7eB                      ZD G d8 d9eBe          ZEdS )<    )ListOptionalTupleUnionN)nn)CrossEntropyLoss   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)_flash_attention_forward)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONS)PreTrainedModel)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forward#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )GraniteMoeConfigr      gate_logitsnum_expertsattention_maskreturnc                    | t          | t                    sdS t          | t                    r/| d         j        t          j        fd| D             d          }t          j        j                            |d          }t          j        ||d          \  }}t          j        j        	                    ||          }|@t          j
        |                                d          }	t          j
        |d          }
n.|j        \  }}|j        d         ||z  z  }|dddddddf                             |||||f                              d||                                        }t          j        |                                |z  d          t          j        |d          z  }	|ddddddf                             ||||f                              d|                                        }t          j        ||z  d          t          j        |d          z  }
t          j        |	|
                    d          z            }||z  S )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   c                 :    g | ]}|                               S  )to).0
layer_gatecompute_devices     n/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/granitemoe/modeling_granitemoe.py
<listcomp>z,load_balancing_loss_func.<locals>.<listcomp>W   s&    -j-j-jPZjmmN.K.K-j-j-j    dim)
isinstancetupledevicetorchcatr   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshaper&   sum	unsqueeze)r   r    top_kr!   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_lossr)   s                    @r*   load_balancing_loss_funcrN   5   s   : *[%"@"@q+u%% s$Q.#(9-j-j-j-j^i-j-j-jpq#r#r#r h)112JPR1SSO*_eDDDA(%--.>LLK!J{'8'8':':BBB "'O!C!C!C&4&:#
O4:1=*B^_ 4AAAtT12V&
OUKXYYWR,,R	 	 "Ik&7&7&9&9<Q&QWXYYY\a\e!q]
 ]
 ]
 
 4AAAt+,V&
O[QRRWR%%R	 	) "'?=]+]cd!e!e!ehmhq,!i
 i
 i
 "
 9.1G1Q1QRS1T1TTUUL+%%r,   c                   ,     e Zd Zd fd	Zd Zd Z xZS )GraniteMoeRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z@
        GraniteMoeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr3   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      r*   rT   zGraniteMoeRMSNorm.__init__   sD     	l5:k#:#:;; #r,   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nr   r/   T)keepdim)	dtyper&   r3   float32powr9   rsqrtrX   rW   )rY   hidden_statesinput_dtypevariances       r*   forwardzGraniteMoeRMSNorm.forward   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r,   c                 H    t          | j        j                   d| j         S )Nz, eps=)r1   rW   r;   rX   rY   s    r*   
extra_reprzGraniteMoeRMSNorm.extra_repr   s&    )**II$2GIIIr,   )rQ   )__name__
__module____qualname__rT   rf   ri   __classcell__r\   s   @r*   rP   rP      sb        $ $ $ $ $ $; ; ;J J J J J J Jr,   rP   c                   Z     e Zd Zdef fdZd Z ej                    d             Z xZ	S )GraniteMoeRotaryEmbeddingconfigc                    t                                                       i | _        |j        9|j                            d|j                            d                    | _        nd| _        |j        | _        |j        | _        || _	        t          | j                 | _         | j        | j	        fdd i| j        \  }| _        |                     d|d           | j        | _        d S )N	rope_typetypedefaultr2   inv_freqF
persistent)rS   rT   rope_kwargsrope_scalinggetrs   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrq   r   rope_init_fnattention_scalingregister_bufferrv   original_inv_freq)rY   rq   rv   r\   s      r*   rT   z"GraniteMoeRotaryEmbedding.__init__   s    *#044[&BUBYBYZ`BaBabbDNN&DN"("@$*$B!/?+<4+<T[+j+jQU+jY]Yi+j+j($(ZeDDD!%r,   c                 ^   t          j        |          dz   }|| j        k    rB | j        | j        |fd|i| j        \  }| _        |                     d|d           || _        || j        k     r;| j        | j        k    r-|                     d| j	        d           | j        | _        dS dS dS )a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   seq_lenrv   Frw   N)
r3   maxr}   r   rq   ry   r   r   r~   r   )rY   position_idsr2   r   rv   s        r*   _dynamic_frequency_updatez3GraniteMoeRotaryEmbedding._dynamic_frequency_update   s     )L))A-T,,,/@t/@V0 0-408<8H0 0,Hd,   X% HHH&-D#T...43JTMf3f3f  T-CPU VVV&*&?D### /.3f3fr,   c                 V   d| j         v r|                     ||j                   | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j        |d	          5  |                                |                                z                      dd
          }t          j        ||fd          }|                                }|                                }	d d d            n# 1 swxY w Y   || j        z  }|	| j        z  }	|                    |j                  |	                    |j                  fS )Ndynamicr2   r   r/   r   mpscpuF)device_typeenabledr   r-   )r_   )rs   r   r2   rv   r:   r<   r;   rt   r0   strr3   autocast	transposer4   cossinr   r&   r_   )
rY   xr   inv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r*   rf   z!GraniteMoeRotaryEmbedding.forward   s   &&**<*III !M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 D**D**vvAGv$$cff17f&;&;;;s   A>EEE)
rj   rk   rl   r   rT   r   r3   no_gradrf   rm   rn   s   @r*   rp   rp      sz        // / / / / / /$@ @ @$ U]__< < _< < < < <r,   rp   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/   r   r-   )r;   r3   r4   )r   x1x2s      r*   rotate_halfr      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r,   c                     |                     |          }|                     |          }| |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.
    )r?   r   )qkr   r   r   unsqueeze_dimq_embedk_embeds           r*   apply_rotary_pos_embr      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr,   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        |||                    | _        || _        || _        || _	        dS )a  
        Initialize the GraniteMoeParallelExperts module.
        The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's comptible 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)
rS   rT   r   rU   r3   emptyrW   r    r   r   )rY   r    r   r   r\   s       r*   rT   z"GraniteMoeParallelExperts.__init__  sW      	l5;{K#T#TUU&$&r,   c                    |                     |d          }g }t          | j                  D ];}|                    t	          j        ||         | j        |                              <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linearrW   r3   r4   )rY   inputsexpert_size
input_listoutput_listiresultss          r*   rf   z!GraniteMoeParallelExperts.forward  s     \\+1\55
t'(( 	H 	HAqx
1t{1~FFGGGG)KQ///r,   rj   rk   rl   intrT   rf   rm   rn   s   @r*   r   r     sh        'C 'S 's 't ' ' ' ' ' ',      r,   r   c                   2     e Zd Zdededef fdZd Z xZS )GraniteMoeTopKGatingr   r    r@   c                     t                                                       || _        || _        || _        t          j        ||d          | _        dS )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)rS   rT   r    r   r@   r   Linearlayer)rY   r   r    r@   r\   s       r*   rT   zGraniteMoeTopKGating.__init__.  sM     	&$
Yz;UCCC


r,   c                    |                      |                                          }|                    | j        d          \  }}t	          j        |d                              |          }t	          j        |                    d          | j	        g|j
        |j                  }|                    d|d          }|                                                    d          }|                                }|                                }	|	                    d          \  }
}|                    | j        d          }|                                }||         }|||||fS )Nr   r-   r   r_   r2   trunc)rounding_mode)r   r:   r7   r@   r3   r6   type_aszerossizer    r_   r2   scatterlongr>   tolistflattensortdiv)rY   rc   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr   top_k_expertsrC   index_sorted_expertsbatch_indexbatch_gatess                 r*   rf   zGraniteMoeTopKGating.forwardA  sQ   M**0022&,kk$*!k&D&D#mmLa888@@OO a  $"23;;LU`Ug
 
 
 a22jjll&&q))!((** &--//"/"4"4Q"7"7*..tz.QQ "))++!"67#[+{FRRr,   r   rn   s   @r*   r   r   -  sq        D3 DS D D D D D D D&S S S S S S Sr,   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.
    rq   c                    t          t          |                                            |j        | _        |j        | _        t          |j                 | _        t          |j
        | j        | j        dz            | _        t          |j
        | j        | j                  | _        t          | j        |j
        |j                  | _        d S )Nr   )r   r    r@   )rS   r   rT   rZ   r   intermediate_sizer
   
hidden_act
activationr   num_local_expertsinput_linearoutput_linearr   num_experts_per_tokrouterrY   rq   r\   s     r*   rT   zGraniteMoeMoE.__init__d  s    mT""++--- ,!3 !235f6NPTP_aeaqtuauvv6v7OQUQacgcrss*0,
 
 
r,   c                 T   |                                 \  }}}|                    d|          }|                     |          \  }}}}}	||         }
|                     |
|          }|                    dd          }|                     |d                   |d         z  }|                     ||          }||dddf         z  }t          j        ||z  | j	        f|j
        |j                  }|                    d||          }|                    ||| j	                  }||	fS )a  
        Forward pass of the mixture of experts layer.

        Args:
            layer_input (Tensor):
                Input tensor.

        Returns:
            Tensor:
                Output tensor.
            Tensor:
                Router logits.
        r/   r   r-   r   r   Nr   )r   r=   r   r   chunkr   r   r3   r   r   r_   r2   	index_addview)rY   layer_inputbszlengthemb_sizerC   r   r   r   router_logitsexpert_inputsrc   chunked_hidden_statesexpert_outputsr   layer_outputs                   r*   rf   zGraniteMoeMoE.forwards  s5    !, 0 0 2 2VX!))"h77BF++kBZBZ?;[-#K0))-EE - 3 3A2 3 > >(=a(@AADYZ[D\\++M;GG'+aaag*>>S6\4?;>CW`n`uvvvq+~FF#((fdoFF]**r,   )rj   rk   rl   __doc__r   rT   rf   rm   rn   s   @r*   r   r   [  s^         
/ 
 
 
 
 
 
+ + + + + + +r,   r   rc   n_repc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||z  ||          S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r;   r<   r=   )rc   r   batchnum_key_value_headsslenhead_dims         r*   	repeat_kvr     s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr,   c                   R    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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' paperNrq   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _	        |j
        | _        | j	        | j        z  | _        |j        | _        | j        | j        z  | _        d| _        |j        | _        | j        | j        z  | j	        k    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                  | _        d S )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   )rS   rT   rq   r   loggerwarning_oncer\   rj   attention_dropoutrZ   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rY   rq   r   r\   s      r*   rT   zGraniteMoeAttention.__init__  s   ",!8 , , ,   "(!9!-3(DN:#)#= $(Nd6N$N!2MDN*t/???8RVRb 8 8%)^8 8 8  
 i 0$.4=2PW]Wlmmmi 0$2JT]2Zagavwwwi 0$2JT]2Zagavwwwi 0$2BI^___r,   Frc   r!   r   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr"   c	                    |                                 \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|\  }}t          ||||          \  }}|&|||d}|
                    ||| j        |          \  }}t          || j                  }t          || j                  }t          j        ||                    dd                    | j        z  }|$|d d d d d d d |j        d         f         }||z   }t$          j                            |dt          j                                      |j                  }t$          j                            || j        | j                  }t          j        ||          }|                                 |
| j        || j        fk    r5t7          d	|
| j        || j        f d
|                                            |                    dd                                          }|                    |
|d          }|                     |          }|sd }|||fS )Nr   r   r   r   r  r	   r/   )r.   r_   )ptrainingz `attn_output` should be of size z	, but is )r   r  r  r  r   r   r   r   r   r   updater   r   r   r3   matmulr  r;   r   r5   r6   r`   r&   r_   dropoutr   r  r  
contiguousr	  )rY   rc   r!   r   r  r  r  r  r  kwargsr   q_lenrC   query_states
key_statesvalue_statesr   r   cache_kwargsattn_weightscausal_maskattn_outputs                         r*   rf   zGraniteMoeAttention.forward  s    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTP\\%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!&&sE266kk+..  	 LL.88r,   NNNNFFNN)rj   rk   rl   r   r   r   r   rT   r3   Tensor
LongTensorr   boolr   rf   rm   rn   s   @r*   r   r     s>       GG` `/ `HSM ` ` ` ` ` `F 2637*."'59KO:9 :9|:9 !.:9 u/0	:9
 !:9  :9 :9 !!12:9 &eEL%,,F&GH:9 
u|Xel3XeEL>Q5RR	S:9 :9 :9 :9 :9 :9 :9 :9r,   r   c                   :    e Zd ZdZ fdZ	 	 	 	 	 	 	 ddej        deej                 deej                 dee	         d	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 )GraniteMoeFlashAttention2aP  
    GraniteMoe flash attention module. This module inherits from `GraniteMoeAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S r"  )rS   rT   r   _flash_attn_uses_top_left_mask)rY   argsr  r\   s      r*   rT   z"GraniteMoeFlashAttention2.__init__	  s9    $)&)))
 3V2W2W.W+++r,   NFrc   r!   r   r  r  r  r  r  r"   c	                    d}|                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|\  }}t          ||||          \  }}|&|||d}|
                    ||| j        |          \  }}|                    dd          }|                    dd          }|                    dd          }| j        r| j        nd}|j        }|t          j        k    rt          j                    rt          j                    }n3t'          | j        d          r| j        j        }n| j        j        j        }t.                              d| d           |                    |          }|                    |          }|                    |          }t5          |||||
||| j        t9          | d	d           | j        | j        
          }|                    |	|
d                                           }| !                    |          }|sd }|||fS )NFr   r   r          _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)r   r  softmax_scaler0  use_top_left_maskr  r/   )"r   r  r  r  r   r   r   r   r   r   r  r   r  r   r_   r3   r`   is_autocast_enabledget_autocast_gpu_dtypehasattrrq   r.  rW   r   r   r&   r   r  getattrr*  r  r=   r  r	  )rY   rc   r!   r   r  r  r  r  r  r   r  rC   r  r  r  r   r   r  dropout_raterd   target_dtyper!  r  s                          r*   rf   z!GraniteMoeFlashAttention2.forward  s    "%**,,UA{{=11[[//
{{=11
 $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J $--a33))!Q//
#--a3315Gt--C #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L.% ,"4)94@@"An
 
 
 "))#ub99DDFFkk+..  	 LL.88r,   r#  )rj   rk   rl   r   rT   r3   r$  r   r%  r   r&  r   rf   rm   rn   s   @r*   r(  r(    s3        X X X X X 6:37*."'59KOX9 X9|X9 !!12X9 u/0	X9
 !X9  X9 X9 !!12X9 &eEL%,,F&GHX9 
u|Xel3XeEL>Q5RR	SX9 X9 X9 X9 X9 X9 X9 X9r,   r(  c                   4    e Zd ZdZ	 	 	 	 	 	 	 ddej        deej                 deej                 dee         d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 fdZ xZS )GraniteMoeSdpaAttentiona  
    GraniteMoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `GraniteMoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrc   r!   r   r  r  r  r  r  r"   c	           
         |rCt                               d           t                                          ||||||||          S |                                \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j	        | j
                                      dd          }|                    |
|| j        | j
                                      dd          }|                    |
|| j        | j
                                      dd          }|\  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t!          || j                  }t!          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||dk    rdnd	}t,          j        j                            ||||| j        r| j        nd
|| j                  }|                    dd                                          }|                    |
|d          }|                     |          }|d |fS )Na  GraniteMoeModel is using GraniteMoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rc   r!   r   r  r  r  r  r  r   r   r  r  cudaTFr-  )	attn_mask	dropout_pr  scaler/   )r   r   rS   rf   r   r  r  r  r   r   r   r   r   r   r  r   r   r   r;   r2   rt   r  r3   r   r5   scaled_dot_product_attentionr  r   r  r	  )rY   rc   r!   r   r  r  r  r  r  r  r   r  rC   r  r  r  r   r   r  r   r  r!  r\   s                         r*   rf   zGraniteMoeSdpaAttention.forwardu  s     	[   77??+-)-"3#-$7 # 	 	 	 &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!04Fd,,3, G 
 
 "++Aq11<<>>!&&sE266kk+..D.00r,   r#  )rj   rk   rl   r   r3   r$  r   r%  r   r&  r   rf   rm   rn   s   @r*   r:  r:  m  s          2637*."'59KOP1 P1|P1 !.P1 u/0	P1
 !P1  P1 P1 !!12P1 &eEL%,,F&GHP1 
u|Xel3XeEL>Q5RR	SP1 P1 P1 P1 P1 P1 P1 P1 P1 P1r,   r:  )eagerflash_attention_2sdpac                   `    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 )GraniteMoeDecoderLayerrq   r   c                 b   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        |j        | _        d S )N)rq   r   r[   )rS   rT   rZ   GRANITEMOE_ATTENTION_CLASSES_attn_implementation	self_attnr   block_sparse_moerP   rms_norm_epsinput_layernormpost_attention_layernormresidual_multiplierr
  s      r*   rT   zGraniteMoeDecoderLayer.__init__  s    !-5f6QRZ`luvvv -f 5 501CI\]]](9&:LRXRe(f(f(f%#)#=   r,   NFrc   r!   r   r  r  r  r  output_router_logitsr  r"   c
                 0   |}|                      |          } | j        d||||||||	d|
\  }}}||| j        z  z   }|}|                     |          }|                     |          \  }}||| j        z  z   }|f}|r||fz  }|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            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%   )rN  rK  rP  rO  rL  )rY   rc   r!   r   r  r  r  r  rQ  r  r  residualself_attn_weightspresent_key_valuer   outputss                   r*   rf   zGraniteMoeDecoderLayer.forward  s   L !,,];; ?Mdn 
?
')%)/) 3
?
 
?
 
?
 
?
;(*; !=43K#KK !55mDD'+'<'<]'K'K$} =43K#KK " 	,)++G 	,)++G 	(''Gr,   )NNNFFNFN)rj   rk   rl   r   r   rT   r3   r$  r   r%  r   r&  r   FloatTensorrf   rm   rn   s   @r*   rF  rF    sR       
>/ 
>C 
> 
> 
> 
> 
> 
> 2637*.,1$)59/4KOK K|K !.K u/0	K
 !K $D>K D>K !!12K 'tnK &eEL%,,F&GHK 
u (51BEDU1U+V"WW	XK K K K K K K Kr,   rF  aO  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`GraniteMoeConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zXThe bare GraniteMoe Model outputting raw hidden-states without any specific head on top.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dS )GraniteMoePreTrainedModelmodelTrF  past_key_valuesc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rU|j        j                            d|           |j        +|j        j        |j                 	                                 d S d S t          |t          j                  r?|j        j        	                                 |j        j                            d           d S t          |t                    r-|j        j                            d| j         j                   d S d S )Nr-  )r9   stdg      ?)rq   initializer_ranger0   r   r   rW   datanormal_r   zero_	Embeddingpadding_idx	LayerNormfill_r   )rY   moduler]  s      r*   _init_weightsz'GraniteMoePreTrainedModel._init_weightsK  si   k+fbi(( 	TM&&CS&999{& &&((((( '&-- 	TM&&CS&999!-"6#56<<>>>>> .--- 	TK""$$$M$$S))))) 9:: 	TM&&CT[5R&SSSSS	T 	Tr,   N)rj   rk   rl   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_cacherg  r%   r,   r*   rY  rY  ;  sj        
 $L&*#12#4"5!N  $!T T T T Tr,   rY  a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        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`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                       e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 	 dde
j        dee
j                 d	ee
j                 d
eeeee
j                 f                  dee
j                 dee         dee         dee         dee         dee         dee
j                 deeef         fd            Zde
j        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
j        defd            Z xZS )GraniteMoeModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GraniteMoeDecoderLayer`]

    Args:
        config: GraniteMoeConfig
    rq   c                 |   t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        t          j        j                  | _        d| _        j        | _        j        | _        j        | _        | j        | j        z  | _        j        | _        j        | _        t/                    | _        |                                  d S )Nc                 0    g | ]}t          |          S r%   )rF  )r'   r   rq   s     r*   r+   z,GraniteMoeModel.__init__.<locals>.<listcomp>  s$    hhh9#FI66hhhr,   rH  F)rS   rT   pad_token_idrc  
vocab_sizer   rb  rZ   embed_tokens
ModuleListr   rJ   layersrP   rM  normgradient_checkpointingembedding_multiplierr   r   r   r|   
rope_thetarp   
rotary_emb	post_initr   s    `r*   rT   zGraniteMoeModel.__init__  s      !. +L):F<NPTP`aamhhhhfNfHgHghhh
 
 &f&8f>QRRR	&+#$*$?!!-3(DN:'-'E$ + 4F;; 	r,   c                     | j         S r"  rx  rh   s    r*   get_input_embeddingsz$GraniteMoeModel.get_input_embeddings  s      r,   c                     || _         d S r"  r  rY   values     r*   set_input_embeddingsz$GraniteMoeModel.set_input_embeddings  s    !r,   N	input_idsr!   r   r[  inputs_embedsr  r  output_hidden_statesrQ  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          	                    d           d}|| 
                    |          }|| j        z  }d}|rEt          |t                    s0d}t          j        |          }t          	                    d           |B||                                nd}t#          j        |||j        d         z   |j                  }||                    d          }|                     |||||          }|}|                     ||          }|rd	nd }|rd	nd }|	rd	nd }d }| j        D ]}|r||fz  }| j        r+| j        r$|                     |j        ||||||||	|
  
        }n |||||||||	|
	  	        }|d         }|r||rdnd         }|r||d         fz  }|	r||d         fz  }|                     |          }|r||fz  }|r|nd }|r|                                }|
st;          d ||||fD                       S t=          |||||          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   r%   )r!   r   r  r  r  r  rQ  r  r   r/   c              3      K   | ]}||V  	d S r"  r%   )r'   vs     r*   	<genexpr>z*GraniteMoeModel.forward.<locals>.<genexpr>J  s(      ttqfgfsfsfsfsfsttr,   )last_hidden_stater[  rc   
attentionsr   )rq   r  r  r  use_return_dictr  r|  r  r   r   rx  r}  r0   r   r   from_legacy_cacheget_seq_lengthr3   aranger;   r2   r?   _update_causal_maskr  rz  _gradient_checkpointing_func__call__r{  to_legacy_cacher1   r   )rY   r  r!   r   r[  r  r  r  r  rQ  r  r  return_legacy_cachepast_seen_tokensr   rc   r  all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                           r*   rf   zGraniteMoeModel.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M%(AA# 	Z?? 	"&*<_MMO]  
 !CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 

 & #oom\JJ #7@BBD0:d"6@BBD!![ '	: '	:M# 6!m%55!* t}  $ A A!*! #%"('! ! !.!#.!-#2&7'#1)=(;
! 
! 
! *!,M R%28I3P11q%Q"  6=#3"55# :!mB&7%99!		-00   	2-!11+4>''$
 	6#3355J 	utt]J@QSa$btttttt%+&+%+
 
 
 	
r,   input_tensorc                 $   | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}t          j        |          j        }
|j        d         }|r|                                }n/t          |t          j                  r|j        d         n||z   dz   }|C|                                dk    r+|                                dk    rt%          d	          |}nt          j        ||f|
||	
          }|dk    rt          j        |d          }|t          j        ||	          |                    dd          k    z  }|d d d d d d f                             |j        d         ddd          }||                                }|j        d         }|d d d d d d d |f         |d d d d d d f         z   }|dk    }|d d d d d d d |f                             ||
          |d d d d d d d |f<   | j         j        dk    r)|'|j	        j        dk    r|st          j        ||
          }|S )NrC  r-  r   rD  )r  past_key_values_lengthis_trainingr   r/      zGCustom 4D attention mask should be passed in inverted form with max==0`
fill_valuer_   r2   diagonalr   r=  )rq   rJ  r  r0   r   r   _ignore_causal_mask_sdpar  r_   r2   r3   finfominr;   get_max_lengthr$  r.   r   r  fulltriur  r=   r<   clonemasked_fillrt   _unmask_unattended)rY   r!   r  r  r[  r  r  using_static_cacher_   r2   	min_dtyperI   target_lengthr   mask_lengthpadding_masks                   r*   r  z#GraniteMoeModel._update_causal_maskS  s>    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?vK&&*	&,Q/ 	+::<<MM nel;;<$R((%7!;  %.*<*<*>*>!*C*C!!##q(( !jkkk(KK* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>|?QRS?TVWY[]_``K))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 K,66*%*f44% 5 1CKQZ[[Kr,   rI   r  r_   r2   rH   c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        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.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr  r  r   r  r   r/   r   )r.   r3   r  r  r  r  r  r=   r<   r  r;   r  )r!   rI   r  r_   r2   r  rH   r  r   r  r  r  s               r*   5_prepare_4d_causal_attention_mask_with_cache_positionzEGraniteMoeModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r,   )NNNNNNNNNNN)rj   rk   rl   r   r   rT   r  r  r   GRANITEMOE_INPUTS_DOCSTRINGr3   r%  r   r$  r   r   r   rW  r&  r   r   rf   r  staticmethodr   r_   r2   r  rm   rn   s   @r*   rs  rs    sa       
 /      2! ! !" " " +*+FGG '+1537KO59$(,0/3/3&*59
 
#
 !.
 u/0	

 "%tE4E/F(F"GH
   12
 D>
 $D>
 'tn
 'tn
 d^
 !!12
 
u--	.
 
 
 HG
BNN lN 	N
 N  N N N N` 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r,   rs  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e           eee
          	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 deeeeej                 f                  deej                 dee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ed             Z xZS )GraniteMoeForCausalLMzlm_head.weightrq   c                 F   t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        |j	        | _	        |j
        | _        |j        | _        |                                  d S )NFr   )rS   rT   rs  rZ  rw  r   r   rZ   lm_headrouter_aux_loss_coefr   r    r   r  r   s     r*   rT   zGraniteMoeForCausalLM.__init__  s       $V,,
 +y!3V5FUSSS$*$?!!3#)#=  	r,   c                     | j         j        S r"  rZ  rx  rh   s    r*   r  z*GraniteMoeForCausalLM.get_input_embeddings  s    z&&r,   c                     || j         _        d S r"  r  r  s     r*   r  z*GraniteMoeForCausalLM.set_input_embeddings  s    "'
r,   c                     | j         S r"  r  rh   s    r*   get_output_embeddingsz+GraniteMoeForCausalLM.get_output_embeddings  s
    |r,   c                     || _         d S r"  r  )rY   new_embeddingss     r*   set_output_embeddingsz+GraniteMoeForCausalLM.set_output_embeddings  s    %r,   c                     || _         d S r"  rZ  )rY   decoders     r*   set_decoderz!GraniteMoeForCausalLM.set_decoder  s    


r,   c                     | j         S r"  r  rh   s    r*   get_decoderz!GraniteMoeForCausalLM.get_decoder  s
    zr,   )output_typerh  Nr  r!   r   r[  r  labelsr  r  r  rQ  r  r  r"   c                    ||n| j         j        }|
|
n| j         j        }
|	|	n| j         j        }	||n| j         j        }|                     ||||||||	|
||          }|d         }|                     |          }|| j         j        z  }d}||                                }|dddddf         	                                }|dddf         	                                }t                      }|                    d| j         j                  }|                    d          }|                    |j                  } |||          }d}|
rRt          |r|j        n|d         | j        | j        |          }|%|| j        |                    |j                  z  z  }|s |f|dd         z   }|
r|f|z   }||f|z   n|S t)          ||||j        |j        |j        |j                  S )a  
        Args:
            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]`.

        Returns:

        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!   r   r[  r  r  r  r  rQ  r  r  r   .r/   r   )lossaux_lossr   r[  rc   r  r   )rq   r  rQ  r  r  rZ  r  logits_scalingr:   r  r   r   rw  r&   r2   rN   r   r    r   r  r   r[  rc   r  )rY   r  r!   r   r[  r  r  r  r  r  rQ  r  r  rV  rc   r   r  shift_logitsshift_labelsloss_fctr  outputs                         r*   rf   zGraniteMoeForCausalLM.forward  si   T 2C1N--TXT_Tq$8$D  $+Jj 	 %9$D  $+Jj 	 &1%<kk$+B] **)%+'/!5!5#)  
 
  
m,,$+44\\^^F!#ssAAA+.99;;L!#qrr'?5577L'))H',,R1GHHL',,R00L'??<+>??L8L,77D 	M/)4E%%'"+ (	 H !1HKK4L4LLL 	DY,F# ."v-'+'7D7V##VC(#3!/)!/
 
 
 	
r,   c                 T    d}| D ]!}|t          fd|D                       fz  }"|S )Nr%   c              3   t   K   | ]2}|                     d                     |j                            V  3dS )r   N)index_selectr&   r2   )r'   
past_statebeam_idxs     r*   r  z7GraniteMoeForCausalLM._reorder_cache.<locals>.<genexpr>t  sC      nnU_j--aZ=N1O1OPPnnnnnnr,   )r1   )r[  r  reordered_past
layer_pasts    `  r*   _reorder_cachez$GraniteMoeForCausalLM._reorder_cacheo  sQ    ) 	 	Jnnnncmnnnnn NN r,   )NNNNNNNNNNNN)rj   rk   rl   _tied_weights_keysr   rT   r  r  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr3   r%  r   r$  r   r   r   rW  r&  r   rf   r  r  rm   rn   s   @r*   r  r    s-       *+/      ' ' '( ( (  & & &     +*+FGG+DSbccc '+1537KO59-1$(,0/3/3&*59l
 l
#l
 !.l
 u/0	l

 "%tE4E/F(F"GHl
   12l
 )*l
 D>l
 $D>l
 'tnl
 'tnl
 d^l
 !!12l
 
u//	0l
 l
 l
 dc HGl
\   \    r,   r  )Nr   N)Nr   )Ftypingr   r   r   r   r3   torch.nn.functionalr   r5   r   torch.utils.checkpointtorch.nnr   activationsr
   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   modeling_rope_utilsr   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   configuration_granitemoer   
get_loggerrj   r   r  r$  r   rN   ModulerP   r   rp   r   r   r   r   r   r   r   r(  r:  rI  rF  GRANITEMOE_START_DOCSTRINGrY  r  rs  r  r%   r,   r*   <module>r     s    0 / / / / / / / / / / /                     % % % % % % ! ! ! ! ! ! ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) > > > > > > F F F F F F         
 7 6 6 6 6 6 - - - - - - 1 1 1 1 1 1              7 6 6 6 6 6 
	H	%	%$ "&
-1	O& O&u|U5<%8$>?O&#O& U\*	O&
 5<O& O& O& O&fJ J J J J	 J J J(   - . . .:< :< :< :< :<	 :< :< :<|( ( (   8' ' ' ' '	 ' ' 'V+S +S +S +S +S29 +S +S +S\5+ 5+ 5+ 5+ 5+BI 5+ 5+ 5+r	UU\ 	U# 	U%, 	U 	U 	U 	U]9 ]9 ]9 ]9 ]9") ]9 ]9 ]9Bg9 g9 g9 g9 g9 3 g9 g9 g9VX1 X1 X1 X1 X11 X1 X1 X1x !2#    X X X X XRY X X Xv " ^ T T T T T T T	 T:G T ^ p p p p p/ p p	 pf	Y Y Y Y Y5 Y Y Y Y Yr,   