
    qi                     ,   d Z ddlZddlmZ ddlmZ ddlZddlmc 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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! ddl"m#Z#m$Z$ ddl%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l0m1Z1  e-jd                  e3      Z4d Z5 G d dejl                        Z7 G d dejp                        Z9d Z:d8dZ; G d dejp                        Z<dej                  de=d ej                  fd!Z> G d" d#ejp                        Z? G d$ d%e?      Z@ G d& d'e?      ZAe?e@eAd(ZB G d) d*e!      ZCe+ G d+ d,e)             ZDe+ G d- d.eD             ZE G d/ d0eDe      ZF G d1 d2eeD      ZG G d3 d4eeD      ZH G d5 d6e eD      ZIg d7ZJy)9zPyTorch Nemotron model.    N)Callable)Optional)SizeTensornn   )initialization)ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)create_causal_mask)_flash_attention_forward!flash_attn_supports_top_left_mask)GenericForQuestionAnswering GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringcan_return_tuplelogging)maybe_autocast   )NemotronConfigc                     t        j                         s|S t        j                  |       }t         j                  j                  j                  || |      S N)torchis_autocast_enabledget_autocast_dtypeampautocast_mode_cast)device_typeargstarget_dtypes      `/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/nemotron/modeling_nemotron.py_cast_if_autocast_enabledr-   6   sB    $$&//<yy&&,,T;MM    c            	       ^     e Zd Z	 	 	 	 	 d	deee   z  ez  dededef fdZde	de	fdZ
 xZS )
NemotronLayerNorm1Pnormalized_shapeepselementwise_affinebiasc                 .    t         |   ||||||       y r"   )super__init__)selfr1   r2   r3   r4   devicedtype	__class__s          r,   r7   zNemotronLayerNorm1P.__init__?   s     	)30BD&RWXr.   inputreturnc                 l   |j                   j                  dk7  r|j                   j                  nd}t        ||| j                  | j                  dz   | j
                  | j                        }t        |j                   j                  d      5  t        j                  | cd d d        S # 1 sw Y   y xY w)Nmpscpur   Fr)   enabled)
r9   typer-   r1   weightr4   r2   r   F
layer_norm)r8   r<   r)   r*   s       r,   forwardzNemotronLayerNorm1P.forwardJ   s    +0<<+<+<+Eell''5( 5 5t{{Q		SWS[S[
 (9(95I 	'<<&	' 	' 	's   B**B3)gh㈵>TTNN)__name__
__module____qualname__intlistr   floatboolr7   r   rG   __classcell__r;   s   @r,   r0   r0   >   sd     #'	YS	/D0	Y 	Y !		Y
 	Y'V ' 'r.   r0   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )NemotronRotaryEmbeddinginv_freqNconfigc                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultrS   F)
persistentoriginal_inv_freq)r6   r7   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrT   rope_parametersrV   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r8   rT   r9   rope_init_fnrS   r;   s        r,   r7   z NemotronRotaryEmbedding.__init__W   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr.   r9   ztorch.deviceseq_lenr=   ztorch.Tensorc                 n   | j                   d   }| j                   j                  dd      }t        | dd      xs | j                  | j                  z  }t        ||z        }d}d|t        j                  d|dt        j                        j                  |t        j                  	      |z  z  z  }||fS )
a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetapartial_rotary_factorg      ?head_dimNr      r:   )r9   r:   )r]   getgetattrhidden_sizenum_attention_headsrK   r#   arangeint64torM   )	rT   r9   rc   baserf   rg   dimattention_factorrS   s	            r,   r^   z7NemotronRotaryEmbedding.compute_default_rope_parametersg   s    ( %%l3 & 6 6 : :;RTW X6:t4h8J8JfNhNh8h(223 U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r.   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r   r?   r@   FrA   rh   rr   ri   )rS   rM   expandshaperp   r9   
isinstancerC   strr   	transposer#   catcosr_   sinr:   )
r8   xposition_idsinv_freq_expandedposition_ids_expandedr)   freqsembr}   r~   s
             r,   rG   zNemotronRotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$r"   )NNN)rH   rI   rJ   r#   r   __annotations__r    r7   staticmethodr   rK   tuplerM   r^   no_gradr   rG   rO   rP   s   @r,   rR   rR   T   s    llV~ V   )-+/"*%*(* t* 
~u$	%	* *> U]]_<  <r.   rR   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nru   rh   rv   )rx   r#   r|   )r   x1x2s      r,   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r.   c                 `   |j                  |      }|j                  |      }|j                  d   }| dd|f   | d|df   }} |dd|f   |d|df   }}| |z  t        |       |z  z   }||z  t        |      |z  z   }	t        j                  ||fd      t        j                  |	|f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.
        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.
    ru   .Nrv   )	unsqueezerx   r   r#   r|   )
