a
    hA                     @   sV  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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Z#G dd d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Z(G dd  d eZ)g d!Z*dS )"    )CallableOptionalN)nn   )Cache)ALL_ATTENTION_FUNCTIONS)Unpack)TransformersKwargslogging   )LlamaConfig)
LlamaAttentionLlamaDecoderLayerLlamaForCausalLMLlamaForTokenClassification
LlamaModelLlamaPreTrainedModelLlamaRMSNormLlamaRotaryEmbeddingapply_rotary_pos_embeager_attention_forward)NemotronMLPc                       sl   e Zd ZdZdZddddddddZdd	d
dddddddddddddddddddddf fdd	Z  ZS ) ApertusConfiga  
    This is the configuration class to store the configuration of a [`ApertusModel`]. It is used to instantiate a Apertus
    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to that of the Apertus-8B.
    e.g. [swiss-ai/Apertus-8B](https://huggingface.co/swiss-ai/Apertus-8B)

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.


    Args:
        vocab_size (`int`, *optional*, defaults to 131072):
            Vocabulary size of the Apertus model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`ApertusModel`]
        hidden_size (`int`, *optional*, defaults to 4096):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 14336):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 32):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 32):
            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 `"xielu"`):
            The non-linear activation function (function or string) in the decoder.
        max_position_embeddings (`int`, *optional*, defaults to 65536):
            The maximum sequence length that this model might ever be used with. Apertus supports up to 65536 tokens.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the rms normalization layers.
        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 3):
            Padding token id.
        bos_token_id (`int`, *optional*, defaults to 1):
            Beginning of stream token id.
        eos_token_id (`int`, *optional*, defaults to 2):
            End of stream token id.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether to tie weight embeddings
        rope_theta (`float`, *optional*, defaults to 12000000.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`, *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.

    ```python
    >>> from transformers import ApertusModel, ApertusConfig

    >>> # Initializing a Apertus-8B style configuration
    >>> configuration = ApertusConfig()

    >>> # Initializing a model from the Apertus-8B style configuration
    >>> model = ApertusModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```ZapertusZcolwise_repZrowwise_repZ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.up_projzlayers.*.mlp.down_projzlayers.*.mlp.gate_proji   i   i 8      NZxielui   g{Gz?gh㈵>Tr      r   Fg    `fAZllama3g       @i    g      ?g      @)Z	rope_typefactorZ original_max_position_embeddingsZlow_freq_factorZhigh_freq_factor        c                    sJ   t  jf |||||||||	|
