o
    Zh                     @   s~  d Z ddlZddlmZmZmZmZ ddlZddlm	  m
Z ddlZddlmZmZ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mZ ddlmZmZmZ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*m+Z+m,Z,m-Z- ddl.m/Z/ e, rddl0m1Z1 ddl2m3Z3 e-4e5Z6dd Z7G dd de	j8Z9e(:e9 G dd de	j;Z<dd Z=d=ddZ>G dd de	j;Z?d ejd!e@d"ejfd#d$ZAG d%d& d&e	j;ZBG d'd( d(eBZCG d)d* d*eBZDeBeCeDd+ZEG d,d- d-e	j;ZFe*G d.d/ d/e&ZGe*G d0d1 d1eGZHG d2d3 d3eGeZIe*d4d5G d6d7 d7eGZJe*G d8d9 d9eGZKe*G d:d; d;eGZLg d<ZMdS )>zPyTorch Nemotron model.    N)ListOptionalTupleUnion)SizeTensornn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)_flash_attention_forward!flash_attn_supports_top_left_mask)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)ALL_LAYERNORM_LAYERS)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )NemotronConfig)	BlockMask)make_flex_block_causal_maskc                  G   s"   t  s| S t jjj| t  S N)torchis_autocast_enabledcudaampZautocast_modeZ_castget_autocast_gpu_dtype)args r*   ]/var/www/auris/lib/python3.10/site-packages/transformers/models/nemotron/modeling_nemotron.py_cast_if_autocast_enabled6   s   r,   c                	       sZ   e Zd Z					ddeeee ef dededef fdd	Z	d
e
de
fddZ  ZS )NemotronLayerNorm1Ph㈵>TNnormalized_shapeepselementwise_affinebiasc                    s   t  |||||| d S r#   )super__init__)selfr/   r0   r1   r2   devicedtype	__class__r*   r+   r4   >   s   	zNemotronLayerNorm1P.__init__inputreturnc                 C   s^   t || j| jd | j| j}tjj|jj	dd t
j| W  d    S 1 s(w   Y  d S )Nr   F)enabled)r,   r/   weightr2   r0   r$   r'   autocastr6   typeFZ
layer_norm)r5   r:   r)   r*   r*   r+   forwardI   s   $zNemotronLayerNorm1P.forward)r.   TTNN)__name__
__module____qualname__r   intr   r   floatboolr4   r   rA   __classcell__r*   r*   r8   r+   r-   =   s     r-   c                       s:   e Zd Z	ddef fddZe edd Z  Z	S )NemotronRotaryEmbeddingNconfigc                    sb   t    d| _|j| _|j| _|| _t| j | _| | j|\}| _	| j
d|dd | j| _d S )Ndefaultinv_freqF)
persistent)r3   r4   Z	rope_typemax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenrJ   r   Zrope_init_fnattention_scalingZregister_bufferrL   Zoriginal_inv_freq)r5   rJ   r6   rL   r8   r*   r+   r4   U   s   
z NemotronRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r   ZmpscpuF)device_typer<      dim)r7   )rL   rF   expandshapetor6   
isinstancer?   strr$   r>   	transposecatcosrO   sinr7   )
r5   xposition_idsZinv_freq_expandedZposition_ids_expandedrR   ZfreqsZembr]   r^   r*   r*   r+   rA   g   s   0&zNemotronRotaryEmbedding.forwardr#   )
rB   rC   rD   r    r4   r$   Zno_gradr   rA   rH   r*   r*   r8   r+   rI   S   s    rI   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..NrP   rS   rT   )rW   r$   r\   )r_   x1Zx2r*   r*   r+   rotate_halfx   s   rb   c                 C   s   | |}| |}|jd }| dd|f | d|df } }|dd|f |d|df }}| | t| |  }	|| t||  }
tj|	|fddtj|
|fddfS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    rP   .NrT   )	unsqueezerW   rb   r$   r\   )qkr]   r^   r`   Zunsqueeze_dimZrot_dimZq_passZk_passZq_embedZk_embedr*   r*   r+   apply_rotary_pos_emb   s   


""$rf   c                       s$   e Zd Z fddZdd Z  ZS )NemotronMLPc                    s`   t    || _|j| _|j| _tj| j| j|jd| _tj| j| j|jd| _	t
|j | _d S )Nr2   )r3   r4   rJ   hidden_sizeZintermediate_sizer   LinearZmlp_biasup_proj	down_projr
   Z