qkr}   r~   unsqueeze_dimrot_dimq_passk_passq_embedk_embeds
             r,   apply_rotary_pos_embr      s    $ --
&C
--
&CiimG#xx- !CM"2vA#xx- !CM"2vA3w;q>C/0G3w;q>C/0G99gv&B/GV;LRT1UUUr.   c                   $     e Zd Z fdZd Z xZS )NemotronMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        |j                     | _        y )Nr4   )r6   r7   rT   rl   intermediate_sizer   Linearmlp_biasup_proj	down_projr
   
hidden_actact_fnr8   rT   r;   s     r,   r7   zNemotronMLP.__init__   s    !--!'!9!9yy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r.   c                 `    | j                  | j                  | j                  |                  S r"   )r   r   r   )r8   r   s     r,   rG   zNemotronMLP.forward   s"    ~~dkk$,,q/:;;r.   )rH   rI   rJ   r7   rG   rO   rP   s   @r,   r   r      s    0<r.   r   hidden_statesn_repr=   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      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)rx   rw   reshape)r   r   batchnum_key_value_headsslenrg   s         r,   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr.   c                   b    e Zd ZdZddededz  f fdZ	 	 	 	 	 	 ddej                  de	ej                  ej                  f   dej                  dz  d	ej                  dz  d
edz  dededej                  dz  de	ej                  ej                  dz  e	ej                     dz  f   fdZ xZS )NemotronAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrT   	layer_idxc                 <   t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        |j                  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        |j                   d   | _        d| _        t'        |      | _        t+        j,                  | j                  | j                  | j                  z  |j.                        | _        t+        j,                  | j                  | j                  | j                  z  |j.                        | _        t+        j,                  | j                  | j                  | j                  z  |j.                        | _        t+        j,                  | j                  | j                  z  | j                  |j.                        | _        y )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.rf   TrT   r   )r6   r7   rT   r   loggerwarning_oncer;   rH   attention_dropoutrl   rm   	num_headsrg   r   num_key_value_groupsrZ   r]   rf   	is_causalrR   
rotary_embr   r   attention_biasq_projk_projv_projo_projr8   rT   r   r;   s      r,   r7   zNemotronAttention.__init__   s   " !8!8 9 :, , "(!9!9!--33#)#=#= $(NNd6N6N$N!'-'E'E$%+%;%;<S%T"1@ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii >@P@PW]WlWlmr.   r   position_embeddingsattention_maskr   past_key_valuesoutput_attentions	use_cachecache_positionr=   c	                    |j                         \  }	}
}| j                  |      }| j                  |      }| j                  |      }|j	                  |	|
| j
                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t        || j                        }t        || j                        }t        j                  ||j                  dd            t!        j"                  | j                        z  }|||z   }t$        j&                  j)                  |dt        j*                        j-                  |j.                        }t$        j&                  j1                  || j2                  | j4                        }t        j                  ||      }|j                  dd      j7                         }|j9                  |	|
d      }| j;                  |      }|sd }||fS )Nr   rh   r~   r}   r   r   ru   )rr   r:   )ptraining)sizer   r   r   viewr   rg   r{   r   r   updater   r   r   r#   matmulmathsqrtr   
functionalsoftmaxfloat32rp   r:   dropoutr   r   
contiguousr   r   )r8   r   r   r   r   r   r   r   r   bszq_len_query_states
key_statesvalue_statesr}   r~   cache_kwargsattn_weightsattn_outputs                       r,   rG   zNemotronAttention.forward   sD    &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$Jz4+D+DE
 t/H/HI||L*2F2Fq!2LMPTPYPYZ^ZgZgPhh%'.8L }},,\r,WZZ[g[m[mn}},,\T=S=S^b^k^k,lll<>!++Aq1<<>!))#ub9kk+. LL((r.   r"   NNNFFN)rH   rI   rJ   __doc__r    rK   r7   r#   r   r   
