
    i<                     |   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 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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j^                  e0      Z1dZ2dZ3 ed      e G d de                    Z4 G d de)      Z5 G d de!      Z6 G d dejn                        Z8 G d d e.      Z9 G d! d"e-      Z: G d# d$e(      Z; G d% d&e;e'      Z< G d' d(e#      Z= G d) d*e%      Z> G d+ d,e&      Z? G d- d.e$      Z@g d/ZAy)0zLG AI Research EXAONE Lab    )CallableN)strict)nn   )CacheDynamicCache)PreTrainedConfig)create_causal_mask!create_sliding_window_causal_mask)BaseModelOutputWithPastCausalLMOutputWithPast)RopeParameters)ALL_ATTENTION_FUNCTIONS)Unpack)TransformersKwargsauto_docstring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Exaone4Config)
checkpointc            
           e Zd ZU dZdZdgZdd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Ze	e
d<   dZe	e
d<   dZe	e
d<   dZe	e
d<   dZe	e
d<   dZe	e
d<   dZee
d<   dZe	e
d<   dZee
d<   dZee
d<   dZee
d <   d!Ze	d"z  e
d#<   d$Ze	ee	   z  d"z  e
d%<   d"Ze	d"z  e
d&<   d'Zee
d(<   d"Zeez  d"z  e
d)<   d*Z ee	z  e
d+<   dZ!e	d"z  e
d,<   d-Z"ee	z  d"z  e
d.<   d"Z#ee   d"z  e
d/<    fd0Z$ xZ%S )1r#   a~  
    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)

    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replicated_with_grad_allreducerowwise)	zlayers.*.self_attn.q_projzlayers.*.self_attn.k_projzlayers.*.self_attn.v_projzlayers.*.self_attn.q_normzlayers.*.self_attn.k_normz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normi  
vocab_sizei   hidden_sizei @  intermediate_size    num_hidden_layersnum_attention_headsnum_key_value_headssilu
hidden_acti   max_position_embeddingsg{Gz?initializer_rangegh㈵>rms_norm_epsT	use_cacher   Nbos_token_idr   eos_token_idpad_token_idFtie_word_embeddingsrope_parameters        attention_dropoutsliding_window   sliding_window_patternlayer_typesc                    | j                   d| _        | j                  Nt        | j                        D cg c]*  }|dz   | j                  z  dk7  r|| j                  k  rdnd, c}| _        t        |   di | y c c}w )Nr      sliding_attentionfull_attention )rF   rH   rI   ranger6   super__post_init__)selfkwargsi	__class__s      |/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/exaone4/modular_exaone4.pyrQ   zExaone4Config.__post_init__   s    &*+D'#
 t556	   Ut::;q@QI_I_E_ $%& D 	'' s   /A?)&__name__
__module____qualname____doc__
model_typekeys_to_ignore_at_inferencebase_model_tp_planbase_model_pp_planr2   int__annotations__r3   r4   r6   r7   r8   r:   strr;   r<   floatr=   r>   boolr?   r@   listrA   rB   rC   r   dictrE   rF   rH   rI   rQ   __classcell__rU   s   @rV   r#   r#   9   s   8 J#4"5 &/%.%.%E%E%."+ )"+
 &(9:#%568IJ!"_$56 JK"s"s!!!!J#'S'#u#L%It L#* +,L#S	/D(,#L#*# %%48O^d*T18%(us{(!%NC$J%/0C#I,0$(KcT!(( (    c                       e Zd Zy)Exaone4RMSNormNrW   rX   rY   rN   rh   rV   rj   rj          rh   rj   c                       e Zd Zy)Exaone4RotaryEmbeddingNrk   rN   rh   rV   rn   rn      rl   rh   rn   c                       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
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      rI   rL   F)biaseps)rP   __init__rq   rr   r7   r8   r3   getattrrt   num_key_value_groupsrE   	is_causalscalingrF   rH   hasattrrI   
is_slidingr   Linearq_projk_projv_projo_projrj   r=   q_normk_norm)rR   rq   rr   
layer_typerU   s       rV   rx   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rh   Nr-   position_embeddingsr.   r'   rS   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        ||	||      \  }}	| |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 )NrK   r   rD   )dropoutr|   rF   )shapert   r   view	transposer   r   r   r   rF   r~   r   updaterr   r   get_interfacerq   _attn_implementationr    trainingrE   r|   reshape
contiguousr   )rR   r-   r   r.   r'   rS   input_shapehidden_shapequery_states
key_statesvalue_statescossinattention_interfaceattn_outputattn_weightss                   rV   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*&'6'='=j,X\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL26//4..t
%
 