hidden_actact_fnr5   rJ   r8   r*   r+   r4      s   
zNemotronMLP.__init__c                 C   s   |  | | |S r#   )rl   rm   rk   )r5   r_   r*   r*   r+   rA      s   zNemotronMLP.forward)rB   rC   rD   r4   rA   rH   r*   r*   r8   r+   rg      s    	rg   hidden_statesn_repr;   c                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rW   rV   reshape)ro   rp   batchnum_key_value_headsslenhead_dimr*   r*   r+   	repeat_kv   s
   0rv   c                       s   e Zd ZdZddedee f fddZ						ddej	d	e
ej	ej	f d
eej	 deej dee dededeej de
ej	eej	 ee
ej	  f fddZ  ZS )NemotronAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrJ   	layer_idxc                    s  t    || _|| _|d u rtd| jj d |j| _|j	| _	|j
| _|j| _|j| _| j| j | _|j| _|j| _|j| _d| _tj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j	| j| j |jd| _tj| j| j | j	|jd| _d S )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Trh   )r3   r4   rJ   rx   loggerwarning_oncer9   rB   attention_dropoutri   Znum_attention_heads	num_headsru   rs   num_key_value_groupsrN   Z
rope_thetaZpartial_rotary_factor	is_causalr   rj   Zattention_biasq_projk_projv_projo_projr5   rJ   rx   r8   r*   r+   r4      s*   
"zNemotronAttention.__init__Fro   position_embeddingsattention_maskr`   past_key_valueoutput_attentions	use_cachecache_positionr;   c	                 C   s  |  \}	}
}| |}| |}| |}||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}|d urH|\}}t	||||\}}|d urf|||d}|
||| j|\}}t|| j}t|| j}t||ddt| j }|d ur|d d d d d d d |jd f }|| }tjj|dtjd|j}tjj|| j| jd}t||}|dd }||	|
d}| |}|sd }|||fS )	Nr   rS   r^   r]   r   r	   rP   )rU   r7   )ptraining)sizer   r   r   viewr|   ru   r[   rs   rf   updaterx   rv   r}   r$   matmulmathsqrtrW   r   
functionalZsoftmaxfloat32rX   r7   dropoutr{   r   
contiguousrq   r   )r5   ro   r   r   r`   r   r   r   r   bszq_len_query_states
key_statesvalue_statesr]   r^   cache_kwargsattn_weightscausal_maskattn_outputr*   r*   r+   rA      s8   


 &

zNemotronAttention.forwardr#   NNNFFN)rB   rC   rD   __doc__r    r   rE   r4   r$   r   r   
LongTensorr   rG   rA   rH   r*   r*   r8   r+   rw      s8    	
rw   c                       s   e Zd ZdZ fddZ						ddejdeejejf deej	 d	eej	 d
ee
 dededeej	 deejeej eeej  f fddZ  ZS )NemotronFlashAttention2aL  
    Nemotron flash attention module. This module inherits from `NemotronAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|i | t | _d S r#   )r3   r4   r   _flash_attn_uses_top_left_mask)r5   r)   kwargsr8   r*   r+   r4     s   z NemotronFlashAttention2.__init__NFro   r   r   r`   r   r   r   r   r;   c	                 C   s  t |tr	tdd}| \}	}
}| |}| |}| |}||	|
| j| j	
dd}||	|
| j| j	
dd}||	|
| j| j	
dd}|d urS|\}}t||||\}}|d urq|||d}|||| j|\}}|
dd}|
dd}|
dd}| jr| jnd}|j}|tjkrt rt }nt| jdr| jj}n| jjj}td| d	 ||}||}||}t|||||
||t| d
d | j| j d
}|!|	|
d" }| #|}|sd }|||fS )Nz`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformersFr   rS   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)r`   r   r   Zuse_top_left_maskr~   rP   )$rY   r   
ValueErrorr   r   r   r   r   r|   ru   r[   rs   rf   r   rx   r   r{   r7   r$   r   r%   r(   hasattrrJ   r   r=   ry   rz   rX   r   getattrr   r~   rq   r   r   )r5   ro   r   r   r`   r   r   r   r   r   r   r   r   r   r   r]   r^   r   Zdropout_rateZinput_dtypeZtarget_dtyper   r   r*   r*   r+   rA   #  sl   













zNemotronFlashAttention2.forwardr   )rB   rC   rD   r   r4   r$   r   r   r   r   r   rG   rA   rH   r*   r*   r8   r+   r     s8    	
r   c                       s   e Zd ZdZ						ddejdeejejf deej deej dee	 d	e
d
e
deej deejeej eeej  f f fddZ  ZS )NemotronSdpaAttentionz
    Nemotron attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `NemotronAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFro   r   r   r`   r   r   r   r   r;   c	              
      s  |rt d t j||||||||dS | \}
}}| |}| |}| |}||
|| j	| j
dd}||
|| j| j
dd}||
|| j| j
dd}|d ur]|\}}t||||\}}|d ur{|||d}|||| j|\}}t|| j}t|| j}|}|d ur|d d d d d d d |jd f }|jjdkr|d ur| }| }| }|d u r|dkrdnd	}tjjj||||| jr| jnd
|d}|dd }||
|d}| |}|d |fS )Na  NemotronModel is using NemotronSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.ro   r   r`   r   r   r   r   r   r   rS   r   r   r&   TFr   )Z	attn_maskZ	dropout_pr~   rP   )ry   rz   r3   rA   r   r   r   r   r   r|   ru   r[   rs   rf   r   rx   rv   r}   rW   r6   r?   r   r$   r   r   Zscaled_dot_product_attentionr   r{   r   )r5   ro   r   r   r`   r   r   r   r   r   r   r   r   r   r   r   r]   r^   r   r   r~   r   r8   r*   r+   rA     sb   


&	

zNemotronSdpaAttention.forwardr   )rB   rC   rD   r   r$   r   r   r   r   r   rG   rA   rH   r*   r*   r8   r+   r     s6    	r   )eagerflash_attention_2sdpac                       s   e Zd Zdedef fddZ							ddejdeej d	eej	 d
ee
 dee dee deej	 deeejejf  deejeeejejf  f fddZ  ZS )NemotronDecoderLayerrJ   rx   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )N)rJ   rx   r0   )r3   r4   ri   NEMOTRON_ATTENTION_CLASSES_attn_implementation	self_attnrg   mlpr-   norm_epsinput_layernormpost_attention_layernormr   r8   r*   r+   r4     s   

zNemotronDecoderLayer.__init__NFro   r   r`   r   r   r   r   r   r;   c	                 K   s   |}
|  |}| jd||||||||d|	\}}}|
| }|}
| |}| |}|
| }|f}|r9||f7 }|r@||f7 }|S )a.  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r   Nr*   )r   r   r   r   )r5   ro   r   r`   r   r   r   r   r   r   ZresidualZself_attn_weightsZpresent_key_valueoutputsr*   r*   r+   rA     s2   "
	



zNemotronDecoderLayer.forward)NNNFFNN)rB   rC   rD   r    rE   r4   r$   r   r   r   r   rG   r   FloatTensorrA   rH   r*   r*   r8   r+   r     s8    	r   c                   @   s@   e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdd ZdS )NemotronPreTrainedModelmodelTr   past_key_valuesc                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rC|jjjd|d |jd urA|jj|j 	  d S d S t|trW|jjd |jj	  d S d S )Nr   )meanstdg      ?)rJ   Zinitializer_rangerY   r   rj   r=   dataZnormal_r2   Zzero_	Embeddingpadding_idxr-   Zfill_)r5   moduler   r*   r*   r+   _init_weightsH  s   


z%NemotronPreTrainedModel._init_weightsN)rB   rC   rD   r    Zconfig_classbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_quantized_cacheZ_supports_static_cacher   r*   r*   r*   r+   r   ;  s    r   c                       s  e Zd ZdZdef fddZdd Zdd Zee																			d!d
e
ej de
ej de
ej de
eeeej f  de
ej de
e de
e de
e de
ej defddZ	d"deejdf dejdejdedef
ddZedejdededejdejdefdd Z  ZS )#NemotronModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`NemotronDecoderLayer`]

    Args:
        config: NemotronConfig
    rJ   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r*   )r   ).0rx   rJ   r*   r+   
<listcomp>g  s    z*NemotronModel.__init__.<locals>.<listcomp>r   r   F)r3   r4   pad_token_idr   
vocab_sizer   r   ri   embed_tokensZ
ModuleListrangeZnum_hidden_layerslayersr-   r   normrI   
rotary_embgradient_checkpointing	post_initrn   r8   r   r+   r4   `  s   zNemotronModel.__init__c                 C      | j S r#   r   r5   r*   r*   r+   get_input_embeddingsp     z"NemotronModel.get_input_embeddingsc                 C   
   || _ d S r#   r   r5   valuer*   r*   r+   set_input_embeddingss     