LongTensorr   rN   rG   rO   rP   s   @r,   r   r      s    Gn~ n#* n@ /304(,"'263)||3) #5<<#=>3) t+	3)
 &&-3) 3)  3) 3) ((4/3) 
u||U\\D0%2E2LL	M3)r.   r   c                   P    e Zd ZdZ fdZ	 	 	 	 	 	 ddej                  deej                  ej                  f   dej                  dz  dej                  dz  de	dz  d	e
d
e
dej                  dz  deej                  ej                  dz  eej                     dz  f   fdZ x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                 B    t        |   |i | t               | _        y r"   )r6   r7   r   _flash_attn_uses_top_left_mask)r8   r*   kwargsr;   s      r,   r7   z NemotronFlashAttention2.__init__8  s#    $)&)
 /P.Q+r.   Nr   r   r   r   r   r   r   r   r=   c	                 :   t        |t              rt        d      d}|j                         \  }	}
}| j	                  |      }| j                  |      }| j                  |      }|j                  |	|
| j                  | j                        j                  dd      }|j                  |	|
| j                  | j                        j                  dd      }|j                  |	|
| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}|j                  dd      }|j                  dd      }|j                  dd      }| j                  r| j                   nd}|j"                  }|j$                  j&                  dk7  r|j$                  j&                  nd}|t(        j*                  k(  rt)        j,                         rt)        j.                  |      }nMt1        | j2                  d	      r| j2                  j"                  }n | j                  j4                  j"                  }t6        j9                  d
| d       |j;                  |      }|j;                  |      }|j;                  |      }t=        |||||
||t?        | dd       | j@                  | jB                  
      }|jE                  |	|
d      jG                         }| jI                  |      }|sd }|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   rh   r           r?   r@   _is_quantizedzThe 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   use_top_left_maskr   ru   )%ry   r   
ValueErrorr   r   r   r   r   r   rg   r{   r   r   r   r   r   r   r:   r9   rC   r#   r   r$   r%   hasattrrT   rD   r   r   rp   r   rk   r   r   r   r   r   )r8   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r}   r~   r   dropout_rateinput_dtyper)   r+   r   r   s                           r,   rG   zNemotronFlashAttention2.forward@  s    o{3} 
 "%**,UA{{=1[[/
{{=1
 $((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J $--a3))!Q/
#--a315t--C #((2>2E2E2J2Je2Sl))..Y^%--'((*$77Do6#{{00#{{1177 >$ (??<8L#|4J'??<8L.% "4)94@"AAnn
 "))#ub9DDFkk+. LL((r.   r   )rH   rI   rJ   r   r7   r#   r   r   r   r   rN   rG   rO   rP   s   @r,   r   r   1  s    R 3704(,"'26^)||^) #5<<#=>^) ((4/	^)
 &&-^) ^)  ^) ^) ((4/^) 
u||U\\D0%2E2LL	M^)r.   r   c                   >   e Zd ZdZ	 	 	 	 	 	 ddej
                  deej
                  ej
                  f   dej
                  dz  dej                  dz  dedz  de	d	e	d
ej                  dz  deej
                  ej
                  dz  eej
                     dz  f   fdZ
