
     `imP                        d dl mZmZ d dl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 dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(  ej)        e*          Z+ G d de
          Z, G d de$          Z- G d de"          Z. G d de          Z/ G d de           Z0 G d de#          Z1 G d de(          Z2 G d d e!          Z3g d!Z4dS )"    )CallableOptionalN   )CacheDynamicCache)PretrainedConfiglayer_type_validation)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)BaseModelOutputWithPast)rope_config_validation)ALL_ATTENTION_FUNCTIONS)Unpack)TransformersKwargslogging)deprecate_kwarg   )CohereAttentionCohereDecoderLayerCohereForCausalLMCohereLayerNormCoherePreTrainedModelCohereRotaryEmbeddingapply_rotary_pos_embeager_attention_forward)Gemma2Modelc                        e Zd ZdZdZdgZddddddddZdgdgfd	d
gd	gfd	gd	gfdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Z xZ	S ) Cohere2Configa2  
    This is the configuration class to store the configuration of a [`CohereModel`]. It is used to instantiate an Cohere
    model according to the specified arguments, defining the model architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information. Instantiating a configuration
    with the defaults will yield a similar configuration to that of the [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01) model.


    Args:
        vocab_size (`int`, *optional*, defaults to 256000):
            Vocabulary size of the Cohere model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`CohereModel`]
        hidden_size (`int`, *optional*, defaults to 8192):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 22528):
            Dimension of the MLP representations.
        logit_scale (`float`, *optional*, defaults to 0.0625):
            The scaling factor for the output logits.
        num_hidden_layers (`int`, *optional*, defaults to 40):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 64):
            Number of attention heads for each attention layer in the Transformer decoder.
        num_key_value_heads (`int`, *optional*):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
            by meanpooling all the original heads within that group. For more details, check out [this
            paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
            `num_attention_heads`.
        hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 8192):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the layer normalization.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        pad_token_id (`int`, *optional*, defaults to 0):
            Padding token id.
        bos_token_id (`int`, *optional*, defaults to 5):
            Beginning of stream token id.
        eos_token_id (`int`, *optional*, defaults to 255001):
            End of stream token id.
        tie_word_embeddings (`bool`, *optional*, defaults to `True`):
            Whether to tie weight embeddings
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The base period of the RoPE embeddings.
        rope_scaling (`Dict`, *optional*):
            Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
            and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
            accordingly.
            Expected contents:
                `rope_type` (`str`):
                    The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
                    'llama3'], with 'default' being the original RoPE implementation.
                `factor` (`float`, *optional*):
                    Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
                    most scaling types, a `factor` of x will enable the model to handle sequences of length x *
                    original maximum pre-trained length.
                `original_max_position_embeddings` (`int`, *optional*):
                    Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
                    pretraining.
                `attention_factor` (`float`, *optional*):
                    Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
                    computation. If unspecified, it defaults to value recommended by the implementation, using the
                    `factor` field to infer the suggested value.
                `beta_fast` (`float`, *optional*):
                    Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
                    ramp function. If unspecified, it defaults to 32.
                `beta_slow` (`float`, *optional*):
                    Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
                    ramp function. If unspecified, it defaults to 1.
                `short_factor` (`list[float]`, *optional*):
                    Only used with 'longrope'. The scaling factor to be applied to short contexts (<
                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
                    size divided by the number of attention heads divided by 2
                `long_factor` (`list[float]`, *optional*):
                    Only used with 'longrope'. The scaling factor to be applied to long contexts (<
                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
                    size divided by the number of attention heads divided by 2
                `low_freq_factor` (`float`, *optional*):
                    Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
                `high_freq_factor` (`float`, *optional*):
                    Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
        attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
            Whether to use a bias in the query, key, value and output projection layers during self-attention.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        sliding_window (`int`, *optional*, defaults to 4096):
            Size of the sliding window attention context.
        layer_types (`list`, *optional*):
            Attention pattern for each layer.

    ```python
    >>> from transformers import Cohere2Model, Cohere2Config

    >>> # Initializing a Cohere Nextmodel configuration
    >>> configuration = Cohere2Config()

    >>> # Initializing a model from the Cohere2 configuration
    >>> model = Cohere2Model(configuration) # doctest: +SKIP

    >>> # Accessing the model configuration
    >>> configuration = model.config # doctest: +SKIP
    ```
    cohere2past_key_valuescolwiserowwise)zlayers.*.self_attn.q_projzlayers.*.self_attn.k_projzlayers.*.self_attn.v_projzlayers.*.self_attn.o_projzlayers.*.mlp.gate_projzlayers.*.mlp.up_projzlayers.*.mlp.down_proj	input_idsinputs_embedshidden_statesattention_mask)embed_tokenslayersnorm       X        ?(   @   Nsilu{Gz?h㈵>Tr            @F           c                 j    | _         |	 _        | _        | _        | _        | _        | _        ||}| _        | _        |
 _	        | _
        | _        | _        | _        | _        | _        | _        | _        ||z   _        t'                       t)                      j        d||||d| |                    dd           _         j        ;t1           dd           _         fdt3           j                  D              _        t5           j         j                   d S )N)pad_token_idbos_token_ideos_token_idtie_word_embeddingssliding_window_pattern   c                 L    g | ] }t          |d z   j        z            rdnd!S )   sliding_attentionfull_attention)bool_sliding_window_pattern).0iselfs     /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/transformers/models/cohere2/modular_cohere2.py
<listcomp>z*Cohere2Config.__init__.<locals>.<listcomp>   sI           (,QUd6R,R'S'Si##Yi          )
vocab_sizemax_position_embeddingshidden_sizelogit_scaleintermediate_sizenum_hidden_layersnum_attention_headsnum_key_value_heads
hidden_actinitializer_rangelayer_norm_eps	use_cache
rope_thetarope_scalingattention_biasattention_dropoutsliding_windowlayer_typeshead_dimr   super__init__getrE   getattrranger	   )rH   rM   rO   rQ   rP   rR   rS   rT   rU   rN   rV   rW   rX   r:   r;   r<   r=   rY   rZ   r[   r\   r]   r^   kwargs	__class__s   `                       rI   ra   zCohere2Config.__init__   s   4 %'>$&&!2!2#6  &"5#6 $!2,"$(,!2,&#':: 	t$$$ 	
%%% 3		
 	

 	
 	
 	
 (.zz2JA'N'N$#+249QST+U+UD(       t566     D 	d.0FGGGGGrK   )r+   r,   r-   r.   r/   r0   Nr1   r,   r2   r3   Tr   r4   r5   Tr6   NFr7   r8   N)
__name__
__module____qualname____doc__
model_typekeys_to_ignore_at_inferencebase_model_tp_planbase_model_pp_planra   __classcell__rf   s   @rI   r   r   /   s       n n` J#4"5%.%.%.%."+ )"+  &(9:#%568IJ!"_$56    $ /IH IH IH IH IH IH IH IH IH IHrK   r   c                       e Zd ZdS )Cohere2RotaryEmbeddingNrg   rh   ri   rL   rK   rI   rr   rr              DrK   rr   c                       e Zd ZdS )Cohere2LayerNormNrs   rL   rK   rI   rv   rv     rt   rK   rv   c                   H   e Zd ZdZddedee         fdZ eddd	          	 	 dd
e	j
        dee	j
        e	j
        f         dee	j
                 dee         dee	j                 dee         dee	j
        ee	j
                 eee	j
                          f         fd            ZdS )Cohere2Attentionz=Multi-headed attention from 'Attention Is All You Need' paperNconfig	layer_idxc                    t           j                            |            || _        || _        t          |d|j        |j        z            | _        |j        |j	        z  | _
        | j        dz  | _        |j        | _        d| _        |j        |         dk    r|j        n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                  | _        d S )Nr_   g      TrB   )bias)nnModulera   ry   rz   rc   rO   rS   r_   rT   num_key_value_groupsscalingr\   	is_causalr^   r]   Linearr[   q_projk_projv_projo_proj)rH   ry   rz   s      rI   ra   zCohere2Attention.__init__  se   
	4   "
F4F&Jd4dee$*$>&B\$\!}d*!'!97=7I)7TXk7k7kf33qui :T] JQWQf
 
 
 i :T] JQWQf
 
 
 i :T] JQWQf
 
 
 i&68JQWQf
 
 
rK   past_key_valuer!   4.58new_nameversionr&   position_embeddingsr'   cache_positionre   returnc                 ^   |j         d d         }g |d| j        R }|                     |                              |                              dd          }	|                     |                              |                              dd          }
|                     |                              |                              dd          }|\  }}| j        t          |	|
||          \  }	}
|&|||d}|	                    |
|| j
        |          \  }
}t          }| j        j        dk    rt          | j        j                 } || |	|
||f| j        sdn| j        | j        | j        d|\  }} |j        g |dR                                  }|                     |          }||fS )NrA   r   )sincosr   eagerr7   )dropoutr   r]   )shaper_   r   view	transposer   r   r]   r   updaterz   r   ry   _attn_implementationr   trainingr\   r   reshape
contiguousr   )rH   r&   r   r'   r!   r   re   input_shapehidden_shapequery_states
key_statesvalue_statesr   r   cache_kwargsattention_interfaceattn_outputattn_weightss                     rI   forwardzCohere2Attention.forward   s    $)#2#.88b8$-88{{=1166|DDNNqRSTT[[//44\BBLLQPQRR
{{=1166|DDNNqRSTT&S*';L*VY[^'_'_$L*&#&snUUL'6'='=j,X\Xfht'u'u$J(?;+w66"9$+:Z"[$7$7
%
  $}HCC$2HL.
%
 
%
 
%
 
%
!\ *k);;;;;;FFHHkk+..L((rK   N)NN)rg   rh   ri   rj   r   r   intra   r   torchTensortupler   
LongTensorr   r   r   rL   rK   rI   rx   rx     s       GG
 
} 
# 
 
 
 
0 _%0A6RRR ,059*) *)|*) #5<#=>*) !.	*)
 "%*) !!12*) -.*) 
u|Xel3XeEL>Q5RR	S*) *) *) SR*) *) *)rK   rx   c                   J    e Zd Zdedef fdZ eddd          	 	 	 	 dd
ej        de	ej        ej        f         de
ej                 de
e         de
e         de
ej                 dee         de	ej        e
e	ej        ej        f                  f         fd            Z xZS )Cohere2DecoderLayerry   rz   c                 p    t                                          ||           |j        |         | _        d S r   )r`   ra   r^   attention_type)rH   ry   rz   rf   s      rI   ra   zCohere2DecoderLayer.__init__O  s3    +++$0;rK   r   r!   r   r   NFr&   r   r'   rX   r   re   r   c           
          |}|                      |          } | j        d||||||d|\  }	}
