
    qi`                        d dl mZ d dlmZ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 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 ddlmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1  G d ded      Z2 G d dejf                        Z4 ed       G d dejf                               Z5 G d  d!ejf                        Z6 G d" d#ejf                        Z7 G d$ d%ejf                        Z8d& Z9 ed'      dFd(       Z:d)ejv                  d*e<d+ejv                  fd,Z=	 dGd-ejf                  d.ejv                  d/ejv                  d0ejv                  d1ejv                  dz  d2e>d3e>d4e&e(   fd5Z? ee:       G d6 d7ejf                               Z@ G d8 d9e      ZAe) G d: d;e$             ZB G d< d=ejf                        ZCe) G d> d?eB             ZD	 	 	 dHd@ejv                  eEejv                     z  dz  dAe<dz  d1ejv                  dz  d+ejv                  e<z  fdBZFe) G dC dDeBe             ZGg dEZHy)I    )Callable)Optional	TypedDictN)nn)
functional   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstring)can_return_tuplemaybe_autocastmerge_with_config_defaults)capture_outputs   )GraniteMoeSharedConfigc                       e Zd ZU dZej
                  ed<   ej
                  ed<   eed<   eed<   ej                  ed<   y)GraniteFlashAttentionKwargsaT  
    Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
    Use cases include padding-free training and fewer `torch.compile` graph breaks.

    cu_seq_lens_q (`torch.LongTensor`):
        Gets cumulative sequence length for query state.
    cu_seq_lens_k (`torch.LongTensor`):
        Gets cumulative sequence length for key state.
    max_length_q (`int`):
        Maximum sequence length for query state.
    max_length_k (`int`):
        Maximum sequence length for key state.
    seq_idx (`torch.IntTensor):
        Index of each packed sequence.
    cu_seq_lens_qcu_seq_lens_kmax_length_qmax_length_kseq_idxN)	__name__
