
    ipR                     B   d Z ddlmZ ddl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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' ddl(m)Z)m*Z*  ejV                  e,      Z-dZ.dZ/ G d de      Z0 G d de%      Z1 G d de      Z2 G d dejf                        Z4 G d de*      Z5 G d de)      Z6 G d  d!e$      Z7 G d" d#e7e#      Z8 G d$ d%e      Z9 G d& d'e!      Z: G d( d)e"      Z; G d* d+e       Z<g d,Z=y)-zLG AI Research EXAONE Lab    )CallableN)nn)check_model_inputs   )CacheDynamicCache)PreTrainedConfiglayer_type_validation)create_causal_mask!create_sliding_window_causal_mask)BaseModelOutputWithPastCausalLMOutputWithPast)RopeParameters)ALL_ATTENTION_FUNCTIONS)Unpack)TransformersKwargslogging   )Gemma2RotaryEmbedding)	LlamaForCausalLMLlamaForQuestionAnsweringLlamaForSequenceClassificationLlamaForTokenClassification
LlamaModelLlamaPreTrainedModelLlamaRMSNormapply_rotary_pos_embeager_attention_forward)Olmo2DecoderLayerOlmo2MLPzLGAI-EXAONE/EXAONE-4.0-32BExaone4Configc            *       p    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"dedz  dedz  dedz  dedz  dedz  dedz  de	dz  dedz  de
dz  dedz  dedz  dedz  dedz  dedz  dedz  deee	ef   z  dz  de
dz  dedz  dedz  d ee	   dz  f( fd!Z xZS )#r!   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normN
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                 B   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        || _        || _        || _        | j                  d}| j$                  Dt'        | j                        D cg c]   }|dz   |z  dk7  r|| j                  k  rdnd" c}| _        t)        | j$                  | j                         || _        t-        | \  di | y c c}w )Nr      sliding_attentionfull_attention )r.   r/   r1   r2   r3   r0   r4   r5   r6   r7   r8   r>   r?   r@   r9   r:   r;   r<   rA   ranger
   r=   super__init__)selfr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   kwargsi	__class__s                          u/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/exaone4/modular_exaone4.pyrI   zExaone4Config.__init__   s@   0 %&!2#6 #6 !2$'>$!2("!2,&<#(((#6 &&%&"#
 t556	   U56!;DDZDZ@Z $%& D 	d..0F0FG."6" s   8%D)i     i @      rP   rP   silui   g{Gz?gh㈵>Tr   r   NFN        rO      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listrI   __classcell__rM   s   @rN   r!   r!   ;   s   Sj J#4"5 &/%.%.%."+ )"+ &(9:#%568IJ!"_$56 "("&(-(**,*,!'.2*.#'!%#$#$#'+0MQ*-%)-.(,+9#$J9# 4Z9# :	9#
 :9# !4Z9# !4Z9# $J9# "%t9# !4<9# Dj9# $;9# Dj9# Dj9# Dj9#  "D[!9#" ($sN/B*CCdJ#9#$ !4<%9#& d
'9#( !$d
)9#* #Y%+9# 9#    c                       e Zd Zy)Exaone4RMSNormNrT   rU   rV   rF   rd   rN   rf   rf          rd   rf   c                       e Zd Zy)Exaone4RotaryEmbeddingNrg   rF   rd   rN   rj   rj      rh   rd   rj   c                   4    e Zd Zdedef fdZ	 	 	 ddej                  deej                  ej                  f   dej                  dz  de	dz  d	ej                  dz  d
ee   deej                  ej                  dz  eej                     dz  f   fdZ xZS )Exaone4Attentionconfig	layer_idxc                    t         |           || _        || _        |j                  | _        |j
                  | _        |j                  | _        t        |d|j                  |j                  z        | _        |j                  |j
                  z  | _	        |j                  | _
        d| _        | j                  dz  | _        |j                  | _        |j                  | _        t        |d      r|j                   |   nd }|dk(  | _        t%        j&                  | j                  | j                  | j                  z  d      | _        t%        j&                  | j                  | j
                  | j                  z  d      | _        t%        j&                  | j                  | j
                  | j                  z  d      | _        t%        j&                  | j                  | j                  z  | j                  d      | _        t1        | j                  |j2                        | _        t1        | j                  |j2                        | _        y )	Nhead_dimTg      rA   rD   F)biaseps)rH   rI   rm   rn   r2   r3   r/   getattrrp   num_key_value_groupsr>   	is_causalscalingr?   r@   hasattrrA   
is_slidingr   Linearq_projk_projv_projo_projrf   r7   q_normk_norm)rJ   rm   rn   
layer_typerM   s       rN   rI   zExaone4Attention.__init__   s   "#)#=#= #)#=#= !--
F4F4F&JdJd4de$*$>$>&B\B\$\!!'!9!9}}d*$33&,&C&C#6=fm6TV''	2Z^
$(;;ii 0 0$2J2JT]]2Zafgii 0 0$2J2JT]]2Zafgii 0 0$2J2JT]]2Zafgii 8 84== H$JZJZafg$T]]8K8KL$T]]8K8KLrd   Nr)   position_embeddingsr*   r$   cache_positionrK   returnc                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }| j                  |	      }	| j                  |
      }