|                     |          }||	z   |z   }|S )N)r&   r   r'   r!   rX   r   rL   )input_layernorm	self_attnmlp)rH   r&   r   r'   r!   rX   r   re   residualhidden_states_attention_hidden_states_mlps               rI   r   zCohere2DecoderLayer.forwardS  s     !,,];;%3T^ &
' 3)+)&
 &
 &
 &
" !HH]33 #::=NNrK   )NNFN)rg   rh   ri   r   r   ra   r   r   r   r   r   r   rD   r   r   r   FloatTensorr   ro   rp   s   @rI   r   r   N  s0       <} < < < < < < < _%0A6RRR
 26+/$)59 | #5<#=> !.	
 "% D> !!12 -. 
u (51BEDU1U+V"WW	X   SR    rK   r   c                       e Zd ZU eed<   dS )Cohere2PreTrainedModelry   N)rg   rh   ri   r   __annotations__rL   rK   rI   r   r   o  s         rK   r   c                        e Zd Zdef fdZ	 	 	 	 	 	 	 ddeej                 deej                 deej                 dee	         deej
                 d	ee         d
eej                 dee         defdZ xZS )Cohere2Modelry   c                     t                                          |           t          |j        |j                  | _        t          |          | _        d S )N)rO   epsry   )r`   ra   rv   rO   rW   r*   rr   
rotary_emb)rH   ry   rf   s     rI   ra   zCohere2Model.__init__t  sK       $&2D6K`aaa	0???rK   Nr$   r'   position_idsr!   r%   rX   r   re   r   c           
         |d u |d uz  rt          d          ||                     |          }|r|| j        st          | j                  }|B||                                nd}	t          j        |	|	|j        d         z   |j	                  }||
                    d          }t          |x}