__module____qualname____doc__torch
LongTensor__annotations__int	IntTensor     p/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/modeling_granitemoeshared.pyr#   r#   -   s7      ######__r3   r#   F)totalc                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )GraniteMoeSharedMLPz~
    MLP layer for shared experts

    Args:
        config:
            Configuration object with model hyperparameters.
    configc                 `   t         |           |j                  | _        |j                  | _        t
        |j                     | _        t        j                  | j                  | j                  dz  d      | _
        t        j                  | j                  | j                  d      | _        y )N   Fbias)super__init__hidden_size
input_sizeshared_intermediate_sizer
   
hidden_act
activationr   Linearinput_linearoutput_linearselfr8   	__class__s     r4   r>   zGraniteMoeSharedMLP.__init__N   s     ,,!:: !2!23IIdoot7G7G!7KRWXYYt'7'7uUr3   hidden_statesreturnc                     | j                  |      }|j                  dd      }| j                  |d         |d   z  }| j                  |      }|S )Nr:   dimr   r    )rE   chunkrC   rF   )rH   rJ   chunked_hidden_statess      r4   forwardzGraniteMoeSharedMLP.forwardW   s^    ))-8 - 3 3A2 3 >(=a(@ADYZ[D\\**=9r3   )
r)   r*   r+   r,   r!   r>   r-   TensorrR   __classcell__rI   s   @r4   r7   r7   E   s2    V5 VU\\ ell r3   r7   RMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	GraniteMoeSharedRMSNormepsrK   Nc                     t         |           t        j                  t	        j
                  |            | _        || _        y)zF
        GraniteMoeSharedRMSNorm is equivalent to T5LayerNorm
        N)r=   r>   r   	Parameterr-   onesweightvariance_epsilon)rH   r?   rY   rI   s      r4   r>   z GraniteMoeSharedRMSNorm.__init__a   s1     	ll5::k#:; #r3   rJ   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr:   rM   T)keepdim)	dtypetor-   float32powmeanrsqrtr^   r]   )rH   rJ   input_dtypevariances       r4   rR   zGraniteMoeSharedRMSNorm.forwardi   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler]   shaper^   )rH   s    r4   
extra_reprz"GraniteMoeSharedRMSNorm.extra_reprp   s*    ))*+6$2G2G1HIIr3   )gư>)
r)   r*   r+   floatr>   r-   rS   rR   rl   rT   rU   s   @r4   rX   rX   _   s7    $ $$ $;U\\ ;ell ;Jr3   rX   c                   6     e Zd Zdedededdf fdZd Z xZS )GraniteMoeSharedParallelExpertsnum_expertsr@   output_sizerK   Nc                     t         |           t        j                  t	        j
                  |||            | _        || _        || _        || _	        y)a  
        Initialize the GraniteMoeSharedParallelExperts 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)
r=   r>   r   r[   r-   emptyr]   rp   r@   rq   )rH   rp   r@   rq   rI   s       r4   r>   z(GraniteMoeSharedParallelExperts.__init__u   sD    " 	ll5;;{K#TU&$&r3   c                     |j                  |d      }g }t        | j                        D ]7  }|j                  t	        j
                  ||   | j                  |                9 t        j                  |d      }|S )a  
        Forward pass of the GraniteMoeSharedParallelExperts module.

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

        Returns:
            Tensor: Output tensor.
        r   rN   )	splitrangerp   appendFlinearr]   r-   cat)rH   inputsexpert_size
input_listoutput_listiresultss          r4   rR   z'GraniteMoeSharedParallelExperts.forward   sq     \\+1\5
t''( 	HAqxx
1t{{1~FG	H))KQ/r3   r)   r*   r+   r0   r>   rR   rT   rU   s   @r4   ro   ro   t   s)    'C 'S 's 't '.r3   ro   c                   2     e Zd Zdededef fdZd Z xZS )GraniteMoeSharedTopKGatingr@   rp   top_kc                     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.
        Fr;   N)r=   r>   rp   r@   r   r   rD   layer)rH   r@   rp   r   rI   s       r4   r>   z#GraniteMoeSharedTopKGating.__init__   s:     	&$
YYz;UC
r3   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    rN   r   ra   devicetrunc)rounding_mode)r   rm   topkr   r-   softmaxtype_aszerossizerp   ra   r   scatterlongsumtolistflattensortdiv)rH   rJ   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr|   top_k_experts_index_sorted_expertsbatch_indexbatch_gatess                 r4   rR   z"GraniteMoeSharedTopKGating.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Rr3   r   rU   s   @r4   r   r      s'    D3 DS D D(Sr3   r   c                   .     e Zd ZdZdef fdZd Z xZS )GraniteMoeSharedMoEz
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    r8   c                    t         |           |j                  | _        |j                  | _        t
        |j                     | _        t        |j                  | j                  | j                  dz        | _
        t        |j                  | j                  | j                        | _        t        | j                  |j                  |j                        | _        y )Nr:   )r@   rp   r   )r=   r>   r?   r@   intermediate_sizer
   rB   rC   ro   num_local_expertsrE   rF   r   num_experts_per_tokrouterrG   s     r4   r>   zGraniteMoeSharedMoE.__init__   s     ,,!33 !2!23;$$doot7G7G!7K
 =$$d&6&6
 100,,
r3   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                        }|S )NrM   r:   rN   r   r    r   )r   reshaper   rE   rP   rC   rF   r-   r   r@   ra   r   	index_addview)rH   layer_inputbszlengthemb_sizer   r   r   r|   expert_inputsrJ   rQ   expert_outputsr   layer_outputs                  r4   rR   zGraniteMoeSharedMoE.forward   s    + 0 0 2VX!))"h76:kk+6N3;[!#K0))-E - 3 3A2 3 >(=a(@ADYZ[D\\++M;G'+ag*>>S6\4??;>CWCW`n`u`uvq+~F#((fdooFr3   )r)   r*   r+   r,   r!   r>   rR   rT   rU   s   @r4   r   r      s    
5 
&r3   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..NrM   r:   rN   )rk   r-   rz   )xx1x2s      r4   rotate_halfr     sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkcossinunsqueeze_dimq_embedk_embeds          r4   apply_rotary_pos_embr     sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr3   rJ   n_reprK   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r    N)rk   expandr   )rJ   r   batchnum_key_value_headsslenhead_dims         r4   	repeat_kvr   "  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr3   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr:   r   rM   )rO   ra   )ptrainingr    )r   num_key_value_groupsr-   matmul	transposer   r   r   rc   rb   ra   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r4   eager_attention_forwardr   .  s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r3   c                       e Zd ZdZdedef fdZ	 	 	 	 ddej                  de	ej                  ej                  f   dz  dej                  dz  d	e
dz  d
ej                  dz  dee   de	ej                  ej                  f   fdZ xZS )GraniteMoeSharedAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr8   	layer_idxc                 ^   t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        |j                  | _        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j                  | j                  z  |j
                  |j                         | _        y )Nr   Tr;   )r=   r>   r8   r   getattrr?   num_attention_headsr   r   r   attention_multiplierr   attention_dropout	is_causalr   rD   attention_biasq_projk_projv_projo_projrH   r8   r   rI   s      r4   r>   z"GraniteMoeSharedAttention.__init__K  sJ   "