z"NemotronModel.set_input_embeddingsN	input_idsr   r`   r   inputs_embedsr   r   output_hidden_statesr   r;   c
                 C   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u |d uA r*td| jr9| jr9|r9td d}|rB|d u rBt	 }|d u rK| 
|}|rT|d u rTt	 }|	d u rp|d ur`| nd}
tj|
|
|jd  |jd}	|d u ry|	d}| |||	||}|}| ||}|rdnd }|rdnd }d }| jD ]A}|r||f7 }| jr| jr| |j|||||||	|	}n||||||||	|d}|d }|r||rd	nd }|r||d f7 }q| |}|r||f7 }|r|nd }t||||d
S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   r   r6   r*   )r   r`   r   r   r   r   r   rS   )last_hidden_stater   ro   
attentions)rJ   r   r   r   r   r   r   ry   rz   r   r   get_seq_lengthr$   arangerW   r6   rc   _update_causal_maskr   r   Z_gradient_checkpointing_func__call__r   r   )r5   r   r   r`   r   r   r   r   r   r   past_seen_tokensr   ro   r   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheZdecoder_layerZlayer_outputsZ
next_cacher*   r*   r+   rA   v  s   






zNemotronModel.forwardFr!   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )Nr   r   Zflex_attentionr   Fr   )r   Zpast_key_values_lengthZis_trainingr   rP   )sequence_lengthtarget_lengthr7   r   
batch_size)r&   ZxpuZnpu)rJ   r   anyrY   r$   r   r"   r   Zis_compileabler   Z_ignore_causal_mask_sdpar   r7   rW   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr6   r?   finfominZ_unmask_unattended)r5   r   r   r   r   r   r   Zusing_compilable_cacher7   r   r   r   	min_dtyper*   r*   r+   r     sT   




z!NemotronModel._update_causal_maskr   r   r7   r   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuer7   r6   r   )Zdiagonalr   rP   r   )rU   r$   r   r   fullr6   Ztriur   rq   rV   clonerW   rX   Zmasked_fill)r   r   r   r7   r   r   r   r   r   Zmask_lengthZpadding_maskr*   r*   r+   r   +  s,    $
6  zCNemotronModel._prepare_4d_causal_attention_mask_with_cache_position	NNNNNNNNN)F)rB   rC   rD   r   r    r4   r   r   r   r   r   r$   r   r   r   r   r   r   rG   r   rA   r   staticmethodrE   r7   r   rH   r*   r*   r8   r+   r   W  s~    	
u
Dr   c                       s   e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
ee											d deej deej deej deeeeej f  deej deej dee dee dee deej deeejf defddZ  ZS )!NemotronForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S NFrh   )
r3   r4   r   r   r   r   rj   ri   lm_headr   rn   r8   r*   r+   r4   h  s
   
zNemotronForCausalLM.__init__c                 C      | j jS r#   r   r   r   r*   r*   r+   r   q     z(NemotronForCausalLM.get_input_embeddingsc                 C      || j _d S r#   r   r   r*   r*   r+   r   t     z(NemotronForCausalLM.set_input_embeddingsc                 C   r   r#   r   r   r*   r*   r+   get_output_embeddingsw  r   z)NemotronForCausalLM.get_output_embeddingsc                 C   r   r#   r  )r5   Znew_embeddingsr*   r*   r+   set_output_embeddingsz  r   z)NemotronForCausalLM.set_output_embeddingsc                 C   r   r#   r   )r5   decoderr*   r*   r+   set_decoder}  r   zNemotronForCausalLM.set_decoderc                 C   r   r#   r  r   r*   r*   r+   get_decoder  r   zNemotronForCausalLM.get_decoderNr   r   r   r`   r   r   labelsr   r   r   r   logits_to_keepr;   c                 K   s   |dur|n| j j}|	dur|	n| j j}	| j||||||||	|
d	}|j}t|tr0t| dn|}| |dd|ddf }d}|durR| j	||| j
fi |}t|||j|j|jdS )a  
        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, NemotronForCausalLM

        >>> model = NemotronForCausalLM.from_pretrained("nvidia/nemotron-3-8b-base-4k-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("nvidia/nemotron-3-8b-base-4k-hf")

        >>> 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."
        ```N)	r   r   r`   r   r   r   r   r   r   losslogitsr   ro   r   )rJ   r   r   r   r   rY   rE   slicer   loss_functionr   r   r   ro   r   )r5   r   r   r`   r   r   r	  r   r   r   r   r
  Zloss_kwargsr   ro   Zslice_indicesr  r  r*   r*   r+   rA     s6   'zNemotronForCausalLM.forward)NNNNNNNNNNr   )rB   rC   rD   Z_tied_weights_keysr4   r   r   r  r  r  r  r   r   r   r$   r   r   r   r   r   r   rG   rE   r   rA   rH   r*   r*   r8   r+   r   e  s^    		
r   a  
    The Nemotron Model transformer with a sequence classification head on top (linear layer).

    [`NemotronForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    )Zcustom_introc                          e Zd Z fddZdd Zdd Zee									ddee	j
 d	ee	j d