|\  }}| j                  | j                  rt        |	|
||      \  }	}
|%d|i}|j                  |
|| j                  |      \  }
}t        j                  | j                   j"                  t$              } || |	|
||f| j&                  sdn| j(                  | j*                  | j                  r| j                  nd d|\  }} |j,                  g |d j/                         }| j1                  |      }||fS )NrC   r   r   rR   )dropoutrw   r?   )shaperp   r{   view	transposer|   r}   r   r   r?   ry   r   updatern   r   get_interfacerm   _attn_implementationr   trainingr>   rw   reshape
contiguousr~   )rJ   r)   r   r*   r$   r   rK   input_shapehidden_shapequery_states
key_statesvalue_statescossincache_kwargsattention_interfaceattn_outputattn_weightss                     rN   forwardzExaone4Attention.forward  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 {{<0[[,
&S&$//';L*VY[^'_$L*& .L (7'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL26//4..t
%
 
%
!\ *k));;;;FFHkk+.L((rd   )NNN)rT   rU   rV   r!   r\   rI   torchTensortupler   
LongTensorr   r   r   rb   rc   s   @rN   rl   rl      s    M} M M: /3(,261)||1) #5<<#=>1) t+	1)
 1) ((4/1) +,1) 
u||U\\D0%2E2LL	M1)rd   rl   c                       e Zd Zy)
Exaone4MLPNrg   rF   rd   rN   r   r   5  rh   rd   r   c                       e Zd Zy)Exaone4DecoderLayerNrg   rF   rd   rN   r   r   9  rh   rd   r   c                       e Zd ZeZdgZy)Exaone4PreTrainedModelr   N)rT   rU   rV   r!   config_class_no_split_modulesrF   rd   rN   r   r   =  s     L./rd   r   c                       e Zd Zdef fdZ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ez  fd       Z xZS )Exaone4Modelrm   c           	      $   t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        | j                          y c c}w )Nrr   )rH   rI   r   
ModuleListrG   r1   r   r,   rf   r/   r7   r-   	post_init)rJ   rm   rn   rM   s      rN   rI   zExaone4Model.__init__C  so     mmEJ6KcKcEde	 3e
 #6#5#56;N;NO	 	 fs   BNr'   r*   position_idsr$   r(   r8   r   rK   r   c                    |d u |d uz  rt        d      || j                  |      }|r|t        | j                        }|F||j	                         nd}	t        j                  |	|	|j                  d   z   |j                        }||j                  d      }t        |x}
t              sF| j                  |||||d}dt        di |i}
d| j                  j                  v rt        di ||
d<   |}| j                  ||      }t!        | j"                        D ]1  \  }}| j                  j                  |   } ||f|
|   |||||d	|}3 | j%                  |      }t'        ||r|
      S d 
      S )Nz:You must specify exactly one of input_ids or inputs_embeds)rm   r   rC   )device)rm   input_embedsr*   r   r$   r   rE   rD   )r*   r   r$   r8   r   r   )last_hidden_stater$   rF   )
ValueErrorr+   r   rm   get_seq_lengthr   aranger   r   	unsqueeze
isinstancer`   r   rA   r   
rotary_emb	enumerater,   r-   r   )rJ   r'   r*   r   r$   r(   r8   r   rK   past_seen_tokenscausal_mask_mappingmask_kwargsr)   r   rL   decoder_layerr   s                    rN   r   zExaone4Model.forwardM  s    -t";<YZZ  --i8M0*$++>O!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L ?-F ++ -"0"0#2 ,K !"4"C{"C# #dkk&=&==;\;k_j;k#$78%"oom\J )$++ 6 	A}003J)	2:>) /#-$7	 	M	 		-0&+/8O
 	
>B
 	
rd   )NNNNNNN)rT   rU   rV   r!   rI   r   r   r   r   r   FloatTensorr_   r   r   r   r   r   rb   rc   s   @rN   r   r   B  s    }   .2.204(,26!%26D
##d*D
 t+D
 &&-	D

 D
 ((4/D
 $;D
 ((4/D
 +,D
 
(	(D
 D
rd   r   c                   (    e Zd Z	 	 	 	 	 	 	 	 	 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   def fdZ xZS )Exaone4ForCausalLMNr'   r*   r   r$   r(   labelsr8   r   logits_to_keeprK   r   c
                 8    t        |   d|||||||||	d	|
 y)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   r8   r   r   NrF   )rH   r   )rJ   r'   r*   r   r$   r(   r   r8   r   r   rK   rM   s              rN   r   zExaone4ForCausalLM.forward  s<    X 	 	
)%+'))	
 	
rd   )	NNNNNNNNr   )rT   rU   rV   r   r   r   r   r   r_   r\   r   r   r   r   rb   rc   s   @rN   r   r     s     .2.204(,26*.!%26-.7
##d*7
 t+7
 &&-	7

 7
 ((4/7
   4'7
 $;7
 ((4/7
 ell*7
 +,7
 
 7
 7
rd   r   c                       e Zd Zy) Exaone4ForSequenceClassificationNrg   rF   rd   rN   r   r     rh   rd   r   c                       e Zd Zy)Exaone4ForTokenClassificationNrg   rF   rd   rN   r   r     rh   rd   r   c                       e Zd Zy)Exaone4ForQuestionAnsweringNrg   rF   rd   rN   r   r     rh   rd   r   )r!   r   r   r   r   r   r   )>rW   collections.abcr   r   r   transformers.utils.genericr   cache_utilsr   r   configuration_utilsr	   r
   masking_utilsr   r   modeling_outputsr   r   modeling_rope_utilsr   modeling_utilsr   processing_utilsr   utilsr   r   gemma2.modeling_gemma2r   llama.modeling_llamar   r   r   r   r   r   r   r   r   olmo2.modeling_olmo2r   r    
get_loggerrT   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCr!   rf   rj   Modulerl   r   r   r   r   r   r   r   r   __all__rF   rd   rN   <module>r      s     $   9 . J R 2 5 & ;
 
 
 ? 
		H	%2 !a#$ a#H	\ 		2 	K)ryy K)\	 		+ 	01 0
P
): P
f8
) 8
v	'E 		$? 		"; 	rd   