F4F4F&JdJd4de$*$>$>&B\B\$\!22!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r3   NrJ   position_embeddingsr   past_key_valuescache_positionr   rK   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        j                  | j                  j                  t              } || |	|
||f| j                  sdn| j                   | j"                  d|\  }} |j$                  g |d j'                         }| j)                  |      }||fS )NrM   r    r:   )r   r   r           )r   r   )rk   r   r   r   r   r   r   r   updater   r   get_interfacer8   _attn_implementationr   r   r   r   r   r   r   )rH   rJ   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r4   rR   z!GraniteMoeSharedAttention.forwardb  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r3   )NNNN)r)   r*   r+   r,   r!   r0   r>   r-   rS   rj   r   r.   r   r   rR   rT   rU   s   @r4   r   r   G  s    G
5 
# 
4 IM.2(,26))||)) #5<<#=>E)) t+	))
 )) ((4/)) +,)) 
u||U\\)	*))r3   r   c                   p    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
e
dz  dej                  dz  deej                  ej                  f   dz  dee   deej                  eej                  ej                  f   dz  f   fdZ xZS )GraniteMoeSharedDecoderLayerr8   r   c                    t         |           |j                  | _        t        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |      | _
        |j                  | _        |j                  dk(  rd | _        y t        |      | _        y )N)r8   r   rY   r   )r=   r>   r?   r   	self_attnrX   rms_norm_epsinput_layernormpost_attention_layernormr   block_sparse_moeresidual_multiplierrA   r7   
shared_mlpr   s      r4   r>   z%GraniteMoeSharedDecoderLayer.__init__  s    !--2&IV6v7I7IvObObc(?@R@RX^XkXk(l% 3F ;#)#=#= "("A"AQ"F$L_`fLgr3   NrJ   r   position_idsr   output_attentions	use_cacher   r   r   rK   c	                 >   |}
| j                  |      } | j                  d||||||||d|	\  }}|
|| j                  z  z   }|}
| j                  |      }| j	                  |      }| j
                  |}n|| j                  |      z   }|
|| j                  z  z   }|S )N)rJ   r   r  r   r  r	  r   r   r2   )r  r   r  r  r  r  )rH   rJ   r   r  r   r  r	  r   r   r   residualr   moe_hidden_statess                r4   rR   z$GraniteMoeSharedDecoderLayer.forward  s     !,,]; *4>> 

')%+/) 3

 

q !=43K3K#KK 55mD 11-@??"-M-0NNM =43K3K#KKr3   )NNNFFNN)r)   r*   r+   r!   r0   r>   r-   rS   r.   r   boolrj   r   r#   FloatTensorrR   rT   rU   s   @r4   r   r     s   h5 h# h /304(,).!&26HL'||' t+' &&-	'
 '  $;' $;' ((4/' #5<<#=>E' 45' 