ee	j
 dee dee	j dee	j
 dee dee dee defddZ  ZS )!NemotronForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r   )
r3   r4   
num_labelsr   r   r   rj   ri   scorer   rn   r8   r*   r+   r4     s
   
z*NemotronForSequenceClassification.__init__c                 C   r   r#   r   r   r*   r*   r+   r     r   z6NemotronForSequenceClassification.get_input_embeddingsc                 C   r   r#   r   r   r*   r*   r+   r     r  z6NemotronForSequenceClassification.set_input_embeddingsNr   r   r`   r   r   r	  r   r   r   r;   c
              
   C   s(  | j ||||||||	d}
|
j}| |}|dur|jd }n|jd }| jjdu r2|dkr2td| jjdu r;d}n1|dur`|| jjk|jt	j
}t	j|jd |jt	j
d}|| d}nd}t| jj d |t	j||jd	|f }d}|dur| j|||| jd
}t|||
j|
j|
jdS )  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        r   r`   r   r   r   r   r   Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.rP   )r6   r7   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r   )r  r	  pooled_logitsrJ   r  )r   r   r  rW   rJ   r   r   rX   r6   r$   Zint32r   Zargmaxry   rz   r9   rB   r  r   r   ro   r   )r5   r   r   r`   r   r   r	  r   r   r   Ztransformer_outputsro   r  r   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesr  r  r*   r*   r+   rA     sL   


z)NemotronForSequenceClassification.forwardr   )rB   rC   rD   r4   r   r   r   r   r   r$   r   r   r   r   rG   r   rA   rH   r*   r*   r8   r+   r    sH    		
r  c                       s   e Zd ZdZ fddZdd Zdd Zee									dd	e	e
j d
e	e
j de	e
j de	e de	e
j de	e
j de	e
j de	e de	e defddZ  ZS )NemotronForQuestionAnsweringtransformerc                    s2   t  | t|| _t|jd| _|   d S )NrS   )	r3   r4   r   r  r   rj   ri   
qa_outputsr   rn   r8   r*   r+   r4   9  s   
z%NemotronForQuestionAnswering.__init__c                 C   r   r#   r  r   r   r*   r*   r+   r   A  r   z1NemotronForQuestionAnswering.get_input_embeddingsc                 C   r   r#   r  r   r*   r*   r+   r   D  r  z1NemotronForQuestionAnswering.set_input_embeddingsNr   r   r`   r   r   start_positionsend_positionsr   r   r;   c
              	   K   s   | j |||||||	d}|j}| |}|jddd\}}|d }|d }d }|d urA|d urA| j||||fi |
}t||||j|j	dS )N)r   r`   r   r   r   r   r   rP   rT   )r  start_logits
end_logitsro   r   )
r  r   r  splitZsqueezer   r  r   ro   r   )r5   r   r   r`   r   r   r  r  r   r   r   r   sequence_outputr  r  r  r  r*   r*   r+   rA   G  s0   