t                    s'| j        |||||d}t          d
i |t          d
i |d}
|}|                     ||          }| j        D ]} ||f||
|j                 |||d|}|                     |          }t'          ||	          S )Nz:You must specify exactly one of input_ids or inputs_embedsr   r   rA   )device)ry   input_embedsr'   r   r!   r   )rC   rB   )r   r'   r!   rX   r   )last_hidden_stater!   rL   )
ValueErrorr(   r   r   ry   get_seq_lengthr   aranger   r   	unsqueeze
isinstancedictr
   r   r   r)   r   r*   r   )rH   r$   r'   r   r!   r%   rX   r   re   past_seen_tokenscausal_mask_mappingmask_kwargsr&   r   decoder_layers                  rI   r   zCohere2Model.forwardy  s    -t";< 	[YZZZ  --i88M 	?00*$+>>>O!CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L?-FF 	+ -"0"0#2 , K #5"C"C{"C"C%F%U%U%U%U# #
 &"oom\JJ![ 		 		M)M$72=3OP /#-   MM 		-00&++
 
 
 	
rK   )NNNNNNN)rg   rh   ri   r   ra   r   r   r   r   r   r   rD   r   r   r   r   ro   rp   s   @rI   r   r   s  s       @} @ @ @ @ @ @ 151537+/59$(59<
 <
E,-<
 !.<
 u/0	<

 "%<
   12<
 D><
 !!12<
 +,<
 
!<
 <
 <
 <
 <
 <
 <
 <
rK   r   c                       e Zd ZdS )Cohere2ForCausalLMNrs   rL   rK   rI   r   r     rt   rK   r   )r   r   r   r   )5typingr   r   r   torch.nnr}   cache_utilsr   r   configuration_utilsr   r	   masking_utilsr
   r   modeling_flash_attention_utilsr   modeling_outputsr   modeling_rope_utilsr   modeling_utilsr   processing_utilsr   utilsr   r   utils.deprecationr   cohere.modeling_coherer   r   r   r   r   r   r   r   gemma2.modeling_gemma2r   
get_loggerrg   loggerr   rr   rv   rx   r   r   r   r   __all__rL   rK   rI   <module>r      s    & % % % % % % %        . . . . . . . . J J J J J J J J R R R R R R R R B B B B B B 7 7 7 7 7 7 9 9 9 9 9 9 5 5 5 5 5 5 & & & & & & 0 0 0 0 0 0 0 0 0 0 0 0 0 0	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 1 0 0 0 0 0 
	H	%	%KH KH KH KH KH$ KH KH KH\	 	 	 	 	2 	 	 		 	 	 	 	 	 	 	F) F) F) F) F) F) F) F)R    ,   B    2   B
 B
 B
 B
 B
; B
 B
 B
J	 	 	 	 	* 	 	 	 \
[
[rK   