u  %(9(95;L;L(L"MPT"TT	U'r3   r   c                        e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZeedZ ej$                          fd       Z xZS )	GraniteMoeSharedPreTrainedModelr8   modelTr   r   F)rJ   
attentionsc                     t         |   |       t        |t              r7t	        j
                  |j                  d| j                  j                         y y )Nr   )re   std)	r=   _init_weights
isinstancero   initnormal_r]   r8   initializer_range)rH   r   rI   s     r4   r  z-GraniteMoeSharedPreTrainedModel._init_weights  s>    f%f=>LLSdkk6S6ST ?r3   )r)   r*   r+   r!   r/   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r   _can_record_outputsr-   no_gradr  rT   rU   s   @r4   r  r    sp    ""&*#78#4"5N""&5/
 U]]_U Ur3   r  c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )GraniteMoeSharedRotaryEmbeddinginv_freqNr8   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultr'  F)
persistentoriginal_inv_freq)r=   r>   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr8   rope_parametersr)  compute_default_rope_parametersr   attention_scalingregister_bufferclone)rH   r8   r   rope_init_fnr'  rI   s        r4   r>   z(GraniteMoeSharedRotaryEmbedding.__init__  s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr3   r   ztorch.deviceseq_lenrK   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetar   Ng      ?r   r:   ra   )r   ra   )	r0  r   r?   r   r-   arangeint64rb   rm   )r8   r   r6  baserO   attention_factorr'  s          r4   r1  z?GraniteMoeSharedRotaryEmbedding.compute_default_rope_parameters  s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r3   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   rM   r    mpscpuF)device_typeenabledr:   rN   r9  )r'  rm   r   rk   rb   r   r  typestrr   r   r-   rz   r   r2  r   ra   )
rH   r   r  inv_freq_expandedposition_ids_expandedrA  freqsembr   r   s
             r4   rR   z'GraniteMoeSharedRotaryEmbedding.forward  sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$)N)NNN)r)   r*   r+   r-   rS   r/   r!   r>   staticmethodr   r0   rj   rm   r1  r$  r   rR   rT   rU   s   @r4   r&  r&    s    llV5 V  04+/"*&-*(* t* 
~u$	%	* *: U]]_<  <r3   r&  c                       e Zd Zdef fdZeee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  d	edz  d
ej                  dz  dee   defd                     Z xZS )GraniteMoeSharedModelr8   c           	      .   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        |j(                  | _        | j+                          y c c}w )Nr   r8   F)r=   r>   pad_token_idpadding_idx
vocab_sizer   	Embeddingr?   embed_tokens
ModuleListrv   num_hidden_layersr   layersrX   r  normr&  
rotary_embgradient_checkpointingembedding_multiplier	post_initr   s      r4   r>   zGraniteMoeSharedModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammNSTZTlTlNmn)&)<n
 ,F,>,>FDWDWX	9H&+#$*$?$?! 	 os   DN	input_idsr   r  r   inputs_embedsr	  r   r   rK   c                 b   |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|F||j	                         nd}	t        j                  |	|	|j                  d   z   |j                        }||j                  d      }t        | j                  |||||      }
