
    qiOS                     N   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jZ                  e.      Z/dZ0dZ1 G d de	      Z2 G d de'      Z3 G d de      Z4 G d dejj                        Z6 G d de,      Z7 G d d e+      Z8 G d! d"e&      Z9 G d# d$e9e%      Z: G d% d&e!      Z; 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   )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            *       t    e Zd Z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#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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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 )r0   r1   r3   r4   r5   r2   r6   r7   r8   r9   r:   r@   rA   rB   r;   r<   r=   r>   rC   ranger	   r?   super__init__)selfr0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   kwargsi	__class__s                          ]/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/exaone4/modular_exaone4.pyrK   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 @      rR   rR   silui   g{Gz?gh㈵>Tr   r   NFN        rQ      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listrK   __classcell__rO   s   @rP   r"   r"   ;   s   Sj J#4"5 &/%.%.%E%E%."+ )"+
 &(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rV   rW   rX   rH   rf   rP   rh   rh          rf   rh   c                       e Zd Zy)Exaone4RotaryEmbeddingNri   rH   rf   rP   rl   rl      rj   rf   rl   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      rC   rF   F)biaseps)rJ   rK   ro   rp   r4   r5   r1   getattrrr   num_key_value_groupsr@   	is_causalscalingrA   rB   hasattrrC   
is_slidingr   Linearq_projk_projv_projo_projrh   r9   q_normk_norm)rL   ro   rp   
layer_typerO   s       rP   rK   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rf   Nr+   position_embeddingsr,   r%   cache_positionrM   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 )NrE   r   r   rT   )dropoutry   rA   )shaperr   r}   view	transposer~   r   r   r   rA   r{   r   updaterp   r   get_interfacero   _attn_implementationr   trainingr@   ry   reshape
contiguousr   )rL   r+   r   r,   r%   r   rM   input_shapehidden_shapequery_states
key_statesvalue_statescossincache_kwargsattention_interfaceattn_outputattn_weightss                     rP   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((rf   )NNN)rV   rW   rX   r"   r^   rK   torchTensortupler   
LongTensorr   r   r   rd   re   s   @rP   rn   rn      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)rf   rn   c                       e Zd Zy)
Exaone4MLPNri   rH   rf   rP   r   r   7  rj   rf   r   c                       e Zd Zy)Exaone4DecoderLayerNri   rH   rf   rP   r   r   ;  rj   rf   r   c                       e Zd ZeZdgZy)Exaone4PreTrainedModelr   N)rV   rW   rX   r"   config_class_no_split_modulesrH   rf   rP   r   r   ?  s     L./rf   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j                  dz  dee   deez  fd              Z xZS )Exaone4Modelro   c           	      $   t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        | j                          y c c}w )Nrt   )rJ   rK   r   
ModuleListrI   r3   r   r.   rh   r1   r9   r/   	post_init)rL   ro   rp   rO   s      rP   rK   zExaone4Model.__init__E  so     mmEJ6KcKcEde	 3e
 #6#5#56;N;NO	 	 fs   BNr)   r,   position_idsr%   r*   r:   r   rM   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)ro   r   rE   )device)ro   r*   r,   r   r%   r   rG   rF   )r,   r   r%   r:   r   r   )last_hidden_stater%   rH   )
ValueErrorr-   r   ro   get_seq_lengthr   aranger   r   	unsqueeze
isinstancerb   r
   rC   r   
rotary_emb	enumerater.   r/   r   )rL   r)   r,   r   r%   r*   r:   r   rM   past_seen_tokenscausal_mask_mappingmask_kwargsr+   r   rN   decoder_layerr   s                    rP   r   zExaone4Model.forwardO  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
 	
rf   )NNNNNNN)rV   rW   rX   r"   rK   r   r   r   r   r   r   FloatTensorra   r   r   r   r   r   rd   re   s   @rP   r   r   D  s    }    .2.204(,26!%26D
##d*D
 t+D
 &&-	D

 D
 ((4/D
 $;D
 ((4/D
 +,D
 
(	(D
   D
rf   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*   labelsr:   r   logits_to_keeprM   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   r:   r   r   NrH   )rJ   r   )rL   r)   r,   r   r%   r*   r   r:   r   r   rM   rO   s              rP   r   zExaone4ForCausalLM.forward  s<    X 	 	
)%+'))	
 	
rf   )	NNNNNNNNr   )rV   rW   rX   r   r   r   r   r   ra   r^   r   r   r   r   rd   re   s   @rP   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
rf   r   c                       e Zd Zy) Exaone4ForSequenceClassificationNri   rH   rf   rP   r   r     rj   rf   r   c                       e Zd Zy)Exaone4ForTokenClassificationNri   rH   rf   rP   r   r     rj   rf   r   c                       e Zd Zy)Exaone4ForQuestionAnsweringNri   rH   rf   rP   r   r     rj   rf   r   )r"   r   r   r   r   r   r   )@rY   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_loggerrV   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCr"   rh   rl   Modulern   r   r   r   r   r   r   r   r   __all__rH   rf   rP   <module>r      s     $   . J R 2 5 & 8 5 :
 
 
 ? 
		H	%2 !c#$ c#L	\ 		2 	K)ryy K)\	 		+ 	01 0
Q
): Q
h8
) 8
v	'E 		$? 		"; 	rf   