%
!\ *k));;;;FFHkk+.L((rh   )NN)rW   rX   rY   r#   r_   rx   torchTensortupler   r   r   r   rf   rg   s   @rV   rp   rp      s    M} M M: /3(,-)||-) #5<<#=>-) t+	-)
 -) +,-) 
u||U\\D0%2E2LL	M-)rh   rp   c                       e Zd Zy)
Exaone4MLPNrk   rN   rh   rV   r   r      rl   rh   r   c                       e Zd Zy)Exaone4DecoderLayerNrk   rN   rh   rV   r   r      rl   rh   r   c                       e Zd ZeZdgZy)Exaone4PreTrainedModelr   N)rW   rX   rY   r#   config_class_no_split_modulesrN   rh   rV   r   r      s     L./rh   r   c                        e Zd Zdef fdZe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e   deez  fd              Z xZS )Exaone4Modelrq   c           	      $   t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        | j                          y c c}w )Nrv   )rP   rx   r   
ModuleListrO   r6   r   r0   rj   r3   r=   r1   	post_init)rR   rq   rr   rU   s      rV   rx   zExaone4Model.__init__   so     mmEJ6KcKcEde	 3e
 #6#5#56;N;NO	 	 fs   BNr+   r.   position_idsr'   r,   r>   rS   r   c           
         |d u |d uz  rt        d      || j                  |      }|r|t        | j                        }|V||j	                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        |x}	t              sE| j                  ||||d}
dt        di |
i}	d| j                  j                  v rt        di |
|	d<   |}| j                  ||      }t!        | j"                        D ]0  \  }}| j                  j                  |   } ||f|	|   ||||d	|}2 | j%                  |      }t'        ||r|
      S d 
      S )Nz:You must specify exactly one of input_ids or inputs_embeds)rq   r   rK   )device)rq   r,   r.   r'   r   rM   rL   )r.   r   r'   r>   r   )last_hidden_stater'   rN   )
ValueErrorr/   r   rq   get_seq_lengthr   aranger   r   	unsqueeze
isinstancere   r
   rI   r   
rotary_emb	enumerater0   r1   r   )rR   r+   r.   r   r'   r,   r>   rS   past_seen_tokenscausal_mask_mappingmask_kwargsr-   r   rT   decoder_layerr   s                   rV   r   zExaone4Model.forward   s    -t";<YZZ  --i8M0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L ?-F ++!."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
 	
rh   )NNNNNN)rW   rX   rY   r#   rx   r   r   r   
LongTensorr   r   FloatTensorrc   r   r   r   r   r   rf   rg   s   @rV   r   r      s    }    .2.204(,26!%=
##d*=
 t+=
 &&-	=

 =
 ((4/=
 $;=
 +,=
 
(	(=
   =
rh   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	ej
                  z  d
e
e   def fdZ xZS )Exaone4ForCausalLMNr+   r.   r   r'   r,   labelsr>   logits_to_keeprS   r   c	                 6    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   r>   r   NrN   )rP   r   )rR   r+   r.   r   r'   r,   r   r>   r   rS   rU   s             rV   r   zExaone4ForCausalLM.forward<  s9    V 	 
	
)%+')
	
 
	
rh   )NNNNNNNr   )rW   rX   rY   r   r   r   r   r   rc   r_   r   r   r   r   rf   rg   s   @rV   r   r   ;  s     .2.204(,26*.!%-.5
##d*5
 t+5
 &&-	5

 5
 ((4/5
   4'5
 $;5
 ell*5
 +,5
 
 5
 5
rh   r   c                       e Zd Zy) Exaone4ForSequenceClassificationNrk   rN   rh   rV   r   r   t  rl   rh   r   c                       e Zd Zy)Exaone4ForTokenClassificationNrk   rN   rh   rV   r   r   x  rl   rh   r   c                       e Zd Zy)Exaone4ForQuestionAnsweringNrk   rN   rh   rV   r   r   |  rl   rh   r   )r#   r   r   r   r   r   r   )BrZ   collections.abcr   r   huggingface_hub.dataclassesr   r   cache_utilsr   r   configuration_utilsr	   masking_utilsr
   r   modeling_outputsr   r   modeling_rope_utilsr   modeling_utilsr   processing_utilsr   utilsr   r   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_loggerrW   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCr#   rj   rn   Modulerp   r   r   r   r   r   r   r   r   __all__rN   rh   rV   <module>r      s?     $  .  . 3 R 2 5 & @ @ 7 5 :
 
 
 ? 
		H	%2 ! 78Q($ Q(  9Q(h	\ 		2 	G)ryy G)T	 		+ 	01 0
J
): J
Z6
) 6
r	'E 		$? 		"; 	rh   