|| j                  z  }|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f||
||||d|} | j                  |      }t!        ||      S )	Nz:You must specify exactly one of input_ids or inputs_embedsrM  r   r    )r   )r8   r\  r   r   r   r  )r   r   r  r   r	  r   )last_hidden_stater   )
ValueErrorr   r8   rR  get_seq_lengthr-   r:  rk   r   r   r   rY  rW  rU  rT  rV  r   )rH   r[  r   r  r   r\  r	  r   r   past_seen_tokenscausal_maskrJ   r   decoder_layers                 r4   rR   zGraniteMoeSharedModel.forward/  sp    -t";<YZZ0*$++>O  --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L(;;'))+%
 &(A(AA% #oom\J![[)H4;;+H+HI 
	M)	$7*) /#-	 	M
	 		-0%++
 	
r3   )NNNNNNN)r)   r*   r+   r!   r>   r   r   r   r-   r.   rS   r   r  r  r   r   r   rR   rT   rU   s   @r4   rK  rK    s    5 "   .2.204(,26!%26;
##d*;
 t+;
 &&-	;

 ;
 ((4/;
 $;;
 ((4/;
 +,;
 
 ;
    ;
r3   rK  gate_logitsrp   c                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

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

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

    Returns:
        The auxiliary loss.
    Nr   rN   rM   )r  rj   r   r-   rz   rb   r   r   r   r   one_hotre   rm   rk   r   r   r   r   )rd  rp   r   r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr   selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthrT  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r4   load_balancing_loss_funcrt  p  s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&
O[QRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1G1Q1QRS1TTUL+%%[ .ks   Ic                   d    e Zd ZddiZddiZddgdgfiZdef fdZee		 	 	 	 	 	 	 	 	 dd
e
j                  d	z  de
j                  d	z  de
j                  d	z  ded	z  de
j                  d	z  de
j                  d	z  ded	z  de
j                  d	z  dee
j                  z  deez  fd              Z xZS )GraniteMoeSharedForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputrJ   r   r8   c                 p   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        |j                  | _        | j                          y )NFr;   )r=   r>   rK  r  rP  r   rD   r?   rw  router_aux_loss_coefr   rp   r   logits_scalingrZ  rG   s     r4   r>   z$GraniteMoeSharedForCausalLM.__init__  s     *62
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#= $33 	r3   Nr[  r   r  r   r\  labelsoutput_router_logitsr   logits_to_keeprK   c
           
         ||n| j                   j                  } | j                  d||||||d|
}|j                  }t	        |	t
              rt        |	 d      n|	}| j                  |dd|ddf         }|| j                   j                  z  }d}|* | j                  ||fd| j                   j                  i|
}d}|rYt        |j                  | j                  | j                  |      }|+|| j                  |j!                  |j"                        z  z  }t%        ||||j&                  |j(                  |j*                  |j                        S )ax  
        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, GraniteMoeSharedForCausalLM

        >>> model = GraniteMoeSharedForCausalLM.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   rP  )lossaux_lossr   r   rJ   r  router_logitsr2   )r8   r}  r  r^  r  r0   slicerw  r{  loss_functionrP  rt  r  rp   r   rz  rb   r   r   r   rJ   r  )rH   r[  r   r  r   r\  r|  r}  r   r~  r   outputsrJ   slice_indicesr   r  r  s                    r4   rR   z#GraniteMoeSharedForCausalLM.forward  s   L %9$D $++JjJj 	 $** 
)%+')
 
  118B>SV8W~ot4]kmA}a,?@A$++444%4%%  ;;11 	D /%%  ((	H !11HKK4LLL(#33!//))!//
 	
r3   )	NNNNNNNNr   )r)   r*   r+   _tied_weights_keys_tp_plan_pp_planr!   r>   r   r   r-   r.   rS   r   r  r  r0   rj   r   rR   rT   rU   s   @r4   rv  rv    s9   *,GH23H_-z:;H5   .2.204(,26*.,026-.S
##d*S
 t+S
 &&-	S

 S
 ((4/S
   4'S
 #TkS
 ((4/S
 ell*S
 
*	*S
  S
r3   rv  )rv  rK  r  )r    )r   )Nr:   N)Icollections.abcr   typingr   r   r-   r   torch.nnr   rx    r	   r  activationsr
   cache_utilsr   r   
generationr   integrationsr   r   r   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.genericr   r   r   utils.output_capturingr   configuration_granitemoesharedr!   r#   Moduler7   rX   ro   r   r   r   r   rS   r0   r   rm   r   r   r   r  r&  rK  rj   rt  rv  __all__r2   r3   r4   <module>r     s  * % &   $ & ! . ) f f / 9 Q K F & 7 Y Y 5 B)5 0")) 4 Y'Jbii J (J(*bii *Z.S .Sb,")) ,^( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*C)		 C) +C)L2#= 2j Uo U U.><bii ><B P
; P
 P
j #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d g
"A? g
 g
T fr3   