y)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.
    Nr   r   r   r   r   r   r   r   r=   c	                    |r,t         j                  | j                  j                   d       |j	                         \  }
}}| j                  |      }| j                  |      }| j                  |      }|j                  |
|| j                  | j                        j                  dd      }|j                  |
|| j                  | j                        j                  dd      }|j                  |
|| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t!        || j"                        }t!        || j"                        }|}||d d d d d d d |j$                  d   f   }|d u xr |dkD  }t&        j(                  j*                  j-                  ||||| j.                  r| j0                  nd|      }|j                  dd      j3                         }|j                  |
|d      }| j5                  |      }|d fS )	Nz does not support `output_attentions=True`. The returned attention weights will be `None`. If you want to get attention weights, please set `attn_implementation='eager'` when loading the model.r   rh   r   r   )	attn_mask	dropout_pr   ru   )r   r   r;   rH   r   r   r   r   r   r   rg   r{   r   r   r   r   r   r   rx   r#   r   r   scaled_dot_product_attentionr   r   r   r   )r8   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r}   r~   r   causal_maskr   r   s                         r,   rG   zNemotronSdpaAttention.forward  sA    >>**+ ,D D &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$Jz4+D+DE
 t/H/HI$%%aA/E1A1A"1E/E&EFK  4'5EAI	hh))FF!04d,,3 G 
 "++Aq1<<>!&&sE26kk+.D  r.   r   )rH   rI   rJ   r   r#   r   r   r   r   rN   rG    r.   r,   r   r     s     /304(,"'26<!||<! #5<<#=><! t+	<!
 &&-<! <!  <! <! ((4/<! 
u||U\\D0%2E2LL	M<!r.   r   )eagerflash_attention_2sdpac                   f    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
e
dz  dej                  dz  deej                  ej                  f   dz  deej                  eej                  ej                  f   dz  f   fdZ xZS )NemotronDecoderLayerrT   r   c                 :   t         |           |j                  | _        t        |j                     ||      | _        t        |      | _        t        |j                  |j                        | _
        t        |j                  |j                        | _        y )N)rT   r   r2   )r6   r7   rl   NEMOTRON_ATTENTION_CLASSES_attn_implementation	self_attnr   mlpr0   norm_epsinput_layernormpost_attention_layernormr   s      r,   r7   zNemotronDecoderLayer.__init__  sx    !--3F4O4OPX^jstv&263E3E6??[(;F<N<NTZTcTc(d%r.   Nr   r   r   r   r   r   r   r   r=   c	                     |}
| j                  |      } | j                  d||||||||d|	\  }}|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|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_values (`Cache`, *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   r   r   r   r   r   r   r   r   )r  r  r  r  )r8   r   r   r   r   r   r   r   r   r   residualself_attn_weightsoutputss                r,   rG   zNemotronDecoderLayer.forward  s    D !,,]; ,:4>> 
,
')%+/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr.   )NNNFFNN)rH   rI   rJ   r    rK   r7   r#   r   r   r   rN   r   FloatTensorrG   rO   rP   s   @r,   r   r     s    e~ e# e /304(,).!&26HL?||? t+? &&-	?
 ?  $;? $;? ((4/? #5<<#=>E? 
u  %(9(95;L;L(L"MPT"TT	U?r.   r   c                   r     e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZ ej                          fd       Z xZS )NemotronPreTrainedModelrT   modelTr   r   c                     t         |   |       t        |t              r?t	        j
                  |j                         t	        j                  |j                         y y r"   )	r6   _init_weightsry   r0   initones_rD   zeros_r4   )r8   moduler;   s     r,   r  z%NemotronPreTrainedModel._init_weightsL  s@    f%f12JJv}}%KK$ 3r.   )rH   rI   rJ   r    r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraphr#   r   r  rO   rP   s   @r,   r  r  @  sR    &*#/0#4"5N!U]]_% %r.   r  c                       e Zd 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dz  dedz  dej                  dz  defd              Z xZS )NemotronModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`NemotronDecoderLayer`]

    Args:
        config: NemotronConfig
    rT   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   r   F)r6   r7   pad_token_idpadding_idx
vocab_sizer   	Embeddingrl   embed_tokens
ModuleListrangenum_hidden_layersr   layersr0   r  normrR   r   gradient_checkpointing	post_initr   s      r,   r7   zNemotronModel.__init__]  s     !.. ++LL):):F<N<NPTP`P`ammFKFLdLdFef!&)4f
 ((:(:P	1@&+# 	 gs   DN	input_idsr   r   r   inputs_embedsr   r   output_hidden_statesr   r=   c
                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}|r|t        | j                         }|| j                  |      }|r|t        | j                         }|	F||j                         nd}t        j                  |||j                  d   z   |j                        }	||	j!                  d      }t#        | j                   |||	||      }|}| j%                  ||	      }|rd