|||||||||d| | `| `| `d S )N)
vocab_sizehidden_sizeintermediate_sizenum_hidden_layersnum_attention_headsnum_key_value_heads
hidden_actmax_position_embeddingsinitializer_rangerms_norm_eps	use_cachepad_token_idbos_token_ideos_token_idtie_word_embeddings
rope_thetarope_scalingattention_biasattention_dropout)super__init__Zpretraining_tpZmlp_biashead_dim)selfr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   kwargs	__class__ g/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/apertus/modular_apertus.pyr1      s4    zApertusConfig.__init__)__name__
__module____qualname____doc__Z
model_typeZbase_model_tp_planr1   __classcell__r7   r7   r5   r8   r   ,   sF   jr   c                       s   e Zd Z fddZ  ZS )
ApertusMLPc                    s:   t    tj| j| jdd| _tj| j| jdd| _d S )NF)Zbias)r0   r1   r   ZLinearr   r   Zup_projZ	down_proj)r3   configr5   r7   r8   r1      s    
zApertusMLP.__init__)r9   r:   r;   r1   r=   r7   r7   r5   r8   r>      s   r>   c                   @   s   e Zd ZdS )ApertusRMSNormNr9   r:   r;   r7   r7   r7   r8   r@      s   r@   c                   @   s   e Zd ZdS )ApertusRotaryEmbeddingNrA   r7   r7   r7   r8   rB      s   rB   c                
       st   e Zd Zdeee d fddZd	eje	ejejf eej ee
 eej ee e	ejejf dddZ  ZS )
ApertusAttentionNr?   	layer_idxc                    s2   t  || t| j|j| _t| j|j| _d S )N)r0   r1   r@   r2   r&   q_normk_normr3   r?   rE   r5   r7   r8   r1      s    zApertusAttention.__init__)hidden_statesposition_embeddingsattention_maskpast_key_valuescache_positionr4   returnc                 K   s8  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}| |	}	| |
}
|\}}t	|	|
||\}	}
|d ur|||d}|
|
|| j|\}
}t}| jjdkrt| jj }|| |	|
||f| jsdn| j| jd|\}}|jg |dR   }| |}||fS )Nr   r   )sincosrM   eagerr   )Zdropoutscaling)shaper2   Zq_projviewZ	transposeZk_projZv_projrF   rG   r   updaterE   r   r?   Z_attn_implementationr   Ztrainingr/   rS   Zreshape
contiguousZo_proj)r3   rI   rJ   rK   rL   rM   r4   Zinput_shapeZhidden_shapeZquery_statesZ
key_statesZvalue_statesrQ   rP   Zcache_kwargsZattention_interfaceZattn_outputZattn_weightsr7   r7   r8   forward   s<    	



zApertusAttention.forward)N)NN)r9   r:   r;   r   r   intr1   torchTensortupler   
LongTensorr   r	   rX   r=   r7   r7   r5   r8   rC      s   
  rC   c                       sz   e Zd Zeed fddZd	ejeej eej	 ee
 ee eej	 eeejejf  ee eej d	ddZ  ZS )
ApertusDecoderLayerrD   c                    s>   t  || t|j|jd| _t|j|jd| _| `| `d S )N)eps)	r0   r1   r@   r   r&   attention_layernormfeedforward_layernormZinput_layernormZpost_attention_layernormrH   r5   r7   r8   r1     s
    zApertusDecoderLayer.__init__NF)	rI   rK   position_idsrL   r'   rM   rJ   r4   rN   c              
   K   s^   |}	|  |}| jf |||||||d|\}}
|	| }|}	| |}| |}|	| }|S )N)rI   rK   rb   rL   r'   rM   rJ   )r`   Z	self_attnra   Zmlp)r3   rI   rK   rb   rL   r'   rM   rJ   r4   Zresidual_r7   r7   r8   rX   %  s&    




zApertusDecoderLayer.forward)NNNFNN)r9   r:   r;   r   rY   r1   rZ   r[   r   r]   r   boolr\   r   r	   rX   r=   r7   r7   r5   r8   r^     s$         r^   c                   @   s   e Zd ZdS )ApertusPreTrainedModelNrA   r7   r7   r7   r8   re   F  s   re   c                   @   s   e Zd ZdS )ApertusModelNrA   r7   r7   r7   r8   rf   J  s   rf   c                       s   e Zd Z fddZ  ZS )ApertusForCausalLMc                    s   t  jf i |S )an  
        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, ApertusForCausalLM

        >>> model = ApertusForCausalLM.from_pretrained("swiss-ai/Apertus-8B")
        >>> tokenizer = AutoTokenizer.from_pretrained("swiss-ai/Apertus-8B")

        >>> 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."
        ```)r0   rX   )r3   Zsuper_kwargsr5   r7   r8   rX   O  s    zApertusForCausalLM.forward)r9   r:   r;   rX   r=   r7   r7   r5   r8   rg   N  s   rg   c                   @   s   e Zd ZdS )ApertusForTokenClassificationNrA   r7   r7   r7   r8   rh   i  s   rh   )r   rf   rg   rh   re   )+typingr   r   rZ   r   Zcache_utilsr   Zmodeling_utilsr   Zprocessing_utilsr   utilsr	   r
   Zllama.configuration_llamar   Zllama.modeling_llamar   r   r   r   r   r   r   r   r   r   Znemotron.modeling_nemotronr   Z
get_loggerr9   loggerr   r>   r@   rB   rC   r^   re   rf   rg   rh   __all__r7   r7   r7   r8   <module>   s,   0
 /3*