a
    hQ                     @   s~  d dl Z 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*e+Z,G dd deZ-G dd de%Z.G dd de#Z/G dd de Z0G dd de!Z1G dd de$Z2G dd de)Z3G dd  d e"Z4g d!Z5dS )"    N)CallableOptional   )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                       s   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d	Ze	d d! Z
e
jd"d! Z
  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
    ```
    Zcohere2past_key_valuesZcolwiseZ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                    s   | _ |	 _| _| _| _| _| _|d u r6|}| _| _|
 _	| _
| _| _| _| _| _| _| _||  _t  t jf ||||d| |dd _ jd u rt dd _ fddt jD  _t j d S )N)pad_token_idbos_token_ideos_token_idtie_word_embeddingssliding_window_pattern   c                    s&   g | ]}t |d   j rdndqS )   sliding_attentionfull_attention)bool_sliding_window_pattern).0iself g/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/cohere2/modular_cohere2.py
<listcomp>   s   z*Cohere2Config.__init__.<locals>.<listcomp>)
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__getr>   getattrranger   )rB   rF   rH   rJ   rI   rK   rL   rM   rN   rG   rO   rP   rQ   r4   r5   r6   r7   rR   rS   rT   rU   rV   rW   kwargs	__class__rA   rD   rZ      sJ    
	

zCohere2Config.__init__c                 C   s   t dt | jS )NzTThe `sliding_window_pattern` attribute is deprecated and will be removed in v4.55.0.)warningswarnFutureWarningr>   rA   rC   rC   rD   r8      s
    z$Cohere2Config.sliding_window_patternc                 C   s
   || _ d S N)r>   )rB   valuerC   rC   rD   r8     s    )r&   r'   r(   r)   r*   r+   Nr,   r'   r-   r.   Tr   r/   r0   Tr1   NFr2   r3   N)__name__
__module____qualname____doc__Z
model_typeZkeys_to_ignore_at_inferenceZbase_model_tp_planZbase_model_pp_planrZ   propertyr8   setter__classcell__rC   rC   r_   rD   r   0   sT   p


                      K
r   c                   @   s   e Zd ZdS )Cohere2RotaryEmbeddingNrf   rg   rh   rC   rC   rC   rD   rm   
  s   rm   c                   @   s   e Zd ZdS )Cohere2LayerNormNrn   rC   rC   rC   rD   ro     s   ro   c                   @   s   e Zd ZdZdeee dddZedddd	de	j
ee	j
e	j
f ee	j
 ee ee	j ee ee	j
ee	j
 eee	j
  f d
ddZdS )Cohere2Attentionz=Multi-headed attention from 'Attention Is All You Need' paperNconfig	layer_idxc                 C   s   t j|  || _|| _t|d|j|j | _|j|j	 | _
| jd | _|j| _d| _|j| dkrj|jnd | _t j|j|j| j |jd| _t j|j|j	| j |jd| _t j|j|j	| j |jd| _t j|j| j |j|jd| _d S )NrX   g      Tr;   )Zbias)nnModulerZ   rr   rs   r\   rH   rL   rX   rM   Znum_key_value_groupsscalingrU   Z	is_causalrW   rV   ZLinearrT   q_projk_projv_projo_projrB   rr   rs   rC   rC   rD   rZ     s*    zCohere2Attention.__init__past_key_valuer   4.58new_nameversion)r!   position_embeddingsr"   r   cache_positionr^   returnc                 K   s2  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}| jd urt|	|
||\}	}
|d ur|||d}|	|
|| j
|\}
}t}| jjdkrt| jj }|| |	|
||f| jsdn| j| j| jd|\}}|jg |dR   }| |}||fS )Nr:   r   )sincosr   eagerr2   )Zdropoutrv   rV   )shaperX   rw   viewZ	transposerx   ry   rV   r   updaters   r   rr   Z_attn_implementationr   trainingrU   rv   Zreshape
contiguousrz   )rB   r!   r   r"   r   r   r^   Zinput_shapeZhidden_shapeZquery_statesZ
key_statesZvalue_statesr   r   Zcache_kwargsZattention_interfaceZattn_outputZattn_weightsrC   rC   rD   forward-  s<    

	

zCohere2Attention.forward)N)NN)rf   rg   rh   ri   r   r   intrZ   r   torchTensortupler   
LongTensorr   r   r   rC   rC   rC   rD   rp     s     rp   c                       s   e Zd Zeed fddZedddddeje	ejejf e
ej e
e e
e e
ej ee e	eje
e	ejejf  f d
ddZ  ZS )Cohere2DecoderLayerrq   c                    s   t  || |j| | _d S rd   )rY   rZ   rW   attention_typer{   r_   rC   rD   rZ   \  s    zCohere2DecoderLayer.__init__r|   r   r}   r~   NF)r!   r   r"   r   rQ   r   r^   r   c              	   K   sJ   |}|  |}| jf ||||||d|\}	}
| |}||	 | }|S )N)r!   r   r"   r   rQ   r   )Zinput_layernormZ	self_attnZmlp)rB   r!   r   r"   r   rQ   r   r^   ZresidualZhidden_states_attention_Zhidden_states_mlprC   rC   rD   r   `  s    