z$NemotronForQuestionAnswering.forwardr   )rB   rC   rD   r   r4   r   r   r   r   r   r$   r   r   r   r   rG   r   rA   rH   r*   r*   r8   r+   r  3  sJ    	
r  c                       r  )NemotronForTokenClassificationc                    s|   t  | |j| _t|| _t|dd d ur|j}nt|dd d ur'|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropouthidden_dropoutg?)r3   r4   r  r   r   r   r"  r#  r   ZDropoutr   rj   ri   r  r   )r5   rJ   r"  r8   r*   r+   r4   w  s   
z'NemotronForTokenClassification.__init__c                 C   r   r#   r   r   r*   r*   r+   r     r   z3NemotronForTokenClassification.get_input_embeddingsc                 C   r   r#   r   r   r*   r*   r+   r     r  z3NemotronForTokenClassification.set_input_embeddingsNr   r   r`   r   r   r	  r   r   r   r;   c
              
   C   sd   | j ||||||||	d}
|
j}| |}| |}d}|dur(| ||| j}t|||
j|
jdS )r  r  N)r  r  ro   r   )	r   r   r   r  r  rJ   r   ro   r   )r5   r   r   r`   r   r   r	  r   r   r   r   r   r  r  r*   r*   r+   rA     s,   


z&NemotronForTokenClassification.forwardr   )rB   rC   rD   r4   r   r   r   r   r   r$   r   r   r   r   rG   r   rA   rH   r*   r*   r8   r+   r!  t  sH    	
r!  )r  r   r   r   r  r!  )Nr   )Nr   r   typingr   r   r   r   r$   Ztorch.nn.functionalr   r   r@   Ztorch.utils.checkpointr   r   Zactivationsr
   Zcache_utilsr   r   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   Zpytorch_utilsr   utilsr   r   r   r   Zconfiguration_nemotronr    Z!torch.nn.attention.flex_attentionr!   Zintegrations.flex_attentionr"   Z
get_loggerrB   ry   r,   Z	LayerNormr-   appendModulerI   rb   rf   rg   rE   rv   rw   r   r   r   r   r   r   r   r  r  r!  __all__r*   r*   r*   r+   <module>   sl   

%
!Xs\	Q  iV?F