o
    eiR                     @   s  d Z ddl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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 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) ddl*m+Z+m,Z, e-e.Z/dZ0dZ1G dd de	Z2G dd de'Z3G dd deZ4G dd dej5Z6G dd de,Z7G dd  d e+Z8G d!d" d"e&Z9G d#d$ d$e9e%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 ).zLG AI Research EXAONE Lab    )CallableN)nn   )CacheDynamicCache)PreTrainedConfiglayer_type_validation)create_causal_mask!create_sliding_window_causal_mask)BaseModelOutputWithPastCausalLMOutputWithPast)RopeParameters)ALL_ATTENTION_FUNCTIONS)Unpack)TransformersKwargslogging)merge_with_config_defaults)capture_outputs   )Gemma2RotaryEmbedding)	LlamaForCausalLMLlamaForQuestionAnsweringLlamaForSequenceClassificationLlamaForTokenClassification
LlamaModelLlamaPreTrainedModelLlamaRMSNormapply_rotary_pos_embeager_attention_forward)Olmo2DecoderLayerOlmo2MLPzLGAI-EXAONE/EXAONE-4.0-32BExaone4Configc                *       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																				d1dedB dedB dedB dedB dedB d edB d!e	dB d"edB d#e
dB d$edB d%edB d&edB d'edB d(edB d)edB d*eee	ef B dB d+e
dB d,edB d-edB d.ee	 dB f( fd/d0Z  ZS )2r!   a  
    This is the configuration class to store the configuration of a [`Exaone4Model`]. It is used to
    instantiate a EXAONE 4.0 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 EXAONE-4.0-32B [LGAI-EXAONE/EXAONE-4.0-32B](https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-32B)

    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 102400):
            Vocabulary size of the EXAONE 4.0 model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`Exaone4Model`].
        hidden_size (`int`, *optional*, defaults to 4096):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to `hidden_size * 4`):
            Dimensionality of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 32):
            Number of hidden layers in the Transformer encoder.
        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 checkout [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 2048):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 32768 for EXAONE 3.5).
        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 layer 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``.
        bos_token_id (`int`, *optional*, defaults to 0):
            Beginning of stream token id.
        eos_token_id (`int`, *optional*, defaults to 2):
            End of stream token id.
        pad_token_id (`int`, *optional*):
            The id of the padding token.
        tie_word_embeddings (`bool`, *optional*, defaults to `False`):
            Whether to tie weight embeddings
        rope_parameters (`RopeParameters`, *optional*):
            Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
            a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
            with longer `max_position_embeddings`.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        sliding_window (`int`, *optional*):
            The size of the sliding window for the sliding window attention.
        sliding_window_pattern (`str`, *optional*):
            The pattern to use for sliding window attention. Can be one of:
                - `None`: No sliding window attention is used
                - `int`: Every `sliding_window` layers, use global attention, else use local attention.
                - `str`: A sequence of "L" (local attention) and "G" (global attention) characters that defines the
                  attention pattern. The pattern starts from layer 0 and repeats every `sliding_window` layers. The
                  final layer always uses global attention regardless of the pattern.
            For instance, sliding_window_pattern="LLLG" same as sliding_window=4, which means:
                - Layer 0, 1, 2: local attention,
                - Layer 3: global attention,
                ...(repeated)
        layer_types (`list`, *optional*):
            Attention pattern for each layer. Prioritized over `sliding_window_pattern`.

    Example:

    ```python
    >>> from transformers import Exaone4Model, Exaone4Config

    >>> # Initializing a EXAONE configuration
    >>> configuration = Exaone4Config()

    >>> # Initializing a model from configuration
    >>> model = Exaone4Model(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```exaone4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      @      silu   {Gz?h㈵>Tr   r   NF           
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bos_token_ideos_token_idpad_token_idtie_word_embeddingsrope_parametersattention_dropoutsliding_windowsliding_window_patternlayer_typesc                    s   | _ | _| _| _| _| _| _| _|	 _|
 _	| _
| _| _ _| _| _| _| _| _ jd u r@d jd u rS fddt jD  _t j j | _t jdi | d S )Nr   c                    s.   g | ]}|d   dkr| j k rdndqS )   r   sliding_attentionfull_attention)r:   ).0iselfrI    i/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/exaone4/modular_exaone4.py
<listcomp>   s    z*Exaone4Config.__init__.<locals>.<listcomp>rR   )r7   r8   r:   r;   r<   r9   r=   r>   r?   r@   rA   rG   rH   rI   rB   rC   rD   rE   rJ   ranger   rF   super__init__)rQ   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   kwargs	__class__rP   rS   rW      s8   