zCohere2DecoderLayer.forward)NNFN)rf   rg   rh   r   r   rZ   r   r   r   r   r   r   r=   r   r   r   FloatTensorr   rl   rC   rC   r_   rD   r   [  s        r   c                   @   s   e Zd ZU eed< dS )Cohere2PreTrainedModelrr   N)rf   rg   rh   r   __annotations__rC   rC   rC   rD   r   |  s   
r   c                       sl   e Zd Zed fddZdeej eej eej ee	 eej
 ee eej ee ed	ddZ  ZS )	Cohere2Modelrr   c                    s.   t  | t|j|jd| _t|d| _d S )N)rH   epsr   )rY   rZ   ro   rH   rP   r%   rm   
rotary_emb)rB   rr   r_   rC   rD   rZ     s    zCohere2Model.__init__N)	r   r"   position_idsr   r    rQ   r   r^   r   c              	   K   s&  |d u |d uA rt d|d u r*| |}|rH|d u rH| jsHt| jd}|d u r|d ur`| nd}	tj|	|	|jd  |j	d}|d u r|
d}t| }
ts| j|||||d}tf i |tf i |d}
|}| ||}| jD ]&}||f||
|j |||d|}q| |}t||d	S )
Nz:You must specify exactly one of input_ids or inputs_embedsr   r   r:   )device)rr   Zinput_embedsr"   r   r   r   )r<   r;   )r   r"   r   rQ   r   )Zlast_hidden_stater   )
ValueErrorr#   r   r   rr   Zget_seq_lengthr   Zaranger   r   Z	unsqueeze
isinstancedictr	   r
   r   r$   r   r%   r   )rB   r   r"   r   r   r    rQ   r   r^   Zpast_seen_tokensZcausal_mask_mappingZmask_kwargsr!   r   Zdecoder_layerrC   rC   rD   r     sV    

	


zCohere2Model.forward)NNNNNNN)rf   rg   rh   r   rZ   r   r   r   r   r   r   r=   r   r   r   r   rl   rC   rC   r_   rD   r     s&          r   c                   @   s   e Zd ZdS )Cohere2ForCausalLMNrn   rC   rC   rC   rD   r     s   r   )r   r   r   r   )6ra   typingr   r   r   Ztorch.nnrt   Zcache_utilsr   r   Zconfiguration_utilsr   r   Zmasking_utilsr	   r
   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   Zmodeling_rope_utilsr   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   Zutils.deprecationr   Zcohere.modeling_coherer   r   r   r   r   r   r   r   Zgemma2.modeling_gemma2r   Z
get_loggerrf   loggerr   rm   ro   rp   r   r   r   r   __all__rC   rC   rC   rD   <module>   s4   (

 [I!E