nd }|rd
nd }| j&                  D ]+  }|r||fz  } ||||||||	|      }|d   }|s#||d   fz  }- | j)                  |      }|r||fz  }t+        ||||      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   r   )r9   )rT   r+  r   r   r   r   )r   r   )r   r   r   r   r   r   r   )last_hidden_stater   r   
attentions)rT   r   r,  r   r   r(  r   r   r   r   r"  get_seq_lengthr#   rn   rx   r9   r   r   r   r&  r'  r   )r8   r*  r   r   r   r+  r   r   r,  r   r   past_seen_tokensr   r   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r,   rG   zNemotronModel.forwardm  s/    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I0*$++>O  --i8M0*$++>O!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L(;;'))+%
 &"oom,oW #7BD0d![[ 	6M#!m%55!)*) /"3#-$7	M *!,M =#3"55%	6( 		-0  -!11&+++%	
 	
r.   )	NNNNNNNNN)rH   rI   rJ   r   r    r7   r   r   r#   r   r   r   r
  rN   r   rG   rO   rP   s   @r,   r  r  T  s    ~    .2.204(,26!%)-,026]
##d*]
 t+]
 &&-	]

 ]
 ((4/]
 $;]
  $;]
 #Tk]
 ((4/]
 
!]
  ]
r.   r  c                   X    e Zd ZddiZ 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j                  dz  dedz  dedz  dedz  dej                  dz  deej                  z  defd              Z xZS )NemotronForCausalLMzlm_head.weightzmodel.embed_tokens.weightc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y )NFr   )
r6   r7   r  r  r   r   r   rl   lm_headr)  r   s     r,   r7   zNemotronForCausalLM.__init__  sU     "6*
 ++yy!3!3V5F5FUS 	r.   Nr*  r   r   r   r+  labelsr   r   r,  r   logits_to_keepr=   c                    ||n| j                   j                  }|	|	n| j                   j                  }	| j                  ||||||||	|
	      }|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |}t        |||j                  |j                  |j                        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   r   r/  )rT   r   r,  r  r.  ry   rK   slicer9  loss_functionr   r   r   r   r/  )r8   r*  r   r   r   r+  r:  r   r   r,  r   r;  r   r	  r   slice_indicesr>  r=  s                     r,   rG   zNemotronForCausalLM.forward  s   N 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,0::)%+'/!5) ,6 
,
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD%#33!//))
 	
r.   )NNNNNNNNNNr   )rH   rI   rJ   _tied_weights_keysr7   r   r   r#   r   r   r   r
  rN   rK   r   rG   rO   rP   s   @r,   r7  r7    s0   *,GH  .2.204(,26*.!%)-,026-.F
##d*F
 t+F
 &&-	F

 F
 ((4/F
   4'F
 $;F
  $;F
 #TkF
 ((4/F
 ell*F
 
 F
  F
r.   r7  c                       e Zd Zy)!NemotronForSequenceClassificationNrH   rI   rJ   r   r.   r,   rD  rD  '      r.   rD  c                       e Zd ZdZy)NemotronForQuestionAnsweringtransformerN)rH   rI   rJ   r  r   r.   r,   rH  rH  *  s    %r.   rH  c                       e Zd Zy)NemotronForTokenClassificationNrE  r   r.   r,   rK  rK  .  rF  r.   rK  )rH  r7  r  r  rD  rK  )r   )Kr   r   collections.abcr   typingr   r#   torch.nn.functionalr   r   rE   r   r    r	   r  activationsr
   cache_utilsr   r   r   
generationr   masking_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   r   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   r   utils.genericr   configuration_nemotronr    
get_loggerrH   r   r-   	LayerNormr0   ModulerR   r   r   r   rK   r   r   r   r   r   r   r  r  r7  rD  rH  rK  __all__r   r.   r,   <module>r`     s     $     " " & ! ; ; ) / i  . > > + 2 
		H	%N'",, ',A<bii A<J(V><")) <	UU\\ 	U# 	U%,, 	UR)		 R)nm)/ m)dC!- C!N 0! K5 K\ %o % %& w
+ w
 w
vT
1? T
n h(HJa g&#>@W & b%BD[ ar.   