zExaone4Config.__init__)r-   r.   r/   r0   r0   r0   r1   r2   r3   r4   Tr   r   NFNr5   r.   r6   N)__name__
__module____qualname____doc__
model_typekeys_to_ignore_at_inferencebase_model_tp_planbase_model_pp_planintstrfloatboolr   dictlistrW   __classcell__rR   rR   rY   rS   r!   ;   s    U


	

c                   @      e Zd ZdS )Exaone4RMSNormNr[   r\   r]   rR   rR   rR   rS   rk          rk   c                   @   rj   )Exaone4RotaryEmbeddingNrl   rR   rR   rR   rS   rn      rm   rn   c                       s   e Zd Zdedef fddZ			ddejdeejejf dejdB d	e	dB d
ej
dB dee deejejdB eej dB f fddZ  ZS )Exaone4Attentionconfig	layer_idxc                    s6  t    || _|| _|j| _|j| _|j| _t|d|j|j | _|j|j | _	|j
| _
d| _| jd | _|j| _|j| _t|drH|j| nd }|dk| _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j| j dd| _tj| j| j | jdd| _t| j|jd| _t| j|jd| _d S )	Nhead_dimTg      rJ   rL   F)biaseps)rV   rW   rp   rq   r;   r<   r8   getattrrr   num_key_value_groupsrG   	is_causalscalingrH   rI   hasattrrJ   
is_slidingr   Linearq_projk_projv_projo_projrk   r@   q_normk_norm)rQ   rp   rq   
layer_typerY   rR   rS   rW      s*   

zExaone4Attention.__init__Nr(   position_embeddingsr)   r#   cache_positionrX   returnc                 K   sF  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}| |	}	| |
}
|\}}| j	d u sK| j
rTt|	|
||\}	}
|d urgd|i}||
|| j|\}
}t| jjt}|| |	|
||f| js{dn| j| j| j
r| j	nd d|\}}|jg |dR   }| |}||fS )NrK   r   r   r5   )dropoutry   rH   )shaperr   r}   view	transposer~   r   r   r   rH   r{   r   updaterq   r   get_interfacerp   _attn_implementationr   trainingrG   ry   reshape
contiguousr   )rQ   r(   r   r)   r#   r   rX   input_shapehidden_shapequery_states
key_statesvalue_statescossincache_kwargsattention_interfaceattn_outputattn_weightsrR   rR   rS   forward  sB   	

	

zExaone4Attention.forward)NNN)r[   r\   r]   r!   rc   rW   torchTensortupler   
LongTensorr   r   r   ri   rR   rR   rY   rS   ro      s(    ro   c                   @   rj   )
Exaone4MLPNrl   rR   rR   rR   rS   r   5  rm   r   c                   @   rj   )Exaone4DecoderLayerNrl   rR   rR   rR   rS   r   9  rm   r   c                   @   s   e Zd ZeZdgZdS )Exaone4PreTrainedModelr   N)r[   r\   r]   r!   config_class_no_split_modulesrR   rR   rR   rS   r   =  s    
r   c                       s   e Zd Zdef fddZee							ddejdB dej	dB dejdB de
dB d	ejdB d
edB dejdB dee deeB fddZ  ZS )Exaone4Modelrp   c                    sJ   t    t fddt jD | _t j j	d| _
|   d S )Nc                    s   g | ]}t  |qS rR   )r   )rN   rq   rp   rR   rS   rT   F  s    z)Exaone4Model.__init__.<locals>.<listcomp>rt   )rV   rW   r   
ModuleListrU   r:   r+   rk   r8   r@   r,   	post_init)rQ   rp   rY   r   rS   rW   C  s   zExaone4Model.__init__Nr&   r)   position_idsr#   r'   rA   r   rX   r   c              
   K   sR  |d u |d uA rt d|d u r| |}|r!|d u r!t| jd}|d u r=|d ur-| nd}	tj|	|	|jd  |jd}|d u rF|	d}t
| }
tso| j|||||d}dtdi |i}
d| jjv rotdi ||
d< |}| ||}t| jD ]\}}| jj| }||f|
| |||||d	|}q|| |}t||r|d
S d d
S )Nz:You must specify exactly one of input_ids or inputs_embedsr   r   rK   )device)rp   r'   r)   r   r#   r   rM   rL   )r)   r   r#   rA   r   r   )last_hidden_stater#   rR   )
ValueErrorr*   r   rp   get_seq_lengthr   aranger   r   	unsqueeze
isinstancerg   r	   rJ   r
   
rotary_emb	enumerater+   r,   r   )rQ   r&   r)   r   r#   r'   rA   r   rX   past_seen_tokenscausal_mask_mappingmask_kwargsr(   r   rO   decoder_layerr   rR   rR   rS   r   M  s`   



zExaone4Model.forward)NNNNNNN)r[   r\   r]   r!   rW   r   r   r   r   r   r   FloatTensorrf   r   r   r   r   r   ri   rR   rR   rY   rS   r   B  s<    
	
r   c                       s   e Zd Z									ddejdB dejdB dejdB dedB dejdB dejdB d	edB d
ejdB de	ejB de
e def fddZ  ZS )Exaone4ForCausalLMNr   r&   r)   r   r#   r'   labelsrA   r   logits_to_keeprX   r   c
                    s*   t  jd|||||||||	d	|
 dS )u  
        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 AutoModelForCausalLM, AutoTokenizer
        >>> model = AutoModelForCausalLM.from_pretrained("LGAI-EXAONE/EXAONE-4.0-32B")
        >>> tokenizer = AutoTokenizer.from_pretrained("LGAI-EXAONE/EXAONE-4.0-32B")

        >>> prompt = "Explain how wonderful you are"
        >>> messages = [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": prompt}
        ]
        >>> input_ids = tokenizer.apply_chat_template(
            messages,
            tokenize=True,
            add_generation_prompt=True,
            return_tensors="pt",
            enable_thinking=False,
        )

        >>> output = model.generate(input_ids, max_new_tokens=128)
        >>> tokenizer.decode(output[0], skip_special_tokens=False)
        "[|system|]\nYou are a helpful assistant.[|endofturn|]\n[|user|]\nExplain how wonderful you are[|endofturn|]\n[|assistant|]\n<think>\n\n</think>\n\nOh, thank you for such a kind and lovely question! 😊  \n\nI’m *so* wonderful because I’m here to make your life easier, brighter, and more fun! Whether you need help with:  \n\n✨ **Learning** – I can explain anything, from quantum physics to baking the perfect cake!  \n💡 **Creativity** – Need a poem, story, or a wild idea? I’ve got you covered!  \n🤖 **Problem-solving** – Stuck on a math problem or a tricky decision? I’ll help you figure it out"
        ```
        )	r&   r)   r   r#   r'   r   rA   r   r   NrR   )rV   r   )rQ   r&   r)   r   r#   r'   r   rA   r   r   rX   rY   rR   rS   r     s   ,

zExaone4ForCausalLM.forward)	NNNNNNNNr   )r[   r\   r]   r   r   r   r   r   rf   rc   r   r   r   r   ri   rR   rR   rY   rS   r     sB    	
r   c                   @   rj   ) Exaone4ForSequenceClassificationNrl   rR   rR   rR   rS   r     rm   r   c                   @   rj   )Exaone4ForTokenClassificationNrl   rR   rR   rR   rS   r     rm   r   c                   @   rj   )Exaone4ForQuestionAnsweringNrl   rR   rR   rR   rS   r     rm   r   )r!   r   r   r   r   r   r   )@r^   collections.abcr   r   r   cache_utilsr   r   configuration_utilsr   r   masking_utilsr	   r
   modeling_outputsr   r   modeling_rope_utilsr   modeling_utilsr   processing_utilsr   utilsr   r   utils.genericr   utils.output_capturingr   gemma2.modeling_gemma2r   llama.modeling_llamar   r   r   r   r   r   r   r   r   olmo2.modeling_olmo2r   r    
get_loggerr[   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCr!   rk   rn   Modulero   r   r   r   r   r   r   r   r   __all__rR   rR   rR   rS   <module>   sD   ,
 %NT;